blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
6f040cb40de3a11a526700d57961c4c9cd304470
Java
AnneStephie18/TestProject
/JavaConcepts/src/InterfaceDemo.java
UTF-8
367
3.234375
3
[]
no_license
interface Phone { void call(); default void message() { System.out.println("sent"); } } class AndroidPhone implements Phone { @Override public void call() { System.out.println("calling"); } } public class InterfaceDemo { public static void main(String[] args) { Phone p=new AndroidPhone(); p.call();p.message(); } }
true
788bc2abe7685ee7b27b389bcdc8395e9d6c6c11
Java
hburaksavas/Mobile-Waitress-System
/MobilGarsonAdminWeb/src/java/com/mobilgarson/managedbeans/ProductBean.java
UTF-8
4,137
1.984375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mobilgarson.managedbeans; import com.garson.model.DAO.CategoryDAO; import com.garson.model.DAO.ProductDAO; import com.garson.model.DAO.ProductImageDAO; import com.garson.model.entity.Category; import com.garson.model.entity.Product; import com.mobilgarson.managedbeans.helper.SessionUtils; import java.io.Serializable; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.event.AjaxBehaviorEvent; import javax.servlet.http.HttpSession; @ManagedBean(name = "productBean") @ViewScoped public class ProductBean implements Serializable { private static final long serialVersionUID = 20111021L; private long restaurantid; private HttpSession session; private ProductDAO dao; private List<Category> categoryList; private long selectedCategoryId; private String selectedCategoryName; private List<Product> productList; private List<Product> filteredProductList; private String selectedProductName; private long selectedProductId; public ProductBean() { } @PostConstruct public void init() { } public void pullProductsAjaxListener(AjaxBehaviorEvent e) { initProductList(); } public void pullCategoryAjaxListener(AjaxBehaviorEvent e) { session = SessionUtils.getSession(); restaurantid = (long) session.getAttribute("restaurantid"); CategoryDAO cdao = new CategoryDAO(); categoryList = cdao.getAllCategories(restaurantid); if (filteredProductList != null) { filteredProductList.clear(); } } private void initProductList() { session = SessionUtils.getSession(); restaurantid = (long) session.getAttribute("restaurantid"); if (restaurantid > 0 && selectedCategoryId > 0) { dao = new ProductDAO(); productList = dao.getRestaurantProductsByCategory(restaurantid, selectedCategoryId); } } public void deleteProduct(AjaxBehaviorEvent e) { dao = new ProductDAO(); dao.deleteProduct(selectedProductId); ProductImageDAO piDAO = new ProductImageDAO(); try { piDAO.deleteProductImages(selectedProductId); } catch (Exception ex) { } initProductList(); } public List<Category> getCategoryList() { return categoryList; } public void setCategoryList(List<Category> categoryList) { this.categoryList = categoryList; } public List<Product> getFilteredProductList() { return filteredProductList; } public void setFilteredProductList(List<Product> filteredProductList) { this.filteredProductList = filteredProductList; } public List<Product> getProductList() { return productList; } public void setProductList(final List<Product> productList) { this.productList = productList; } public String getSelectedProductName() { return selectedProductName; } public void setSelectedProductName(String selectedProductName) { this.selectedProductName = selectedProductName; } public long getSelectedProductId() { return selectedProductId; } public void setSelectedProductId(long selectedProductId) { this.selectedProductId = selectedProductId; } public long getSelectedCategoryId() { return selectedCategoryId; } public void setSelectedCategoryId(long selectedCategoryId) { this.selectedCategoryId = selectedCategoryId; } public String getSelectedCategoryName() { return selectedCategoryName; } public void setSelectedCategoryName(String selectedCategoryName) { this.selectedCategoryName = selectedCategoryName; } }
true
17a2b6a9e57cdec053ba4b94387aa82ee9c7e2c0
Java
koszojudit/MasterPiece
/app/src/main/java/com/example/android/a5_masterpiece/DiscoverActivity.java
UTF-8
2,926
2.359375
2
[]
no_license
package com.example.android.a5_masterpiece; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; /** * Created by koszojudit on 2017. 07. 02.. */ public class DiscoverActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_discover); // Find the toolbar view inside the activity layout // Set the Toolbar to act as the ActionBar for this Activity window // Make sure the toolbar exists in the activity and is not null Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar_main); setSupportActionBar(myToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); // Find the view pager that will allow the user to swipe between fragments // Create an adapter that knows which fragment should be shown on each page // Set the adapter onto the view pager DiscoverFragmentAdapter adapter = new DiscoverFragmentAdapter(getSupportFragmentManager()); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setAdapter(adapter); //Find the tab layout // Connect the tab layout with the view pager. TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } // Code for inflation the main menu @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } // Handling the menu options selection in toolbar @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_search: // User chose the "Search" action // Search dialog should open and search in the content of the screen // CODE TO BE PUT HERE return true; case R.id.action_subscription: // User chose the "Subscription" action //Create intent for SubscriptionActivity and start it Intent paymentIntent = new Intent(this, PaymentActivity.class); startActivity(paymentIntent); return true; default: // If we got here, the user's action was not recognized. // Invoke the superclass to handle it. return super.onOptionsItemSelected(item); } } }
true
9903db531bdfdd70e04b8152586fcfff7e479573
Java
jcgharvey/javax
/src/javatraits/visitors/DefinitionVisitor.java
UTF-8
2,427
2.9375
3
[]
no_license
package javatraits.visitors; import japa.parser.ast.body.VariableDeclarator; import japa.parser.ast.expr.VariableDeclarationExpr; import japa.parser.ast.stmt.BlockStmt; import japa.parser.ast.stmt.CatchClause; import japa.parser.ast.stmt.ForStmt; import japa.parser.ast.stmt.ForeachStmt; import japa.parser.ast.stmt.IfStmt; import japa.parser.ast.stmt.SwitchStmt; import japa.parser.ast.stmt.WhileStmt; import japa.parser.ast.visitor.VoidVisitorAdapter; import java.util.List; import javatraits.scopes.Scope; import javatraits.scopes.Scope.ScopeType; import javatraits.symbols.Symbol; import javatraits.symbols.VariableSymbol; /** * Fourth Visitor * Local variables * @author Jourdan Harvey * */ public class DefinitionVisitor extends VoidVisitorAdapter<Scope>{ @Override public void visit(VariableDeclarator n, Scope arg) { super.visit(n, null); } @Override public void visit(VariableDeclarationExpr n, Scope arg) { arg = n.getJTScope(); Scope enclosingScope = n.getJTScope().getEnclosingScope(); System.out.println("Scope: " + enclosingScope.getScopeType()); if(enclosingScope.getScopeType() == ScopeType.Class){ System.out.println("Found some variableDecExpr in a class scope so they must be fields!"); } else if (enclosingScope.getScopeType() == ScopeType.Local){ List<VariableDeclarator> variables = n.getVars(); for(VariableDeclarator v : variables){ Symbol variableSymbol = new VariableSymbol(v.getId().getName(), n.getType(), n.getModifiers()); enclosingScope.addSymbol(variableSymbol); } } super.visit(n, null); } @Override public void visit(BlockStmt n, Scope arg) { arg = n.getJTScope(); super.visit(n, null); } @Override public void visit(CatchClause n, Scope arg) { arg = n.getJTScope(); super.visit(n, null); } @Override public void visit(ForeachStmt n, Scope arg) { arg = n.getJTScope(); super.visit(n, null); } @Override public void visit(ForStmt n, Scope arg) { arg = n.getJTScope(); super.visit(n, null); } @Override public void visit(IfStmt n, Scope arg) { arg = n.getJTScope(); super.visit(n, null); } @Override public void visit(SwitchStmt n, Scope arg) { arg = n.getJTScope(); super.visit(n, null); } @Override public void visit(WhileStmt n, Scope arg) { arg = n.getJTScope(); super.visit(n, null); } }
true
b50e00587bca1bfdaf7b7fb406202b3437e8415b
Java
zhentaoJin/skywalking
/oap-server/server-query-plugin/query-graphql-plugin/src/main/java/org/apache/skywalking/oap/query/graphql/resolver/LogQuery.java
UTF-8
2,537
1.835938
2
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
/* * 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.skywalking.oap.query.graphql.resolver; import com.coxautodev.graphql.tools.GraphQLQueryResolver; import java.io.IOException; import org.apache.skywalking.oap.server.core.CoreModule; import org.apache.skywalking.oap.server.core.query.LogQueryService; import org.apache.skywalking.oap.server.core.query.input.LogQueryCondition; import org.apache.skywalking.oap.server.core.query.type.Logs; import org.apache.skywalking.oap.server.library.module.ModuleManager; import static java.util.Objects.nonNull; public class LogQuery implements GraphQLQueryResolver { private final ModuleManager moduleManager; private LogQueryService logQueryService; public LogQuery(ModuleManager moduleManager) { this.moduleManager = moduleManager; } private LogQueryService getQueryService() { if (logQueryService == null) { this.logQueryService = moduleManager.find(CoreModule.NAME).provider().getService(LogQueryService.class); } return logQueryService; } public Logs queryLogs(LogQueryCondition condition) throws IOException { long startSecondTB = 0; long endSecondTB = 0; if (nonNull(condition.getQueryDuration())) { startSecondTB = condition.getQueryDuration().getStartTimeBucketInSec(); endSecondTB = condition.getQueryDuration().getEndTimeBucketInSec(); } return getQueryService().queryLogs( condition.getMetricName(), condition.getServiceId(), condition.getServiceInstanceId(), condition .getEndpointId(), condition.getTraceId(), condition.getState(), condition.getStateCode(), condition.getPaging(), startSecondTB, endSecondTB ); } }
true
e56fa21d7ce16305ba61aa2537bd9903f4158f36
Java
SangeunLeeKorea/Course_Application_Program
/Code/Server/src/Manager/LectureManager.java
UTF-8
2,300
2.875
3
[]
no_license
package Manager; import java.util.Vector; import java.util.concurrent.Semaphore; import DAO.DAOLecture; import Entity.ELecture; public class LectureManager { Semaphore semaphore; public LectureManager(Semaphore semaphore) { this.semaphore = semaphore; } public Vector<Object> getItems(Vector<Object> data) { String userID = (String)data.get(0); Vector<Object> result = new Vector<Object>(); DAOLecture daoLecture = new DAOLecture("lecturedata", (String)data.get(1), semaphore); Vector<ELecture> items = daoLecture.getItems(userID); for (ELecture item : items) { result.add(item.getNumber()); result.add(item.getName()); result.add(item.getProfessor()); result.add(item.getCredit()); result.add(item.getDay()); result.add(item.getTime()); } return result; } public Vector<Object> search(Vector<Object> data){ String tableName = data.get(0).toString(); String searchType = data.get(1).toString(); String keyword = data.get(2).toString(); String day = data.get(3).toString(); DAOLecture daoLecture = new DAOLecture("lecturedata", tableName, semaphore); Vector<Object> result = daoLecture.search(searchType, keyword, day); return result; } public Vector<Object> addLecture(Vector<Object> data){ String tableName = data.get(0).toString(); String professor = data.get(3).toString(); data.removeElementAt(0); System.out.println(tableName); DAOLecture daoLecture = new DAOLecture("lecturedata", tableName, semaphore); daoLecture.addLecture(data); daoLecture = new DAOLecture("professordata", professor, semaphore); daoLecture.addLecture(data); Vector<Object> result = new Vector<Object>(); return result; } public Vector<Object> getProfessorLecture(Vector<Object> data){ String userID = (String)data.get(0); Vector<Object> result = new Vector<Object>(); DAOLecture daoLecture = new DAOLecture("professordata", userID, semaphore); Vector<ELecture> items = daoLecture.getItems(userID); for (ELecture item : items) { result.add(item.getNumber()); result.add(item.getName()); result.add(item.getProfessor()); result.add(item.getCredit()); result.add(item.getDay()); result.add(item.getTime()); } return result; } }
true
59864f3fca68e2b1b6f3236c9aa7e601a63b777e
Java
trashksmarty/My-Snake-game-example
/src/mysnakegameexample/GameField.java
UTF-8
5,353
3.078125
3
[]
no_license
package mysnakegameexample; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Random; public class GameField extends JPanel implements ActionListener { private int SIZE_BLOCK = 30; private int SIZE_FIELD = SIZE_BLOCK * SIZE_BLOCK; private int snakeSize; private Image imgSnake; private Image imgApple; private int[] x = new int[SIZE_FIELD]; private int[] y = new int[SIZE_FIELD]; private int appleX; private int appleY; private boolean left = false; private boolean right = true; private boolean up = false; private boolean down = false; private boolean inGame = true; private boolean keyLock = true; public GameField() { setBackground(Color.gray); loadImg(); initGame(); Timer timer = new Timer(250, this); timer.start(); addKeyListener(new FieldKeyListener()); setFocusable(true); } public void initGame() { snakeSize = 3; for (int i = 0; i < snakeSize; i++) { x[i] = snakeSize * SIZE_BLOCK - i * SIZE_BLOCK; y[i] = 90; } createApple(); } public void createApple() { appleX = new Random().nextInt(SIZE_BLOCK - 1) * SIZE_BLOCK; appleY = new Random().nextInt(SIZE_BLOCK - 1) * SIZE_BLOCK; } public void loadImg() { imgSnake = new ImageIcon(getClass().getResource("/images/snake.png")).getImage(); imgApple = new ImageIcon(getClass().getResource("/images/apple.png")).getImage(); } public void moveSnake() { for (int i = snakeSize; i > 0; i--) { x[i] = x[i - 1]; y[i] = y[i - 1]; } if (left) { x[0] -= SIZE_BLOCK; } if (right) { x[0] += SIZE_BLOCK; } if (up) { y[0] -= SIZE_BLOCK; } if (down) { y[0] += SIZE_BLOCK; } } @Override protected void paintComponent(Graphics grphcs) { super.paintComponent(grphcs); if (inGame) { grphcs.drawImage(imgApple, appleX, appleY, this); for (int i = 0; i < snakeSize; i++) { grphcs.drawImage(imgSnake, x[i], y[i], this); } } else { setBackground(Color.BLACK); grphcs.setColor(Color.white); grphcs.setFont(new Font(TOOL_TIP_TEXT_KEY, 50, 50)); grphcs.drawString("Game Over", 300, 400); grphcs.setFont(new Font(TOOL_TIP_TEXT_KEY, 30, 30)); grphcs.drawString("Press \"SPACE\" for a new game!", 230, 500); grphcs.setFont(new Font(TOOL_TIP_TEXT_KEY, 30, 30)); grphcs.drawString("Score: " + (snakeSize - 3), 330, 800); } } @Override public void actionPerformed(ActionEvent ae) { if (inGame) { checkApple(); checkCollisions(); moveSnake(); keyLock = true; repaint(); } } private void checkCollisions() { if (x[0] >= SIZE_FIELD || x[0] < 0 || y[0] >= SIZE_FIELD || y[0] < 0) { inGame = false; } for (int i = snakeSize; i > 0; i--) { if (snakeSize > 4 && x[0] == x[i] && y[0] == y[i]) { inGame = false; } } } private void checkApple() { if (x[0] == appleX && y[0] == appleY) { snakeSize++; createApple(); } } public void clearAll() { left = false; right = true; up = false; down = false; inGame = true; x = new int[SIZE_FIELD]; y = new int[SIZE_FIELD]; } class FieldKeyListener extends KeyAdapter { @Override public void keyPressed(KeyEvent ke) { int key = ke.getKeyCode(); if (key == KeyEvent.VK_LEFT && !right || key == KeyEvent.VK_A && !right) { if (keyLock) { left = true; up = false; down = false; keyLock = false; } } if (key == KeyEvent.VK_UP && !down || key == KeyEvent.VK_W && !down) { if (keyLock) { up = true; left = false; right = false; keyLock = false; } } if (key == KeyEvent.VK_RIGHT && !left || key == KeyEvent.VK_D && !left) { if (keyLock) { right = true; up = false; down = false; keyLock = false; } } if (key == KeyEvent.VK_DOWN && !up || key == KeyEvent.VK_S && !up) { if (keyLock) { down = true; left = false; right = false; keyLock = false; } } if (key == KeyEvent.VK_SPACE) { if (!inGame) { clearAll(); setBackground(Color.gray); initGame(); } } } } }
true
6bb0ce7b2a2a8533ba63cbbc2b1f102421afe76e
Java
MajaTr/GraqlMetamorphicTesting
/src/main/java/uk/ac/cam/gp/charlie/metamorphic/properties/Property.java
UTF-8
466
2.125
2
[]
no_license
package uk.ac.cam.gp.charlie.metamorphic.properties; import grakn.client.answer.ConceptMap; import java.util.List; /* A property interface. test(answers) is supposed to take a list of results from "get" queries (a result from a single query is a List<ConceptMap>, therefore the argument is a List<List<ConceptMap>>) and return a boolean whether they hold the desired property. */ public interface Property { boolean test(List<List<ConceptMap>> answers); }
true
1b4fa5e4296f5f5297ed2f0d178a682f3fe7fc8b
Java
enedaniela/Cloud-Backup-System
/326CC_Ene_Daniela_Elena/SURSE/src/Folder.java
UTF-8
2,700
2.53125
3
[]
no_license
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Vector; import javax.swing.text.BadLocationException; public class Folder implements Repository, Cloneable{ String numeFolder; String dataCreare; int dimensiune; Folder parent; MachineID machineID; Vector<Folder> subdir; public List<Repository> childTree = new ArrayList<Repository>(); public Vector<Permisiuni> permisiuniFolder; public Folder(Folder copie){ this.numeFolder = copie.numeFolder; this.dataCreare = copie.dataCreare; this.dimensiune = copie.dimensiune; this.permisiuniFolder = copie.permisiuniFolder; for(int i = 0; i < copie.childTree.size(); i++) if(copie.childTree.get(i) instanceof Folder){ Folder f = new Folder((Folder)copie.childTree.get(i)); f.parent = this; this.childTree.add(f); } else{ File f = new File((File)copie.childTree.get(i)); this.childTree.add(f); } } public Folder(String nume){ this.numeFolder = nume; this.dataCreare = getCurrentDate(); this.dimensiune = 0; this.parent = Main.FolderCurent; permisiuniFolder = new Vector<Permisiuni>(); //creez permisiuni pentru root si guest Permisiuni rootPermisiuni = new Permisiuni(true, true, Main.listaUtilizatori.get(0)); Permisiuni guestPermisiuni = new Permisiuni(); Permisiuni currentPermisiuni = new Permisiuni(true, true, Main.UtilizatorCurent); //le adaug in vectorul de permisiuni al folderului this.permisiuniFolder.add(0,rootPermisiuni); this.permisiuniFolder.add(1,guestPermisiuni); this.permisiuniFolder.add(2,currentPermisiuni); //adaug permisiuni pentru toti ceilalti utilizatori for(int i = 2; i < Main.listaUtilizatori.size(); i++){ if(!Main.listaUtilizatori.get(i).equals(Main.UtilizatorCurent)){ Permisiuni allPermisiuni = new Permisiuni(false,false,Main.listaUtilizatori.get(i)); this.permisiuniFolder.add(allPermisiuni); } } } public String getCurrentDate(){ DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } @Override public void accept(Command c) throws CommandException, BadLocationException { c.execute(this); } public void folderDetails() throws BadLocationException{ Main.frame.addTextArea("<D: "+this.numeFolder+" "+this.dimensiune + " " + this.dataCreare); } //adauga subarbore la ierarhie public void add(Repository component) { childTree.add(component); } //sterge subarbore din ierarhie public void remove(Repository component) { childTree.remove(component); } }
true
00163c842c7871c99c4eb47c0a20dda8ab75e4b9
Java
AngeloWei/jk
/src/main/java/cn/zw/jk/service/ContractProductService.java
UTF-8
564
1.765625
2
[]
no_license
package cn.zw.jk.service; import cn.zw.jk.entity.Contract; import cn.zw.jk.entity.ContractProduct; import java.io.Serializable; import java.util.List; import java.util.Map; public interface ContractProductService { void insert(ContractProduct contractProduct); List<ContractProduct> find (Map map); void deleteById(Serializable id); void delete(Serializable[] ids); ContractProduct get(Serializable id); void update(ContractProduct contractProduct); //void updateState(Map map); void deleteByContarctId(Serializable[] ids); }
true
0d1ff892b6b72873fee29622ac188f362d8933da
Java
cga2351/code
/DecompiledViberSrc/app/src/main/java/com/facebook/drawee/backends/pipeline/DraweeConfig.java
UTF-8
3,422
1.953125
2
[]
no_license
package com.facebook.drawee.backends.pipeline; import com.facebook.common.internal.ImmutableList; import com.facebook.common.internal.Preconditions; import com.facebook.common.internal.Supplier; import com.facebook.common.internal.Suppliers; import com.facebook.imagepipeline.drawable.DrawableFactory; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; public class DraweeConfig { @Nullable private final ImmutableList<DrawableFactory> mCustomDrawableFactories; private final Supplier<Boolean> mDebugOverlayEnabledSupplier; @Nullable private final PipelineDraweeControllerFactory mPipelineDraweeControllerFactory; private DraweeConfig(Builder paramBuilder) { ImmutableList localImmutableList; if (paramBuilder.mCustomDrawableFactories != null) { localImmutableList = ImmutableList.copyOf(paramBuilder.mCustomDrawableFactories); this.mCustomDrawableFactories = localImmutableList; if (paramBuilder.mDebugOverlayEnabledSupplier == null) break label55; } label55: for (Supplier localSupplier = paramBuilder.mDebugOverlayEnabledSupplier; ; localSupplier = Suppliers.of(Boolean.valueOf(false))) { this.mDebugOverlayEnabledSupplier = localSupplier; this.mPipelineDraweeControllerFactory = paramBuilder.mPipelineDraweeControllerFactory; return; localImmutableList = null; break; } } public static Builder newBuilder() { return new Builder(); } @Nullable public ImmutableList<DrawableFactory> getCustomDrawableFactories() { return this.mCustomDrawableFactories; } public Supplier<Boolean> getDebugOverlayEnabledSupplier() { return this.mDebugOverlayEnabledSupplier; } @Nullable public PipelineDraweeControllerFactory getPipelineDraweeControllerFactory() { return this.mPipelineDraweeControllerFactory; } public static class Builder { private List<DrawableFactory> mCustomDrawableFactories; private Supplier<Boolean> mDebugOverlayEnabledSupplier; private PipelineDraweeControllerFactory mPipelineDraweeControllerFactory; public Builder addCustomDrawableFactory(DrawableFactory paramDrawableFactory) { if (this.mCustomDrawableFactories == null) this.mCustomDrawableFactories = new ArrayList(); this.mCustomDrawableFactories.add(paramDrawableFactory); return this; } public DraweeConfig build() { return new DraweeConfig(this, null); } public Builder setDebugOverlayEnabledSupplier(Supplier<Boolean> paramSupplier) { Preconditions.checkNotNull(paramSupplier); this.mDebugOverlayEnabledSupplier = paramSupplier; return this; } public Builder setDrawDebugOverlay(boolean paramBoolean) { return setDebugOverlayEnabledSupplier(Suppliers.of(Boolean.valueOf(paramBoolean))); } public Builder setPipelineDraweeControllerFactory(PipelineDraweeControllerFactory paramPipelineDraweeControllerFactory) { this.mPipelineDraweeControllerFactory = paramPipelineDraweeControllerFactory; return this; } } } /* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_dex2jar.jar * Qualified Name: com.facebook.drawee.backends.pipeline.DraweeConfig * JD-Core Version: 0.6.2 */
true
5f58f48bb769077f3cfc3d64c4f8c3a2bd14b9a2
Java
TriptiSaijwar/java-codes
/src/com/company/interviewBit/Level1/HotelBookings.java
UTF-8
1,839
3.1875
3
[]
no_license
package com.company.interviewBit.Level1; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; /** * Created by tripti on 11/06/18. */ public class HotelBookings { public boolean hotel(ArrayList<Integer> arrive, ArrayList<Integer> depart, int K) { if(arrive == null || arrive.size() == 0|| depart == null || depart.size() == 0 || depart.size() != arrive.size() || K < 1) return false; Collections.sort(arrive); Collections.sort(depart); int aIndex = 0; int dIndex = 0; int currentRooms = 0; // int max =0; at a point max this many rooms are required while(aIndex < arrive.size() && dIndex < arrive.size()){ if(arrive.get(aIndex) < depart.get(dIndex)) { aIndex++; currentRooms++; // max = Math.max(max, currentRooms); } else { dIndex++; currentRooms--; } if (currentRooms > K) { return false; } } // return max <= K return true; } public void takeCustomInput() { ArrayList<Integer> testList1 = new ArrayList<>(); ArrayList<Integer> testList2 = new ArrayList<>(); int k; Scanner scanner = new Scanner(System.in); int numx = scanner.nextInt(); for (int i = 0; i < numx; i++) { testList1.add(scanner.nextInt()); } scanner.nextLine(); int numy = scanner.nextInt(); for (int i = 0; i < numy; i++) { testList2.add(scanner.nextInt()); } scanner.nextLine(); k = scanner.nextInt(); System.out.println(hotel(testList1,testList2,k)); } }
true
c1a5cba08c4645c35298eec06b9021bf1605d272
Java
arielmartin/control-nutricional
/src/main/java/dao/UsuarioDaoImpl.java
WINDOWS-1250
4,383
2.546875
3
[]
no_license
package dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import modelo.Usuario; import javax.inject.Inject; // implelemtacion del DAO de usuarios, la anotacion @Repository indica a Spring que esta clase es un componente que debe // ser manejado por el framework, debe indicarse en applicationContext que busque en el paquete "dao" // para encontrar esta clase. @Repository("usuarioDao") public class UsuarioDaoImpl implements UsuarioDao { // Como todo dao maneja acciones de persistencia, normalmente estar inyectado el session factory de hibernate // el mismo est difinido en el archivo hibernateContext.xml @Inject private SessionFactory sessionFactory; @Override public Usuario consultarUsuario(Usuario usuario) { // Se obtiene la sesion asociada a la transaccion iniciada en el servicio que invoca a este metodo y se crea un criterio // de busqueda de Usuario donde el email y password sean iguales a los del objeto recibido como parametro // uniqueResult da error si se encuentran mas de un resultado en la busqueda. final Session session = sessionFactory.getCurrentSession(); return (Usuario) session.createCriteria(Usuario.class) .add(Restrictions.eq("email", usuario.getEmail())) .add(Restrictions.eq("password", usuario.getPassword())) .uniqueResult(); } @Override public Long crearUsuario(Usuario usuario) { final Session session = sessionFactory.getCurrentSession(); Usuario resultado = (Usuario) session.createCriteria(Usuario.class) .add(Restrictions.eq("email", usuario.getEmail())) .uniqueResult(); if(resultado != null) { return (long) 0; } else { session.save(usuario); return usuario.getId(); } } @Override public boolean checkMailUsuario(Usuario usuario) { final Session session = sessionFactory.getCurrentSession(); Usuario resultado = (Usuario) session.createCriteria(Usuario.class) .add(Restrictions.eq("email", usuario.getEmail())) .uniqueResult(); if(resultado != null) { return false; } else { return true; } } @Override public void cargarUsuariosIniciales() { final Session session = sessionFactory.getCurrentSession(); Usuario doctor = new Usuario(); doctor.setNombre("Gonzalo"); doctor.setApellido("Garcia"); doctor.setEmail("gonzalogarcia@gmail.com"); doctor.setFechaNacimiento("20/03/1987"); doctor.setRol("medico"); doctor.setId((long)1); doctor.setPassword(""); Usuario doctor2 = new Usuario(); doctor2.setNombre("Gabriela"); doctor2.setApellido("Perez"); doctor2.setEmail("gabrielaperez@gmail.com"); doctor2.setFechaNacimiento("15/05/1990"); doctor2.setRol("medico"); doctor2.setId((long)2); doctor2.setPassword(""); session.save(doctor); session.save(doctor2); Usuario paciente = new Usuario(); paciente.setNombre("Pedro"); paciente.setApellido("Smith"); paciente.setEmail("pedrosmith@gmail.com"); paciente.setFechaNacimiento("12/08/1993"); paciente.setRol("paciente"); paciente.setId((long)3); paciente.setPassword(""); Usuario paciente2 = new Usuario(); paciente2.setNombre("Jimena"); paciente2.setApellido("Atila"); paciente2.setEmail("jimenaatila@gmail.com"); paciente2.setFechaNacimiento("23/07/1995"); paciente2.setRol("paciente"); paciente2.setId((long)4); paciente2.setPassword(""); Usuario paciente3 = new Usuario(); paciente3.setNombre("Carlos"); paciente3.setApellido("Carrizo"); paciente3.setEmail("carloscarrizo@gmail.com"); paciente3.setFechaNacimiento("1/07/1988"); paciente3.setRol("paciente"); paciente3.setId((long)5); paciente3.setPassword(""); Usuario paciente4 = new Usuario(); paciente4.setNombre("Pamela"); paciente4.setApellido("Borges"); paciente4.setEmail("pamelaborges@gmail.com"); paciente4.setFechaNacimiento("11/11/1994"); paciente4.setRol("paciente"); paciente4.setId((long)6); paciente4.setPassword(""); Usuario paciente5 = new Usuario(); paciente5.setNombre("Pablo"); paciente5.setApellido("Garcia"); paciente5.setEmail("pablogarcia@gmail.com"); paciente5.setFechaNacimiento("20/02/1997"); paciente5.setRol("paciente"); paciente5.setId((long)7); paciente5.setPassword(""); session.save(paciente); session.save(paciente2); session.save(paciente3); session.save(paciente4); session.save(paciente5); } }
true
162d43ace3ba26dd6df1cf1baeddcaec7099a68e
Java
GPC-debug/andclient
/common/src/main/java/com/easymi/common/entity/AdvInfo.java
UTF-8
577
2.046875
2
[]
no_license
package com.easymi.common.entity; import android.support.annotation.NonNull; /** * Created by liuzihao on 2018/12/3. */ public class AdvInfo implements Comparable<AdvInfo> { public String advertisementImg;//显示的图片地址 public String urlAddress;//点击的链接 public int sort;//排序 public int displayPosition; public String elasticFrame; @Override public int compareTo(@NonNull AdvInfo advInfo) { if (sort > advInfo.sort) { //升序排列 return 1; } else { return -1; } } }
true
5641716080df35766578a53f1b41e15f20a88b83
Java
tangtaoshadow/Propro-Server
/src/main/java/com/westlake/air/propro/dao/UnimodDAO.java
UTF-8
2,904
2.5
2
[ "Apache-2.0" ]
permissive
package com.westlake.air.propro.dao; import com.westlake.air.propro.algorithm.parser.model.chemistry.Unimod; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.*; import java.util.HashMap; /** * Created by James Lu MiaoShan * Time: 2018-06-20 09:51 */ @Component public class UnimodDAO { public final Logger logger = LoggerFactory.getLogger(UnimodDAO.class); public HashMap<String, Unimod> unimodMap = new HashMap<>(); @PostConstruct public void init() throws IOException { InputStream stream = getClass().getClassLoader().getResourceAsStream("dbfile/unimod.obo"); File file = new File("dbfile/unimod.obo"); FileUtils.copyInputStreamToFile(stream, file); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String line = null; //如果检测到[Term]这个标签就保存上一组的Unimod对象 Unimod unimod = null; while ((line = reader.readLine()) != null) { line = line.trim().toLowerCase(); if (line.equals("[term]")) { if (unimod != null) { unimodMap.put(unimod.getId(), unimod); } unimod = new Unimod(); } if (line.startsWith("id:")) { unimod.setId(line.replace("id:", "").trim().replace("unimod:", "").trim()); } if (line.startsWith("name:")) { unimod.setName(line.replace("name:", "").trim()); } if (line.contains("delta_mono_mass")) { unimod.setMonoMass(Double.parseDouble(line.replace("property_value:", "").trim().replace("delta_mono_mass=", "").trim().replace("\"", ""))); } if (line.contains("delta_avge_mass")) { unimod.setAverageMass(Double.parseDouble(line.replace("property_value:", "").trim().replace("delta_avge_mass=", "").trim().replace("\"", ""))); } } if (unimod != null) { unimodMap.put(unimod.getId(), unimod); } reader.close(); logger.info("Init Unimod Database file success!!!"); } catch (IOException e) { logger.info("Init Unimod Database file failed!!!"); e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } public Unimod getUnimod(String unimodId) { return unimodMap.get(unimodId); } }
true
16cb559c8ec140f5a0f16d8b2d37e49df0e24827
Java
hyungjun26/Algorithm-Study
/src/Programmers/Solution_42627.java
UTF-8
1,830
3.125
3
[]
no_license
package Programmers; import java.util.*; public class Solution_42627 { class Task implements Comparable<Task>{ int come; int len; public Task(int come, int len){ this.come = come; this.len = len; } @Override public int compareTo(Task other){ return this.len <= other.len ? -1 : 1; } } public int solution(int[][] jobs) { int jobCnt = jobs.length; PriorityQueue<Task>[] timeStamp = new PriorityQueue[1001]; for(int i = 0; i < timeStamp.length; i++){ timeStamp[i] = new PriorityQueue<>(); } for(int i = 0; i < jobs.length; i++){ timeStamp[jobs[i][0]].add(new Task(jobs[i][0], jobs[i][1])); } PriorityQueue<Task> schedule = new PriorityQueue<>(); int time = 0; int remain = 0; int sum = 0; Task t = null; while(jobCnt > 0){ if(time < 1001){ while(!timeStamp[time].isEmpty()){ if(t==null && schedule.isEmpty()){ t = timeStamp[time].poll(); remain = t.len; sum += time + t.len - t.come; jobCnt--; } else { schedule.add(timeStamp[time].poll()); } } } time++; remain--; if(remain==0 && !schedule.isEmpty()){ t = schedule.poll(); remain = t.len; sum += time + t.len - t.come; jobCnt--; } else if(remain==0 && schedule.isEmpty()){ t = null; } } return sum/jobs.length; } }
true
9fdecec428f88040d6f72b403651a6c810adf1a0
Java
HappyHouse5/happyhouse_back
/HappyHouseFinalPJT/src/main/java/com/ssafy/happyhouse/service/MemberServiceImpl.java
UTF-8
1,533
2.359375
2
[]
no_license
package com.ssafy.happyhouse.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ssafy.happyhouse.dao.MemberDao; import com.ssafy.happyhouse.dto.MemberDto; @Service public class MemberServiceImpl implements MemberService{ @Autowired private MemberDao memberDao; String uploadFolder = "upload"; @Override public int register(MemberDto member) throws Exception { System.out.println(member.getName()); List<MemberDto> duplMember = memberDao.idEmailCheck(member); for(int i=0; i<duplMember.size(); i++) { if(duplMember.get(i).getUserId().equals(member.getUserId())) { System.out.println("중복 ID"); return -1; } else if(duplMember.get(i).getEmail().equals(member.getEmail())) { System.out.println("중복 Email"); return -2; } } int ret = memberDao.register(member); System.out.println("keyId : " + member.getKeyId()); return ret; } @Override public int setMemberInfo(MemberDto member) throws Exception { System.out.println(member.getLocationCode()); return memberDao.setMemberInfo(member); } @Override public MemberDto login(MemberDto member) throws Exception { member = memberDao.login(member); return member; } @Override public int deleteMember(MemberDto member) throws Exception { return memberDao.deleteMember(member); } @Override public int checkId(String userId) throws Exception { return memberDao.checkId(userId); } }
true
ef760fa4c7033c68aa1a094d7e136f364299afa6
Java
ywtnhm/OA
/sys-oa/service-user/src/main/java/cn/yj/user/shiro/ShiroUtils.java
UTF-8
3,608
2.484375
2
[]
no_license
package cn.yj.user.shiro; import cn.yj.common.JedisUtils; import cn.yj.tools.exception.Error; import cn.yj.tools.exception.ServiceException; import cn.yj.common.LoginUser; import java.util.Collection; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * <br> * * @author 永健 * @since 2020-11-29 00:17 */ public class ShiroUtils { private static final ConcurrentHashMap<String, Set<String>> ROLES_MAP = new ConcurrentHashMap<String, Set<String>>(); private static final ConcurrentHashMap<String, Set<String>> PERMISSIONS = new ConcurrentHashMap<>(); private static final String ROLE_KEY = "roles_key_"; private static final String PERM_KEY = "perm_key_"; public static void setUser(LoginUser user) { //ROLES_MAP.put(user.getToken(), user.getRoles().stream().map(role -> (String) role.get("code")).collect(Collectors.toSet())); //PERMISSIONS.put(user.getToken(), user.getPermission()); JedisUtils.setObject(ROLE_KEY.concat(user.getToken()), user.getRoles().stream().map(role -> (String) role.get("code")).collect(Collectors.toSet())); JedisUtils.setObject(PERM_KEY.concat(user.getToken()), user.getPermission()); } public static void checkRole(String token, String role) { Set<String> roles = JedisUtils.getObject(ROLE_KEY.concat(token), Set.class);//ROLES_MAP.get(token); if (roles == null || !roles.contains(role)) { throw new ServiceException(Error.权限异常, "没有角色权限"); } } public static void checkRoles(String token, Collection<String> roles, boolean or) { Set<String> rolesCache = JedisUtils.getObject(ROLE_KEY.concat(token), Set.class); boolean flag = false; if (roles != null && !roles.isEmpty()) { for (String roleName : roles) { if (!or) { flag = true; checkRole(token, roleName); } else { if (rolesCache.contains(roleName)) { flag = true; break; } } } if (!flag) { throw new ServiceException(Error.权限异常, "没有角色权限"); } } } public static void checkPermission(String token, String perm) { Set<String> perms = JedisUtils.getObject(PERM_KEY.concat(token), Set.class); if (perms == null || !perms.contains(perm)) { throw new ServiceException(Error.权限异常); } } public static void checkPermissions(String token, Collection<String> perms, boolean or) { boolean flag = false; if (perms != null && !perms.isEmpty()) { for (String perm : perms) { if (!or) { flag = true; checkPermission(token, perm); } else { Set<String> permsCache = JedisUtils.getObject(ROLE_KEY.concat(token), Set.class); if (permsCache.contains(perm)) { flag = true; break; } } } if (!flag) { throw new ServiceException(Error.权限异常, "没有角色权限"); } } } }
true
3c20548c0f6abf93089e6d3ceca51f52c28784e5
Java
BartekRO/Invoices
/src/main/java/com/java/ro/invoices/controler/TaxRateController.java
UTF-8
844
2.03125
2
[]
no_license
package com.java.ro.invoices.controler; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.java.ro.invoices.model.entity.TaxRate; import com.java.ro.invoices.model.service.TaxRateService; @Controller public class TaxRateController { @Autowired private TaxRateService taxRateService; @PreAuthorize("hasRole('ROLE_USER')") @RequestMapping(value="/getTaxRates", method= RequestMethod.GET) public @ResponseBody List<TaxRate> getContranctors() { return taxRateService.getTaxRates(); } }
true
5153aa655d9a232164ac2844ff356c29fafd75b8
Java
Alonyaik/L5PR
/Stream/StreamServer/src/streaming/ScreenRecorder.java
UTF-8
25,888
2.296875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package streaming; import java.awt.AWTException; import java.awt.Color; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import org.imgscalr.Scalr; /** * * @author olegb */ public class ScreenRecorder extends javax.swing.JFrame { private int port = 1331; private static DatagramSocket datagramSocket; private byte[] buffer; private MouseEvent getPositionEvent; private boolean running = false; private boolean streamStatus = false; // Colors private Color brightRed = new Color(242, 38, 19); private Color darkRed = new Color(84, 11, 12); private Color brightGreen = new Color(127, 255, 0); private Color darkGreen = new Color(0, 75, 0); private ArrayList<StreamConnection> streamConnections = new ArrayList<StreamConnection>(); /** * Creates new form Server */ public ScreenRecorder() { initComponents(); try { datagramSocket = new DatagramSocket(port); } catch (Exception ex) { Logger.getLogger(ScreenRecorder.class.getName()).log(Level.SEVERE, null, ex); } // Set button StreamStatusOff to on position jPanelStreamStatusOff.setBackground(brightRed); jLabelStreamStatusOff.setForeground(Color.white); // Set button StreamStatusOn to off position jPanelStreamStatusOn.setBackground(darkGreen); jLabelStreamStatusOn.setForeground(Color.GRAY); } /** * 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() { jPanelDragWindow = new javax.swing.JPanel(); jPanelCloseWindow = new javax.swing.JPanel(); jPanelMinimizeWindow = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabelDisplayImages = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); jPanelStreamStatusOn = new javax.swing.JPanel(); jLabelStreamStatusOn = new javax.swing.JLabel(); jPanelStreamStatusOff = new javax.swing.JPanel(); jLabelStreamStatusOff = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextPaneChat = new javax.swing.JTextPane(); jTextFieldMessage = new javax.swing.JTextField(); jButtonSendMessage = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); setPreferredSize(new java.awt.Dimension(700, 400)); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanelDragWindow.setBackground(new java.awt.Color(1, 50, 67)); jPanelDragWindow.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { jPanelDragWindowMouseDragged(evt); } }); jPanelDragWindow.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { jPanelDragWindowMousePressed(evt); } }); javax.swing.GroupLayout jPanelDragWindowLayout = new javax.swing.GroupLayout(jPanelDragWindow); jPanelDragWindow.setLayout(jPanelDragWindowLayout); jPanelDragWindowLayout.setHorizontalGroup( jPanelDragWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 600, Short.MAX_VALUE) ); jPanelDragWindowLayout.setVerticalGroup( jPanelDragWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 50, Short.MAX_VALUE) ); getContentPane().add(jPanelDragWindow, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 600, 50)); jPanelCloseWindow.setBackground(new java.awt.Color(228, 141, 154)); jPanelCloseWindow.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { jPanelCloseWindowMousePressed(evt); } }); javax.swing.GroupLayout jPanelCloseWindowLayout = new javax.swing.GroupLayout(jPanelCloseWindow); jPanelCloseWindow.setLayout(jPanelCloseWindowLayout); jPanelCloseWindowLayout.setHorizontalGroup( jPanelCloseWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 50, Short.MAX_VALUE) ); jPanelCloseWindowLayout.setVerticalGroup( jPanelCloseWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 50, Short.MAX_VALUE) ); getContentPane().add(jPanelCloseWindow, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 0, -1, 50)); jPanelMinimizeWindow.setBackground(new java.awt.Color(228, 241, 254)); jPanelMinimizeWindow.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { jPanelMinimizeWindowMousePressed(evt); } }); javax.swing.GroupLayout jPanelMinimizeWindowLayout = new javax.swing.GroupLayout(jPanelMinimizeWindow); jPanelMinimizeWindow.setLayout(jPanelMinimizeWindowLayout); jPanelMinimizeWindowLayout.setHorizontalGroup( jPanelMinimizeWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 50, Short.MAX_VALUE) ); jPanelMinimizeWindowLayout.setVerticalGroup( jPanelMinimizeWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 50, Short.MAX_VALUE) ); getContentPane().add(jPanelMinimizeWindow, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 0, -1, 50)); jPanel1.setBackground(new java.awt.Color(240, 240, 255)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.add(jLabelDisplayImages, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 46, 480, 296)); jPanel6.setBackground(new java.awt.Color(92, 151, 191)); jPanel6.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanelStreamStatusOn.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { jPanelStreamStatusOnMousePressed(evt); } }); jLabelStreamStatusOn.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelStreamStatusOn.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelStreamStatusOn.setText("1"); javax.swing.GroupLayout jPanelStreamStatusOnLayout = new javax.swing.GroupLayout(jPanelStreamStatusOn); jPanelStreamStatusOn.setLayout(jPanelStreamStatusOnLayout); jPanelStreamStatusOnLayout.setHorizontalGroup( jPanelStreamStatusOnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelStreamStatusOnLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabelStreamStatusOn, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanelStreamStatusOnLayout.setVerticalGroup( jPanelStreamStatusOnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelStreamStatusOnLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabelStreamStatusOn, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel6.add(jPanelStreamStatusOn, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 0, 50, 40)); jPanelStreamStatusOff.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { jPanelStreamStatusOffMousePressed(evt); } }); jLabelStreamStatusOff.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabelStreamStatusOff.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelStreamStatusOff.setText("0"); javax.swing.GroupLayout jPanelStreamStatusOffLayout = new javax.swing.GroupLayout(jPanelStreamStatusOff); jPanelStreamStatusOff.setLayout(jPanelStreamStatusOffLayout); jPanelStreamStatusOffLayout.setHorizontalGroup( jPanelStreamStatusOffLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelStreamStatusOffLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabelStreamStatusOff, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanelStreamStatusOffLayout.setVerticalGroup( jPanelStreamStatusOffLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelStreamStatusOffLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabelStreamStatusOff, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel6.add(jPanelStreamStatusOff, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 0, 50, 40)); jPanel1.add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); jTextPaneChat.setEditable(false); jScrollPane1.setViewportView(jTextPaneChat); jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 60, 190, 239)); jTextFieldMessage.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextFieldMessageKeyPressed(evt); } }); jPanel1.add(jTextFieldMessage, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 310, 110, 20)); jButtonSendMessage.setText("Send"); jButtonSendMessage.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { jButtonSendMessageMousePressed(evt); } }); jPanel1.add(jButtonSendMessage, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 310, 70, 20)); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 50, 700, 360)); pack(); }// </editor-fold>//GEN-END:initComponents private void jPanelDragWindowMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelDragWindowMousePressed // Get current position getPositionEvent = evt; }//GEN-LAST:event_jPanelDragWindowMousePressed private void jPanelDragWindowMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelDragWindowMouseDragged // Set new location setLocation(evt.getXOnScreen() - getPositionEvent.getX(), evt.getYOnScreen() - getPositionEvent.getY()); }//GEN-LAST:event_jPanelDragWindowMouseDragged private void jPanelMinimizeWindowMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelMinimizeWindowMousePressed this.setState(ICONIFIED); }//GEN-LAST:event_jPanelMinimizeWindowMousePressed private void jPanelCloseWindowMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelCloseWindowMousePressed running = false; String message = "\\offline"; sendMessageToAllClients(message.getBytes()); System.exit(0); }//GEN-LAST:event_jPanelCloseWindowMousePressed private void jPanelStreamStatusOffMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelStreamStatusOffMousePressed changeStreamStatus(); }//GEN-LAST:event_jPanelStreamStatusOffMousePressed private void jPanelStreamStatusOnMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelStreamStatusOnMousePressed changeStreamStatus(); }//GEN-LAST:event_jPanelStreamStatusOnMousePressed private void jTextFieldMessageKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldMessageKeyPressed if (evt.getKeyCode() == evt.VK_ENTER) { String message = jTextFieldMessage.getText(); if (!message.isEmpty()) { jTextFieldMessage.setText(""); // Add message to chat panel jTextPaneChat.setText(jTextPaneChat.getText().concat(" Server: " + message + "\n")); String messageToSend = "\\message: Admin" + ": " + message + "\\end"; sendMessageToAllClients(messageToSend.getBytes()); } } }//GEN-LAST:event_jTextFieldMessageKeyPressed private void jButtonSendMessageMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonSendMessageMousePressed String message = jTextFieldMessage.getText(); if (!message.isEmpty()) { jTextFieldMessage.setText(""); // Add message to chat panel jTextPaneChat.setText(jTextPaneChat.getText().concat(" Server: " + message + "\n")); String messageToSend = "\\message: Server" + ": " + message + "\\end"; sendMessageToAllClients(messageToSend.getBytes()); } }//GEN-LAST:event_jButtonSendMessageMousePressed private void changeStreamStatus() { changeStreamStatusColor(); if (!streamStatus) { startStream(); } else { stopStream(); } // Change stream status streamStatus = !streamStatus; } private void changeStreamStatusColor() { // If stream is on than change to off if (jPanelStreamStatusOff.getBackground() == brightRed || jPanelStreamStatusOn.getBackground() == darkGreen) { // Set button StreamStatusOff to off position jPanelStreamStatusOff.setBackground(darkRed); jLabelStreamStatusOff.setForeground(Color.GRAY); // Set button StreamStatusOn to on position jPanelStreamStatusOn.setBackground(brightGreen); jLabelStreamStatusOn.setForeground(Color.white); // else if stream is of than change to on } else if (jPanelStreamStatusOff.getBackground() == darkRed || jPanelStreamStatusOn.getBackground() == brightGreen) { // Set button StreamStatusOff to on position jPanelStreamStatusOff.setBackground(brightRed); jLabelStreamStatusOff.setForeground(Color.white); // Set button StreamStatusOn to off position jPanelStreamStatusOn.setBackground(darkGreen); jLabelStreamStatusOn.setForeground(Color.GRAY); } else { System.out.println("Stream status error"); } } private void startStream() { // Set running to true running = true; // Create new screen recording thread startStreamThread(); // Create new waiting for clients thread startWaitingMessagesThread(); // Send message that stream is online String message = "\\online"; sendMessageToAllClients(message.getBytes()); } private BufferedImage getImage() { try { Robot robot = new Robot(); Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage bufferedImage = robot.createScreenCapture(rectangle); return bufferedImage; } catch (AWTException ex) { Logger.getLogger(ScreenRecorder.class.getName()).log(Level.SEVERE, null, ex); } return null; } private void startStreamThread() { new Thread("Screen Recorder") { BufferedImage image; BufferedImage scaledImage; @Override public void run() { try { while (running) { // Get a desktop screenshot image = getImage(); // Scale image and scaledImage = Scalr.resize(image, Scalr.Method.BALANCED, 480, 270); // Send image sendMessageToAllClients(getBytes(scaledImage)); // Set screenshot as label icon jLabelDisplayImages.setIcon(new ImageIcon(scaledImage)); } image = ImageIO.read(ScreenRecorder.class.getResource("/images/StreamOffline.jpg")); scaledImage = Scalr.resize(image, Scalr.Method.BALANCED, 480, 270); jLabelDisplayImages.setIcon(new ImageIcon(scaledImage)); } catch (IOException ex) { Logger.getLogger(ScreenRecorder.class.getName()).log(Level.SEVERE, null, ex); } } }.start(); } private void startWaitingMessagesThread() { new Thread("Waiting for Clients Thread") { DatagramPacket packet; byte[] waitingBuffer; @Override public void run() { while (running) { try { waitingBuffer = new byte[256]; packet = new DatagramPacket(waitingBuffer, waitingBuffer.length); datagramSocket.receive(packet); processingMessage(packet); } catch (IOException ex) { Logger.getLogger(ScreenRecorder.class.getName()).log(Level.SEVERE, null, ex); } } } }.start(); } private byte[] getBytes(BufferedImage image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(image, "jpg", baos); } catch (IOException ex) { Logger.getLogger(ScreenRecorder.class.getName()).log(Level.SEVERE, null, ex); } byte[] bytes = baos.toByteArray(); return bytes; } private byte[] getBytes(String message) { buffer = new byte[256]; buffer = message.getBytes(); return buffer; } private void sendMessage(byte[] bytes, InetAddress address, int port) { try { if (running) { // Send bytes DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port); datagramSocket.send(packet); } } catch (IOException ex) { Logger.getLogger(ScreenRecorder.class.getName()).log(Level.SEVERE, null, ex); } } private void sendMessageToAllClients(byte[] bytes) { for (int i = 0; i < streamConnections.size(); i++) { StreamConnection streamConnection = streamConnections.get(i); //String name = streamConnection.getName(); InetAddress address = streamConnection.getAddress(); int port = streamConnection.getPort(); sendMessage(bytes, address, port); } } // Proccesing message private void processingMessage(DatagramPacket packet) { String message = new String(packet.getData()); if (message.startsWith("\\message:")) { String messageToAdd = message.substring(message.indexOf(":") + 1, message.indexOf("\\end")); // Add message to chat panel jTextPaneChat.setText(jTextPaneChat.getText().concat(messageToAdd + "\n")); sendMessageToAllClients(packet.getData()); } else if (message.startsWith("\\connect:")) { // Get user data String name = message.substring(message.indexOf(":") + 1, message.indexOf("\\end")); InetAddress address = packet.getAddress(); int port = packet.getPort(); if (verifyName(name)) { // Create new user StreamConnection newUser = new StreamConnection(name, address, port); // Add new user to list streamConnections.add(newUser); // Add text to chat jTextPaneChat.setText(jTextPaneChat.getText().concat(" [" + name + "] entered the stream." + "\n")); // Send message about new user to all client sendMessageToAllClients(getBytes("\\message: [" + name + "] entered the stream." + "\\end")); // Send message that stream is online String messageStreamOnline = "\\online"; sendMessageToAllClients(messageStreamOnline.getBytes()); } else sendMessage("\\busyName".getBytes(), address, port); } else if (message.startsWith("\\disconnect:")) { // Get user name String name = message.substring(message.indexOf(":") + 1, message.indexOf("\\end")); // Disconnect user for (int i = 0; i < streamConnections.size(); i++) { StreamConnection user = streamConnections.get(i); if (user.getName().equals(name)) { streamConnections.remove(i); break; } } // Add text to chat jTextPaneChat.setText(jTextPaneChat.getText().concat(" [" + name + "] came out of the stream." + "\n")); // Send message about new user to all client sendMessageToAllClients(getBytes("\\message: [" + name + "] came out of the stream." + "\\end")); } } // Verify if user exist in list boolean verifyName(String name) { for (int i = 0; i < streamConnections.size(); i++) { StreamConnection user = streamConnections.get(i); if (user.getName().equals(name)) { return false; } } return true; } private void stopStream() { // Send message that stream is online sendMessageToAllClients("\\offline".getBytes()); // Set running to true running = false; } /** * @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(ScreenRecorder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ScreenRecorder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ScreenRecorder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ScreenRecorder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ScreenRecorder().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonSendMessage; private javax.swing.JLabel jLabelDisplayImages; private javax.swing.JLabel jLabelStreamStatusOff; private javax.swing.JLabel jLabelStreamStatusOn; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanelCloseWindow; private javax.swing.JPanel jPanelDragWindow; private javax.swing.JPanel jPanelMinimizeWindow; private javax.swing.JPanel jPanelStreamStatusOff; private javax.swing.JPanel jPanelStreamStatusOn; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField jTextFieldMessage; private javax.swing.JTextPane jTextPaneChat; // End of variables declaration//GEN-END:variables }
true
84a9d827bece60880c332fdf698d5ea7f667f7ce
Java
FlameAndHammer/mainacademy_kurs_2
/kurs/src/yuriy/labs/labs_3/l_07/LabWork_1_7_1/Main.java
UTF-8
1,010
2.8125
3
[]
no_license
package yuriy.labs.labs_3.l_07.LabWork_1_7_1; import java.util.Arrays; import java.util.Comparator; import java.util.Random; /** * Created by Ruble on 04.09.2017. */ public class Main { public static void main(String[] args) { Integer[] arr = getRandomArr (15); System.out.println(Arrays.toString(arr)); Arrays.sort(arr); System.out.println(Arrays.toString(arr)); /* Arrays.sort(arr, new Comparator <Integer>() { public int compare (Integer i1, Integer i2){ return i2 - i1;} }); System.out.println(Arrays.toString(arr)); */ Arrays.sort(arr, (i1, i2) -> i2 - i1); System.out.println(Arrays.toString(arr)); //// } private static Integer [] getRandomArr (int size) { Integer[] arr = new Integer[size]; Random generator = new Random(); for (int i = 0; i < size; i++) { arr[i] = generator.nextInt(100); } return arr; } }
true
f920e38bedb44ad89e8858b4071a90b0548a0bdb
Java
mziernik/fra
/src/com/database/queries/InsertOrUpdate.java
UTF-8
3,577
2.84375
3
[]
no_license
package com.database.queries; import com.utils.Is; import com.utils.text.StrWriter; import com.database.queries.builder.QueryBuilder; import com.database.Database; import com.database.queries.builder.QueryObject; import com.database.queries.builder.QueryStringWriter; import com.utils.collections.Strings; /** * W zależności od tego czy parametr 'where' jest zdefiniowany, wykonany * zostanie insert lub update * * @author milosz */ public class InsertOrUpdate extends QueryBuilder<InsertOrUpdate> { protected boolean orReplace = false; // SQLite protected final String table; protected final String where; protected final Strings returning = new Strings() .trim(true) .unique(true) .nonEmpty(true); public InsertOrUpdate(Database db, String table, String where) { super(db); this.table = table; this.where = where; } public InsertOrUpdate addReturningColumn(String column) { returning.add(column); return this; } @Override public InsertOrUpdate arg(String name, Object value) { addParam(name, value).array(true); return this; } public QueryObject arg_(String name, Object value) { return addParam(name, value).array(true); } public InsertOrUpdate argIns(String name, Object value) { if (isInsert()) addParam(name, value).array(true); return this; } public InsertOrUpdate argUpd(String name, Object value) { if (isUpdate()) addParam(name, value).array(true); return this; } public boolean isInsert() { return where == null || where.trim().isEmpty(); } public boolean isUpdate() { return !isInsert(); } @Override public boolean isEmpty() { return isUpdate() && params.isEmpty(); } @Override public String buildQuery() { return isUpdate() ? buildUpdate() : buildInsert(); } protected String buildUpdate() { if (isEmpty()) return ""; StrWriter sb = new StrWriter(); sb.append("UPDATE ").append(table).append(" SET\n"); for (int i = 0; i < params.size(); i++) { sb.append("\t").append(Database.escapeSQL(params.get(i).name())); sb.append(" = "); sb.append(params.get(i).getEscapedValue()); if (i < params.size() - 1) sb.append(","); sb.append("\n"); } if (!Is.empty(where)) sb.append("WHERE ") .append(where); if (!returning.isEmpty()) sb.append("\nRETURNING ").append(returning.toString(", ")); return sb.toString(); } protected String buildInsert() { QueryStringWriter sw = new QueryStringWriter(this) .append("INSERT").append(orReplace ? " OR REPLACE" : "").append(" INTO ") .append(table) .space(); if (params.isEmpty()) sw.append("DEFAULT VALUES"); else sw.append("(") .getNames() .append(")") .lineBreak() .append("VALUES") .space() .append("(") .lineBreak() .getValues() .lineBreak() .append(")"); if (!returning.isEmpty()) sw.append("\nRETURNING ").append(returning.toString(", ")); return sw.toString(); } }
true
36bbdaf1faaa17aa2aa8b2edf9d1c3f6dacf67ae
Java
annaannaR/movie_rental
/src/main/java/pl/ampv/movie_cart/service/ReviewService.java
UTF-8
145
1.773438
2
[]
no_license
package pl.ampv.movie_cart.service; import pl.ampv.movie_cart.model.Review; public interface ReviewService { void save(Review review); }
true
c8e00c2aa2eed27b346231ba3299cd49b4bc4444
Java
MonicaMerino/AppTuVoto
/tuvoto/src/modelo/DaoVoto.java
UTF-8
2,597
2.6875
3
[]
no_license
package modelo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DaoVoto { String cadenaConexion = "jdbc:mysql://localhost:3306/tuvoto"; String user = "root"; String pwd = "root"; public DaoVoto() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Alta voto public boolean votacion(String idUsuario, String idPartido) { if (votoIdUsuario(idUsuario)) { return false; } try (Connection cn = DriverManager.getConnection(cadenaConexion, user, pwd);) { String sql = "insert into votos (idUsuario, idPartido)"; sql += "values(?, ?)"; PreparedStatement ps = cn.prepareStatement(sql); ps.setString(1, idUsuario); ps.setString(2, idPartido); ps.execute(); } catch (SQLException e) { e.printStackTrace(); } return true; } // Comprobamos si el usuario ya ha votado private boolean votoIdUsuario(String idUsuario) { boolean encontrado = false; try (Connection cn = DriverManager.getConnection(cadenaConexion, user, pwd);) { String sql = "select * from votos where idUsuario=?" ; PreparedStatement ps = cn.prepareStatement(sql); ps.setString(1, idUsuario); ResultSet rs = ps.executeQuery(); if (rs.next()) { encontrado = true; } } catch (SQLException e) { e.printStackTrace(); } return encontrado; } // Baja voto. Realmente no lo necesito // public void eliminarVoto(int idVoto) { // try (Connection cn = DriverManager.getConnection(cadenaConexion, user, pwd);) { // // String sql = "delete from votos where idVoto =?"; // PreparedStatement ps = cn.prepareStatement(sql); // ps.setInt(1, idVoto); // ps.executeUpdate(); // // } catch (SQLException e) { // e.printStackTrace(); // } // // } // Buscamos los votos por partido public int votosPartido(String idPartido) { int votos = 0; try (Connection cn = DriverManager.getConnection(cadenaConexion, user, pwd);) { String sql = "select * from votos where idPartido = ?"; PreparedStatement st = cn.prepareStatement(sql); st.setString(1, idPartido); ResultSet rs = st.executeQuery(); while (rs.next()) { if (idPartido.equals(rs.getString("idPartido"))) { votos++; } } } catch (SQLException e) { e.printStackTrace(); } return votos; } }
true
da24c0d8f9eb899665972b45b6d8d4ab9cd057ae
Java
Xenia-geek/Course-3.2-mobile-part
/app/src/main/java/com/example/courseproject/adapters/NameLabsTeacherAdapter.java
UTF-8
1,079
2.484375
2
[]
no_license
package com.example.courseproject.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.example.courseproject.R; import com.example.courseproject.db.units.Lab; import java.util.List; public class NameLabsTeacherAdapter extends ArrayAdapter<Lab> { private LayoutInflater inflater; private int layout; private List<Lab> labs; public NameLabsTeacherAdapter(Context context, int resource, List<Lab> list) { super(context, resource, list); this.labs = list; this.layout = resource; this.inflater = LayoutInflater.from(context); } public View getView(int position, View convertView, ViewGroup parent) { View view = inflater.inflate(this.layout, parent, false); TextView nameLab = (TextView) view.findViewById(R.id.name_lab_teacher_1); Lab lab = labs.get(position); nameLab.setText(lab.NameLab); return view; } }
true
fcbc526fc2cb58b089ef1d2883229e771821fd18
Java
jfredyromero/Reto3
/src/main/java/com/usa/ciclo3/reto3/repository/crud/ReservationCrudRepository.java
UTF-8
309
1.585938
2
[]
no_license
package com.usa.ciclo3.reto3.repository.crud; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.usa.ciclo3.reto3.model.Reservation; @Repository public interface ReservationCrudRepository extends CrudRepository<Reservation, Integer> { }
true
9b728be1770a2c9523f7cfef33ac3fc698ff0703
Java
RareScrap/SyncLib
/src/main/java/ru/rarescrap/synclib/ISynchable.java
UTF-8
1,176
2.328125
2
[]
no_license
package ru.rarescrap.synclib; public interface ISynchable<T extends ISynchable, V extends IChange> { /** * Создает копию объекта, которая будет хранить состояние последней синхронизации (будущий объект-клиент). * @return */ T createEmptyClientCopy(); /** * Находит изменения между актуальным объектом (серверным) и сохраненным (клиентским). * @param clientState Состояние объекта на клиенте * @return Различия (изменения) между серверным и клиентским состоянием */ /*IChange*/V[] getChanges(T clientState); /** * Вызывается для объекта-клиента, для которого нужно применить пришедшие изменения * @param changes Изменения, пришедшие от серверного объекта */ void applyChanges(/*IChange*/V[] changes); // из-за java6 // Class getChangeClass(); }
true
088f9d0f0f076748484b7f8589c61f77176beea9
Java
JuvenalSantisoDeveloper/FastTap
/app/src/main/java/com/mustbear/app_fasttap/network/NetworkConnections.java
UTF-8
242
1.679688
2
[]
no_license
package com.mustbear.app_fasttap.network; import android.os.Bundle; public interface NetworkConnections { public void onConnectionFailed(); public void onConnected(Bundle bundle); public void onConnectionSuspended(int i); }
true
3e746429e66bd3172fec8a65da31b1659c2d9d32
Java
sohyoun/Kitri----project2
/TaYo/src/com/kitri/together/controller/TogetherPlansServlet.java
UTF-8
2,799
2.109375
2
[]
no_license
package com.kitri.together.controller; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.servlet.RequestDispatcher; 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; import com.kitri.api.tour.service.TourResionCodeService; import com.kitri.dto.TripDetailDTO; import com.kitri.together.service.TogetherService; @WebServlet("/togetherplans") public class TogetherPlansServlet extends HttpServlet { private static final long serialVersionUID = 1L; private TourResionCodeService codeService; private TogetherService service; public TogetherPlansServlet() { service = new TogetherService(); codeService = new TourResionCodeService(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // System.out.println("여기온것이냔?"); int tripSeq = Integer.parseInt(request.getParameter("tripSeq")); String dd = request.getParameter("dd"); String startDate = request.getParameter("startDate"); String url = request.getParameter("url"); System.out.println(url); //loc_id String areaCodes = codeService.getResionCode(); SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd"); try { Date startD = transFormat.parse(startDate); //dd-2만큼 for문 Calendar cal = Calendar.getInstance(); int num = Integer.parseInt(dd); List<String> daylist = new ArrayList<String>(); // String tripDay[] = new String[num]; for(int i =0; i<num; i++) { cal.setTime(startD); cal.add(Calendar.DATE, i); //하루 더하기 // tripDay[i] = transFormat.format(cal.getTime()); daylist.add(transFormat.format(cal.getTime())); System.out.println(daylist); // request.setAttribute("tripDay["+i+"]", tripDay[i]); request.setAttribute("daylist", daylist); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<TripDetailDTO> list = service.findTripDetail(tripSeq); System.out.println(list); request.setAttribute("list", list); request.setAttribute("tripSeq", tripSeq); request.setAttribute("dd", dd); HttpSession session = request.getSession(); session.setAttribute("areaCodes", areaCodes); String path="/tayotogether/"+url+".jsp"; RequestDispatcher rd = request.getRequestDispatcher(path); rd.forward(request, response); } }
true
406d40f34b95793ab8c7cc5710ecc730113a57ce
Java
google/schemaorg-java
/src/main/java/com/google/schemaorg/core/impl/MusicReleaseImpl.java
UTF-8
50,901
1.53125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.schemaorg.core; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.google.schemaorg.SchemaOrgType; import com.google.schemaorg.SchemaOrgTypeImpl; import com.google.schemaorg.ValueType; import com.google.schemaorg.core.datatype.Date; import com.google.schemaorg.core.datatype.DateTime; import com.google.schemaorg.core.datatype.Integer; import com.google.schemaorg.core.datatype.Number; import com.google.schemaorg.core.datatype.Text; import com.google.schemaorg.core.datatype.URL; import com.google.schemaorg.goog.GoogConstants; import com.google.schemaorg.goog.PopularityScoreSpecification; /** Implementation of {@link MusicRelease}. */ public class MusicReleaseImpl extends MusicPlaylistImpl implements MusicRelease { private static final ImmutableSet<String> PROPERTY_SET = initializePropertySet(); private static ImmutableSet<String> initializePropertySet() { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); builder.add(CoreConstants.PROPERTY_ABOUT); builder.add(CoreConstants.PROPERTY_ACCESSIBILITY_API); builder.add(CoreConstants.PROPERTY_ACCESSIBILITY_CONTROL); builder.add(CoreConstants.PROPERTY_ACCESSIBILITY_FEATURE); builder.add(CoreConstants.PROPERTY_ACCESSIBILITY_HAZARD); builder.add(CoreConstants.PROPERTY_ACCOUNTABLE_PERSON); builder.add(CoreConstants.PROPERTY_ADDITIONAL_TYPE); builder.add(CoreConstants.PROPERTY_AGGREGATE_RATING); builder.add(CoreConstants.PROPERTY_ALTERNATE_NAME); builder.add(CoreConstants.PROPERTY_ALTERNATIVE_HEADLINE); builder.add(CoreConstants.PROPERTY_ASSOCIATED_MEDIA); builder.add(CoreConstants.PROPERTY_AUDIENCE); builder.add(CoreConstants.PROPERTY_AUDIO); builder.add(CoreConstants.PROPERTY_AUTHOR); builder.add(CoreConstants.PROPERTY_AWARD); builder.add(CoreConstants.PROPERTY_AWARDS); builder.add(CoreConstants.PROPERTY_CATALOG_NUMBER); builder.add(CoreConstants.PROPERTY_CHARACTER); builder.add(CoreConstants.PROPERTY_CITATION); builder.add(CoreConstants.PROPERTY_COMMENT); builder.add(CoreConstants.PROPERTY_COMMENT_COUNT); builder.add(CoreConstants.PROPERTY_CONTENT_LOCATION); builder.add(CoreConstants.PROPERTY_CONTENT_RATING); builder.add(CoreConstants.PROPERTY_CONTRIBUTOR); builder.add(CoreConstants.PROPERTY_COPYRIGHT_HOLDER); builder.add(CoreConstants.PROPERTY_COPYRIGHT_YEAR); builder.add(CoreConstants.PROPERTY_CREATOR); builder.add(CoreConstants.PROPERTY_CREDITED_TO); builder.add(CoreConstants.PROPERTY_DATE_CREATED); builder.add(CoreConstants.PROPERTY_DATE_MODIFIED); builder.add(CoreConstants.PROPERTY_DATE_PUBLISHED); builder.add(CoreConstants.PROPERTY_DESCRIPTION); builder.add(CoreConstants.PROPERTY_DISCUSSION_URL); builder.add(CoreConstants.PROPERTY_DURATION); builder.add(CoreConstants.PROPERTY_EDITOR); builder.add(CoreConstants.PROPERTY_EDUCATIONAL_ALIGNMENT); builder.add(CoreConstants.PROPERTY_EDUCATIONAL_USE); builder.add(CoreConstants.PROPERTY_ENCODING); builder.add(CoreConstants.PROPERTY_ENCODINGS); builder.add(CoreConstants.PROPERTY_EXAMPLE_OF_WORK); builder.add(CoreConstants.PROPERTY_FILE_FORMAT); builder.add(CoreConstants.PROPERTY_GENRE); builder.add(CoreConstants.PROPERTY_HAS_PART); builder.add(CoreConstants.PROPERTY_HEADLINE); builder.add(CoreConstants.PROPERTY_IMAGE); builder.add(CoreConstants.PROPERTY_IN_LANGUAGE); builder.add(CoreConstants.PROPERTY_INTERACTION_STATISTIC); builder.add(CoreConstants.PROPERTY_INTERACTIVITY_TYPE); builder.add(CoreConstants.PROPERTY_IS_BASED_ON_URL); builder.add(CoreConstants.PROPERTY_IS_FAMILY_FRIENDLY); builder.add(CoreConstants.PROPERTY_IS_PART_OF); builder.add(CoreConstants.PROPERTY_KEYWORDS); builder.add(CoreConstants.PROPERTY_LEARNING_RESOURCE_TYPE); builder.add(CoreConstants.PROPERTY_LICENSE); builder.add(CoreConstants.PROPERTY_LOCATION_CREATED); builder.add(CoreConstants.PROPERTY_MAIN_ENTITY); builder.add(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE); builder.add(CoreConstants.PROPERTY_MENTIONS); builder.add(CoreConstants.PROPERTY_MUSIC_RELEASE_FORMAT); builder.add(CoreConstants.PROPERTY_NAME); builder.add(CoreConstants.PROPERTY_NUM_TRACKS); builder.add(CoreConstants.PROPERTY_OFFERS); builder.add(CoreConstants.PROPERTY_POSITION); builder.add(CoreConstants.PROPERTY_POTENTIAL_ACTION); builder.add(CoreConstants.PROPERTY_PRODUCER); builder.add(CoreConstants.PROPERTY_PROVIDER); builder.add(CoreConstants.PROPERTY_PUBLICATION); builder.add(CoreConstants.PROPERTY_PUBLISHER); builder.add(CoreConstants.PROPERTY_PUBLISHING_PRINCIPLES); builder.add(CoreConstants.PROPERTY_RECORDED_AT); builder.add(CoreConstants.PROPERTY_RECORD_LABEL); builder.add(CoreConstants.PROPERTY_RELEASED_EVENT); builder.add(CoreConstants.PROPERTY_RELEASE_OF); builder.add(CoreConstants.PROPERTY_REVIEW); builder.add(CoreConstants.PROPERTY_REVIEWS); builder.add(CoreConstants.PROPERTY_SAME_AS); builder.add(CoreConstants.PROPERTY_SCHEMA_VERSION); builder.add(CoreConstants.PROPERTY_SOURCE_ORGANIZATION); builder.add(CoreConstants.PROPERTY_TEXT); builder.add(CoreConstants.PROPERTY_THUMBNAIL_URL); builder.add(CoreConstants.PROPERTY_TIME_REQUIRED); builder.add(CoreConstants.PROPERTY_TRACK); builder.add(CoreConstants.PROPERTY_TRACKS); builder.add(CoreConstants.PROPERTY_TRANSLATOR); builder.add(CoreConstants.PROPERTY_TYPICAL_AGE_RANGE); builder.add(CoreConstants.PROPERTY_URL); builder.add(CoreConstants.PROPERTY_VERSION); builder.add(CoreConstants.PROPERTY_VIDEO); builder.add(CoreConstants.PROPERTY_WORK_EXAMPLE); builder.add(GoogConstants.PROPERTY_DETAILED_DESCRIPTION); builder.add(GoogConstants.PROPERTY_POPULARITY_SCORE); return builder.build(); } static final class BuilderImpl extends SchemaOrgTypeImpl.BuilderImpl<MusicRelease.Builder> implements MusicRelease.Builder { @Override public MusicRelease.Builder addAbout(Thing value) { return addProperty(CoreConstants.PROPERTY_ABOUT, value); } @Override public MusicRelease.Builder addAbout(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_ABOUT, value.build()); } @Override public MusicRelease.Builder addAbout(String value) { return addProperty(CoreConstants.PROPERTY_ABOUT, Text.of(value)); } @Override public MusicRelease.Builder addAccessibilityAPI(Text value) { return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_API, value); } @Override public MusicRelease.Builder addAccessibilityAPI(String value) { return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_API, Text.of(value)); } @Override public MusicRelease.Builder addAccessibilityControl(Text value) { return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_CONTROL, value); } @Override public MusicRelease.Builder addAccessibilityControl(String value) { return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_CONTROL, Text.of(value)); } @Override public MusicRelease.Builder addAccessibilityFeature(Text value) { return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_FEATURE, value); } @Override public MusicRelease.Builder addAccessibilityFeature(String value) { return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_FEATURE, Text.of(value)); } @Override public MusicRelease.Builder addAccessibilityHazard(Text value) { return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_HAZARD, value); } @Override public MusicRelease.Builder addAccessibilityHazard(String value) { return addProperty(CoreConstants.PROPERTY_ACCESSIBILITY_HAZARD, Text.of(value)); } @Override public MusicRelease.Builder addAccountablePerson(Person value) { return addProperty(CoreConstants.PROPERTY_ACCOUNTABLE_PERSON, value); } @Override public MusicRelease.Builder addAccountablePerson(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_ACCOUNTABLE_PERSON, value.build()); } @Override public MusicRelease.Builder addAccountablePerson(String value) { return addProperty(CoreConstants.PROPERTY_ACCOUNTABLE_PERSON, Text.of(value)); } @Override public MusicRelease.Builder addAdditionalType(URL value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, value); } @Override public MusicRelease.Builder addAdditionalType(String value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, Text.of(value)); } @Override public MusicRelease.Builder addAggregateRating(AggregateRating value) { return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, value); } @Override public MusicRelease.Builder addAggregateRating(AggregateRating.Builder value) { return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, value.build()); } @Override public MusicRelease.Builder addAggregateRating(String value) { return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, Text.of(value)); } @Override public MusicRelease.Builder addAlternateName(Text value) { return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, value); } @Override public MusicRelease.Builder addAlternateName(String value) { return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, Text.of(value)); } @Override public MusicRelease.Builder addAlternativeHeadline(Text value) { return addProperty(CoreConstants.PROPERTY_ALTERNATIVE_HEADLINE, value); } @Override public MusicRelease.Builder addAlternativeHeadline(String value) { return addProperty(CoreConstants.PROPERTY_ALTERNATIVE_HEADLINE, Text.of(value)); } @Override public MusicRelease.Builder addAssociatedMedia(MediaObject value) { return addProperty(CoreConstants.PROPERTY_ASSOCIATED_MEDIA, value); } @Override public MusicRelease.Builder addAssociatedMedia(MediaObject.Builder value) { return addProperty(CoreConstants.PROPERTY_ASSOCIATED_MEDIA, value.build()); } @Override public MusicRelease.Builder addAssociatedMedia(String value) { return addProperty(CoreConstants.PROPERTY_ASSOCIATED_MEDIA, Text.of(value)); } @Override public MusicRelease.Builder addAudience(Audience value) { return addProperty(CoreConstants.PROPERTY_AUDIENCE, value); } @Override public MusicRelease.Builder addAudience(Audience.Builder value) { return addProperty(CoreConstants.PROPERTY_AUDIENCE, value.build()); } @Override public MusicRelease.Builder addAudience(String value) { return addProperty(CoreConstants.PROPERTY_AUDIENCE, Text.of(value)); } @Override public MusicRelease.Builder addAudio(AudioObject value) { return addProperty(CoreConstants.PROPERTY_AUDIO, value); } @Override public MusicRelease.Builder addAudio(AudioObject.Builder value) { return addProperty(CoreConstants.PROPERTY_AUDIO, value.build()); } @Override public MusicRelease.Builder addAudio(String value) { return addProperty(CoreConstants.PROPERTY_AUDIO, Text.of(value)); } @Override public MusicRelease.Builder addAuthor(Organization value) { return addProperty(CoreConstants.PROPERTY_AUTHOR, value); } @Override public MusicRelease.Builder addAuthor(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_AUTHOR, value.build()); } @Override public MusicRelease.Builder addAuthor(Person value) { return addProperty(CoreConstants.PROPERTY_AUTHOR, value); } @Override public MusicRelease.Builder addAuthor(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_AUTHOR, value.build()); } @Override public MusicRelease.Builder addAuthor(String value) { return addProperty(CoreConstants.PROPERTY_AUTHOR, Text.of(value)); } @Override public MusicRelease.Builder addAward(Text value) { return addProperty(CoreConstants.PROPERTY_AWARD, value); } @Override public MusicRelease.Builder addAward(String value) { return addProperty(CoreConstants.PROPERTY_AWARD, Text.of(value)); } @Override public MusicRelease.Builder addAwards(Text value) { return addProperty(CoreConstants.PROPERTY_AWARDS, value); } @Override public MusicRelease.Builder addAwards(String value) { return addProperty(CoreConstants.PROPERTY_AWARDS, Text.of(value)); } @Override public MusicRelease.Builder addCatalogNumber(Text value) { return addProperty(CoreConstants.PROPERTY_CATALOG_NUMBER, value); } @Override public MusicRelease.Builder addCatalogNumber(String value) { return addProperty(CoreConstants.PROPERTY_CATALOG_NUMBER, Text.of(value)); } @Override public MusicRelease.Builder addCharacter(Person value) { return addProperty(CoreConstants.PROPERTY_CHARACTER, value); } @Override public MusicRelease.Builder addCharacter(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_CHARACTER, value.build()); } @Override public MusicRelease.Builder addCharacter(String value) { return addProperty(CoreConstants.PROPERTY_CHARACTER, Text.of(value)); } @Override public MusicRelease.Builder addCitation(CreativeWork value) { return addProperty(CoreConstants.PROPERTY_CITATION, value); } @Override public MusicRelease.Builder addCitation(CreativeWork.Builder value) { return addProperty(CoreConstants.PROPERTY_CITATION, value.build()); } @Override public MusicRelease.Builder addCitation(Text value) { return addProperty(CoreConstants.PROPERTY_CITATION, value); } @Override public MusicRelease.Builder addCitation(String value) { return addProperty(CoreConstants.PROPERTY_CITATION, Text.of(value)); } @Override public MusicRelease.Builder addComment(Comment value) { return addProperty(CoreConstants.PROPERTY_COMMENT, value); } @Override public MusicRelease.Builder addComment(Comment.Builder value) { return addProperty(CoreConstants.PROPERTY_COMMENT, value.build()); } @Override public MusicRelease.Builder addComment(String value) { return addProperty(CoreConstants.PROPERTY_COMMENT, Text.of(value)); } @Override public MusicRelease.Builder addCommentCount(Integer value) { return addProperty(CoreConstants.PROPERTY_COMMENT_COUNT, value); } @Override public MusicRelease.Builder addCommentCount(String value) { return addProperty(CoreConstants.PROPERTY_COMMENT_COUNT, Text.of(value)); } @Override public MusicRelease.Builder addContentLocation(Place value) { return addProperty(CoreConstants.PROPERTY_CONTENT_LOCATION, value); } @Override public MusicRelease.Builder addContentLocation(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_CONTENT_LOCATION, value.build()); } @Override public MusicRelease.Builder addContentLocation(String value) { return addProperty(CoreConstants.PROPERTY_CONTENT_LOCATION, Text.of(value)); } @Override public MusicRelease.Builder addContentRating(Text value) { return addProperty(CoreConstants.PROPERTY_CONTENT_RATING, value); } @Override public MusicRelease.Builder addContentRating(String value) { return addProperty(CoreConstants.PROPERTY_CONTENT_RATING, Text.of(value)); } @Override public MusicRelease.Builder addContributor(Organization value) { return addProperty(CoreConstants.PROPERTY_CONTRIBUTOR, value); } @Override public MusicRelease.Builder addContributor(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_CONTRIBUTOR, value.build()); } @Override public MusicRelease.Builder addContributor(Person value) { return addProperty(CoreConstants.PROPERTY_CONTRIBUTOR, value); } @Override public MusicRelease.Builder addContributor(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_CONTRIBUTOR, value.build()); } @Override public MusicRelease.Builder addContributor(String value) { return addProperty(CoreConstants.PROPERTY_CONTRIBUTOR, Text.of(value)); } @Override public MusicRelease.Builder addCopyrightHolder(Organization value) { return addProperty(CoreConstants.PROPERTY_COPYRIGHT_HOLDER, value); } @Override public MusicRelease.Builder addCopyrightHolder(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_COPYRIGHT_HOLDER, value.build()); } @Override public MusicRelease.Builder addCopyrightHolder(Person value) { return addProperty(CoreConstants.PROPERTY_COPYRIGHT_HOLDER, value); } @Override public MusicRelease.Builder addCopyrightHolder(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_COPYRIGHT_HOLDER, value.build()); } @Override public MusicRelease.Builder addCopyrightHolder(String value) { return addProperty(CoreConstants.PROPERTY_COPYRIGHT_HOLDER, Text.of(value)); } @Override public MusicRelease.Builder addCopyrightYear(Number value) { return addProperty(CoreConstants.PROPERTY_COPYRIGHT_YEAR, value); } @Override public MusicRelease.Builder addCopyrightYear(String value) { return addProperty(CoreConstants.PROPERTY_COPYRIGHT_YEAR, Text.of(value)); } @Override public MusicRelease.Builder addCreator(Organization value) { return addProperty(CoreConstants.PROPERTY_CREATOR, value); } @Override public MusicRelease.Builder addCreator(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_CREATOR, value.build()); } @Override public MusicRelease.Builder addCreator(Person value) { return addProperty(CoreConstants.PROPERTY_CREATOR, value); } @Override public MusicRelease.Builder addCreator(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_CREATOR, value.build()); } @Override public MusicRelease.Builder addCreator(String value) { return addProperty(CoreConstants.PROPERTY_CREATOR, Text.of(value)); } @Override public MusicRelease.Builder addCreditedTo(Organization value) { return addProperty(CoreConstants.PROPERTY_CREDITED_TO, value); } @Override public MusicRelease.Builder addCreditedTo(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_CREDITED_TO, value.build()); } @Override public MusicRelease.Builder addCreditedTo(Person value) { return addProperty(CoreConstants.PROPERTY_CREDITED_TO, value); } @Override public MusicRelease.Builder addCreditedTo(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_CREDITED_TO, value.build()); } @Override public MusicRelease.Builder addCreditedTo(String value) { return addProperty(CoreConstants.PROPERTY_CREDITED_TO, Text.of(value)); } @Override public MusicRelease.Builder addDateCreated(Date value) { return addProperty(CoreConstants.PROPERTY_DATE_CREATED, value); } @Override public MusicRelease.Builder addDateCreated(DateTime value) { return addProperty(CoreConstants.PROPERTY_DATE_CREATED, value); } @Override public MusicRelease.Builder addDateCreated(String value) { return addProperty(CoreConstants.PROPERTY_DATE_CREATED, Text.of(value)); } @Override public MusicRelease.Builder addDateModified(Date value) { return addProperty(CoreConstants.PROPERTY_DATE_MODIFIED, value); } @Override public MusicRelease.Builder addDateModified(DateTime value) { return addProperty(CoreConstants.PROPERTY_DATE_MODIFIED, value); } @Override public MusicRelease.Builder addDateModified(String value) { return addProperty(CoreConstants.PROPERTY_DATE_MODIFIED, Text.of(value)); } @Override public MusicRelease.Builder addDatePublished(Date value) { return addProperty(CoreConstants.PROPERTY_DATE_PUBLISHED, value); } @Override public MusicRelease.Builder addDatePublished(String value) { return addProperty(CoreConstants.PROPERTY_DATE_PUBLISHED, Text.of(value)); } @Override public MusicRelease.Builder addDescription(Text value) { return addProperty(CoreConstants.PROPERTY_DESCRIPTION, value); } @Override public MusicRelease.Builder addDescription(String value) { return addProperty(CoreConstants.PROPERTY_DESCRIPTION, Text.of(value)); } @Override public MusicRelease.Builder addDiscussionUrl(URL value) { return addProperty(CoreConstants.PROPERTY_DISCUSSION_URL, value); } @Override public MusicRelease.Builder addDiscussionUrl(String value) { return addProperty(CoreConstants.PROPERTY_DISCUSSION_URL, Text.of(value)); } @Override public MusicRelease.Builder addDuration(Duration value) { return addProperty(CoreConstants.PROPERTY_DURATION, value); } @Override public MusicRelease.Builder addDuration(Duration.Builder value) { return addProperty(CoreConstants.PROPERTY_DURATION, value.build()); } @Override public MusicRelease.Builder addDuration(String value) { return addProperty(CoreConstants.PROPERTY_DURATION, Text.of(value)); } @Override public MusicRelease.Builder addEditor(Person value) { return addProperty(CoreConstants.PROPERTY_EDITOR, value); } @Override public MusicRelease.Builder addEditor(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_EDITOR, value.build()); } @Override public MusicRelease.Builder addEditor(String value) { return addProperty(CoreConstants.PROPERTY_EDITOR, Text.of(value)); } @Override public MusicRelease.Builder addEducationalAlignment(AlignmentObject value) { return addProperty(CoreConstants.PROPERTY_EDUCATIONAL_ALIGNMENT, value); } @Override public MusicRelease.Builder addEducationalAlignment(AlignmentObject.Builder value) { return addProperty(CoreConstants.PROPERTY_EDUCATIONAL_ALIGNMENT, value.build()); } @Override public MusicRelease.Builder addEducationalAlignment(String value) { return addProperty(CoreConstants.PROPERTY_EDUCATIONAL_ALIGNMENT, Text.of(value)); } @Override public MusicRelease.Builder addEducationalUse(Text value) { return addProperty(CoreConstants.PROPERTY_EDUCATIONAL_USE, value); } @Override public MusicRelease.Builder addEducationalUse(String value) { return addProperty(CoreConstants.PROPERTY_EDUCATIONAL_USE, Text.of(value)); } @Override public MusicRelease.Builder addEncoding(MediaObject value) { return addProperty(CoreConstants.PROPERTY_ENCODING, value); } @Override public MusicRelease.Builder addEncoding(MediaObject.Builder value) { return addProperty(CoreConstants.PROPERTY_ENCODING, value.build()); } @Override public MusicRelease.Builder addEncoding(String value) { return addProperty(CoreConstants.PROPERTY_ENCODING, Text.of(value)); } @Override public MusicRelease.Builder addEncodings(MediaObject value) { return addProperty(CoreConstants.PROPERTY_ENCODINGS, value); } @Override public MusicRelease.Builder addEncodings(MediaObject.Builder value) { return addProperty(CoreConstants.PROPERTY_ENCODINGS, value.build()); } @Override public MusicRelease.Builder addEncodings(String value) { return addProperty(CoreConstants.PROPERTY_ENCODINGS, Text.of(value)); } @Override public MusicRelease.Builder addExampleOfWork(CreativeWork value) { return addProperty(CoreConstants.PROPERTY_EXAMPLE_OF_WORK, value); } @Override public MusicRelease.Builder addExampleOfWork(CreativeWork.Builder value) { return addProperty(CoreConstants.PROPERTY_EXAMPLE_OF_WORK, value.build()); } @Override public MusicRelease.Builder addExampleOfWork(String value) { return addProperty(CoreConstants.PROPERTY_EXAMPLE_OF_WORK, Text.of(value)); } @Override public MusicRelease.Builder addFileFormat(Text value) { return addProperty(CoreConstants.PROPERTY_FILE_FORMAT, value); } @Override public MusicRelease.Builder addFileFormat(String value) { return addProperty(CoreConstants.PROPERTY_FILE_FORMAT, Text.of(value)); } @Override public MusicRelease.Builder addGenre(Text value) { return addProperty(CoreConstants.PROPERTY_GENRE, value); } @Override public MusicRelease.Builder addGenre(URL value) { return addProperty(CoreConstants.PROPERTY_GENRE, value); } @Override public MusicRelease.Builder addGenre(String value) { return addProperty(CoreConstants.PROPERTY_GENRE, Text.of(value)); } @Override public MusicRelease.Builder addHasPart(CreativeWork value) { return addProperty(CoreConstants.PROPERTY_HAS_PART, value); } @Override public MusicRelease.Builder addHasPart(CreativeWork.Builder value) { return addProperty(CoreConstants.PROPERTY_HAS_PART, value.build()); } @Override public MusicRelease.Builder addHasPart(String value) { return addProperty(CoreConstants.PROPERTY_HAS_PART, Text.of(value)); } @Override public MusicRelease.Builder addHeadline(Text value) { return addProperty(CoreConstants.PROPERTY_HEADLINE, value); } @Override public MusicRelease.Builder addHeadline(String value) { return addProperty(CoreConstants.PROPERTY_HEADLINE, Text.of(value)); } @Override public MusicRelease.Builder addImage(ImageObject value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value); } @Override public MusicRelease.Builder addImage(ImageObject.Builder value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value.build()); } @Override public MusicRelease.Builder addImage(URL value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value); } @Override public MusicRelease.Builder addImage(String value) { return addProperty(CoreConstants.PROPERTY_IMAGE, Text.of(value)); } @Override public MusicRelease.Builder addInLanguage(Language value) { return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, value); } @Override public MusicRelease.Builder addInLanguage(Language.Builder value) { return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, value.build()); } @Override public MusicRelease.Builder addInLanguage(Text value) { return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, value); } @Override public MusicRelease.Builder addInLanguage(String value) { return addProperty(CoreConstants.PROPERTY_IN_LANGUAGE, Text.of(value)); } @Override public MusicRelease.Builder addInteractionStatistic(InteractionCounter value) { return addProperty(CoreConstants.PROPERTY_INTERACTION_STATISTIC, value); } @Override public MusicRelease.Builder addInteractionStatistic(InteractionCounter.Builder value) { return addProperty(CoreConstants.PROPERTY_INTERACTION_STATISTIC, value.build()); } @Override public MusicRelease.Builder addInteractionStatistic(String value) { return addProperty(CoreConstants.PROPERTY_INTERACTION_STATISTIC, Text.of(value)); } @Override public MusicRelease.Builder addInteractivityType(Text value) { return addProperty(CoreConstants.PROPERTY_INTERACTIVITY_TYPE, value); } @Override public MusicRelease.Builder addInteractivityType(String value) { return addProperty(CoreConstants.PROPERTY_INTERACTIVITY_TYPE, Text.of(value)); } @Override public MusicRelease.Builder addIsBasedOnUrl(URL value) { return addProperty(CoreConstants.PROPERTY_IS_BASED_ON_URL, value); } @Override public MusicRelease.Builder addIsBasedOnUrl(String value) { return addProperty(CoreConstants.PROPERTY_IS_BASED_ON_URL, Text.of(value)); } @Override public MusicRelease.Builder addIsFamilyFriendly(Boolean value) { return addProperty(CoreConstants.PROPERTY_IS_FAMILY_FRIENDLY, value); } @Override public MusicRelease.Builder addIsFamilyFriendly(String value) { return addProperty(CoreConstants.PROPERTY_IS_FAMILY_FRIENDLY, Text.of(value)); } @Override public MusicRelease.Builder addIsPartOf(CreativeWork value) { return addProperty(CoreConstants.PROPERTY_IS_PART_OF, value); } @Override public MusicRelease.Builder addIsPartOf(CreativeWork.Builder value) { return addProperty(CoreConstants.PROPERTY_IS_PART_OF, value.build()); } @Override public MusicRelease.Builder addIsPartOf(String value) { return addProperty(CoreConstants.PROPERTY_IS_PART_OF, Text.of(value)); } @Override public MusicRelease.Builder addKeywords(Text value) { return addProperty(CoreConstants.PROPERTY_KEYWORDS, value); } @Override public MusicRelease.Builder addKeywords(String value) { return addProperty(CoreConstants.PROPERTY_KEYWORDS, Text.of(value)); } @Override public MusicRelease.Builder addLearningResourceType(Text value) { return addProperty(CoreConstants.PROPERTY_LEARNING_RESOURCE_TYPE, value); } @Override public MusicRelease.Builder addLearningResourceType(String value) { return addProperty(CoreConstants.PROPERTY_LEARNING_RESOURCE_TYPE, Text.of(value)); } @Override public MusicRelease.Builder addLicense(CreativeWork value) { return addProperty(CoreConstants.PROPERTY_LICENSE, value); } @Override public MusicRelease.Builder addLicense(CreativeWork.Builder value) { return addProperty(CoreConstants.PROPERTY_LICENSE, value.build()); } @Override public MusicRelease.Builder addLicense(URL value) { return addProperty(CoreConstants.PROPERTY_LICENSE, value); } @Override public MusicRelease.Builder addLicense(String value) { return addProperty(CoreConstants.PROPERTY_LICENSE, Text.of(value)); } @Override public MusicRelease.Builder addLocationCreated(Place value) { return addProperty(CoreConstants.PROPERTY_LOCATION_CREATED, value); } @Override public MusicRelease.Builder addLocationCreated(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_LOCATION_CREATED, value.build()); } @Override public MusicRelease.Builder addLocationCreated(String value) { return addProperty(CoreConstants.PROPERTY_LOCATION_CREATED, Text.of(value)); } @Override public MusicRelease.Builder addMainEntity(Thing value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY, value); } @Override public MusicRelease.Builder addMainEntity(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY, value.build()); } @Override public MusicRelease.Builder addMainEntity(String value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY, Text.of(value)); } @Override public MusicRelease.Builder addMainEntityOfPage(CreativeWork value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value); } @Override public MusicRelease.Builder addMainEntityOfPage(CreativeWork.Builder value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value.build()); } @Override public MusicRelease.Builder addMainEntityOfPage(URL value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value); } @Override public MusicRelease.Builder addMainEntityOfPage(String value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, Text.of(value)); } @Override public MusicRelease.Builder addMentions(Thing value) { return addProperty(CoreConstants.PROPERTY_MENTIONS, value); } @Override public MusicRelease.Builder addMentions(Thing.Builder value) { return addProperty(CoreConstants.PROPERTY_MENTIONS, value.build()); } @Override public MusicRelease.Builder addMentions(String value) { return addProperty(CoreConstants.PROPERTY_MENTIONS, Text.of(value)); } @Override public MusicRelease.Builder addMusicReleaseFormat(MusicReleaseFormatType value) { return addProperty(CoreConstants.PROPERTY_MUSIC_RELEASE_FORMAT, value); } @Override public MusicRelease.Builder addMusicReleaseFormat(String value) { return addProperty(CoreConstants.PROPERTY_MUSIC_RELEASE_FORMAT, Text.of(value)); } @Override public MusicRelease.Builder addName(Text value) { return addProperty(CoreConstants.PROPERTY_NAME, value); } @Override public MusicRelease.Builder addName(String value) { return addProperty(CoreConstants.PROPERTY_NAME, Text.of(value)); } @Override public MusicRelease.Builder addNumTracks(Integer value) { return addProperty(CoreConstants.PROPERTY_NUM_TRACKS, value); } @Override public MusicRelease.Builder addNumTracks(String value) { return addProperty(CoreConstants.PROPERTY_NUM_TRACKS, Text.of(value)); } @Override public MusicRelease.Builder addOffers(Offer value) { return addProperty(CoreConstants.PROPERTY_OFFERS, value); } @Override public MusicRelease.Builder addOffers(Offer.Builder value) { return addProperty(CoreConstants.PROPERTY_OFFERS, value.build()); } @Override public MusicRelease.Builder addOffers(String value) { return addProperty(CoreConstants.PROPERTY_OFFERS, Text.of(value)); } @Override public MusicRelease.Builder addPosition(Integer value) { return addProperty(CoreConstants.PROPERTY_POSITION, value); } @Override public MusicRelease.Builder addPosition(Text value) { return addProperty(CoreConstants.PROPERTY_POSITION, value); } @Override public MusicRelease.Builder addPosition(String value) { return addProperty(CoreConstants.PROPERTY_POSITION, Text.of(value)); } @Override public MusicRelease.Builder addPotentialAction(Action value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value); } @Override public MusicRelease.Builder addPotentialAction(Action.Builder value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value.build()); } @Override public MusicRelease.Builder addPotentialAction(String value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, Text.of(value)); } @Override public MusicRelease.Builder addProducer(Organization value) { return addProperty(CoreConstants.PROPERTY_PRODUCER, value); } @Override public MusicRelease.Builder addProducer(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_PRODUCER, value.build()); } @Override public MusicRelease.Builder addProducer(Person value) { return addProperty(CoreConstants.PROPERTY_PRODUCER, value); } @Override public MusicRelease.Builder addProducer(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_PRODUCER, value.build()); } @Override public MusicRelease.Builder addProducer(String value) { return addProperty(CoreConstants.PROPERTY_PRODUCER, Text.of(value)); } @Override public MusicRelease.Builder addProvider(Organization value) { return addProperty(CoreConstants.PROPERTY_PROVIDER, value); } @Override public MusicRelease.Builder addProvider(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_PROVIDER, value.build()); } @Override public MusicRelease.Builder addProvider(Person value) { return addProperty(CoreConstants.PROPERTY_PROVIDER, value); } @Override public MusicRelease.Builder addProvider(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_PROVIDER, value.build()); } @Override public MusicRelease.Builder addProvider(String value) { return addProperty(CoreConstants.PROPERTY_PROVIDER, Text.of(value)); } @Override public MusicRelease.Builder addPublication(PublicationEvent value) { return addProperty(CoreConstants.PROPERTY_PUBLICATION, value); } @Override public MusicRelease.Builder addPublication(PublicationEvent.Builder value) { return addProperty(CoreConstants.PROPERTY_PUBLICATION, value.build()); } @Override public MusicRelease.Builder addPublication(String value) { return addProperty(CoreConstants.PROPERTY_PUBLICATION, Text.of(value)); } @Override public MusicRelease.Builder addPublisher(Organization value) { return addProperty(CoreConstants.PROPERTY_PUBLISHER, value); } @Override public MusicRelease.Builder addPublisher(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_PUBLISHER, value.build()); } @Override public MusicRelease.Builder addPublisher(Person value) { return addProperty(CoreConstants.PROPERTY_PUBLISHER, value); } @Override public MusicRelease.Builder addPublisher(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_PUBLISHER, value.build()); } @Override public MusicRelease.Builder addPublisher(String value) { return addProperty(CoreConstants.PROPERTY_PUBLISHER, Text.of(value)); } @Override public MusicRelease.Builder addPublishingPrinciples(URL value) { return addProperty(CoreConstants.PROPERTY_PUBLISHING_PRINCIPLES, value); } @Override public MusicRelease.Builder addPublishingPrinciples(String value) { return addProperty(CoreConstants.PROPERTY_PUBLISHING_PRINCIPLES, Text.of(value)); } @Override public MusicRelease.Builder addRecordedAt(Event value) { return addProperty(CoreConstants.PROPERTY_RECORDED_AT, value); } @Override public MusicRelease.Builder addRecordedAt(Event.Builder value) { return addProperty(CoreConstants.PROPERTY_RECORDED_AT, value.build()); } @Override public MusicRelease.Builder addRecordedAt(String value) { return addProperty(CoreConstants.PROPERTY_RECORDED_AT, Text.of(value)); } @Override public MusicRelease.Builder addRecordLabel(Organization value) { return addProperty(CoreConstants.PROPERTY_RECORD_LABEL, value); } @Override public MusicRelease.Builder addRecordLabel(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_RECORD_LABEL, value.build()); } @Override public MusicRelease.Builder addRecordLabel(String value) { return addProperty(CoreConstants.PROPERTY_RECORD_LABEL, Text.of(value)); } @Override public MusicRelease.Builder addReleasedEvent(PublicationEvent value) { return addProperty(CoreConstants.PROPERTY_RELEASED_EVENT, value); } @Override public MusicRelease.Builder addReleasedEvent(PublicationEvent.Builder value) { return addProperty(CoreConstants.PROPERTY_RELEASED_EVENT, value.build()); } @Override public MusicRelease.Builder addReleasedEvent(String value) { return addProperty(CoreConstants.PROPERTY_RELEASED_EVENT, Text.of(value)); } @Override public MusicRelease.Builder addReleaseOf(MusicAlbum value) { return addProperty(CoreConstants.PROPERTY_RELEASE_OF, value); } @Override public MusicRelease.Builder addReleaseOf(MusicAlbum.Builder value) { return addProperty(CoreConstants.PROPERTY_RELEASE_OF, value.build()); } @Override public MusicRelease.Builder addReleaseOf(String value) { return addProperty(CoreConstants.PROPERTY_RELEASE_OF, Text.of(value)); } @Override public MusicRelease.Builder addReview(Review value) { return addProperty(CoreConstants.PROPERTY_REVIEW, value); } @Override public MusicRelease.Builder addReview(Review.Builder value) { return addProperty(CoreConstants.PROPERTY_REVIEW, value.build()); } @Override public MusicRelease.Builder addReview(String value) { return addProperty(CoreConstants.PROPERTY_REVIEW, Text.of(value)); } @Override public MusicRelease.Builder addReviews(Review value) { return addProperty(CoreConstants.PROPERTY_REVIEWS, value); } @Override public MusicRelease.Builder addReviews(Review.Builder value) { return addProperty(CoreConstants.PROPERTY_REVIEWS, value.build()); } @Override public MusicRelease.Builder addReviews(String value) { return addProperty(CoreConstants.PROPERTY_REVIEWS, Text.of(value)); } @Override public MusicRelease.Builder addSameAs(URL value) { return addProperty(CoreConstants.PROPERTY_SAME_AS, value); } @Override public MusicRelease.Builder addSameAs(String value) { return addProperty(CoreConstants.PROPERTY_SAME_AS, Text.of(value)); } @Override public MusicRelease.Builder addSchemaVersion(Text value) { return addProperty(CoreConstants.PROPERTY_SCHEMA_VERSION, value); } @Override public MusicRelease.Builder addSchemaVersion(URL value) { return addProperty(CoreConstants.PROPERTY_SCHEMA_VERSION, value); } @Override public MusicRelease.Builder addSchemaVersion(String value) { return addProperty(CoreConstants.PROPERTY_SCHEMA_VERSION, Text.of(value)); } @Override public MusicRelease.Builder addSourceOrganization(Organization value) { return addProperty(CoreConstants.PROPERTY_SOURCE_ORGANIZATION, value); } @Override public MusicRelease.Builder addSourceOrganization(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_SOURCE_ORGANIZATION, value.build()); } @Override public MusicRelease.Builder addSourceOrganization(String value) { return addProperty(CoreConstants.PROPERTY_SOURCE_ORGANIZATION, Text.of(value)); } @Override public MusicRelease.Builder addText(Text value) { return addProperty(CoreConstants.PROPERTY_TEXT, value); } @Override public MusicRelease.Builder addText(String value) { return addProperty(CoreConstants.PROPERTY_TEXT, Text.of(value)); } @Override public MusicRelease.Builder addThumbnailUrl(URL value) { return addProperty(CoreConstants.PROPERTY_THUMBNAIL_URL, value); } @Override public MusicRelease.Builder addThumbnailUrl(String value) { return addProperty(CoreConstants.PROPERTY_THUMBNAIL_URL, Text.of(value)); } @Override public MusicRelease.Builder addTimeRequired(Duration value) { return addProperty(CoreConstants.PROPERTY_TIME_REQUIRED, value); } @Override public MusicRelease.Builder addTimeRequired(Duration.Builder value) { return addProperty(CoreConstants.PROPERTY_TIME_REQUIRED, value.build()); } @Override public MusicRelease.Builder addTimeRequired(String value) { return addProperty(CoreConstants.PROPERTY_TIME_REQUIRED, Text.of(value)); } @Override public MusicRelease.Builder addTrack(ItemList value) { return addProperty(CoreConstants.PROPERTY_TRACK, value); } @Override public MusicRelease.Builder addTrack(ItemList.Builder value) { return addProperty(CoreConstants.PROPERTY_TRACK, value.build()); } @Override public MusicRelease.Builder addTrack(MusicRecording value) { return addProperty(CoreConstants.PROPERTY_TRACK, value); } @Override public MusicRelease.Builder addTrack(MusicRecording.Builder value) { return addProperty(CoreConstants.PROPERTY_TRACK, value.build()); } @Override public MusicRelease.Builder addTrack(String value) { return addProperty(CoreConstants.PROPERTY_TRACK, Text.of(value)); } @Override public MusicRelease.Builder addTracks(MusicRecording value) { return addProperty(CoreConstants.PROPERTY_TRACKS, value); } @Override public MusicRelease.Builder addTracks(MusicRecording.Builder value) { return addProperty(CoreConstants.PROPERTY_TRACKS, value.build()); } @Override public MusicRelease.Builder addTracks(String value) { return addProperty(CoreConstants.PROPERTY_TRACKS, Text.of(value)); } @Override public MusicRelease.Builder addTranslator(Organization value) { return addProperty(CoreConstants.PROPERTY_TRANSLATOR, value); } @Override public MusicRelease.Builder addTranslator(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_TRANSLATOR, value.build()); } @Override public MusicRelease.Builder addTranslator(Person value) { return addProperty(CoreConstants.PROPERTY_TRANSLATOR, value); } @Override public MusicRelease.Builder addTranslator(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_TRANSLATOR, value.build()); } @Override public MusicRelease.Builder addTranslator(String value) { return addProperty(CoreConstants.PROPERTY_TRANSLATOR, Text.of(value)); } @Override public MusicRelease.Builder addTypicalAgeRange(Text value) { return addProperty(CoreConstants.PROPERTY_TYPICAL_AGE_RANGE, value); } @Override public MusicRelease.Builder addTypicalAgeRange(String value) { return addProperty(CoreConstants.PROPERTY_TYPICAL_AGE_RANGE, Text.of(value)); } @Override public MusicRelease.Builder addUrl(URL value) { return addProperty(CoreConstants.PROPERTY_URL, value); } @Override public MusicRelease.Builder addUrl(String value) { return addProperty(CoreConstants.PROPERTY_URL, Text.of(value)); } @Override public MusicRelease.Builder addVersion(Number value) { return addProperty(CoreConstants.PROPERTY_VERSION, value); } @Override public MusicRelease.Builder addVersion(String value) { return addProperty(CoreConstants.PROPERTY_VERSION, Text.of(value)); } @Override public MusicRelease.Builder addVideo(VideoObject value) { return addProperty(CoreConstants.PROPERTY_VIDEO, value); } @Override public MusicRelease.Builder addVideo(VideoObject.Builder value) { return addProperty(CoreConstants.PROPERTY_VIDEO, value.build()); } @Override public MusicRelease.Builder addVideo(String value) { return addProperty(CoreConstants.PROPERTY_VIDEO, Text.of(value)); } @Override public MusicRelease.Builder addWorkExample(CreativeWork value) { return addProperty(CoreConstants.PROPERTY_WORK_EXAMPLE, value); } @Override public MusicRelease.Builder addWorkExample(CreativeWork.Builder value) { return addProperty(CoreConstants.PROPERTY_WORK_EXAMPLE, value.build()); } @Override public MusicRelease.Builder addWorkExample(String value) { return addProperty(CoreConstants.PROPERTY_WORK_EXAMPLE, Text.of(value)); } @Override public MusicRelease.Builder addDetailedDescription(Article value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value); } @Override public MusicRelease.Builder addDetailedDescription(Article.Builder value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value.build()); } @Override public MusicRelease.Builder addDetailedDescription(String value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, Text.of(value)); } @Override public MusicRelease.Builder addPopularityScore(PopularityScoreSpecification value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value); } @Override public MusicRelease.Builder addPopularityScore(PopularityScoreSpecification.Builder value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value.build()); } @Override public MusicRelease.Builder addPopularityScore(String value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, Text.of(value)); } @Override public MusicRelease build() { return new MusicReleaseImpl(properties, reverseMap); } } public MusicReleaseImpl( Multimap<String, ValueType> properties, Multimap<String, Thing> reverseMap) { super(properties, reverseMap); } @Override public String getFullTypeName() { return CoreConstants.TYPE_MUSIC_RELEASE; } @Override public boolean includesProperty(String property) { return PROPERTY_SET.contains(CoreConstants.NAMESPACE + property) || PROPERTY_SET.contains(GoogConstants.NAMESPACE + property) || PROPERTY_SET.contains(property); } @Override public ImmutableList<SchemaOrgType> getCatalogNumberList() { return getProperty(CoreConstants.PROPERTY_CATALOG_NUMBER); } @Override public ImmutableList<SchemaOrgType> getCreditedToList() { return getProperty(CoreConstants.PROPERTY_CREDITED_TO); } @Override public ImmutableList<SchemaOrgType> getDurationList() { return getProperty(CoreConstants.PROPERTY_DURATION); } @Override public ImmutableList<SchemaOrgType> getMusicReleaseFormatList() { return getProperty(CoreConstants.PROPERTY_MUSIC_RELEASE_FORMAT); } @Override public ImmutableList<SchemaOrgType> getRecordLabelList() { return getProperty(CoreConstants.PROPERTY_RECORD_LABEL); } @Override public ImmutableList<SchemaOrgType> getReleaseOfList() { return getProperty(CoreConstants.PROPERTY_RELEASE_OF); } }
true
6d53f18377e914e26b3419329ce6635a3e0783fc
Java
fabulousdj/seeworld-api
/src/main/java/com/seeworld/api/domain/service/INaturalLanguageProcessingService.java
UTF-8
365
1.804688
2
[]
no_license
package com.seeworld.api.domain.service; import com.seeworld.api.domain.valueobject.NaturalLanguageClassificationServiceResponse; import com.seeworld.api.domain.valueobject.NaturalLanguageUnderstandingServiceResponse; public interface INaturalLanguageProcessingService { NaturalLanguageClassificationServiceResponse classify(String input, String appState); }
true
40a9f089e8506df77eafc976692936bd354d7f02
Java
cfelde/ResourcePriorityBlockingQueue
/test/com/cfelde/rpqueue/test/TestPriority.java
UTF-8
6,459
2.171875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2013 Christian Felde (cfelde [at] cfelde [dot] com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cfelde.rpqueue.test; import com.cfelde.rpqueue.Resource; import com.cfelde.rpqueue.ResourcePriorityBlockingQueue; import com.cfelde.rpqueue.Task; import com.cfelde.rpqueue.TaskGroup; import com.cfelde.rpqueue.schedulers.AllAllocator; import com.cfelde.rpqueue.schedulers.FixedPrioritizer; import com.cfelde.rpqueue.utils.ImmutableByteArray; import java.util.Collection; import java.util.UUID; 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 cfelde */ public class TestPriority { public TestPriority() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { for (String name: ResourcePriorityBlockingQueue.getAllQueues().keySet().toArray(new String[0])) { ResourcePriorityBlockingQueue.shutdownQueue(name); } } @Test public void taskPriority1() { assertTrue(ResourcePriorityBlockingQueue.createQueue("queue", new FixedPrioritizer(), new AllAllocator())); ResourcePriorityBlockingQueue queue = ResourcePriorityBlockingQueue.getSubscriberQueue("queue", new Resource(ImmutableByteArray.fromLong(1), null)); Task task1 = new Task(ImmutableByteArray.fromUUID(UUID.randomUUID()), ImmutableByteArray.fromString("payload1"), 100); Task task2 = new Task(ImmutableByteArray.fromUUID(UUID.randomUUID()), ImmutableByteArray.fromString("payload2"), 200); assertTrue(queue.offer(task1)); assertEquals(task1, queue.peek()); assertTrue(queue.offer(task2)); assertEquals(task2, queue.peek()); assertEquals(2, queue.size()); assertEquals(task2, queue.poll()); assertEquals(task1, queue.poll()); assertTrue(queue.isEmpty()); } @Test public void taskPriority2() { assertTrue(ResourcePriorityBlockingQueue.createQueue("queue", new FixedPrioritizer(), new AllAllocator())); ResourcePriorityBlockingQueue queue = ResourcePriorityBlockingQueue.getSubscriberQueue("queue", new Resource(ImmutableByteArray.fromLong(1), null)); Task task1 = new Task(ImmutableByteArray.fromUUID(UUID.randomUUID()), ImmutableByteArray.fromString("payload1"), 100); Task task2 = new Task(ImmutableByteArray.fromUUID(UUID.randomUUID()), ImmutableByteArray.fromString("payload2"), 200); assertTrue(queue.offer(task1)); assertEquals(task1, queue.peek()); assertTrue(queue.offer(task2)); assertEquals(task2, queue.peek()); assertEquals(2, queue.size()); Task newTask2 = task2.setPriority(50); assertEquals(Task.STATUS.CANCELED, task2.getStatus()); assertEquals(task1, queue.peek()); assertEquals(task1, queue.poll()); assertEquals(newTask2, queue.poll()); assertTrue(queue.isEmpty()); } @Test public void groupPriority1() { assertTrue(ResourcePriorityBlockingQueue.createQueue("queue", new FixedPrioritizer(), new AllAllocator())); ResourcePriorityBlockingQueue queue = ResourcePriorityBlockingQueue.getSubscriberQueue("queue", new Resource(ImmutableByteArray.fromLong(1), null)); TaskGroup group1 = TaskGroup.createGroup(ImmutableByteArray.fromUUID(UUID.randomUUID()), 1000); TaskGroup group2 = TaskGroup.createGroup(ImmutableByteArray.fromUUID(UUID.randomUUID()), 2000); Task task1 = new Task(ImmutableByteArray.fromUUID(UUID.randomUUID()), ImmutableByteArray.fromString("payload1"), group1); Task task2 = new Task(ImmutableByteArray.fromUUID(UUID.randomUUID()), ImmutableByteArray.fromString("payload2"), group2); assertTrue(queue.offer(task1)); assertEquals(task1, queue.peek()); assertTrue(queue.offer(task2)); assertEquals(task2, queue.peek()); assertEquals(2, queue.size()); assertEquals(task2, queue.poll()); assertEquals(task1, queue.poll()); assertTrue(queue.isEmpty()); } @Test public void groupPriority2() { assertTrue(ResourcePriorityBlockingQueue.createQueue("queue", new FixedPrioritizer(), new AllAllocator())); ResourcePriorityBlockingQueue queue = ResourcePriorityBlockingQueue.getSubscriberQueue("queue", new Resource(ImmutableByteArray.fromLong(1), null)); TaskGroup group1 = TaskGroup.createGroup(ImmutableByteArray.fromUUID(UUID.randomUUID()), 1000); TaskGroup group2 = TaskGroup.createGroup(ImmutableByteArray.fromUUID(UUID.randomUUID()), 2000); Task task1 = new Task(ImmutableByteArray.fromUUID(UUID.randomUUID()), ImmutableByteArray.fromString("payload1"), group1); Task task2 = new Task(ImmutableByteArray.fromUUID(UUID.randomUUID()), ImmutableByteArray.fromString("payload2"), group2); assertTrue(queue.offer(task1)); assertEquals(task1, queue.peek()); assertTrue(queue.offer(task2)); assertEquals(task2, queue.peek()); assertEquals(2, queue.size()); assertEquals(1, group1.size()); Collection<Task> groupTasks = group1.setPriority(3000); assertEquals(1, group1.size()); assertEquals(1, groupTasks.size()); Task newTask1 = groupTasks.iterator().next(); assertEquals(newTask1, queue.poll()); assertEquals(task2, queue.poll()); assertTrue(queue.isEmpty()); } }
true
30b2a1fef0918a4a5ad3a2e705a67d0fe12b47f0
Java
jzlops/JavaWayFromStudentToMaster
/Lesson_001/src/main/java/ru/stikhonov/term4/Run.java
UTF-8
322
3.109375
3
[]
no_license
package ru.stikhonov.term4; /** * @author Sergey Tikhonov */ public class Run { public static void main(String[] args) { Square square = new Square(1, 2, 3); square.show(5, 20, 2); Factorial factorial = new Factorial(); System.out.printf("Factorial = %1$d", factorial.calculate(5)); } }
true
09abd73f56f1caaf088891330f189372ace7d5c7
Java
hiwesyangee/DeepReview
/src/main/java/com/hiwes/cores/thread/thread6/MyThread0220/MyThread01.java
UTF-8
935
3.609375
4
[]
no_license
package com.hiwes.cores.thread.thread6.MyThread0220; /** * 立即加载/饿汉模式: * 在方法调用之前,就创建了实例对象。 */ public class MyThread01 extends Thread { @Override public void run() { System.out.println(MyObject01.getInstance().hashCode()); } } /** * 立即加载方式 == 饿汉模式 */ class MyObject01 { private static MyObject01 myObject = new MyObject01(); private MyObject01() { } public static MyObject01 getInstance() { // 立即加载,但缺点是:不能有其他实例变量。并且因为getInstance()没有同步,可能有非线程安全问题。 return myObject; } } class Run01{ public static void main(String[] args) { MyThread01 t1 = new MyThread01(); MyThread01 t2 = new MyThread01(); MyThread01 t3 = new MyThread01(); t1.start(); t2.start(); t3.start(); } }
true
a9d55853436ac910ec86b7697e255a4469bfdeff
Java
jhgraham/james
/kalah/src/main/java/kalah/exceptions/KalahGameNotFoundException.java
UTF-8
351
2.484375
2
[]
no_license
package kalah.exceptions; /** * Exception thrown when a game referenced by an ID does not exist. * @author James * */ public class KalahGameNotFoundException extends KalahException { /** * Constructor * @param message - description of the error. */ public KalahGameNotFoundException(String message) { super(message); } }
true
07972c87f54971d66b0d9835faecf808c3baf0e7
Java
identifiers-org/cloud-ws-link-checker
/src/main/java/org/identifiers/cloud/ws/linkchecker/api/responses/ServiceResponseManagementRequestPayload.java
UTF-8
631
2.03125
2
[ "MIT" ]
permissive
package org.identifiers.cloud.ws.linkchecker.api.responses; import java.io.Serializable; /** * Project: link-checker * Package: org.identifiers.cloud.ws.linkchecker.api.responses * Timestamp: 2018-07-31 11:35 * * @author Manuel Bernal Llinares <mbdebian@gmail.com> * --- * * This is a generic payload for management requests. */ public class ServiceResponseManagementRequestPayload implements Serializable { private String message = ""; public String getMessage() { return message; } public ServiceResponseManagementRequestPayload setMessage(String message) { this.message = message; return this; } }
true
f2431e50aecb4ec04cb8e02ad74e9eb29a7a9205
Java
ejmvar/page_meteor
/src/src/main/java/org/bonitasoft/meteor/MeteorOperation.java
UTF-8
9,153
2.203125
2
[]
no_license
package org.bonitasoft.meteor; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.bonitasoft.engine.api.APIAccessor; import org.bonitasoft.log.event.BEvent; import org.bonitasoft.log.event.BEvent.Level; import org.bonitasoft.meteor.MeteorAPI.StartParameters; import org.bonitasoft.meteor.MeteorAPI.StatusParameters; import org.bonitasoft.meteor.MeteorSimulation.Estimation; import org.bonitasoft.meteor.MeteorSimulation.STATUS; import org.bonitasoft.meteor.cmd.CmdMeteor; import org.bonitasoft.meteor.scenario.Scenario; import org.bonitasoft.meteor.scenario.process.MeteorMain; import org.bonitasoft.log.event.BEventFactory; public class MeteorOperation { private static BEvent EventNoSimulation = new BEvent(MeteorOperation.class.getName(), 1, Level.APPLICATIONERROR, "No simulation", "No simulation found with this ID", "No status can't be give because the simulation is not retrieved", "Check simulationId"); private static BEvent EventCheckNothingToStart = new BEvent(MeteorOperation.class.getName(), 2, Level.APPLICATIONERROR, "Nothing to start", "No robots can start", "No test can be done if all Robot and Case are equals to 0", "If you set a number of robot, then set a number of case(or inverse)"); public static boolean simulation = false; public static int countRefresh = 0; public static Logger logger = Logger.getLogger(MeteorOperation.class.getName()); public static Map<Long, MeteorSimulation> simulationInProgress = new HashMap<Long, MeteorSimulation>(); public static class MeteorResult { public HashMap<String, Object> result = new HashMap<String, Object>(); public List<BEvent> listEvents = new ArrayList<BEvent>(); public MeteorSimulation.STATUS status; public HashMap<String, Object> getMap() { result.put(CmdMeteor.cstParamResultListEventsSt, BEventFactory.getHtml(listEvents)); // result.put(MeteorAccess.cstParamResultStatus, status == null ? "" // : status.toString()); return result; } } /** * do the operation In the Command architecture, this method is call by the * Command ATTENTION : this call is done by the Command Thread : no * BonitaAPI can be call here, only on the Robot * * @param startParameters * @param tenantId * @param processAPI * @return */ public static MeteorResult start(final StartParameters startParameters, final APIAccessor apiAccessor, final long tenantId) { final MeteorResult meteorResult = new MeteorResult(); final MeteorSimulation meteorSimulation = new MeteorSimulation(); try { logger.info(" &~~~~~~~& MeteorOperation.Start SIMULID[" + meteorSimulation.getId() + "] by [" + MeteorOperation.class.getName() + "] : " + startParameters.toString()); // Decode here the Json startParameters.decodeFromJsonSt(); if (simulation) { logger.info(" >>>>>>>>>>>>>>>>>> Simulation <<<<<<<<<<<<<<<< "); countRefresh = 0; meteorResult.result.put("Start", "at " + new Date()); return meteorResult; } simulationInProgress.put(meteorSimulation.getId(), meteorSimulation); meteorResult.result.put(CmdMeteor.cstParamResultSimulationId, String.valueOf(meteorSimulation.getId())); // first, reexplore the list of process / activity final MeteorMain meteorProcessDefinitionList = new MeteorMain(); // listEvents.addAll( // meteorProcessDefinitionList.calculateListProcess(processAPI)); // second, update this list by the startParameters // startParameters can have multiple source : listOfProcess, // listOfScenario... // 1. ListOfProcess // ListProcess pilot the different information to creates robots meteorResult.listEvents.addAll(meteorProcessDefinitionList.fromList(startParameters.listOfProcesses, null, apiAccessor.getProcessAPI())); meteorResult.listEvents.addAll(meteorProcessDefinitionList.initialize(tenantId)); if (BEventFactory.isError(meteorResult.listEvents)) { logger.info(" &~~~~~~~& MeteorOperation.Start SIMULID[" + meteorSimulation.getId() + "] : NOROBOT - ERROR in InitializeProcess, end"); meteorResult.status = MeteorSimulation.STATUS.NOROBOT; return meteorResult; } // Ok, now let's look on the processDefinition list, and for each // robots // defined, let's register it in the simulation meteorResult.listEvents.addAll(meteorProcessDefinitionList.registerInSimulation(meteorSimulation, apiAccessor)); // 2. Scenario : cmd et groovy for (final Map<String, Object> mapScenario : startParameters.listOfScenarii) { final Scenario meteorScenario = new Scenario(apiAccessor, tenantId); meteorScenario.fromMap(mapScenario); meteorResult.listEvents.addAll(meteorScenario.registerInSimulation(meteorSimulation, apiAccessor)); } logger.info(" &~~~~~~~& MeteorOperation.Start SIMULID[" + meteorSimulation.getId() + "] : Start ? "); if (meteorSimulation.getNumberOfRobots() == 0) { logger.info(" &~~~~~~~& MeteorOperation.Start SIMULID[" + meteorSimulation.getId() + "] : Nothing to start"); // listEvents.add() // it's possible if we have a scenario meteorResult.listEvents.add(new BEvent(EventCheckNothingToStart, "Nothing to start")); meteorResult.status = MeteorSimulation.STATUS.NOROBOT; } else { meteorSimulation.runTheSimulation(); logger.info(" &~~~~~~~& MeteorOperation.Start SIMULID[" + meteorSimulation.getId() + "] : STARTED !"); meteorResult.result.putAll(meteorSimulation.refreshDetailStatus(apiAccessor)); meteorResult.listEvents.add(MeteorSimulation.EventStarted); meteorResult.status = MeteorSimulation.STATUS.STARTED; } } catch (Error er) { StringWriter sw = new StringWriter(); er.printStackTrace(new PrintWriter(sw)); String exceptionDetails = sw.toString(); meteorSimulation.setStatus(STATUS.DONE); meteorResult.listEvents.add(new BEvent(MeteorSimulation.EventLogBonitaException, er.toString())); logger.severe("meteorOperation.Error " + er + " at " + exceptionDetails); meteorResult.status = MeteorSimulation.STATUS.DONE; } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String exceptionDetails = sw.toString(); meteorSimulation.setStatus(STATUS.DONE); meteorResult.listEvents.add(new BEvent(MeteorSimulation.EventLogBonitaException, e, "")); logger.severe("meteorOperation.Error " + e + " at " + exceptionDetails); meteorResult.status = MeteorSimulation.STATUS.DONE; } return meteorResult; } /** * @param processAPI * @return */ public static MeteorResult getStatus(final StatusParameters statusParameters, final APIAccessor apiAccessor) { final MeteorResult meteorResult = new MeteorResult(); statusParameters.decodeFromJsonSt(); Long currentTime = System.currentTimeMillis(); // return all simulation in progress List<Map<String, Object>> listSimulations = new ArrayList<Map<String, Object>>(); for (final MeteorSimulation simulation : simulationInProgress.values()) { Map<String, Object> oneSimulation = new HashMap<String, Object>(); oneSimulation.put(MeteorSimulation.cstJsonId, simulation.getId()); oneSimulation.put(MeteorSimulation.cstJsonStatus, simulation.getStatus().toString()); Estimation estimation = simulation.getEstimatedAdvance(); oneSimulation.put(MeteorSimulation.cstJsonPercentAdvance, estimation.percentAdvance); if (estimation.percentAdvance == 0) { // can't calculated any time } if (estimation.percentAdvance < 100) { oneSimulation.put(MeteorSimulation.cstJsonTimeEstimatedDelay, MeteorToolbox.getHumanDelay(estimation.timeNeedInMs)); oneSimulation.put(MeteorSimulation.cstJsonTimeEstimatedEnd, MeteorToolbox.getHumanDate(new Date(currentTime + estimation.timeNeedInMs))); } else oneSimulation.put(MeteorSimulation.cstJsonTimeEstimatedEnd, MeteorToolbox.getHumanDate(simulation.getDateEndSimulation())); listSimulations.add(oneSimulation); } meteorResult.result.put("listSimulations", listSimulations); final MeteorSimulation meteorSimulation = simulationInProgress.get(statusParameters.simulationId); if (meteorSimulation == null) { String allSimulations = ""; for (final MeteorSimulation simulation : simulationInProgress.values()) { allSimulations += simulation.getId() + ","; } meteorResult.listEvents.add(new BEvent(EventNoSimulation, "SimulationId[" + statusParameters.simulationId + "] allSimulation=[" + allSimulations + "]")); meteorResult.status = MeteorSimulation.STATUS.NOSIMULATION; meteorResult.result.put("status", MeteorSimulation.STATUS.NOSIMULATION.toString()); return meteorResult; } logger.info("MeteorOperation.Status"); meteorResult.status = meteorSimulation.getStatus(); meteorResult.result.putAll(meteorSimulation.refreshDetailStatus(apiAccessor)); return meteorResult; } }
true
31178b2cb69bece1c867dde166c3c3c68ae774e2
Java
Zhhang2016/MyApp
/com.zh.myapp/app/src/main/java/jzwl/com/comzhmyapp/view/MyViewGroup.java
UTF-8
1,573
2.453125
2
[]
no_license
package jzwl.com.comzhmyapp.view; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; /** * 创建日期:2017/10/17 * 描述: 自定义ViewGroup * * @author: zhaoh */ public class MyViewGroup extends ViewGroup { private static final String TAG = "MyViewGoup"; //用做布局文件时,一定要添加。 public MyViewGroup(Context context, AttributeSet attrs) { super(context, attrs); } public MyViewGroup(Context context) { this(context, null); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int height = 0; int count = getChildCount(); View child; for (int i = 0; i < count; i++) { child = getChildAt(i); child.layout(0, height, child.getMeasuredWidth(), height + child.getMeasuredHeight()); height += child.getMeasuredHeight(); } Log.e(TAG, "------------------onLayout-----------------------"); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); measureChildren(widthMeasureSpec, heightMeasureSpec); Log.e(TAG, "------------------onMeasure-----------------------"); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Log.e(TAG, "------------------onDraw-----------------------"); } }
true
a9b1e075ab0f15b05a9197dd8e1f3ca3f97f1721
Java
Kirilllka1993/TelegramBot
/src/main/java/com/example/myproject/exception/MyExceptionHandler.java
UTF-8
1,127
2.453125
2
[]
no_license
package com.example.myproject.exception; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.time.LocalDateTime; import java.util.NoSuchElementException; @RestControllerAdvice public class MyExceptionHandler { @ExceptionHandler({NoSuchElementException.class}) public ResponseEntity<CustomErrorResponce> absentOfTown() { CustomErrorResponce errors = new CustomErrorResponce(LocalDateTime.now(), 500, "Town Not found"); return new ResponseEntity<>(errors, new HttpHeaders(), HttpStatus.valueOf(errors.getStatus())); } @ExceptionHandler({RepidNameOfTownException.class}) public ResponseEntity<CustomErrorResponce> repidNameOfTown() { CustomErrorResponce errors = new CustomErrorResponce(LocalDateTime.now(), 500, "Such town is present"); return new ResponseEntity<>(errors, new HttpHeaders(), HttpStatus.valueOf(errors.getStatus())); } }
true
bf1a6035a790ac7e031c9250b3c536d4c829838b
Java
DipeshKazi/Team-6317
/Team/team6117/robot/commands/Aim.java
UTF-8
810
2.3125
2
[]
no_license
package org.usfirst.frc.team6117.robot.commands; import java.awt.Robot; public class Aim extends AutonomousCommand { public Aim () { requires(Robot.turret); } protected void initialize() { SetTargetAngle(); } public void SetTargetAngle() { // TODO Auto-generated method stub } protected void execute() { CorrectAngle(); } public void CorrectAngle() { // TODO Auto-generated method stub } protected boolean isFinished() { return AtRightAngle(); } public boolean AtRightAngle() { // TODO Auto-generated method stub return (Boolean) null; } protected void end() { HoldAngle(); } public void HoldAngle() { // TODO Auto-generated method stub } protected void interrupted() { end(); } }
true
81e4ab106e449f35045dc206a4c57b4cfd352620
Java
wangzh98/design-pattern
/src/com/behavior/practice/state/Main.java
UTF-8
268
1.765625
2
[]
no_license
package com.behavior.practice.state; public class Main { public static void main(String[] args) { DirectionService directionService = new DirectionService(new Driving()); directionService.getDirection(); directionService.getEta(); } }
true
4bfbfd4f3dec2c7e044d114d45dc8ed8eb5f6221
Java
Johnson-Bob/MicroserviceDayTwo
/monolith/order/src/main/java/it/discovery/microservice/order/OrderItem.java
UTF-8
195
1.710938
2
[]
no_license
package it.discovery.microservice.order; import lombok.Data; @Data public class OrderItem { private final int bookId; private final double price; private final int number; }
true
c5c837b8ce0d5feb82bf68da3c49b79575995aa9
Java
abir2727/NoWasteNoHunger
/app/src/main/java/com/example/nowastenohunger/Class/Userinfo.java
UTF-8
1,267
2.421875
2
[]
no_license
package com.example.nowastenohunger.Class; public class Userinfo { public String fullname, number, address, accountType, cuisineType , Title , Post; public Userinfo() { } public Userinfo(String fullname, String number, String address, String accountType, String cuisineType) { this.fullname = fullname; this.number = number; this.address = address; this.accountType = accountType; this.cuisineType = cuisineType; } public String getFullname() { return fullname; } public void setFullname(String fullname) { this.fullname = fullname; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getNumber() { return number; } public void setNumber(String number1) { this.number = number1; } public String getAccountType() { return accountType; } public void setAccountType(String number2) { this.accountType = accountType; } public String getCuisineType() { return cuisineType; } public void setCuisineType(String number2) { this.cuisineType = cuisineType; } }
true
532f6f787cfff99f6db57b43642cd6fcef2b4b54
Java
darkviruzz/reform-java
/reform-evented/src/main/java/reform/evented/core/EventedProject.java
UTF-8
2,436
2.515625
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
package reform.evented.core; import reform.core.project.Picture; import reform.core.project.Project; import reform.identity.FastIterable; import reform.identity.Identifier; import java.util.ArrayList; public class EventedProject { private final ArrayList<Listener> _listeners = new ArrayList<>(); private final Project _project; public EventedProject(final Project project) { _project = project; } public void addPicture(final Picture picture) { _project.addPicture(picture); for (int i = 0, j = _listeners.size(); i < j; i++) { _listeners.get(i).onPictureAdded(this, picture.getId()); } } public void removePicture(final Identifier<? extends Picture> pictureId) { _project.removePicture(pictureId); for (int i = 0, j = _listeners.size(); i < j; i++) { _listeners.get(i).onPictureRemoved(this, pictureId); } } public FastIterable<Identifier<? extends Picture>> getPictures() { return _project.getPictures(); } public EventedPicture getEventedPicture(final Identifier<? extends Picture> pictureId) { return new EventedPicture(this, pictureId); } Picture getPicture(final Identifier<? extends Picture> pictureId) { return _project.getPicture(pictureId); } public void addListener(final Listener listener) { _listeners.add(listener); } public void removeListener(final Listener listener) { _listeners.remove(listener); } void propagatePictureChange(final Identifier<? extends Picture> pictureId) { for (int i = 0, j = _listeners.size(); i < j; i++) { _listeners.get(i).onPictureChanged(this, pictureId); } } public Project getRaw() { return _project; } public Identifier<? extends Picture> getPictureAtIndex(final int index) { return _project.getPictureAtIndex(index); } boolean containsPicture(final Identifier<? extends Picture> pictureId) { return _project.containsPicture(pictureId); } public int getPictureCount() { return _project.getPictureCount(); } int getIndexOf(final Identifier<? extends Picture> pictureId) { return _project.getIndexOf(pictureId); } public interface Listener { void onPictureAdded(EventedProject project, Identifier<? extends Picture> pictureId); void onPictureRemoved(EventedProject project, Identifier<? extends Picture> pictureId); void onPictureChanged(EventedProject project, Identifier<? extends Picture> pictureId); } }
true
448062db4321bd497b0ac3e70722904233168a9d
Java
Intrinsarc/intrinsarc-evolve
/VectorGraphics/src/org/freehep/graphicsio/swf/DefineMovie.java
UTF-8
1,132
2.59375
3
[]
no_license
// Copyright 2001, FreeHEP. package org.freehep.graphicsio.swf; import java.io.*; /** * DefineMovie TAG. * * @author Mark Donszelmann * @author Charles Loomis * @version $Id: DefineMovie.java,v 1.1 2009-03-04 22:46:52 andrew Exp $ */ public class DefineMovie extends DefinitionTag { private int character; private String name; public DefineMovie(int id, String name) { this(); character = id; this.name = name; } public DefineMovie() { super(38, 4); } public SWFTag read(int tagID, SWFInputStream swf, int len) throws IOException { DefineMovie tag = new DefineMovie(); tag.character = swf.readUnsignedShort(); swf.getDictionary().put(tag.character, tag); tag.name = swf.readString(); return tag; } public void write(int tagID, SWFOutputStream swf) throws IOException { swf.writeUnsignedShort(character); swf.writeString(name); } public String toString() { StringBuffer s = new StringBuffer(); s.append(super.toString() + "\n"); s.append(" character: " + character + "\n"); s.append(" name: " + name); return s.toString(); } }
true
105c6740fc97fa30120c4aeecd2875cb14f793c9
Java
uzma1411/PLproj
/EnterpriseApplication/EnterpriseApplication1-ejb/build/generated-sources/ap-source-output/ee/Show1_.java
UTF-8
487
1.710938
2
[]
no_license
package ee; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-10-08T20:29:51") @StaticMetamodel(Show1.class) public class Show1_ { public static volatile SingularAttribute<Show1, String> name; public static volatile SingularAttribute<Show1, Long> id; public static volatile SingularAttribute<Show1, Integer> seats; }
true
ac531fff0af56c47d23f16dc43579e4d456d4bfc
Java
thejavaprogrammerhrishav/GC-PROJ-AMS-SYS
/src/com/attendance/login/signup/PrincipalSignUpController.java
UTF-8
5,291
2
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.attendance.login.signup; import com.attendance.login.dao.Login; import com.attendance.login.service.LoginService; import com.attendance.login.user.model.SecurityQuestion; import com.attendance.login.user.model.User; import com.attendance.main.Start; import com.attendance.personal.model.PersonalDetails; import com.attendance.util.ExceptionDialog; import com.attendance.util.Fxml; import com.attendance.util.RootFactory; import com.attendance.util.SwitchRoot; import com.attendance.util.SystemUtils; import com.attendance.util.ValidationUtils; import com.jfoenix.controls.JFXButton; import java.io.IOException; import java.security.Principal; import java.util.Base64; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.stage.Modality; import javafx.stage.StageStyle; import javax.validation.ConstraintViolation; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; /** * * @author pc */ public class PrincipalSignUpController extends AnchorPane { @FXML private TextField fullname; @FXML private TextField contact; @FXML private TextField email; @FXML private TextField username; @FXML private JFXButton signup; @FXML private JFXButton loginbutton; @FXML private PasswordField password; @FXML private PasswordField confirmpassword; private FXMLLoader fxml; private User user; private LoginService login; private ExceptionDialog dialog; private Parent parent; private PersonalDetails principal; private SecurityQuestion question; public PrincipalSignUpController(Parent parent) { this.parent = parent; fxml = Fxml.getPrincipalSignUpFXML(); fxml.setController(this); fxml.setRoot(this); try { fxml.load(); } catch (IOException ex) { Logger.getLogger(PrincipalSignUpController.class.getName()).log(Level.SEVERE, null, ex); } } @FXML private void initialize() { user = new User(); principal = new PersonalDetails(); question = new SecurityQuestion(); login = (LoginService) Start.app.getBean("loginservice"); login.setParent(this); dialog = login.getEx(); signup.setOnAction(E -> { if (login.isUsernameExists(username.getText())) { dialog.showError(this, "Principal Signup", "User Already Taken"); } else if (password.getText().equals(confirmpassword.getText())) { user.setType("Principal"); user.setUsername(username.getText()); user.setPassword(password.getText()); user.setImage(SystemUtils.getDefaultAccountIcon()); user.setDepartment("N/A"); user.setStatus("Pending"); user.setDate(DateTime.now().toString(DateTimeFormat.forPattern("dd-MM-yyyy"))); principal.setName(fullname.getText()); principal.setContact(contact.getText()); principal.setEmailId(email.getText()); principal.setGender("Unknown"); question.setQuestion1("Unknown"); question.setQuestion2("Unknown"); question.setQuestion3("Unknown"); question.setAnswer1("Unknown"); question.setAnswer2("Unknown"); question.setAnswer3("Unknown"); user.setDetails(principal); user.setSecurityquestion(question); Set<ConstraintViolation<User>> validate = ValidationUtils.getValidator().validate(user); if (validate.isEmpty()) { user.setPassword(Base64.getEncoder().encodeToString(password.getText().getBytes())); int id = login.saveUser(user); if (id > 0) { dialog.showSuccess(this, "Principal Signup", "Principal Signup Successfully"); } else { dialog.showError(this, "Principal Signup", "Principal Signup Failed"); } } else { validate.stream().forEach(c -> dialog.showWarning(this, "Principal Signup", c.getMessage())); } } else { dialog.showError(this, "Principal Signup", "Password Doesn't Match"); } }); loginbutton.setOnAction(this::LoginAction); } private void LoginAction(ActionEvent evt) { SystemUtils.logout(); SwitchRoot.switchRoot(Start.st, RootFactory.getPrincipalLoginRoot()); } }
true
04683987f08d985b57512aea58c15c15e9d5906f
Java
iqbal6025/StockManagement
/src/main/java/com/ros/inventory/service/stockService.java
UTF-8
2,148
1.9375
2
[]
no_license
package com.ros.inventory.service; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.springframework.util.MultiValueMap; import com.ros.inventory.Exception.InventoryException; import com.ros.inventory.entities.CloseStock; import com.ros.inventory.entities.StockStatus; import com.ros.inventory.entities.Wastage; import com.ros.inventory.controller.dto.CloseStockDetailDto; import com.ros.inventory.controller.dto.CloseStockDto; import com.ros.inventory.controller.dto.OpeningStockDto; import com.ros.inventory.controller.dto.Summary; import com.ros.inventory.controller.dto.purchaseOrderDto; import com.ros.inventory.controller.dto.stock_balance; import com.ros.inventory.controller.dto.wastageDto; public interface stockService { List<OpeningStockDto> getOpenStock() throws InventoryException; // String addWastage(wastageDto ws) throws InventoryException; List<wastageDto> showWastage() throws InventoryException; // String deleteWastage(Long id) throws InventoryException; List<purchaseOrderDto> getpurchaseOrder() throws InventoryException; List<stock_balance> getStockBalance() throws InventoryException; Summary getSummary() throws InventoryException; Double getTotal() throws InventoryException; Double getPurchaseTotal() throws InventoryException; Double getwastageTotal() throws InventoryException; Double getSales() throws InventoryException; Double get_stock_balance_total() throws InventoryException; LocalDate get_stock_start_date() throws InventoryException; List<CloseStock> get_view_close_stock() throws InventoryException; String add_close_stock(String status) throws InventoryException; CloseStockDetailDto view_stock_detail_date(UUID stockID) throws InventoryException; String approved_stock_period(UUID stockID) throws InventoryException; String bulk_approved_stock_period(List<CloseStockDto> close_stock_bulk) throws InventoryException; String back_real_time(); StockStatus getStatus(UUID stockID); // List<CloseStockDetailDto> edit_closed_stock(List<CloseStockDetailDto> // closed_stock) throws InventoryException; }
true
6b0fd90b34b8e13cef8e84912ed86fadb37d1de4
Java
MeowAlienOwO/UnncCsY2FseMiniProject
/src/game/GameFrame.java
UTF-8
624
2.671875
3
[]
no_license
package game; import java.awt.Container; import javax.swing.JFrame; public class GameFrame extends JFrame{ /** * this is the frame of the game */ private static final long serialVersionUID = 1L; //constructor public GameFrame(){ setTitle("Game"); GamePanel defaultPanel = new GamePanel(); Container contentPane = getContentPane(); contentPane.add(defaultPanel); pack(); } public GameFrame(String title){ setTitle(title); GamePanel defaultPanel = new GamePanel(); Container contentPane = getContentPane(); contentPane.add(defaultPanel); pack(); } }
true
c2ad0d576f3347a13b955008880b5351b28e83f0
Java
jdkhome/autoolk
/autoolk_demo/src/main/java/com/jdkhome/demo/Test.java
UTF-8
961
2.171875
2
[]
no_license
package com.jdkhome.demo; import com.jdkhome.autoolk.Autoolk; import com.jdkhome.demo.pojo.City; import com.jdkhome.demo.pojo.Constants; import java.util.List; import java.util.Map; /** * Created by Link on 2017/4/20. */ public class Test { public static void main(String[] args) throws Exception { //任意查询 List<Map<String,Object>> result= Autoolk.select(Constants.SearchAllCity,new Object[]{}); //查询实体 List<City> cityList=Autoolk.select(Constants.SearchCity, new Object[] {142}, City.class); //插入 Autoolk.insert(new City(2333,"测试城市")); //更新 Autoolk.update(Constants.UpdateCity,new Object[]{"城市asd",2333}); //删除 Autoolk.delete(Constants.DeleteCity,new Object[]{2333}); //Count Long count=Autoolk.count(Constants.CountCity,new Object[]{},"count"); System.out.println("city count = " + count); } }
true
d189ff62433f03d01df4044fb512ffc865d57875
Java
pdaga2/hack2021
/hack2021Demo/src/main/java/com/amazon/hack2021Demo/service/Hack2021Service.java
UTF-8
1,183
2.1875
2
[]
no_license
package com.amazon.hack2021Demo.service; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collector; import java.util.stream.Collectors; import com.amazon.hack2021Demo.dao.Hack2021Dao; import com.amazon.hack2021Demo.model.Stream; import com.amazon.hack2021Demo.model.ViewerGraphDatum; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import lombok.extern.slf4j.Slf4j; @Service @Slf4j public class Hack2021Service { @Autowired private Hack2021Dao hack2021Dao; public ViewerGraphDatum createGraphByAsin(String asin) { //TODO write logic to create bucket try { List<Stream> streamList = hack2021Dao.getStreamDataByAsin(asin); List<Long> playhead = streamList.stream().map(s -> {return s.getPlayhead();}).collect(Collectors.toList()); Collections.sort(playhead); } catch (Exception e) { e.printStackTrace(); } return ViewerGraphDatum.builder() .maxScore(100) .strengthPoints(new ArrayList<>()) .asin(asin) .build(); } }
true
c42cee9c7ad0a3dbfd80837e408bec6859ebed82
Java
Chima1707/StackServicei
/src/main/java/com/xhimat/service/StackService.java
UTF-8
1,156
3.1875
3
[]
no_license
package com.xhimat.service; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; import java.util.List; import java.util.Stack; import java.util.stream.Collectors; /** * Created by chima on 1/13/17. * * This class implements a stack service, * it does so by delegating to an instance oof java.util.Stack */ @Component @Scope(value="session", proxyMode = ScopedProxyMode.TARGET_CLASS) public class StackService { private Stack<Integer> stack = new Stack(); /** * Pushes integer to stack * @param val */ public void push(int val) { stack.push(val); } /** * Removes last element in stack */ public void pop () throws StackEmptyException { if (stack.isEmpty()) { throw new StackEmptyException("Stack is empty"); } stack.pop(); } /** * @return list of numbers in the stack */ public List<Integer> show () { return stack.stream() .map(p -> p.intValue()) .collect(Collectors.toList()); } }
true
d67e337b8bc91bfd2b6b05b4b713260bbe4392bb
Java
AhmedBelghiith/BackendSpringPfe
/src/main/java/com/bandsmile/crud/service/FactureService.java
UTF-8
747
2.109375
2
[]
no_license
//package com.bandsmile.crud.service; // //import com.bandsmile.crud.model.Facture; //import com.bandsmile.crud.repository.FactureRepository; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.stereotype.Service; // //import java.util.List; // //@Service //public class FactureService { // // @Autowired // FactureRepository factureRepository; // // // public Facture saveFacture(Facture facture){ // return factureRepository.save(facture); // } // public List<Facture> getFactures(){ // return factureRepository.findAll(); // } // public String deleteFacture(Long id){ // factureRepository.deleteById(id); // return "Facture supprimé !"+id; // } //}
true
0446bf2324bc2cc31835e46cb4a035a95a4a7dfa
Java
leozito22/LPM-Trabalho_Final
/LPM-Trabalho Final/src/Rota.java
UTF-8
406
2.453125
2
[]
no_license
import javax.xml.crypto.Data; public class Rota { private Data data; private int KmRota; Rota(Data data, int KmRota){ this.data = data; this.KmRota = KmRota; } public void setData(Data data){ this.data = data; } public void setKmRota(int KmRota){ this.KmRota = KmRota; } public int getKmRota(){ return this.KmRota; } }
true
40ba40392872d71d76325bf218043552cd644a99
Java
nit-ibaraki-program-design/lecture
/src/week206/2_06_TodoMain3.java
UTF-8
792
3.109375
3
[]
no_license
class TodoMain3 { public static void main(String[] args) { //Viewを作成する TodoView todoview = new TodoView(); //Modelを作成する TodoList todolist = new TodoList(); //Controllerを作成する TodoController todocontroller = new TodoController(); //ViewとModelを相互に関係付ける todolist.setTodoView(todoview); todoview.setTodoList(todolist); //ViewとControllerを相互に参照する todoview.setTodoController(todocontroller); todocontroller.setTodoView(todoview); //ControllerからModelを参照する todocontroller.setTodoList(todolist); //最初にViewを更新しておく todoview.update(); } }
true
1b2e125203583abaa0e5f2d6f8cee64797602bd2
Java
mesofi/mesofi-apps
/mesofi-commons/src/main/java/mx/com/mesofi/services/zip/ZipUtil.java
UTF-8
4,040
2.828125
3
[]
no_license
/* * COPYRIGHT. Mesofi 2015. ALL RIGHTS RESERVED. * * This software is only to be used for the purpose for which it has been * provided. No part of it is to be reproduced, disassembled, transmitted, * stored in a retrieval system nor translated in any human or computer * language in any way or for any other purposes whatsoever without the * prior written consent of Mesofi. */ package mx.com.mesofi.services.zip; import static mx.com.mesofi.services.util.CommonConstants.SLASH_CHAR; import static mx.com.mesofi.services.util.CommonConstants.UNKNOWN_CHAR; import static mx.com.mesofi.services.util.SimpleValidator.isNull; import static mx.com.mesofi.services.util.SimpleValidator.isValid; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import mx.com.mesofi.services.files.FileUtil; /** * Clase que funciona para leer un archivo de propierdades especificando su * ubicacion en el classpath. * * @author mesofi */ public class ZipUtil { /** * Referencia estatica de esta clase. */ private static ZipUtil zip = new ZipUtil(); /** * Constructor privado. */ private ZipUtil() { } /** * Obtiene una instancia de esta clase. * * @return Instancia de esta clase. */ public static ZipUtil getInstance() { return zip; } /** * Zip the current folder in the file system. * * @param folderName * The folder to be zipped. */ public void zipFolder(File folderName) { isNull(folderName, "The folder name must not be null"); isValid(folderName.isDirectory() && folderName.exists(), "Please specify a valid directory to zip"); ZipOutputStream zip = null; FileOutputStream fileWriter = null; try { fileWriter = new FileOutputStream(folderName + ".zip"); zip = new ZipOutputStream(fileWriter); addFolderToZip(UNKNOWN_CHAR.toString(), folderName.getPath(), zip); zip.flush(); } catch (Exception e) { isValid(false, e.getMessage()); } finally { FileUtil.close(zip); FileUtil.close(fileWriter); } } /** * Add a folder into the zip file. * * @param path * The path. * @param srcFolder * The source folder. * @param zipOutputStream * The actual zip file. */ private void addFolderToZip(String path, String srcFolder, ZipOutputStream zipOutputStream) { File folder = new File(srcFolder); for (String fileName : folder.list()) { if (path.equals(UNKNOWN_CHAR.toString())) { addFileToZip(folder.getName(), srcFolder + SLASH_CHAR + fileName, zipOutputStream); } else { addFileToZip(path + SLASH_CHAR + folder.getName(), srcFolder + SLASH_CHAR + fileName, zipOutputStream); } } } /** * Add a file into the zip file. * * @param path * The path. * @param srcFile * The source file. * @param zip * The actual zip file. */ private void addFileToZip(String path, String srcFile, ZipOutputStream zip) { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip); } else { byte[] buf = new byte[1024]; int len = 0; FileInputStream in = null; try { in = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + SLASH_CHAR + folder.getName())); while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); } } catch (Exception e) { isValid(false, e.getMessage()); } finally { FileUtil.close(in); } } } }
true
80496e7e070dcf647d997291f7d3ed1f8da126f4
Java
SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018
/Corpus/ecf/690.java
UTF-8
3,355
1.976563
2
[ "MIT" ]
permissive
/**************************************************************************** * Copyright (c) 2006, 2007 Composent, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Composent, Inc. - initial API and implementation *****************************************************************************/ package org.eclipse.ecf.provider.filetransfer.identity; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import org.eclipse.core.runtime.Assert; import org.eclipse.ecf.core.identity.BaseID; import org.eclipse.ecf.core.identity.Namespace; import org.eclipse.ecf.filetransfer.identity.IFileID; import org.eclipse.ecf.internal.provider.filetransfer.Messages; public class FileTransferID extends BaseID implements IFileID { private static final long serialVersionUID = 1274308869502156992L; URL fileURL; URI fileURI; public FileTransferID(Namespace namespace, URL url) { super(namespace); Assert.isNotNull(url, Messages.FileTransferID_Exception_Url_Not_Null); this.fileURL = url; } /** * @param namespace namespace * @param uri uri * @since 3.2 */ public FileTransferID(Namespace namespace, URI uri) { super(namespace); //$NON-NLS-1$ Assert.isNotNull(uri, "FileTransferID URI cannot be null"); this.fileURI = uri; } protected int namespaceCompareTo(BaseID o) { if (o == null) return 1; if (!(o instanceof FileTransferID)) return 1; return (fileURI != null) ? fileURI.compareTo(((FileTransferID) o).fileURI) : fileURL.toExternalForm().compareTo(((FileTransferID) o).toExternalForm()); } protected boolean namespaceEquals(BaseID o) { if (o == null) return false; if (!(o instanceof FileTransferID)) return false; return (fileURI != null) ? fileURI.equals(((FileTransferID) o).fileURI) : fileURL.equals(((FileTransferID) o).fileURL); } protected String namespaceGetName() { return (fileURI != null) ? fileURI.toASCIIString() : fileURL.toExternalForm(); } protected int namespaceHashCode() { return (fileURI != null) ? fileURI.hashCode() : this.fileURL.hashCode(); } public String getFilename() { return getFileNameOnly(); } public URL getURL() throws MalformedURLException { return (fileURI != null) ? fileURI.toURL() : fileURL; } protected String getFileNameOnly() { String path = (fileURI != null) ? fileURI.getPath() : fileURL.getPath(); //$NON-NLS-1$; return (path == null) ? null : path.substring(path.lastIndexOf("/") + 1); } public String toString() { //$NON-NLS-1$ final StringBuffer b = new StringBuffer("FileTransferID["); b.append(toExternalForm()); //$NON-NLS-1$ b.append("]"); return b.toString(); } /** * @since 3.2 */ public URI getURI() throws URISyntaxException { return (fileURI != null) ? fileURI : new URI(fileURL.toExternalForm()); } }
true
730a4829f64d5c90a81953de92dd3e257c5c847e
Java
gnpavan430/Learn
/src/test/java/testCases/AddABookingTC.java
UTF-8
667
2.015625
2
[]
no_license
package testCases; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import org.junit.Test; import pageobjects.MyTrips; import setup.SetUp; public class AddABookingTC extends SetUp { AndroidDriver<AndroidElement>driver=getDriver(); @Test public void addABooking() throws InterruptedException { Thread.sleep(4000); MyTrips.getHomeScreen_MyTrips().click(); if(MyTrips.getMyTrips_noUpcomingTripsText().isDisplayed()){ MyTrips.getMyTrips_AddABooking().click(); } else{ MyTrips.getMyTrips_AddBookingActionButton().click(); } } }
true
20c026ce150f0a17ec7165f2e6c8bd1a3b29cd6c
Java
duongnguyenhoang103/FileJava
/Resto/SB41/src/vn/com/hkt/pilot/sb41/product/extW48/ui/window/SB41_W48Tutorial.java
UTF-8
1,658
2.53125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package vn.com.hkt.pilot.sb41.product.extW48.ui.window; import javax.swing.JTextArea; /** * * @author tamdong */ public class SB41_W48Tutorial { private JTextArea TenTiengAnh; private JTextArea NgaySanXuat; private JTextArea HanSuDung; private JTextArea MoTaGhiChu; private JTextArea NgayChinhSua; public SB41_W48Tutorial() { TenTiengAnh = new JTextArea(); TenTiengAnh.setText("Nhập tên tiếng anh của sản phẩm "); NgaySanXuat = new JTextArea(); NgaySanXuat.setText("Nhập ngày sản xuất sản phẩm, kiểu nhập ngày/tháng/năm\n" + " hoặc chọn ở lịch bên \n"); HanSuDung = new JTextArea(); HanSuDung.setText("Nhập hạn sử dụng của sản phẩm, kiểu nhập ngày/tháng/năm\n" + "hoặc chọn ở lịch bên\n"); MoTaGhiChu = new JTextArea(); MoTaGhiChu.setText("Nhập mô tả ghi chú sản phẩm"); NgayChinhSua = new JTextArea(); NgayChinhSua.setText("Nhập ngày chỉnh sửa sản phẩm, kiểu nhập ngày/tháng/năm\n" + "hoặc chọn ở lịch bên\n "); } public JTextArea getHanSuDung() { return HanSuDung; } public JTextArea getMoTaGhiChu() { return MoTaGhiChu; } public JTextArea getNgayChinhSua() { return NgayChinhSua; } public JTextArea getNgaySanXuat() { return NgaySanXuat; } public JTextArea getTenTiengAnh() { return TenTiengAnh; } }
true
3dc7adcadcc8ed9e603cc763444093f108d7d691
Java
EXTC27/MyProjects
/Shalendar/소스코드/Back-End/shalendar/src/main/java/com/ssafy/shalendar/springboot/web/BannerController.java
UTF-8
986
2.171875
2
[]
no_license
package com.ssafy.shalendar.springboot.web; import com.ssafy.shalendar.springboot.service.BannerService; import com.ssafy.shalendar.springboot.web.dto.banner.BannerResponseDto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RequestMapping("/banner") @RestController @RequiredArgsConstructor @Slf4j @CrossOrigin({"*"}) public class BannerController { private final BannerService bService; @GetMapping("/getAllBanners") public ResponseEntity<Object> getAllBanners(){ log.trace("getAllBanners"); try { List<BannerResponseDto> result = bService.getBannerList(); return new ResponseEntity<Object>(result, HttpStatus.OK); } catch (RuntimeException e) { log.error("getAllBanners", e); throw e; } } }
true
d0e7e45af74a093ea56d3bb7db092451c102bb6b
Java
AzzaAbdelGhani/SDM_Brique_Game
/src/main/java/Brique_GUI/PositionPanel.java
UTF-8
1,873
3.140625
3
[]
no_license
package Brique_GUI; import Game.*; import javax.swing.*; import java.awt.*; public class PositionPanel extends JPanel{ private JPanel pos; private int row; private int col; private Piece_Color pColor = Piece_Color.BLANK; private Pos_Color pos_color = Pos_Color.LIGHT; private int panelResolution = 48; public PositionPanel(int row, int col) { this.row = row; this.col = col; pos = new JPanel(); pos.setSize(new Dimension(48, 48)); pos.setVisible(true); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor((row + col) % 2 == 0 ? new java.awt.Color(204, 204, 204) : new java.awt.Color(153, 153, 153)); g.fillRect(0, 0, panelResolution, panelResolution); g.drawRect(0, 0, panelResolution, panelResolution); if ((row + col) % 2 != 0) { this.pos_color = Pos_Color.DARK; } if (pColor == Piece_Color.BLACK) { drawPiece(panelResolution / 4, panelResolution / 4, g, Color.BLACK); } else if (pColor == Piece_Color.WHITE) { drawPiece(panelResolution / 4, panelResolution / 4, g, Color.WHITE); } } public void drawPiece(int i, int j, Graphics g, Color pieceColor) { g.setColor(pieceColor); g.fillOval(i, j, panelResolution / 2, panelResolution / 2); g.setColor(Color.BLACK); g.drawOval(i, j, panelResolution / 2, panelResolution / 2); } public void setPieceColor(Piece_Color pColor) { this.pColor = pColor; repaint(); } public Piece_Color getPieceColor() { return this.pColor; } public Pos_Color getPositionColor() { return this.pos_color; } public int getRow() { return this.row; } public int getCol() { return this.col; } }
true
62abcb303aa8fd249fd8e47a44f26b022670c655
Java
domnikkk/papyrus
/sandbox/Alf/org.eclipse.papyrus.alf/src-gen/org/eclipse/papyrus/alf/alf/EqualityExpression.java
UTF-8
3,166
2.03125
2
[]
no_license
/** */ package org.eclipse.papyrus.alf.alf; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Equality Expression</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.eclipse.papyrus.alf.alf.EqualityExpression#getUnaryExpression <em>Unary Expression</em>}</li> * <li>{@link org.eclipse.papyrus.alf.alf.EqualityExpression#getClassificationExpressionCompletion <em>Classification Expression Completion</em>}</li> * </ul> * </p> * * @see org.eclipse.papyrus.alf.alf.AlfPackage#getEqualityExpression() * @model * @generated */ public interface EqualityExpression extends EObject { /** * Returns the value of the '<em><b>Unary Expression</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Unary Expression</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Unary Expression</em>' containment reference. * @see #setUnaryExpression(UnaryExpression) * @see org.eclipse.papyrus.alf.alf.AlfPackage#getEqualityExpression_UnaryExpression() * @model containment="true" * @generated */ UnaryExpression getUnaryExpression(); /** * Sets the value of the '{@link org.eclipse.papyrus.alf.alf.EqualityExpression#getUnaryExpression <em>Unary Expression</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Unary Expression</em>' containment reference. * @see #getUnaryExpression() * @generated */ void setUnaryExpression(UnaryExpression value); /** * Returns the value of the '<em><b>Classification Expression Completion</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Classification Expression Completion</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Classification Expression Completion</em>' containment reference. * @see #setClassificationExpressionCompletion(ClassificationExpressionCompletion) * @see org.eclipse.papyrus.alf.alf.AlfPackage#getEqualityExpression_ClassificationExpressionCompletion() * @model containment="true" * @generated */ ClassificationExpressionCompletion getClassificationExpressionCompletion(); /** * Sets the value of the '{@link org.eclipse.papyrus.alf.alf.EqualityExpression#getClassificationExpressionCompletion <em>Classification Expression Completion</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Classification Expression Completion</em>' containment reference. * @see #getClassificationExpressionCompletion() * @generated */ void setClassificationExpressionCompletion(ClassificationExpressionCompletion value); } // EqualityExpression
true
76abee48ca19755473cf2690d213c4f5a0f6efc0
Java
archie-yuqi/WebPlugin
/frameworks/hybrid/src/pub/hybrid/NativeInterface.java
UTF-8
1,039
2.546875
3
[]
no_license
package pub.hybrid; import android.app.Activity; import com.pub.internal.hybrid.HybridManager; /** * The interface exposed to feature to access internal methods. */ public class NativeInterface { private HybridManager mManager; /** * Construct a new instance. * * @param manager hybrid manager. */ public NativeInterface(HybridManager manager) { mManager = manager; } /** * Get current activity. * * @return current activity. */ public Activity getActivity() { return mManager.getActivity(); } /** * add activity lifecycle listener. * * @param listener listener. */ public void addLifecycleListener(LifecycleListener listener) { mManager.addLifecycleListener(listener); } /** * remove activity lifecycle listener. * * @param listener listener. */ public void removeLifecycleListener(LifecycleListener listener) { mManager.removeLifecycleListener(listener); } }
true
72af54e7c02792c25a1530729d6986012b66ad1a
Java
LeaguePlayer/android_avtorazbor_2
/app/src/main/java/ru/amobilestudio/autorazborassistant/app/MainActivity.java
UTF-8
9,219
1.765625
2
[]
no_license
package ru.amobilestudio.autorazborassistant.app; import android.app.ActionBar; import android.app.AlertDialog; import android.app.FragmentTransaction; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewConfiguration; import android.widget.TextView; import java.lang.reflect.Field; import ru.amobilestudio.autorazborassistant.asyncs.GetAllPartsAsync; import ru.amobilestudio.autorazborassistant.asyncs.GetSelectsDataAsync; import ru.amobilestudio.autorazborassistant.asyncs.OnTaskCompleted; import ru.amobilestudio.autorazborassistant.fragments.ReservedFragment; import ru.amobilestudio.autorazborassistant.fragments.SyncFragment; import ru.amobilestudio.autorazborassistant.helpers.ConnectionHelper; import ru.amobilestudio.autorazborassistant.helpers.UserInfoHelper; import ru.amobilestudio.autorazborassistant.receivers.NetworkChangeReceiver; public class MainActivity extends FragmentActivity implements ActionBar.TabListener, OnTaskCompleted { private NetworkChangeReceiver _networkChangeReceiver; public AppSectionsPagerAdapter mAppSectionsPagerAdapter; private ViewPager _viewPager; final private OnTaskCompleted _taskCompleted = this; final private Context _context = this; // private boolean isUpdateReserve = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _networkChangeReceiver = new NetworkChangeReceiver(); registerReceiver(_networkChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); //TODO: delete this lines //------------------------------------------------------ //deleteDatabase(DbSQLiteHelper.DATABASE_NAME); /*SharedPreferences settings = getSharedPreferences(DataFieldsAsync.DB_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("isDb", false); editor.commit();*/ //------------------------------------------------------ getOverflowMenu(); TextView helloText = (TextView) findViewById(R.id.helloUser); helloText.setVisibility(View.GONE); setTitle(UserInfoHelper.getUserFio(this)); mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager()); final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); _viewPager = (ViewPager) findViewById(R.id.pager); _viewPager.setAdapter(mAppSectionsPagerAdapter); _viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); //add tabs actionBar.addTab(actionBar.newTab().setText(getString(R.string.tab1)).setTabListener(this)); actionBar.addTab(actionBar.newTab().setText(getString(R.string.tab2)).setTabListener(this)); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { Intent intent = getIntent(); int isFromLogin = intent.getIntExtra("from_login", 0); if(isFromLogin == 1){ GetAllPartsAsync allPartsAsync = new GetAllPartsAsync(_context, _taskCompleted); allPartsAsync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } }, 2000); } private void getOverflowMenu() { try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if(menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception e) { e.printStackTrace(); } } @Override protected void onDestroy() { super.onDestroy(); _networkChangeReceiver.cancelMainAsync(); unregisterReceiver(_networkChangeReceiver); } @Override protected void onResume() { super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action buttons switch (item.getItemId()){ case R.id.action_update_data: if(ConnectionHelper.checkNetworkConnection(this)){ GetSelectsDataAsync dataAsync = new GetSelectsDataAsync(this); dataAsync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } break; case R.id.action_sync: if(ConnectionHelper.checkNetworkConnection(this)){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.attention_title)); builder.setMessage(getString(R.string.sync_message)); // Set up the buttons builder.setPositiveButton(getString(R.string.confirm_text), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); GetAllPartsAsync allPartsAsync = new GetAllPartsAsync(_context, _taskCompleted); allPartsAsync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); builder.setNegativeButton(getString(R.string.confirm_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } break; case R.id.action_logout_user: logOut(); break; } return super.onOptionsItemSelected(item); } //when all parts uploads than update fragments lists @Override public void onTaskCompleted() { String reserveFragmentName = makeFragmentName(_viewPager.getId(), 0); String syncFragmentName = makeFragmentName(_viewPager.getId(), 1); Fragment reservedFragment = getSupportFragmentManager().findFragmentByTag(reserveFragmentName); Fragment syncFragment = getSupportFragmentManager().findFragmentByTag(syncFragmentName); if(reservedFragment != null && syncFragment != null && reservedFragment.isResumed() && syncFragment.isResumed()){ ((ReservedFragment) reservedFragment).updateList(); ((SyncFragment) syncFragment).updateList(); } } public ViewPager getViewPager(){ return _viewPager; } private static String makeFragmentName(int viewId, int index) { return "android:switcher:" + viewId + ":" + index; } public static class AppSectionsPagerAdapter extends FragmentPagerAdapter { public AppSectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { switch (i) { case 0: return new ReservedFragment(); default: return new SyncFragment(); } } @Override public int getCount() { return 2; } } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { _viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } private void logOut(){ UserInfoHelper.logoutUser(this); finish(); Intent intent = new Intent(this, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }
true
de2f1cb4e137833b1fbf101e7a1fb752abaecce6
Java
OrangE-3/GitHub-Mash
/app/src/main/java/com/orange/githubmash/data/remote/RemoteOwner.java
UTF-8
1,637
2.328125
2
[ "MIT" ]
permissive
package com.orange.githubmash.data.remote; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class RemoteOwner implements Parcelable { public static final Creator<RemoteOwner> CREATOR = new Creator<RemoteOwner>() { public RemoteOwner createFromParcel(Parcel in) { return new RemoteOwner(in); } public RemoteOwner[] newArray(int size) { return new RemoteOwner[size]; } }; @SerializedName("avatar_url") @Expose private String avatarUrl; @SerializedName("html_url") @Expose private String htmlUrl; @SerializedName("login") @Expose private String login; protected RemoteOwner(Parcel in) { this.login = in.readString(); this.avatarUrl = in.readString(); this.htmlUrl = in.readString(); } public String getLogin() { return this.login; } public void setLogin(String login2) { this.login = login2; } public String getAvatarUrl() { return this.avatarUrl; } public void setAvatarUrl(String avatarUrl2) { this.avatarUrl = avatarUrl2; } public String getHtmlUrl() { return this.htmlUrl; } public void setHtmlUrl(String htmlUrl2) { this.htmlUrl = htmlUrl2; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.login); dest.writeString(this.avatarUrl); dest.writeString(this.htmlUrl); } }
true
70df129f5c60f1d0929703e68d26cd5bb2cdeb26
Java
zhongxingyu/Seer
/Diff-Raw-Data/20/20_f0eed1aa220e7cc7d7e95cd09c40eee0273fb915/Quest/20_f0eed1aa220e7cc7d7e95cd09c40eee0273fb915_Quest_s.java
UTF-8
12,133
2.140625
2
[]
no_license
package me.blackvein.quests; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import java.util.LinkedList; import java.util.List; import me.blackvein.quests.util.ItemUtil; import net.citizensnpcs.api.npc.NPC; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; public class Quest { public String name; public String description; public String finished; public long redoDelay = -1; public int parties = 0; LinkedList<Stage> stages = new LinkedList<Stage>(); NPC npcStart; Location blockStart; Quests plugin; Event initialEvent; //Requirements int moneyReq = 0; int questPointsReq = 0; List<ItemStack> items = new LinkedList<ItemStack>(); List<Boolean> removeItems = new LinkedList<Boolean>(); List<String> neededQuests = new LinkedList<String>(); List<String> blockQuests = new LinkedList<String>(); List<String> permissionReqs = new LinkedList<String>(); public String failRequirements = null; // //Rewards int moneyReward = 0; int questPoints = 0; int exp = 0; List<String> commands = new LinkedList<String>(); List<String> permissions = new LinkedList<String>(); LinkedList<ItemStack> itemRewards = new LinkedList<ItemStack>(); //mcMMO List<String> mcmmoSkills = new LinkedList<String>(); List<Integer> mcmmoAmounts = new LinkedList<Integer>(); // // public void nextStage(Quester q){ String stageCompleteMessage = q.currentStage.completeMessage; if (stageCompleteMessage != null) { q.getPlayer().sendMessage(Quests.parseString(stageCompleteMessage, q.currentQuest)); } if(q.currentStage.delay < 0){ Player player = q.getPlayer(); if(q.currentStageIndex >= (stages.size() - 1)){ if(q.currentStage.script != null) plugin.trigger.parseQuestTaskTrigger(q.currentStage.script, player); if(q.currentStage.event != null) q.currentStage.event.happen(q); completeQuest(q); }else { q.reset(); if(q.currentStage.script != null) plugin.trigger.parseQuestTaskTrigger(q.currentStage.script, player); if(q.currentStage.event != null) q.currentStage.event.happen(q); q.currentStage = stages.get(stages.indexOf(q.currentStage) + 1); q.currentStageIndex++; q.addEmpties(); player.sendMessage(ChatColor.GOLD + "---(Objectives)---"); for(String s : q.getObjectives()){ player.sendMessage(s); } String stageStartMessage = q.currentStage.startMessage; if (stageStartMessage != null) { q.getPlayer().sendMessage(Quests.parseString(stageStartMessage, q.currentQuest)); } } q.delayStartTime = 0; q.delayTimeLeft = -1; }else{ q.startStageTimer(); } } public String getName(){ return name; } public boolean testRequirements(Quester quester){ return testRequirements(quester.getPlayer()); } public boolean testRequirements(Player player){ Quester quester = plugin.getQuester(player.getName()); if(moneyReq != 0 && Quests.economy.getBalance(player.getName()) < moneyReq) return false; PlayerInventory inventory = player.getInventory(); int num = 0; for(ItemStack is : items){ for(ItemStack stack : inventory.getContents()){ if(stack != null){ if(ItemUtil.compareItems(is, stack, true) == 0) num += stack.getAmount(); } } if(num < is.getAmount()) return false; num = 0; } for(String s : permissionReqs){ if(player.hasPermission(s) == false) return false; } if(quester.questPoints < questPointsReq) return false; if(quester.completedQuests.containsAll(neededQuests) == false) return false; for (String q : blockQuests) { if (quester.completedQuests.contains(q)) { return false; } } return true; } public void completeQuest(Quester q){ Player player = plugin.getServer().getPlayerExact(q.name); q.reset(); q.completedQuests.add(name); String none = ChatColor.GRAY + "- (None)"; String ps = Quests.parseString(finished, q.currentQuest); for (String msg : ps.split("<br>")) { player.sendMessage(msg); } if(moneyReward > 0 && Quests.economy != null){ Quests.economy.depositPlayer(q.name, moneyReward); none = null; } if(redoDelay > -1) q.completedTimes.put(this.name, System.currentTimeMillis()); for(ItemStack i : itemRewards){ Quests.addItem(player, i); none = null; } for(String s : commands){ s = s.replaceAll("<player>", player.getName()); plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), s); none = null; } for(String s : permissions){ Quests.permission.playerAdd(player, s); none = null; } for(String s : mcmmoSkills){ new McMMOPlayer(player).getProfile().skillUp(Quests.getMcMMOSkill(s), mcmmoAmounts.get(mcmmoSkills.indexOf(s))); none = null; } if(exp > 0){ player.giveExp(exp); none = null; } player.sendMessage(ChatColor.GOLD + "**QUEST COMPLETE: " + ChatColor.YELLOW + q.currentQuest.name + ChatColor.GOLD + "**"); player.sendMessage(ChatColor.GREEN + "Rewards:"); if(questPoints > 0){ player.sendMessage("- " + ChatColor.DARK_GREEN + questPoints + " Quest Points"); q.questPoints += questPoints; none = null; } for(ItemStack i : itemRewards){ if(i.hasItemMeta() && i.getItemMeta().hasDisplayName()) player.sendMessage("- " + ChatColor.DARK_AQUA + ChatColor.ITALIC + i.getItemMeta().getDisplayName() + ChatColor.RESET + ChatColor.GRAY + " x " + i.getAmount()); else if(i.getDurability() != 0) player.sendMessage("- " + ChatColor.DARK_GREEN + Quester.prettyItemString(i.getTypeId()) + ":" + i.getDurability() + ChatColor.GRAY + " x " + i.getAmount()); else player.sendMessage("- " + ChatColor.DARK_GREEN + Quester.prettyItemString(i.getTypeId()) + ChatColor.GRAY + " x " + i.getAmount()); none = null; } if(moneyReward > 1){ player.sendMessage("- " + ChatColor.DARK_GREEN + moneyReward + " " + ChatColor.DARK_PURPLE + Quests.getCurrency(true)); none = null; }else if(moneyReward == 1){ player.sendMessage("- " + ChatColor.DARK_GREEN + moneyReward + " " + ChatColor.DARK_PURPLE + Quests.getCurrency(false)); none = null; } if(exp > 0){ player.sendMessage("- " + ChatColor.DARK_GREEN + exp + ChatColor.DARK_PURPLE + " Experience"); none = null; } if(none != null){ player.sendMessage(none); } q.currentQuest = null; q.currentStage = null; q.currentStageIndex = 0; q.saveData(); player.updateInventory(); } @Override public boolean equals(Object o){ if(o instanceof Quest){ Quest other = (Quest) o; if(other.blockStart != null && blockStart != null){ if(other.blockStart.equals(blockStart) == false) return false; }else if(other.blockStart != null && blockStart == null){ return false; }else if(other.blockStart == null && blockStart != null) return false; for(String s : other.commands){ if(commands.size() >= (other.commands.indexOf(s))){ if(commands.get(other.commands.indexOf(s)).equals(s) == false) return false; }else{ return false; } } if(other.description.equals(description) == false) return false; if(other.initialEvent != null && initialEvent != null){ if(other.initialEvent.equals(initialEvent) == false) return false; }else if(other.initialEvent != null && initialEvent == null){ return false; }else if(other.initialEvent == null && initialEvent != null) return false; if(other.exp != exp) return false; if(other.failRequirements != null && failRequirements != null){ if(other.failRequirements.equals(failRequirements) == false) return false; }else if(other.failRequirements != null && failRequirements == null){ return false; }else if(other.failRequirements == null && failRequirements != null) return false; if(other.finished.equals(finished) == false) return false; if(other.items.equals(items) == false) return false; if(other.itemRewards.equals(itemRewards) == false) return false; if(other.mcmmoAmounts.equals(mcmmoAmounts) == false) return false; if(other.mcmmoSkills.equals(mcmmoSkills) == false) return false; if(other.moneyReq != moneyReq) return false; if(other.moneyReward != moneyReward) return false; if(other.name.equals(name) == false) return false; if(other.neededQuests.equals(neededQuests) == false) return false; if (other.blockQuests.equals(blockQuests) == false) return false; if(other.npcStart != null && npcStart != null){ if(other.npcStart.equals(npcStart) == false) return false; }else if(other.npcStart != null && npcStart == null){ return false; }else if(other.npcStart == null && npcStart != null) return false; if(other.permissionReqs.equals(permissionReqs) == false) return false; if(other.permissions.equals(permissions) == false) return false; if(other.questPoints != questPoints) return false; if(other.questPointsReq != questPointsReq) return false; if(other.redoDelay != redoDelay) return false; if(other.stages.equals(stages) == false) return false; } return true; } }
true
c7d65cdd29381973380340db173bc7cf77cca395
Java
msmith406/microservices
/developerConsumer/src/main/java/com/captech/wessel/streams/developerConsumer/Developer.java
UTF-8
252
1.804688
2
[]
no_license
package com.captech.wessel.streams.developerConsumer; import lombok.Data; import java.util.UUID; @Data public class Developer { private UUID id; private String name; private String language; public Developer(){} }
true
590b479e41b9ca403cbd0b8005c6d94628a54496
Java
NicDou/apocal
/apocal-model/src/main/java/com/jd/apocal/model/mapper/ProjectMapper.java
UTF-8
263
1.546875
2
[]
no_license
package com.jd.apocal.model.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.jd.apocal.model.entity.Project; import org.springframework.stereotype.Repository; @Repository public interface ProjectMapper extends BaseMapper<Project> { }
true
f6bcee93a23054d6dffd8bbafc41cf6e1e5e2a00
Java
matt0224/Myjava0312
/Myjava0312/src/tw/matt0312/matt0312M12.java
UTF-8
339
3.140625
3
[]
no_license
package tw.matt0312; public class matt0312M12 { public static void main(String[] args) { int a = 20 ; do { System.out.println(a--); }while (a>10); //()括號是布林值 true再從做 do //先做一次 後測試語法 ,java語法結尾不是大括號就是;號 } }
true
270519a557992c5bde54dfb2240ff8c91e7ff1f5
Java
ruslandzh61/mrp
/src/PSO/PSOConfiguration.java
UTF-8
1,774
2.328125
2
[]
no_license
package PSO; /** * Configuratios for PSO-based algorithm */ public enum PSOConfiguration { CONF1(200, false, true, true), // MaxiMin is used, weights of objectives are the same (0.5, 0.5) CONF2(200, true, true, true), // MaxiMin is not used, weights of objectives are different CONF4(200, true, true, false, new double[]{0.15, 0.85}), CONF5(200, true, true, false, new double[]{0.05, 0.95}), // MaxiMin is not used, weights of objectives are same (0.5, 0.5) CONF7(200, true, true, false), // MaxiMin is used, weights of objectives are different CONF8(200, true, true, true, new double[]{0.05, 0.95}); PSOConfiguration(int aMaxIteration, boolean aNormObjs, boolean aEqualClusterNumDistribution, boolean aMaximin) { this(aMaxIteration, aNormObjs, aEqualClusterNumDistribution, aMaximin, new double[]{0.5, 0.5}); } PSOConfiguration(int aMaxIteration, boolean aNormObjs, boolean aEqualClusterNumDistribution, boolean aMaximin, double[] aWeights) { this.maxIteration = aMaxIteration; this.normObjs = aNormObjs; this.equalClusterNumDistribution = aEqualClusterNumDistribution; this.maximin = aMaximin; this.weights = aWeights.clone(); } double c1 = 1.42; double c2 = 1.63; double maxW = 0.9; double minW = 0.4; int maxIteration = 200; int maxIterWithoutImprovement = 25; // maxK depends on size of dataset: Math.sqrt(N), N is a number of data points int maxK = 150; int pMax = 150; // for randomly picking leaders (global best) for each particle double numTopParticlesToPickForLeader = 0.2; boolean equalClusterNumDistribution = true; boolean maximin = true; boolean normObjs; double[] weights = {0.5, 0.5}; }
true
9fa11e94d64d1afb0b497979346cf47a05a9435c
Java
ShuPF8/SSM
/src/main/java/com/controller/test/InterceptorController.java
UTF-8
612
1.828125
2
[]
no_license
package com.controller.test; import com.utils.BaseUtils; import com.utils.ResultJson; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * @Author SPF * @Date 2017/5/3 */ @Controller public class InterceptorController extends BaseUtils{ @RequestMapping("inter") @ResponseBody public void inter() { System.out.println("执行了 controller "); ResultJson json = new ResultJson(); json.success(); backClient(toJSONString(json)); } }
true
d738fa73c46c5d375ddec9b43f0a62ca5a65b184
Java
jasperavisser/hyperlinker
/src/eu/portavita/hyperlinker/Hyperlink.java
UTF-8
2,415
2.640625
3
[]
no_license
package eu.portavita.hyperlinker; import java.net.MalformedURLException; import java.net.URL; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; import eu.portavita.hyperlinker.preferences.PreferenceConstants; /** * Represents a hyperlink that matches a configurable pattern and links to a configurable URL. * * @author Jasper A. Visser */ public class Hyperlink implements IHyperlink { /** * Id of the internal browser to re-use. */ private static final String INTERNAL_BROWSER_ID = "3490328034"; /** * Description of the hyperlink. */ private String description; /** * Region of the hyperlink. */ private IRegion region; /** * Text of the hyperlink. */ private String text; /** * Creates a new hyperlink. * * @param region Region of the hyperlink. * @param text Text of the hyperlink. * @param description */ public Hyperlink(IRegion region, String text, String description) { this.region = region; this.text = text; this.description = description; } @Override public IRegion getHyperlinkRegion() { return region; } @Override public String getHyperlinkText() { return description; } @Override public String getTypeLabel() { return description; } @Override public void open() { // Get preferences. final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); final String targetUrl = preferenceStore.getString(PreferenceConstants.TARGET_URL); final Boolean useExternalBrowser = preferenceStore .getBoolean(PreferenceConstants.USE_EXTERNAL_BROWSER); // Get browser. IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport(); IWebBrowser browser; try { if (useExternalBrowser) { browser = support.getExternalBrowser(); } else { browser = support.createBrowser(INTERNAL_BROWSER_ID); } } catch (PartInitException e) { e.printStackTrace(); return; } // Open URL. try { browser.openURL(new URL(targetUrl.replace("%s", text))); } catch (PartInitException e) { e.printStackTrace(); return; } catch (MalformedURLException e) { e.printStackTrace(); return; } } }
true
c3b03cfa192cb1d812afa5cf7bf1a8bf700e340d
Java
krzysztof-miemiec/ITAD2014Android
/ITAD/src/pl/polsl/dotnet/itacademicday/core/signalr/SignalRClient.java
UTF-8
1,962
2.4375
2
[]
no_license
package pl.polsl.dotnet.itacademicday.core.signalr; import java.util.ArrayList; import microsoft.aspnet.signalr.client.Action; import microsoft.aspnet.signalr.client.LogLevel; import microsoft.aspnet.signalr.client.Logger; import microsoft.aspnet.signalr.client.Platform; import microsoft.aspnet.signalr.client.hubs.HubConnection; import microsoft.aspnet.signalr.client.hubs.HubProxy; public class SignalRClient { protected HubProxy hub; protected HubConnection connection; private static SignalRClient Instance = null; private onMessageReceived received = null; private ArrayList<String> wallInfo = new ArrayList<String>(); private Logger logger = new Logger() { @Override public void log(String message, LogLevel level) { System.out.println(message); } }; private SignalRClient() { Platform.loadPlatformComponent(new AndroidPlatformComponent()); // Change to the IP address and matching port of your SignalR server. String host = "http://itadpolsl.pl/signalr"; HubConnection connection = new HubConnection(host, "", true, logger); hub = connection.createHubProxy("wallHub"); hub.subscribe(new Object() { @SuppressWarnings("unused") public void posted(String message) { wallInfo.add(message); if(received != null){ received.onMessageReceive(message); } } }); connection.start().done(new Action<Void>() { @Override public void run(Void obj) throws Exception { hub.invoke("claimParticipant"); } }); } public boolean sendMessage(String message) { return hub.invoke("Post", message).isDone(); } public static SignalRClient getInstance() { if (Instance == null) { Instance = new SignalRClient(); } return Instance; } public ArrayList<String> getWallInfo() { return wallInfo; } public void setReceiver(onMessageReceived received){ this.received = received; } public interface onMessageReceived{ public void onMessageReceive(String message); } }
true
a67af1f2338be8be6577276e65936439739fc541
Java
Vickykumarverma-11/SQLiteDB
/main/java/com/riteshkm/db/newPersonActivity.java
UTF-8
1,568
2.21875
2
[]
no_license
package com.riteshkm.db; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; public class newPersonActivity extends AppCompatActivity { EditText name,mob; Button add; public static final String Name_Extra = "My Extra Name"; public static final String Mob_Extra = "My Extra Mobile_no"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_person); name = findViewById(R.id.et1); mob = findViewById(R.id.et2); add = findViewById(R.id.btn); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(TextUtils.isEmpty(name.getText().toString())) { name.setError("Can't be empty"); return; } if(TextUtils.isEmpty(mob.getText().toString())) { mob.setError("Can't be empty"); return; } Intent intent = new Intent(); intent.putExtra(Name_Extra,name.getText().toString()); intent.putExtra(Mob_Extra,mob.getText().toString()); setResult(RESULT_OK,intent); finish(); } }); } }
true
51e4d44ad51b59626399fcd2b31f297f330dac56
Java
gatezflg/Year4_LITRealty
/Assignment3_LITRealtyV2_FinalUpload/Assignment3_LITRealtyV2/build/generated-sources/ap-source-output/classes/entities/Agents_.java
UTF-8
1,105
1.59375
2
[]
no_license
package classes.entities; import classes.entities.Properties; import javax.annotation.Generated; import javax.persistence.metamodel.CollectionAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-02-01T15:26:24") @StaticMetamodel(Agents.class) public class Agents_ { public static volatile SingularAttribute<Agents, String> image; public static volatile SingularAttribute<Agents, Integer> agentId; public static volatile SingularAttribute<Agents, String> password; public static volatile SingularAttribute<Agents, String> role; public static volatile SingularAttribute<Agents, String> phone; public static volatile SingularAttribute<Agents, String> name; public static volatile CollectionAttribute<Agents, Properties> propertiesCollection; public static volatile SingularAttribute<Agents, String> fax; public static volatile SingularAttribute<Agents, String> email; public static volatile SingularAttribute<Agents, String> username; }
true
2675c64228985b9bd1dd4ff8f0356f297afcb331
Java
aigerim222225/hw3-ads
/Merge.java
UTF-8
1,603
3.578125
4
[]
no_license
import java.util.*; public class Merge { public static void main(String args[]) { Scanner input = new Scanner(System.in); MergeSort<String> m = new MergeSort(); int n = input.nextInt(); String[] s = new String[n]; for (int i = 0; i < n; ++i) { s[i] = input.next(); } m.MergeSort(s); for (int i = 0; i < n; ++i) { System.out.println(s[i]); } input.close(); } } class MergeSort<T extends Comparable<T>>{ MergeSort() {} public void MergeSort(Object[] a) { int n = a.length; if (n <= 1) { return; } int middle = n/2; Object[] left = new Object[middle]; Object[] right = new Object[n-middle]; for (int i = 0; i < middle; ++i) { left[i] = a[i]; } for (int i = 0; i < n-middle; ++i) { right[i] = a[i+middle]; } MergeSort(left); MergeSort(right); merge(a, left, right); } public void merge(Object[] c, Object[] a, Object[] b) { int n = c.length; int ptr_a = 0, ptr_b = 0; for (int i = 0; i < n; ++i) { if (ptr_a == a.length) { c[i] = (T) b[ptr_b]; ptr_b++; } else if (ptr_b == b.length) { c[i] = (T) a[ptr_a]; ptr_a++; } else if (((T)a[ptr_a]).compareTo((T)b[ptr_b]) <= 0) { c[i] = (T) a[ptr_a]; ptr_a++; } else { c[i] = (T) b[ptr_b]; ptr_b++; } } } }
true
a42a6177d70788d1339587c17b5f53b4d850606a
Java
bsjigi/Programming-Challenge
/week3/Rare/Rare.java
UTF-8
1,503
3.25
3
[]
no_license
import java.util.Scanner; class Main { public static void main(String[] args){ int n,m; Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); int[] buf = new int[m]; if(m <= 100){ for(int i=0;i<m;i++){ buf[i] = sc.nextInt(); } } int ultra_rare = 0; int super_rare =0; int rare =0; int normal = 0; if (n <= 10000){ for(int i=1;i<=n;i++){ int special_case = 0; int num = 0; for(int j=0;j<8;j++){ if(i == Math.pow(2,j)){ special_case = 1; ultra_rare++; break; } } if(special_case==0){ for(int j=0;j<buf.length;j++){ if (i % buf[j] == 0){ num++; } } } else{ continue; } if(num == 0) { normal++; }else if(num==1){ rare++; }else if(num==2){ super_rare++; }else{ ultra_rare++; } } } System.out.print(ultra_rare +" "); System.out.print(super_rare +" "); System.out.print(rare +" "); System.out.print(normal +" "); } }
true
acc9126390ce96c5c0455b8673ad59d3a4044d8e
Java
truward/Tupl
/src/main/java/org/cojen/tupl/io/Utils.java
UTF-8
22,291
2.34375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2013-2015 Cojen.org * * 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 org.cojen.tupl.io; import org.cojen.tupl.CorruptDatabaseException; import java.io.Closeable; import java.io.EOFException; import java.io.InputStream; import java.io.IOException; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Method; import java.nio.Buffer; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Generic data and I/O utility methods. * * @author Brian S O'Neill */ public class Utils { private static final MethodHandle cCompareUnsigned_1; // basic form private static final MethodHandle cCompareUnsigned_2; // offset/length form private static final MethodHandle cCompareUnsigned_3; // start/end form static { MethodType type = MethodType.methodType(int.class, byte[].class, byte[].class); MethodHandle method = findFastCompareMethod("compareUnsigned", type); if (method == null) { method = findLocalCompareMethod("doCompareUnsigned", type); } cCompareUnsigned_1 = method; type = MethodType.methodType (int.class, byte[].class, int.class, int.class, byte[].class, int.class, int.class); method = findFastCompareMethod("compareUnsigned", type); if (method == null) { cCompareUnsigned_2 = findLocalCompareMethod("doCompareUnsigned", type); cCompareUnsigned_3 = null; // won't be used } else { // Use an adapter to fix handling of length paramaters. cCompareUnsigned_2 = findLocalCompareMethod("compareUnsignedAdapter", type); cCompareUnsigned_3 = method; } } private static MethodHandle findFastCompareMethod(String name, MethodType type) { try { return MethodHandles.publicLookup().findStatic(Arrays.class, name, type); } catch (NoSuchMethodException | IllegalAccessException e) { return null; } } private static MethodHandle findLocalCompareMethod(String name, MethodType type) { try { return MethodHandles.lookup().findStatic(Utils.class, name, type); } catch (Exception e2) { throw rethrow(e2); } } protected Utils() { } /** * Performs a lexicographical comparison between two unsigned byte arrays. * * @return negative if 'a' is less, zero if equal, greater than zero if greater */ public static int compareUnsigned(byte[] a, byte[] b) { try { return (int) cCompareUnsigned_1.invokeExact(a, b); } catch (Throwable e) { throw rethrow(e); } } /** * Performs a lexicographical comparison between two unsigned byte arrays. * * @param a array 'a' * @param aoff array 'a' offset * @param alen array 'a' length * @param b array 'b' * @param boff array 'b' offset * @param blen array 'b' length * @return negative if 'a' is less, zero if equal, greater than zero if greater */ public static int compareUnsigned(byte[] a, int aoff, int alen, byte[] b, int boff, int blen) { try { return (int) cCompareUnsigned_2.invokeExact(a, aoff, alen, b, boff, blen); } catch (Throwable e) { throw rethrow(e); } } private static int doCompareUnsigned(byte[] a, byte[] b) { return doCompareUnsigned(a, 0, a.length, b, 0, b.length); } private static int doCompareUnsigned(byte[] a, int aoff, int alen, byte[] b, int boff, int blen) { int minLen = Math.min(alen, blen); for (int i=0; i<minLen; i++) { byte ab = a[aoff + i]; byte bb = b[boff + i]; if (ab != bb) { return (ab & 0xff) - (bb & 0xff); } } return alen - blen; } /** * Adapts the offset/length form to work with the start/end form. */ private static int compareUnsignedAdapter(byte[] a, int aoff, int alen, byte[] b, int boff, int blen) throws Throwable { return (int) cCompareUnsigned_3.invokeExact(a, aoff, aoff + alen, b, boff, boff + blen); } /** * Adds one to an unsigned integer, represented as a byte array. If * overflowed, value in byte array is 0x00, 0x00, 0x00... * * @param value unsigned integer to increment * @param start inclusive index * @param end exclusive index * @return false if overflowed */ public static boolean increment(byte[] value, final int start, int end) { while (--end >= start) { if (++value[end] != 0) { // No carry bit, so done adding. return true; } } // This point is reached upon overflow. return false; } /** * Subtracts one from an unsigned integer, represented as a byte array. If * overflowed, value in byte array is 0xff, 0xff, 0xff... * * @param value unsigned integer to decrement * @param start inclusive index * @param end exclusive index * @return false if overflowed */ public static boolean decrement(byte[] value, final int start, int end) { while (--end >= start) { if (--value[end] != -1) { // No borrow bit, so done subtracting. return true; } } // This point is reached upon overflow. return false; } /** * Encodes a 16-bit integer, in big-endian format. * * @param b encode destination * @param offset offset into byte array * @param v value to encode */ public static final void encodeShortBE(byte[] b, int offset, int v) { b[offset ] = (byte)(v >> 8); b[offset + 1] = (byte)v; } /** * Encodes a 16-bit integer, in little-endian format. * * @param b encode destination * @param offset offset into byte array * @param v value to encode */ public static final void encodeShortLE(byte[] b, int offset, int v) { b[offset ] = (byte)v; b[offset + 1] = (byte)(v >> 8); } /** * Encodes a 32-bit integer, in big-endian format. * * @param b encode destination * @param offset offset into byte array * @param v value to encode */ public static final void encodeIntBE(byte[] b, int offset, int v) { b[offset ] = (byte)(v >> 24); b[offset + 1] = (byte)(v >> 16); b[offset + 2] = (byte)(v >> 8); b[offset + 3] = (byte)v; } /** * Encodes a 32-bit integer, in little-endian format. * * @param b encode destination * @param offset offset into byte array * @param v value to encode */ public static final void encodeIntLE(byte[] b, int offset, int v) { b[offset ] = (byte)v; b[offset + 1] = (byte)(v >> 8); b[offset + 2] = (byte)(v >> 16); b[offset + 3] = (byte)(v >> 24); } /** * Encodes a 48-bit integer, in big-endian format. * * @param b encode destination * @param offset offset into byte array * @param v value to encode */ public static final void encodeInt48BE(byte[] b, int offset, long v) { int w = (int)(v >> 32); b[offset ] = (byte)(w >> 8); b[offset + 1] = (byte)w; w = (int)v; b[offset + 2] = (byte)(w >> 24); b[offset + 3] = (byte)(w >> 16); b[offset + 4] = (byte)(w >> 8); b[offset + 5] = (byte)w; } /** * Encodes a 48-bit integer, in little-endian format. * * @param b encode destination * @param offset offset into byte array * @param v value to encode */ public static final void encodeInt48LE(byte[] b, int offset, long v) { int w = (int)v; b[offset ] = (byte)w; b[offset + 1] = (byte)(w >> 8); b[offset + 2] = (byte)(w >> 16); b[offset + 3] = (byte)(w >> 24); w = (int)(v >> 32); b[offset + 4] = (byte)w; b[offset + 5] = (byte)(w >> 8); } /** * Encodes a 64-bit integer, in big-endian format. * * @param b encode destination * @param offset offset into byte array * @param v value to encode */ public static final void encodeLongBE(byte[] b, int offset, long v) { int w = (int)(v >> 32); b[offset ] = (byte)(w >> 24); b[offset + 1] = (byte)(w >> 16); b[offset + 2] = (byte)(w >> 8); b[offset + 3] = (byte)w; w = (int)v; b[offset + 4] = (byte)(w >> 24); b[offset + 5] = (byte)(w >> 16); b[offset + 6] = (byte)(w >> 8); b[offset + 7] = (byte)w; } /** * Encodes a 64-bit integer, in little-endian format. * * @param b encode destination * @param offset offset into byte array * @param v value to encode */ public static final void encodeLongLE(byte[] b, int offset, long v) { int w = (int)v; b[offset ] = (byte)w; b[offset + 1] = (byte)(w >> 8); b[offset + 2] = (byte)(w >> 16); b[offset + 3] = (byte)(w >> 24); w = (int)(v >> 32); b[offset + 4] = (byte)w; b[offset + 5] = (byte)(w >> 8); b[offset + 6] = (byte)(w >> 16); b[offset + 7] = (byte)(w >> 24); } /** * Decodes a 16-bit unsigned integer, in big-endian format. * * @param b decode source * @param offset offset into byte array * @return decoded value */ public static final int decodeUnsignedShortBE(byte[] b, int offset) { return ((b[offset] & 0xff) << 8) | ((b[offset + 1] & 0xff)); } /** * Decodes a 16-bit unsigned integer, in little-endian format. * * @param b decode source * @param offset offset into byte array * @return decoded value */ public static final int decodeUnsignedShortLE(byte[] b, int offset) { return ((b[offset] & 0xff)) | ((b[offset + 1] & 0xff) << 8); } /** * Decodes a 32-bit integer, in big-endian format. * * @param b decode source * @param offset offset into byte array * @return decoded value */ public static final int decodeIntBE(byte[] b, int offset) { return (b[offset] << 24) | ((b[offset + 1] & 0xff) << 16) | ((b[offset + 2] & 0xff) << 8) | (b[offset + 3] & 0xff); } /** * Decodes a 32-bit integer, in little-endian format. * * @param b decode source * @param offset offset into byte array * @return decoded value */ public static final int decodeIntLE(byte[] b, int offset) { return (b[offset] & 0xff) | ((b[offset + 1] & 0xff) << 8) | ((b[offset + 2] & 0xff) << 16) | (b[offset + 3] << 24); } /** * Decodes a 48-bit unsigned integer, in big-endian format. * * @param b decode source * @param offset offset into byte array * @return decoded value */ public static final long decodeUnsignedInt48BE(byte[] b, int offset) { return (((long)(((b[offset ] & 0xff) << 8 ) | ((b[offset + 1] & 0xff) )) ) << 32) | (((long)(((b[offset + 2] ) << 24) | ((b[offset + 3] & 0xff) << 16) | ((b[offset + 4] & 0xff) << 8 ) | ((b[offset + 5] & 0xff) )) & 0xffffffffL) ); } /** * Decodes a 48-bit unsigned integer, in little-endian format. * * @param b decode source * @param offset offset into byte array * @return decoded value */ public static final long decodeUnsignedInt48LE(byte[] b, int offset) { return (((long)(((b[offset ] & 0xff) ) | ((b[offset + 1] & 0xff) << 8 ) | ((b[offset + 2] & 0xff) << 16) | ((b[offset + 3] ) << 24)) & 0xffffffffL) ) | (((long)(((b[offset + 4] & 0xff) ) | ((b[offset + 5] & 0xff) << 8 )) ) << 32); } /** * Decodes a 64-bit integer, in big-endian format. * * @param b decode source * @param offset offset into byte array * @return decoded value */ public static final long decodeLongBE(byte[] b, int offset) { return (((long)(((b[offset ] ) << 24) | ((b[offset + 1] & 0xff) << 16) | ((b[offset + 2] & 0xff) << 8 ) | ((b[offset + 3] & 0xff) )) ) << 32) | (((long)(((b[offset + 4] ) << 24) | ((b[offset + 5] & 0xff) << 16) | ((b[offset + 6] & 0xff) << 8 ) | ((b[offset + 7] & 0xff) )) & 0xffffffffL) ); } /** * Decodes a 64-bit integer, in little-endian format. * * @param b decode source * @param offset offset into byte array * @return decoded value */ public static final long decodeLongLE(byte[] b, int offset) { return (((long)(((b[offset ] & 0xff) ) | ((b[offset + 1] & 0xff) << 8 ) | ((b[offset + 2] & 0xff) << 16) | ((b[offset + 3] ) << 24)) & 0xffffffffL) ) | (((long)(((b[offset + 4] & 0xff) ) | ((b[offset + 5] & 0xff) << 8 ) | ((b[offset + 6] & 0xff) << 16) | ((b[offset + 7] ) << 24)) ) << 32); } /** * Fully reads the required length of bytes, throwing an EOFException if the end of stream * is reached too soon. */ public static void readFully(InputStream in, byte[] b, int off, int len) throws IOException { if (len > 0) { while (true) { int amt = in.read(b, off, len); if (amt <= 0) { throw new EOFException(); } if ((len -= amt) <= 0) { break; } off += amt; } } } private static volatile boolean cDeleteUnsupported; /** * Attempt to delete the given direct or mapped byte buffer. */ public static boolean delete(Buffer bb) { // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038 if (!cDeleteUnsupported) { try { Method m = bb.getClass().getMethod("cleaner"); if (m != null) { m.setAccessible(true); Object cleaner = m.invoke(bb); if (cleaner != null) { m = cleaner.getClass().getMethod("clean"); if (m != null) { m.setAccessible(true); m.invoke(cleaner); return true; } } } } catch (Exception e) { cDeleteUnsupported = true; } } return false; } private static Map<Closeable, Thread> cCloseThreads; static synchronized void unregister(Closeable resource) { if (cCloseThreads != null) { cCloseThreads.remove(resource); if (cCloseThreads.isEmpty()) { cCloseThreads = null; } } } /** * Closes the given resource, passing the cause if the resource implements {@link * CauseCloseable}. The cause is then rethrown, wrapped by {@link CorruptDatabaseException} * if not an {@link IOException} or unchecked. */ public static IOException closeOnFailure(final Closeable resource, final Throwable cause) throws IOException { // Close in a separate thread, in case of deadlock. Thread closer; int joinMillis; obtainThread: try { synchronized (Utils.class) { if (cCloseThreads == null) { cCloseThreads = new HashMap<>(4); } else { closer = cCloseThreads.get(resource); if (closer != null) { // First thread waited, which is sufficient. joinMillis = 0; break obtainThread; } } closer = new Thread(() -> { try { close(resource, cause); } catch (IOException e2) { // Ignore. } finally { unregister(resource); } }); cCloseThreads.put(resource, closer); } closer.setDaemon(true); closer.start(); // Wait up to one second for close to finish. joinMillis = 1000; } catch (Throwable e2) { closer = null; joinMillis = 0; } if (closer == null) { try { close(resource, cause); } catch (IOException e2) { // Ignore. } finally { unregister(resource); } } else if (joinMillis > 0) { try { closer.join(joinMillis); } catch (InterruptedException e2) { } } if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } if (cause instanceof Error) { throw (Error) cause; } if (cause instanceof IOException) { throw (IOException) cause; } throw new CorruptDatabaseException(cause); } /** * Closes a resource without throwing another exception. If closing a chain of resources, * pass in the first caught exception, and all others are discarded. * * @param first returned if non-null * @param resource can be null * @return IOException which was caught, unless first was non-null */ public static IOException closeQuietly(IOException first, Closeable resource) { if (resource != null) { try { resource.close(); } catch (IOException e) { if (first == null) { return e; } } } return first; } /** * Closes a resource without throwing another exception. If closing a chain of resources, * pass in the first caught exception, and all others are discarded. * * @param first returned if non-null * @param resource can be null * @param cause passed to resource if it implements {@link CauseCloseable} * @return IOException which was caught, unless first was non-null */ public static IOException closeQuietly(IOException first, Closeable resource, Throwable cause) { if (resource != null) { try { close(resource, cause); } catch (IOException e) { if (first == null) { return e; } } } return first; } /** * Closes a resource, which may throw a new exception. * * @param cause passed to resource if it implements {@link CauseCloseable} */ public static void close(Closeable resource, Throwable cause) throws IOException { if (resource instanceof CauseCloseable) { ((CauseCloseable) resource).close(cause); } else { resource.close(); } } /** * Returns the root cause of the given exception. * * @return non-null cause, unless given exception was null */ public static Throwable rootCause(Throwable e) { while (true) { Throwable cause = e.getCause(); if (cause == null) { return e; } e = cause; } } /** * Convenience method to pass the given exception to the current thread's uncaught * exception handler. */ public static void uncaught(Throwable e) { Thread t = Thread.currentThread(); t.getUncaughtExceptionHandler().uncaughtException(t, e); } /** * Rethrows the given exception without the compiler complaining about it being checked or * not. Use as follows: {@code throw rethrow(e)} */ public static RuntimeException rethrow(Throwable e) { Utils.<RuntimeException>castAndThrow(e); return null; } /** * Rethrows the given exception without the compiler complaining about it being checked or * not. The exception can have a root cause initialized, which will be the root cause of * the one given. Use as follows: {@code throw rethrow(e, cause)} * * @param cause initialize the exception's cause, unless it already has one */ public static RuntimeException rethrow(Throwable e, Throwable cause) { if (cause != null && e != cause && e.getCause() == null) { try { e.initCause(rootCause(cause)); } catch (Exception e2) { } } Utils.<RuntimeException>castAndThrow(e); return null; } @SuppressWarnings("unchecked") private static <T extends Throwable> void castAndThrow(Throwable e) throws T { throw (T) e; } }
true
a0b5e1bbcaea96c95e400e7d0aeb827bad9449c0
Java
yunkai-zhang/BUPT
/small_projects_when_learning_java_backend/spring-study/spring-09-aop/src/main/java/com/zhangyk/log/BeforeLog.java
UTF-8
935
2.796875
3
[]
no_license
package com.zhangyk.log; import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect.Method; /* * MethodBeforeAdvice的parent是BeforeAdvice,MethodBeforeAdvic的出现应该是出于一些扩展性需求的设计 * * 本BeforeLog类是方法执行前使用的日志 * */ public class BeforeLog implements MethodBeforeAdvice { /* method:要执行的目标对象的方法 的方法对象 objects:参数,其实命名为args更合理 o:目标对象,其实命名为target更合理 参数命名不规范的问题:可以下载源码来读。点MethodBeforeAdvice接口,代码区的上沿会有“下载源码”的 标识,点击下载后读的源码都是规范命名的 */ public void before(Method method, Object[] objects, Object o) throws Throwable { System.out.println(o.getClass().getName()+"类的对象的"+method.getName()+"方法被执行了"); } }
true
9be500342387005ca257a9f9e9f835560134cc1c
Java
bprashan/iot-platform-sdk
/common/protocol/src/main/java/org/sdo/iotplatformsdk/common/protocol/config/SslContextFactoryBean.java
UTF-8
2,928
1.9375
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2020 Intel Corporation * * 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 org.sdo.iotplatformsdk.common.protocol.config; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBeanNotInitializedException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class SslContextFactoryBean implements FactoryBean<SSLContext> { private ObjectFactory<SecureRandom> secureRandomProvider = null; @Override public SSLContext getObject() throws KeyManagementException, NoSuchAlgorithmException { TrustManager[] trustManagers = new TrustManager[] {new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {} @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }; ObjectFactory<SecureRandom> provider = getSecureRandomProvider(); SecureRandom random; if (null != provider) { random = provider.getObject(); } else { throw new FactoryBeanNotInitializedException("SecureRandom provider must not be null"); } SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustManagers, random); LoggerFactory.getLogger(getClass()).warn("UNSAFE: no-op TrustManager installed"); return context; } @Override public Class<?> getObjectType() { return SSLContext.class; } public ObjectFactory<SecureRandom> getSecureRandomProvider() { return secureRandomProvider; } @Autowired public void setSecureRandomProvider(ObjectFactory<SecureRandom> secureRandomProvider) { this.secureRandomProvider = secureRandomProvider; } }
true
e410fa9ec923d57bfa836f27ce086cb76092b07a
Java
denravonska/Hackathon2010
/src/com/ormgas/hackathon2010/controller/IGameObjectController.java
UTF-8
188
2.015625
2
[]
no_license
package com.ormgas.hackathon2010.controller; import com.ormgas.hackathon2010.gameobjects.Actor; public interface IGameObjectController { public void registerGameObject(Actor object); }
true
78af8cca5c844e9b6b87dd2c5c2008e7a4c0f2ca
Java
ryanchamp-ICE/PopMovies-Udacity
/app/src/main/java/com/icecoldedge/popmovies/Movie.java
UTF-8
2,600
2.6875
3
[]
no_license
package com.icecoldedge.popmovies; import android.os.Parcel; import android.os.Parcelable; import java.util.Date; /** * Created by rchamp on 8/8/2016. */ public class Movie implements Parcelable { public static final String POSTER_BASE_URL = "http://image.tmdb.org/t/p/"; public static final String POSTER_SIZE = "w185"; private int id; private String title; private String posterPath; private String synopsis; private float rating; private Date releaseDate; public Movie() {} public Movie(int id, String title, String posterPath, String synopsis, float rating, Date releaseDate) { this.id = id; this.title = title; this.posterPath = posterPath; this.synopsis = synopsis; this.rating = rating; this.releaseDate = releaseDate; } public Movie(Parcel in) { id = in.readInt(); title = in.readString(); posterPath = in.readString(); synopsis = in.readString(); rating = in.readFloat(); releaseDate = new Date(in.readLong()); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(title); dest.writeString(posterPath); dest.writeString(synopsis); dest.writeFloat(rating); dest.writeLong(getReleaseDate().getTime()); } static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() { @Override public Movie createFromParcel(Parcel parcel) { return new Movie(parcel); } @Override public Movie[] newArray(int i) { return new Movie[i]; } }; public int getMovieId() { return id; } public void setMovieId(int val) { id = val; } public String getTitle() { return title; } public void setTitle(String val) { title = val; } public String getPosterPath() { return posterPath; } public void setPosterPath(String val) { posterPath = val; } public String getSynopsis() { return synopsis; } public void setSynopsis(String val) { synopsis = val; } public float getRating() { return rating; } public void setRating(float val) { rating = val; } public Date getReleaseDate() { return releaseDate; } public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } }
true
c592d15e39ce7de28560578fac52b25a3a7172b8
Java
ajaysamgir/java-8-strings-io
/java-8-strings/src/StringJoinerImpl.java
UTF-8
624
3.71875
4
[]
no_license
import java.util.StringJoiner; public class StringJoinerImpl { public static void main(String[] args) { StringJoiner stringJoiner1 = new StringJoiner(" "); stringJoiner1.add("Ajay").add("Samgir"); StringJoiner stringJoiner2 = new StringJoiner(" ", "{", "}"); stringJoiner2.merge(stringJoiner1); System.out.println("stringJoiner1 : " + stringJoiner1.toString()); System.out.println("stringJoiner1 : " + stringJoiner2.toString()); // join() String[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" }; String week = String.join(", ", days); System.out.println("Week : " + week); } }
true
2491da6b83a6e57ea5a7725ddb7ae5f9fbaa7a93
Java
yongganzhang/spring-study
/spring-ioc-01/src/main/java/com/shsxt/demo/GoodsService.java
UTF-8
182
1.742188
2
[]
no_license
package com.shsxt.demo; public class GoodsService { public void getGoodsInfo () { System.out.println("外星人 贼便宜。。。。"); } }
true
ca983b51c68aa95d5501936ab75b9672526b2f5a
Java
akashantil/Problem-Solving
/Pepcoding Lectures/src/DS/ClientStack.java
UTF-8
586
2.53125
3
[]
no_license
package DS; public class ClientStack { public static void main(String[] args) { // TODO Auto-generated method stub stack st = new stack(4); st.push(10); st.display(); st.push(20); st.display(); st.push(30); st.display(); st.push(40); st.display(); st.push(50); st.display(); System.out.println(st.pop()); st.display(); System.out.println(st.pop()); st.display(); System.out.println(st.pop()); st.display(); System.out.println(st.pop()); st.display(); System.out.println(st.pop()); st.display(); } }
true
03d5e5510879d2513d4788961db68749d14ed7f9
Java
jeon3029/coding-interview-study
/Cracking_The_Coding_Interview/Chap9_Interview_Questions/01_Arrays_And_String/1.1_Duplicate/jeon3029/Solution.java
UTF-8
606
3.59375
4
[]
no_license
//Q1. 문자열이 주어졌을 때 이 문자열에 같은 문자가 중복되어 등장하는지 확인하는 알고리즘 public class Solution{ public static void main(String[] args) { //Assume string is all ASCII code String s = args[0]; boolean[] check = new boolean[256]; // 문자열 중복 확인 변수 for(int i=0;i<s.length();i++){ char c = s.charAt(i); int t = (int)c; //System.out.println(t); if(check[t]==true) { System.out.println(false); return; } check[t]=true; } System.out.println(true); return; } }
true
4940fd748a4ce18a4f878abef471483e75b435df
Java
HenokZewdie/Login
/src/main/java/login/Security.java
UTF-8
1,720
2.140625
2
[]
no_license
package login; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class Security extends WebSecurityConfigurerAdapter{ //HttpServletRequest serve; // HttpSession session = serve.getSession(); // String name = (String) serve.getAttribute("nameSession"); @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests().anyRequest().authenticated(); http .formLogin().failureUrl("/login?error") .defaultSuccessUrl("/") .loginPage("/login") .permitAll() .and() .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login") .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("pass").roles("user"); } }
true
46bab25559994ce16a061d0106e4a96dea68615b
Java
o-w-o/dot
/src/main/java/o/w/o/api/MyApi.java
UTF-8
1,836
2.078125
2
[ "Apache-2.0" ]
permissive
package o.w.o.api; import lombok.extern.slf4j.Slf4j; import o.w.o.domain.core.authorization.domain.AuthorizedUser; import o.w.o.domain.core.user.domain.User; import o.w.o.domain.core.user.service.UserService; import o.w.o.domain.core.user.service.dto.UserProfile; import o.w.o.domain.core.user.service.dtomapper.UserMapper; import o.w.o.infrastructure.definition.ApiResult; import o.w.o.infrastructure.util.ServiceUtil; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; /** * 用户相关 API * * @author symbols@dingtalk.com * @version 1.0 * @date 2020/2/5 */ @Slf4j @RestController @RequestMapping("/api/my") @PreAuthorize("hasRole('ROLE_USER')") public class MyApi { @Resource private UserMapper userMapper; @Resource private UserService userService; @GetMapping("profile") public ApiResult<UserProfile> getOneUserProfile() { var id = ServiceUtil.getPrincipalUserId(); var u = userService.getUserById(id).guard(); return ApiResult.of(userMapper.userToUserProfile(u)); } @PatchMapping("profile") public ApiResult<UserProfile> modifyOneUserProfile(@RequestBody User u) { return ApiResult.of( userMapper.userToUserProfile( userService.modifyProfile(u, ServiceUtil.getPrincipalUserId()) .guard() ) ); } @PatchMapping(path = "password") public ApiResult<Boolean> modifyOneUserPassword( @RequestParam String prevPassword, @RequestParam String password, @AuthenticationPrincipal AuthorizedUser authorizedUser ) { return ApiResult.of( userService.modifyPassword(authorizedUser.getId(), password, prevPassword) .guard() ); } }
true
2b65a942e769b72173084423b998c0868913021f
Java
paullewallencom/java-978-1-7888-3611-1
/_src/Chapter07/src/test/java/com/packtpublishing/tdd/funcprog/functions/ReversePolishNotationTest.java
UTF-8
1,762
3.046875
3
[ "MIT", "Apache-2.0" ]
permissive
package com.packtpublishing.tdd.funcprog.functions; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ReversePolishNotationTest { private ReversePolishNotation reversePolishNotation = new ReversePolishNotation(); @Test(expected = NotReversePolishNotationError.class) public void emptyInputThrowsError() { reversePolishNotation.compute(""); } @Test(expected = NotReversePolishNotationError.class) public void notANumberThrowsError() { reversePolishNotation.compute("a"); } @Test public void oneDigitReturnsNumber() { assertThat(reversePolishNotation.compute("0")).isEqualTo(0); } @Test public void moreThanOneDigitReturnsNumber() { assertThat(reversePolishNotation.compute("120")).isEqualTo(120); } @Test public void addOperationReturnsCorrectValue() { assertThat(reversePolishNotation.compute("1 2 +")).isEqualTo(3); } @Test public void subtractOperationReturnsCorrectValue() { assertThat(reversePolishNotation.compute("2 1 -")).isEqualTo(1); } @Test public void multiplyOperationReturnsCorrectValue() { assertThat(reversePolishNotation.compute("2 1 *")).isEqualTo(2); } @Test public void divideOperationReturnsCorrectValue() { assertThat(reversePolishNotation.compute("2 2 /")).isEqualTo(1); } @Test public void multipleAddOperationsReturnCorrectValue() { assertThat(reversePolishNotation.compute("1 2 5 + +")).isEqualTo(8); } @Test public void multipleDifferentOperationsReturnCorrectValue() { assertThat(reversePolishNotation.compute("5 12 + 3 -")).isEqualTo(14); } @Test public void aComplexTest() { assertThat(reversePolishNotation.compute("5 1 2 + 4 * + 3 -")).isEqualTo(14); } }
true
74c883ed04790e5de37db015c39d8289b79ce6c2
Java
cute-jumper/LeetCode
/Java/401-450/AllOne.java
UTF-8
3,755
3.46875
3
[]
no_license
public class AllOne { Map<String, Node> map = new HashMap<>(); static class VNode { int val; VNode prev; VNode next; Node head; Node tail; int size; public VNode(int val) { this.val = val; head = new Node(); head.parent = this; tail = new Node(); tail.parent = this; head.next = tail; tail.prev = head; size = 0; } public void removeNode(Node node) { node.prev.next = node.next; node.next.prev = node.prev; size--; } public void addNode(Node node) { node.parent = this; node.prev = head; node.next = head.next; head.next = node; node.next.prev = node; size++; } public String getHeadKey() { return head.next.key; } } static class Node { String key; VNode parent; Node prev; Node next; } VNode vhead = new VNode(Integer.MAX_VALUE); VNode vtail = new VNode(Integer.MIN_VALUE); public VNode getSmallerVNode(VNode vnode) { if (vnode.next.val == vnode.val - 1) return vnode.next; VNode n = new VNode(vnode.val - 1); n.next = vnode.next; n.prev = vnode; vnode.next = n; n.next.prev = n; return n; } public VNode getGreaterVNode(VNode vnode) { if (vnode.prev.val == vnode.val + 1 || vnode == vtail && vnode.prev.val == 1) return vnode.prev; VNode n = new VNode(vnode == vtail ? 1 : vnode.val + 1); n.prev = vnode.prev; n.next = vnode; vnode.prev = n; n.prev.next = n; return n; } public void removeVNode(VNode vnode) { vnode.next.prev = vnode.prev; vnode.prev.next = vnode.next; } /** Initialize your data structure here. */ public AllOne() { vhead.next = vtail; vtail.prev = vhead; } /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */ public void inc(String key) { if (map.containsKey(key)) { Node node = map.get(key); VNode parent = node.parent; parent.removeNode(node); VNode newParent = getGreaterVNode(parent); newParent.addNode(node); if (parent.size == 0) removeVNode(parent); } else { Node node = new Node(); node.key = key; VNode parent = getGreaterVNode(vtail); parent.addNode(node); map.put(key, node); } } /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */ public void dec(String key) { if (!map.containsKey(key)) return; Node node = map.get(key); VNode parent = node.parent; parent.removeNode(node); if (parent.val == 1) { map.remove(key); } else { VNode vnode = getSmallerVNode(parent); vnode.addNode(node); } if (parent.size == 0) removeVNode(parent); } /** Returns one of the keys with maximal value. */ public String getMaxKey() { if (vhead.next == vtail) return ""; return vhead.next.getHeadKey(); } /** Returns one of the keys with Minimal value. */ public String getMinKey() { if (vtail.prev == vhead) return ""; return vtail.prev.getHeadKey(); } } /** * Your AllOne object will be instantiated and called as such: * AllOne obj = new AllOne(); * obj.inc(key); * obj.dec(key); * String param_3 = obj.getMaxKey(); * String param_4 = obj.getMinKey(); */
true
544057e85fb50c8e59a4555888f5a8f9621665f0
Java
CJ-Zheng1023/springcloud-alibaba-starter
/springcloud-alibaba-starter-product/src/main/java/com/afterwin/product/controller/ProductController.java
UTF-8
841
1.96875
2
[]
no_license
package com.afterwin.product.controller; import com.afterwin.product.api.UserApi; import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter; import com.alibaba.csp.sentinel.annotation.SentinelResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @description: * @author: zhengchj * @create: 2020-04-29 09:32 **/ @RestController public class ProductController { @Autowired private UserApi userApi; private int i = 0; @GetMapping("/show/product") public String queryProduct(){ String username = userApi.name(); return username + "'s product is computer"; } @GetMapping("/count") public int count(){ i++; return i; } }
true
857dc88e7f47a35473787e83f6a2c78cf28ebcff
Java
sunwenjie/csa_pro
/src/main/java/com/asgab/entity/MailReceiver.java
UTF-8
656
2.078125
2
[]
no_license
package com.asgab.entity; public class MailReceiver { private Long id; private Long mailId; private String mailAddress; private String copyTo; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getMailId() { return mailId; } public void setMailId(Long mailId) { this.mailId = mailId; } public String getMailAddress() { return mailAddress; } public void setMailAddress(String mailAddress) { this.mailAddress = mailAddress; } public String getCopyTo() { return copyTo; } public void setCopyTo(String copyTo) { this.copyTo = copyTo; } }
true
7b6ca56b6a014fcb8420e13ea6dd3a319fbd8114
Java
tayduivn/training
/service/src/converted/gov/georgia/dhr/dfcs/sacwis/conversion/Csub38s.java
UTF-8
75,541
1.59375
2
[]
no_license
package gov.georgia.dhr.dfcs.sacwis.conversion; import gov.georgia.dhr.dfcs.sacwis.conversion.*; import gov.georgia.dhr.dfcs.sacwis.structs.input.CSUB38SI; import gov.georgia.dhr.dfcs.sacwis.structs.output.CSUB38SO; import gov.georgia.dhr.dfcs.sacwis.structs.input.CSES06DI; import gov.georgia.dhr.dfcs.sacwis.structs.output.CSES06DO; import gov.georgia.dhr.dfcs.sacwis.structs.input.CINV51DI; import gov.georgia.dhr.dfcs.sacwis.structs.output.CINV51DO; import gov.georgia.dhr.dfcs.sacwis.structs.input.CCMN45DI; import gov.georgia.dhr.dfcs.sacwis.structs.output.CCMN45DO; import gov.georgia.dhr.dfcs.sacwis.structs.input.CCMN44DI; import gov.georgia.dhr.dfcs.sacwis.structs.output.CCMN44DO; import gov.georgia.dhr.dfcs.sacwis.structs.input.CINT21DI; import gov.georgia.dhr.dfcs.sacwis.structs.output.CINT21DO; import gov.georgia.dhr.dfcs.sacwis.core.validation.wtc.WtcHelperConstants; import gov.georgia.dhr.dfcs.sacwis.core.message.Messages; /*************************************************************************** ** Module File: csub38s.src ** ** Service Name: csub38s ** ** Description: This is the retrieval service for ** the Legal Action/Outcome window. ** ** Environment: HP-UX V9.0 ** FOUNDATION V2.0 for Unix (Construction, Production) ** HP-UX Ansi C Compiler ** ** Date Created: 12Oct95 ** ** Programmer: Mary Sladewski ** ** Archive Information: $Revision: 1.0 $ ** $Date: 27 May 1996 19:17:16 $ ** $Modtime: 30 Mar 1996 00:27:02 $ ** $Author: pvcs $ ** ** Change History: ** Date User Description ** -------- -------- -------------------------------------------------- ** 18Oct95 sladewmf Initial check-in. ** 12/07/95 WILSONET SIR#2163 - Inserted a new call to CINV51 in order ** to get the IdPerson given the Stage and the Role of ** 'CLIENT' (CL). Switch should check for VICTIM (VC) ** then VICTIM PERPETRATOR (VP) and then CL. In APS ** Service Delivery the role is always CL. ** 12/14/95 WILSONET SIR#2171, 2175, 2178, 2185 - (Search on SIR#2171) ** The Retrieve Service was modified to correspond to ** the new window code and to meet standards ** ** 02/20/96 DYARGR SIR 3272 - Need to have the CdStageProgram returned ** to the client, in case the calling window does not ** pass it in. ** ** 1/23/03 DWW Added following line for error handling: ** if (RetVal == FND_SUCESS) { rc=FND_SUCCESS; } ***************************************************************************/ /************************************************************************** ** Service Include Files ***************************************************************************/ /* ** Extern for version control table. */ public class Csub38s { public static final String VICTIM = "VC"; public static final String VICTIM_PERPETRATOR = "VP"; /* ** Declare FOUNDATION variables */ public static final String CLIENT = "CL"; public static final String PRIMARY_CHILD = "PC"; public static final String SUB_CARE = "SUB"; public static final String ADOPTION = "ADO"; public static final String FAM_REUNIFICATION = "FRE"; public static final String FAM_SUBCARE = "FSU"; public static final String FAM_PRESERVATION = "FPR"; /* SIR 5043 */ public static final String INVESTIGATION = "INV"; /* RIOSJA, SIR 19973, SIR 16227 */ public static final String POST_ADOPT = "PAD"; public static final String CAPS_PROG_CPS = "CPS"; public static final String STATUS_NEW = "NEW"; CSUB38SO CSUB38S(CSUB38SI csub38si) { CSUB38SO csub38so = new CSUB38SO(); ErrorStatus ServiceStatus = null; ErrorStatus pServiceStatus = ServiceStatus; pServiceStatus.explan_code = 0; pServiceStatus.severity = 0; int rc = FND_SUCCESS;/* Return code */ int i430 = 0; int RetVal = SUCCESS;/* SIR#2163 - RetVal added */ CSES06DI pCSES06DInputRec = null;/* Legal Action simple retrieve */ /* ** Declare FOUNDATION variables */ /* ** Declare local variables */ CSES06DO pCSES06DOutputRec = null; CINV51DI pCINV51DInputRec = null; CINV51DO pCINV51DOutputRec = null; CCMN45DI pCCMN45DInputRec = null;/* Event simple retrieve */ CCMN45DO pCCMN45DOutputRec = null; CCMN44DI pCCMN44DInputRec = null;/* Get NmPersonFull given IdPerson */ CCMN44DO pCCMN44DOutputRec = null; CINT21DI pCINT21DInputRec = null;/* Full row retrieval from Stage table */ CINT21DO pCINT21DOutputRec = null; /* ** Set rc to ARC_SUCCESS */ rc = ARC_PRFServiceStartTime_TUX(csub38si.getArchInputStruct()); rc = ARC_UTLGetDateAndTime(csub38so.getDtSysDtGenericSysdate() , 0); Arcxmlerrors.PROCESS_TUX_RC_ERROR(); /************************************************************************* ** Call CINT21D to retireve CdStageProgram *************************************************************************/ /* ** Allocate memory for DAM Input and Output Structures */ pCINT21DInputRec = new CINT21DI(); pCINT21DOutputRec = new CINT21DO(); pCINT21DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINT21DInputRec.setUlIdStage(csub38si.getUlIdStage()); rc = cint21dQUERYdam(sqlca, pCINT21DInputRec, pCINT21DOutputRec); switch (rc) { case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; // SIR#2163 - Set RetVal to FND_SUCCESS RetVal = SUCCESS; csub38so.setSzCdStageProgram(pCINT21DOutputRec.getSzCdStageProgram()); if (0 == csub38si.getUlIdEvent()) { if ((0 == INVESTIGATION.compareTo(csub38si.getSzCdStage()) && (0 == CAPS_PROG_CPS.compareTo(pCINT21DOutputRec.getSzCdStageProgram()))) || (0 == FAM_SUBCARE.compareTo(csub38si.getSzCdStage())) || (0 == FAM_REUNIFICATION.compareTo(csub38si.getSzCdStage())) || (0 == FAM_PRESERVATION.compareTo(csub38si.getSzCdStage()))) { break; } else if ((0 == SUB_CARE.compareTo(csub38si.getSzCdStage())) || (0 == ADOPTION.compareTo(csub38si.getSzCdStage())) || (0 == POST_ADOPT.compareTo(csub38si.getSzCdStage()))) { // // (END): Retrieve DAM: cinv51d // Get IdPerson given IdStage & Role // // Allocate memory for DAM Input and Output Structures pCINV51DInputRec = new CINV51DI(); pCINV51DOutputRec = new CINV51DO(); pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec.setSzCdStagePersRole(PRIMARY_CHILD); // Call CLSS11D to retrieve the previous version's services. rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); // Analyze return code switch (rc) { case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and Output Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); // GMS -- FINANCIAL ENHANCEMENT switch (rc) { // Success Case for Dam CCMND9D case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } } // // (END): Retrieve DAM: cinv51d // Get IdPerson given IdStage & Role // // else CdStageProgram is APS else { // // (BEGIN): Retrieve DAM: cinv51d(VC) // Get IdPerson given IdStage & Role // // Allocate memory for DAM Input and Output Structures pCINV51DInputRec = new CINV51DI(); pCINV51DOutputRec = new CINV51DO(); pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec.setSzCdStagePersRole(VICTIM); rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); // Analyze return code switch (rc) { // Success Case for Dam CLSC59D case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and Output Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); // Call CAUD17D. Update the services for the current // version. rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); // Analyze return code switch (rc) { // Success Case for Dam CINV95D (CIU) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; // Success Case for Dam CSES66D (CIU) case NO_DATA_FOUND: pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec.setSzCdStagePersRole(VICTIM_PERPETRATOR); rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); switch (rc) { // Success Case for Dam CSES68D (CIU) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and Output // Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); switch (rc) { // SQL Not Found Case for Dam CSES68D (CIU) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; // Success Case for Dam CSES66D (CIU) case NO_DATA_FOUND: pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec.setSzCdStagePersRole(CLIENT); // Call CLSS37D to retrieve the previous versions // counties. rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); // Analyze error code switch (rc) { // Success Case for Dam CSES68D (CIU) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and // Output Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); // Analyze return code switch (rc) { // SQL Not Found Case for Dam CSES68D (CIU) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; // In this case SQL_NOT_FOUND, a data base access // error has really occured, since a previously // locked version must have services before is can be // saved as locked and the services of a locked // version may not be deleted. // Thus, if this case occurs, the database // couldn't find the rows and should be processed // as a save failed. csub38so.setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); // // (END): Retrieve DAM: ccmn44d Get NmPersonFull given IdPerson // break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR() break; } break; // // (END): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // default for call to CINV51D(CL) default : //## BEGIN TUX/XML: Turn OutputMsg into an XML buffer and send back to Tuxedo Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); } break; // default for CINV51D(VP) default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); } } } // else -> IdEvent != 0 else { // Allocate memory for DAM Input and Output Structures pCCMN45DInputRec = new CCMN45DI(); pCCMN45DOutputRec = new CCMN45DO(); pCCMN45DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN45DInputRec.setUlIdEvent(csub38si.getUlIdEvent()); rc = ccmn45dQUERYdam(sqlca, pCCMN45DInputRec, pCCMN45DOutputRec); switch (rc) { // Success Case for Dam CSES66D (CIU) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; // SIR#2163 - Set RetVal to FND_SUCCESS RetVal = SUCCESS; csub38so.getROWCSUB38SOG00().setSzCdEventType(pCCMN45DOutputRec.getROWCCMN45DO().getSzCdEventType()); csub38so.getROWCSUB38SOG00().setSzTxtEventDescr(pCCMN45DOutputRec.getROWCCMN45DO().getSzTxtEventDescr()); csub38so.getROWCSUB38SOG00().setSzCdTask(pCCMN45DOutputRec.getROWCCMN45DO().getSzCdTask()); csub38so.getROWCSUB38SOG00().setSzCdEventStatus(pCCMN45DOutputRec.getROWCCMN45DO().getSzCdEventStatus()); csub38so.getROWCSUB38SOG00().setUlIdEvent(pCCMN45DOutputRec.getROWCCMN45DO().getUlIdEvent()); csub38so.getROWCSUB38SOG00().setUlIdStage(pCCMN45DOutputRec.getROWCCMN45DO().getUlIdStage()); csub38so.getROWCSUB38SOG00().setUlIdEventPerson(pCCMN45DOutputRec.getROWCCMN45DO().getUlIdPerson()); csub38so.getROWCSUB38SOG00().setDtDtEventOccurred(pCCMN45DOutputRec.getROWCCMN45DO().getDtDtEventOccurred()); csub38so.getROWCSUB38SOG00().setTsLastUpdate(pCCMN45DOutputRec.getROWCCMN45DO().getTsLastUpdate()); break; // Success Case for Dam CSES68D (CIU) case NO_DATA_FOUND: pServiceStatus.severity = FND_SEVERITY_ERROR; pServiceStatus.explan_code = Messages.MSG_DETAIL_DELETED; // Set RetVal to FAIL if SQL_NOT_FOUND RetVal = Csub50s.FND_FAIL; break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); // Set RetVal to FAIL if SQL_NOT_FOUND RetVal = Csub50s.FND_FAIL; // // (END): Retrieve DAM: ccmn44d Get NmPersonFull given IdPerson // break; } if ((0 == STATUS_NEW.compareTo(csub38so.getROWCSUB38SOG00().getSzCdEventStatus())) && (RetVal == SUCCESS)) { if ((0 == INVESTIGATION.compareTo(csub38si.getSzCdStage()) && (0 == CAPS_PROG_CPS.compareTo(pCINT21DOutputRec.getSzCdStageProgram()))) || (0 == FAM_SUBCARE.compareTo(csub38si.getSzCdStage())) || (0 == FAM_REUNIFICATION.compareTo(csub38si.getSzCdStage())) || (0 == FAM_PRESERVATION.compareTo(csub38si.getSzCdStage()))) { break; } else if ((0 == SUB_CARE.compareTo(csub38si.getSzCdStage())) || (0 == ADOPTION.compareTo(csub38si.getSzCdStage())) || (0 == POST_ADOPT.compareTo(csub38si.getSzCdStage()))) { // // (END): Retrieve DAM: cinv51d // Get IdPerson given IdStage & Role // // Allocate memory for DAM Input and Output Structures pCINV51DInputRec = new CINV51DI(); pCINV51DOutputRec = new CINV51DO(); pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec// SIR 2497 .setSzCdStagePersRole(PRIMARY_CHILD); // Call CAUD08D to add the previous // version's counties to the new // version rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); switch (rc) { // SQL Not Found Case for Dam CSES68D (CIU) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so// SIR 2497 .setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); csub38so// SIR 2974 (not a typo) .getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and Output Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec// 2090 .setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); // Set rc to ARC_SUCCESS rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); switch (rc) { // SQL Not Found Case for DAM CSES66D (CIU) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so// 2080 .setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); break; default : Arcxmlerrors// 2030 .PROCESS_TUX_SQL_ERROR(); break; } // // (END): Retrieve DAM: ccmn44d Get NmPersonFull given IdPerson // break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } } // END else if((SUB_CARE == pInputMsg->szCdStage) || // (ADOPTION == pInputMsg->szCdStage) || // (POST_ADOPT == pInputMsg->szCdStage)) // else CdStageProgram is APS else { // // (BEGIN): Retrieve DAM: cinv51d(VC) // Get IdPerson given IdStage & Role // // Allocate memory for DAM Input and Output Structures pCINV51DInputRec = new CINV51DI(); pCINV51DOutputRec = new CINV51DO(); pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec.setSzCdStagePersRole(VICTIM); rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); switch (rc) { // SQL Not Found Case for DAM CINV95D (CIU) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so// 2090 .setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and Output Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); switch (rc) { // Success Case for DAM CINV95D (CIR) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so// 2030 .setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); // // (END): Retrieve DAM: cinv51d Get IdPerson given IdStage & Role // break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; // Success Case for DAM CSES66D Call (CIR) case NO_DATA_FOUND: pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec.setSzCdStagePersRole(VICTIM_PERPETRATOR); rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); // Analyze return code switch (rc) { // Success Case for DAM CSES68D (CIR) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and Output // Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); // Call DAM rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); // Analyze return code switch (rc) { // SQL Not Found Case for DAM CSES68D (CIR) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; // SQL Not Found Case for DAM CSES66D Call (CIR) case NO_DATA_FOUND: pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec.setSzCdStagePersRole(CLIENT); rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); // Analyze return code switch (rc) { // SQL Not Found Case for DAM CINV95D (CIR) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // PROCESS_TUX_SQL_ERROR_TRANSACT is called only when there is an unexpected // SQL error returned from the DAM. csub38so.getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and // Output Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); // Analyze return code switch (rc) { // Success Case for Dam CINV95D (CIO) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); // // (END): Retrieve DAM: ccmn44d Get NmPersonFull given IdPerson // break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); RetVal = Csub50s.FND_FAIL; break; } break; // // (END): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // default for call to CINV51D(CL) default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); } break; // default for CINV51D(VP) default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); } } } // else if Window Mode is New Using else if (WINDOW_MODE_NEW_USING == csub38si.getCSysIndDamCalled()) { // // (BEGIN): Retrieve DAM: cses06d // Legal Action simple retrieve // // Allocate memory for DAM Input and Output Structures pCSES06DInputRec = new CSES06DI(); pCSES06DOutputRec = new CSES06DO(); pCSES06DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCSES06DInputRec.setUlIdLegalActEvent(csub38si.getUlIdEvent()); rc = cses06dQUERYdam(sqlca, pCSES06DInputRec, pCSES06DOutputRec); switch (rc) { // Success Case for Dam CSES68D (CIO) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; // SIR#2163 - Set RetVal to FND_SUCCESS RetVal = SUCCESS; csub38so.getROWCSUB38SOG01().setUlIdLegalActEvent(pCSES06DOutputRec.getUlIdLegalActEvent()); csub38so.getROWCSUB38SOG01().setTsLastUpdate(pCSES06DOutputRec.getTsLastUpdate()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCSES06DOutputRec.getUlIdPerson()); // unsigned short rc=0; csub38so.getROWCSUB38SOG01().setDtDtLegalActDateFiled(pCSES06DOutputRec.getDtDtLegalActDateFiled()); csub38so.getROWCSUB38SOG01().setDtDtLegalActOutcomeDt(pCSES06DOutputRec.getDtDtLegalActOutcomeDt()); csub38so.getROWCSUB38SOG01().setCIndLegalActDocsNCase(pCSES06DOutputRec.getCIndLegalActDocsNCase()); csub38so.getROWCSUB38SOG01().setSzCdLegalActAction(pCSES06DOutputRec.getSzCdLegalActAction()); csub38so.getROWCSUB38SOG01().setSzCdLegalActActnSubtype(pCSES06DOutputRec.getSzCdLegalActActnSubtype()); csub38so.getROWCSUB38SOG01().setSzCdLegalActOutcome(pCSES06DOutputRec.getSzCdLegalActOutcome()); csub38so.getROWCSUB38SOG01().setSzTxtLegalActComment(pCSES06DOutputRec.getSzTxtLegalActComment()); // // End Call to CSES69D // else if ((0 == SUB_CARE.compareTo(csub38si.getSzCdStage())) || (0 == ADOPTION.compareTo(csub38si.getSzCdStage())) || (0 == POST_ADOPT.compareTo(csub38si.getSzCdStage()))) { // // (END): Retrieve DAM: cinv51d // Get IdPerson given IdStage & Role // // Allocate memory for DAM Input and Output Structures pCINV51DInputRec = new CINV51DI(); pCINV51DOutputRec = new CINV51DO(); pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec.setSzCdStagePersRole(PRIMARY_CHILD); rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); switch (rc) { // Success Case for Dam CSEC63D (CIO) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and Output // Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); // Call DAM rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); // Analyze return code switch (rc) { // SQL Not Found Case for Dam CSEC63D (CIO) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } } // // (END): Retrieve DAM: cinv51d // Get IdPerson given IdStage & Role // // else CdStageProgram is APS else { // // (BEGIN): Retrieve DAM: cinv51d(VC) // Get IdPerson given IdStage & Role // // Allocate memory for DAM Input and Output Structures pCINV51DInputRec = new CINV51DI(); pCINV51DOutputRec = new CINV51DO(); pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec.setSzCdStagePersRole(VICTIM); rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); switch (rc) { // SQL Not Found Case for Dam CSES68D (CIO) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and Output // Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); switch (rc) { // SQL Not Found Case for Dam CINV95D (CIO) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; // Success Case for Dam CSES67D (ACP) case NO_DATA_FOUND: pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec.setSzCdStagePersRole(VICTIM_PERPETRATOR); rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); // Analyze return code switch (rc) { // Success Case for Dam CSES68D (ACP) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and Output // Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); // Analyze return code switch (rc) { // SQL Not Found Case for Dam CSES68D (ACP) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; // SQL Not Found Case for Dam CSES67D (ACP) case NO_DATA_FOUND: pCINV51DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCINV51DInputRec.setUlIdStage(csub38si.getUlIdStage()); pCINV51DInputRec.setSzCdStagePersRole(CLIENT); rc = cinv51dQUERYdam(sqlca, pCINV51DInputRec, pCINV51DOutputRec); // Analyze return code switch (rc) { // Success Case for Dam CSES67D (APR) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCINV51DOutputRec.getUlIdTodoPersAssigned()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and // Output Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); // Call DAM if an Ethnicity is added or deleted rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); // Analyze return code switch (rc) { // Success Case for Dam CSES68D (APR) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); RetVal = Csub50s.FND_FAIL; break; } break; // // (END): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // default for call to CINV51D(CL) default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); } break; // default for CINV51D(VP) default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); } } break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); // SIR#2163 - Set RetVal to FND_FAIL RetVal = Csub50s.FND_FAIL; break; } } // // (END): Retrieve DAM: cses06d // Legal Action simple retrieve // // Else -> window mode is anything but New Using and RetVal = Succ. else if (RetVal == SUCCESS) { // // (BEGIN): Retrieve DAM: cses06d // Legal Action simple retrieve // // Allocate memory for DAM Input and Output Structures pCSES06DInputRec = new CSES06DI(); pCSES06DOutputRec = new CSES06DO(); pCSES06DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCSES06DInputRec.setUlIdLegalActEvent(csub38si.getUlIdEvent()); // Do nothing, the output message just returns success or // failure rc = cses06dQUERYdam(sqlca, pCSES06DInputRec, pCSES06DOutputRec); // Analyze return code switch (rc) { // SQL Not Found Case for Dam CSES68D (ACP) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; // SIR#2163 - Set RetVal to FND_SUCCESS RetVal = SUCCESS; csub38so.getROWCSUB38SOG01().setUlIdLegalActEvent(pCSES06DOutputRec.getUlIdLegalActEvent()); csub38so.getROWCSUB38SOG01().setTsLastUpdate(pCSES06DOutputRec.getTsLastUpdate()); csub38so.getROWCSUB38SOG01().setUlIdPerson(pCSES06DOutputRec.getUlIdPerson()); csub38so.getROWCSUB38SOG01().setDtDtLegalActDateFiled(pCSES06DOutputRec.getDtDtLegalActDateFiled()); csub38so.getROWCSUB38SOG01().setDtDtLegalActOutcomeDt(pCSES06DOutputRec.getDtDtLegalActOutcomeDt()); csub38so.getROWCSUB38SOG01().setCIndLegalActDocsNCase(pCSES06DOutputRec.getCIndLegalActDocsNCase()); csub38so.getROWCSUB38SOG01().setSzCdLegalActAction(pCSES06DOutputRec.getSzCdLegalActAction()); csub38so.getROWCSUB38SOG01().setSzCdLegalActActnSubtype(pCSES06DOutputRec.getSzCdLegalActActnSubtype()); csub38so.getROWCSUB38SOG01().setSzCdLegalActOutcome(pCSES06DOutputRec.getSzCdLegalActOutcome()); csub38so.getROWCSUB38SOG01().setSzTxtLegalActComment(pCSES06DOutputRec.getSzTxtLegalActComment()); // // (BEGIN): Retrieve DAM: ccmn44d // Get NmPersonFull given IdPerson // // Allocate memory for DAM Input and // Output Structures pCCMN44DInputRec = new CCMN44DI(); pCCMN44DOutputRec = new CCMN44DO(); pCCMN44DInputRec.setArchInputStruct(csub38si.getArchInputStruct()); pCCMN44DInputRec.setUlIdPerson(csub38so.getROWCSUB38SOG01().getUlIdPerson()); rc = ccmn44dQUERYdam(sqlca, pCCMN44DInputRec, pCCMN44DOutputRec); // Analyze return code for CMSC43D switch (rc) { // SQL Not Found Case for Dam CSES67D (ACP) case WtcHelperConstants.SQL_SUCCESS: pServiceStatus.severity = FND_SEVERITY_OK; pServiceStatus.explan_code = SUCCESS; csub38so.setSzNmPersonFull(pCCMN44DOutputRec.getSzNmPersonFull()); break; default :// default for CSES06D Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); break; } break; default : Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); // SIR#2163 - Set RetVal to FND_FAIL RetVal = Csub50s.FND_FAIL; break; } } } break; default :// default for CSES06D Arcxmlerrors.PROCESS_TUX_SQL_ERROR(); // Set RetVal to FND_FAIL RetVal = Csub50s.FND_FAIL; break; } /* ** Load Translation Map */ /* ** Stop Performance Timer */ ARC_PRFServiceStopTime_TUX(csub38si.getArchInputStruct() , csub38so.getArchOutputStruct()); if (RetVal == SUCCESS) { rc = SUCCESS; } if (Arcxmlerrors.TUX_SUCCESS != rc) { userlog("explan_code=%d, rc=%d", pServiceStatus.explan_code, rc); ARC_TUXHandleRCError(Math.abs(rc) , pServiceStatus, CSourceUtils.getCurrentFileName() , CSourceUtils.getCurrentLineNumber()); } else { if (tpcommit(0) == - 1) {// if they are the same type but one starts on or after the other ends, // it's still ok to insert. it's not overlapping System.err.println("ERROR: tpcommit failed (" + (tpstrerror(tperrno)) + ")"); userlog("ERROR: tpcommit failed (%s)\n", tpstrerror(tperrno)); pServiceStatus.severity = FND_SEVERITY_ERROR; pServiceStatus.explan_code = Arcxmlerrors.ARC_ERR_TUX_TPCOMMIT_FAILED; rc = Arcxmlerrors.ARC_ERR_TUX_TPCOMMIT_FAILED; Arcxmlerrors.PROCESS_TUX_RC_ERROR(); } userlog("APPL STATUS=%d", pServiceStatus.explan_code); } return csub38so; } }
true
f2c8beefca064b6dd226eb09a3312f69f869ae75
Java
abysal/Kanpro
/app/src/main/java/com/example/collegeapp/Activity/UpdateSubmission.java
UTF-8
11,195
1.78125
2
[]
no_license
package com.example.collegeapp.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.StrictMode; import android.provider.OpenableColumns; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.collegeapp.API.SubmissionAPI; import com.example.collegeapp.Model.Submission; import com.example.collegeapp.Model.SubmissionResponse; import com.example.collegeapp.R; import com.example.collegeapp.Url.Url; import com.github.barteksc.pdfviewer.PDFView; import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener; import com.github.barteksc.pdfviewer.listener.OnPageChangeListener; import com.github.barteksc.pdfviewer.listener.OnPageErrorListener; import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle; import com.nbsp.materialfilepicker.MaterialFilePicker; import com.nbsp.materialfilepicker.ui.FilePickerActivity; import com.shockwave.pdfium.PdfDocument; import java.io.File; import java.util.List; import java.util.regex.Pattern; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class UpdateSubmission extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener, OnPageErrorListener { EditText et_assignment_title,et_assignment_links; TextView current_file; Button btn_browse_assignment_file,btn_submit_assignment; ActionBar actionBar; SubmissionAPI submissionAPI; private int pageNumber = 0; String submission_id; private String pdfFileName; private PDFView pdfView; public static final int FILE_PICKER_REQUEST_CODE = 1; private String pdfPath; String user_file,assign_id; SharedPreferences preferences; SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_submission); actionBar=getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle("Update Submission"); et_assignment_title=(EditText)findViewById(R.id.et_assignment_title); et_assignment_links=(EditText)findViewById(R.id.et_assignment_links); btn_browse_assignment_file=(Button)findViewById(R.id.btn_browse_assignment_file); btn_submit_assignment=(Button)findViewById(R.id.btn_submit_assignment); pdfView = (PDFView) findViewById(R.id.pdfView); current_file=(TextView)findViewById(R.id.current_file); Bundle bundle=getIntent().getExtras(); if (bundle!=null){ et_assignment_title.setText(bundle.getString("assignment_title")); et_assignment_links.setText(bundle.getString("assignment_links")); current_file.setText("Current File:"+bundle.getString("assignment_file_user")); submission_id=bundle.getString("id"); } btn_browse_assignment_file.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchPicker(); } }); btn_submit_assignment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (validate()){ updateSubmission(); } } }); } private void launchPicker() { new MaterialFilePicker() .withActivity(this) .withRequestCode(FILE_PICKER_REQUEST_CODE) .withHiddenFiles(true) .withFilter(Pattern.compile(".*\\.pdf$")) .withTitle("Select PDF file") .start(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode == RESULT_OK) { String path = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH); File file = new File(path); displayFromFile(file); if (path != null) { Log.d("Path: ", path); pdfPath = path; Toast.makeText(this, "Picked file: " + path, Toast.LENGTH_LONG).show(); } } } private void displayFromFile(File file) { Uri uri = Uri.fromFile(new File(file.getAbsolutePath())); pdfFileName = getFileName(uri); pdfView.fromFile(file) .defaultPage(pageNumber) .onPageChange(this) .enableAnnotationRendering(true) .onLoad(this) .scrollHandle(new DefaultScrollHandle(this)) .spacing(10) // in dp .onPageError(this) .load(); } public String getFileName(Uri uri) { String result = null; if (uri.getScheme().equals("content")) { Cursor cursor = getContentResolver().query(uri, null, null, null, null); try { if (cursor != null && cursor.moveToFirst()) { result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); } } finally { if (cursor != null) { cursor.close(); } } } if (result == null) { result = uri.getLastPathSegment(); } return result; } @Override public void loadComplete(int nbPages) { PdfDocument.Meta meta = pdfView.getDocumentMeta(); printBookmarksTree(pdfView.getTableOfContents(), "-"); } public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) { for (PdfDocument.Bookmark b : tree) { //Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx())); if (b.hasChildren()) { printBookmarksTree(b.getChildren(), sep + "-"); } } } @Override public void onPageChanged(int page, int pageCount) { pageNumber = page; setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount)); } @Override public void onPageError(int page, Throwable t) { } public void createInstance() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(Url.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); submissionAPI = retrofit.create(SubmissionAPI.class); } private void StrictMode(){ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } private void uploadFile() { if (pdfPath == null) { Toast.makeText(this, "Please select a file ", Toast.LENGTH_LONG).show(); return; } else { File file = new File(pdfPath); // Parsing any Media type file RequestBody rb=RequestBody.create(MediaType.parse("application/pdf"),file); MultipartBody.Part submission=MultipartBody.Part.createFormData("assignment_file_user",file.getName(),rb); createInstance(); Call<SubmissionResponse> call = submissionAPI.updateFile(submission); StrictMode(); try{ Response<SubmissionResponse> submissionResponseResponse=call.execute(); user_file="uploads\\"+submissionResponseResponse.body().getUser_file(); } catch (Exception e){ Toast.makeText(UpdateSubmission.this, "Error", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } } private void updateSubmission(){ final ProgressDialog pd = new ProgressDialog(this); pd.setMessage("Uploading File..."); pd.setCancelable(false); pd.show(); if (pdfPath!=null){ uploadFile(); preferences=this.getSharedPreferences("Userinfo", Context.MODE_PRIVATE); String id1=preferences.getString("id",""); createInstance(); Submission submission=new Submission(id1,assign_id,et_assignment_title.getText().toString(), et_assignment_links.getText().toString(),user_file); Call<SubmissionResponse> submissionResponseCall=submissionAPI.updateSubmission(submission_id,submission); submissionResponseCall.enqueue(new Callback<SubmissionResponse>() { @Override public void onResponse(Call<SubmissionResponse> call, Response<SubmissionResponse> response) { if(!response.isSuccessful()){ Toast.makeText(UpdateSubmission.this, "Code"+response.code(), Toast.LENGTH_SHORT).show(); pd.dismiss(); return; } else if (response.body().getSuc_message()!=null){ Toast.makeText(UpdateSubmission.this, response.body().getSuc_message(), Toast.LENGTH_SHORT).show(); Intent intent=new Intent(UpdateSubmission.this, Dashboard.class); startActivity(intent); finish(); pd.dismiss(); } } @Override public void onFailure(Call<SubmissionResponse> call, Throwable t) { Toast.makeText(UpdateSubmission.this, "Error:"+t.getMessage(), Toast.LENGTH_SHORT).show(); pd.dismiss(); } }); } else{ Toast.makeText(this, "Please select a submission file", Toast.LENGTH_SHORT).show(); pd.dismiss(); } } private boolean validate() { if (TextUtils.isEmpty(et_assignment_title.getText().toString())) { et_assignment_title.setError("Enter Assignment Title"); et_assignment_title.requestFocus(); return false; } if (TextUtils.isEmpty(et_assignment_links.getText().toString())) { et_assignment_links.setError("Enter Assignment Links"); et_assignment_links.requestFocus(); return false; } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId()==android.R.id.home){ super.onBackPressed(); } return super.onOptionsItemSelected(item); } }
true
82881eec0aaa8a727157088f12112964395b0afe
Java
iHelin/seven-generator
/src/main/java/io/github/ihelin/seven/generator/SevenGeneratorApplication.java
UTF-8
542
1.773438
2
[]
no_license
package io.github.ihelin.seven.generator; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Seven 代码生成器 * * @author iHelin ihelin@outlook.com * @since 2021-01-07 12:43 */ @SpringBootApplication @MapperScan("io.github.ihelin.seven.generator.dao") public class SevenGeneratorApplication { public static void main(String[] args) { SpringApplication.run(SevenGeneratorApplication.class, args); } }
true
ff642506dc313e5b52e6f4939e98b7e176cf7a0b
Java
zyxin13/p-recruit
/p-recruit-web/src/main/java/com/chinaredstar/recruit/controller/TestController.java
UTF-8
4,190
2.125
2
[]
no_license
package com.chinaredstar.recruit.controller; import com.chinaredstar.recruit.api.common.ServiceResult; import com.chinaredstar.recruit.api.service.OperationLogService; import com.chinaredstar.recruit.api.service.PushDataLogService; import com.chinaredstar.recruit.api.vo.OperationLogVo; import com.chinaredstar.recruit.api.vo.PushDataLogVo; import com.chinaredstar.recruit.common.Result; import com.chinaredstar.recruit.common.ResultCode; import com.wordnik.swagger.annotations.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * Created by yuxin.zou on 2017/11/22. */ @RestController @RequestMapping("/test") @Api(value = "test", description = "测试页面") public class TestController { private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class); @Autowired private OperationLogService operationLogService; @Autowired private PushDataLogService pushDataLogService; @ApiResponses(value = { @ApiResponse(code = 200, message = "请求成功"), @ApiResponse(code = 401, message = "未授权"), @ApiResponse(code = 403, message = "禁止访问"), @ApiResponse(code = 404, message = "返回数据为空"), @ApiResponse(code = 415, message = "请求参数错误"), @ApiResponse(code = 422, message = "校验错误"), @ApiResponse(code = 500, message = "服务器错误") }) @ApiOperation(value = "getOperationLogById", notes = "根据id获取操作日志信息") @RequestMapping(value = "/operationLog/{id}", method = RequestMethod.GET) public Result<OperationLogVo> getOperationLogById(@ApiParam("操作日志id") @PathVariable("id") Integer id) { if (id == null) { return Result.error(ResultCode.C415, "操作日志ID不能为空"); } try { ServiceResult<OperationLogVo> serviceResult = operationLogService.selectByPrimaryKey(id); if (serviceResult.isSuccess()) { return Result.success(serviceResult.getData()); } else { return Result.error(ResultCode.C500, serviceResult.getMessage()); } } catch (Exception e) { LOGGER.error("根据id{id}获取操作日志信息异常", id, e); return Result.error(ResultCode.C500, "根据id获取操作日志信息异常"); } } @ApiResponses(value = { @ApiResponse(code = 200, message = "请求成功"), @ApiResponse(code = 401, message = "未授权"), @ApiResponse(code = 403, message = "禁止访问"), @ApiResponse(code = 404, message = "返回数据为空"), @ApiResponse(code = 415, message = "请求参数错误"), @ApiResponse(code = 422, message = "校验错误"), @ApiResponse(code = 500, message = "服务器错误") }) @ApiOperation(value = "getPushDataLogById", notes = "根据id获取推送数据日志信息") @RequestMapping(value = "/pushDataLog/{id}", method = RequestMethod.GET) public Result<PushDataLogVo> getPushDataLogById(@ApiParam("推送数据日志id") @PathVariable("id") Integer id) { if (id == null) { return Result.error(ResultCode.C415, "推送数据日志ID不能为空"); } try { ServiceResult<PushDataLogVo> serviceResult = pushDataLogService.selectByPrimaryKey(id); if (serviceResult.isSuccess()) { return Result.success(serviceResult.getData()); } else { return Result.error(ResultCode.C500, serviceResult.getMessage()); } } catch (Exception e) { LOGGER.error("根据id{id}获取推送数据日志信息异常", id, e); return Result.error(ResultCode.C500, "根据id获取推送数据日志信息异常"); } } }
true
fbe2a942d7a4e4eca945bcb6082880e513f381f8
Java
deb-sandeep/DigitalCircuitSim
/src/main/java/com/sandy/apps/dcs/component/DCDJKFlipFlop.java
UTF-8
1,630
2.421875
2
[]
no_license
package com.sandy.apps.dcs.component ; import java.io.Serializable ; import com.sandy.apps.dcs.component.model.DCDGateModel ; import com.sandy.apps.dcs.component.model.DCDJKFlipFlopModel ; import com.sandy.apps.dcs.component.view.DCDGateUI ; import com.sandy.apps.dcs.component.view.DCDJKFlipFlopUI ; import com.sandy.apps.dcs.util.Chain ; public class DCDJKFlipFlop extends DCDFlipFlop implements Serializable { private DCDJKFlipFlopUI ui ; private DCDJKFlipFlopModel model ; // I don't know when this constructor can be used. public DCDJKFlipFlop( Chain c, DCDJKFlipFlopModel model, DCDJKFlipFlopUI ui ) { super( c, model, ui ) ; this.ui = ui ; this.model = model ; } public DCDJKFlipFlop( Chain c ) { super( c, null, null ) ; numInputPorts = 3 ; numOutputPorts = 2 ; setModel( new DCDJKFlipFlopModel( this ) ) ; setUI( new DCDJKFlipFlopUI( this ) ) ; } public DCDJKFlipFlop() { super() ; ui = new DCDJKFlipFlopUI( this ) ; model = new DCDJKFlipFlopModel( this ) ; super.setUI( ui ) ; super.setModel( model ) ; } public String getType() { return "JKFLIPFLOP" ; } public void setModel( DCDGateModel model ) { if( model instanceof DCDJKFlipFlopModel ) { super.setModel( model ) ; this.model = (DCDJKFlipFlopModel) model ; } } public void setUI( DCDGateUI ui ) { if( ui instanceof DCDJKFlipFlopUI ) { super.setUI( ui ) ; this.ui = (DCDJKFlipFlopUI) ui ; } } }
true
0dcd2af5f8cc5c57f0df3f9ee36e9408693ca4e1
Java
herskovi/analytics-bytes
/SmsForGoogleAnalytic/src/main/java/com/analytic/reports/validator/BalanceValidator.java
UTF-8
1,304
2.703125
3
[]
no_license
/** * */ package main.java.com.analytic.reports.validator; import main.java.com.analytic.reports.controller.response.BalanceResponse; import main.java.com.analytic.reports.interfaces.*; import main.java.com.analytic.reports.jdo.model.Customer; /** * @author admin * Aug 14, 2014 */ public class BalanceValidator extends BaseValidator implements IValidator { private Customer cust =null; private String amount =""; /** * @param cust */ public BalanceValidator(Customer cust) { super(); this.cust = cust; } /** * @param cust * @param balance */ public BalanceValidator(Customer cust, String amount) { super(); this.cust = cust; this.amount = amount; } public void validate() throws Exception { validateBalance(); } public String getBalance() { return cust.getBalance(); } public void validateBalance() throws Exception { int balance = Integer.parseInt(getBalance()) + Integer.parseInt(amount); validateBalanceIsGreaterThanZero(balance); } /** *@Author: Moshe Herskovits *@Date: Aug 31, 2014 *@Description: Validate Balance Is Greater Than Zero */ private void validateBalanceIsGreaterThanZero(int balance) throws Exception { if (balance < 0 ) { throw new Exception("Balance cannot be negative"); } } }
true
27613412b10e63f56b781a333e881edbe71bde04
Java
davidsamueljones/COMP1202-CW-SmartMeter
/src/Boiler.java
UTF-8
1,872
3.375
3
[]
no_license
/** * Class of Appliance representing a boiler. * Assumed to be an always on Appliance, which can be toggled, that that uses gas only. * Duty cycle always default. * * ECS Smart Meter - COMP1202 Coursework * @author dsj1n15 */ public class Boiler extends Appliance { // Boiler Defaults private final static int DEFAULT_ELECTRIC_USAGE = 0; private final static int DEFAULT_GAS_USAGE = 1; private final static int DEFAULT_WATER_USAGE = 0; private final static int DEFAULT_TIME_ON = -1; private final static UtilityType[] DEFAULT_ALLOWED_CONSUMPTION = {UtilityType.ELECTRIC, UtilityType.GAS, UtilityType.WATER}; /** * Constructor for Boiler class. * Assign defaults for boiler. */ public Boiler() { this(DEFAULT_GAS_USAGE); } /** * Constructor for Boiler class. * Set gas by parameter, assign defaults for rest. * @param gasUsage Gas use per unit time [>= 0] */ public Boiler(int gasUsage) { this(DEFAULT_ELECTRIC_USAGE, gasUsage, DEFAULT_WATER_USAGE); } /** * Constructor for Boiler class. * Set usage by parameters, only allowing appropriate usage types. * @param electricUsage Electric use per unit time [>= 0] * @param gasUsage Gas use per unit time [>= 0] * @param waterUsage Water use per unit time [>= 0] */ public Boiler(int electricUsage, int gasUsage, int waterUsage) { super(electricUsage, gasUsage, waterUsage, DEFAULT_TIME_ON); // Define Appliance tasks on object instantiation // An exception is thrown if the task method does not exist addTask(new ApplianceTask("TurnOnBoiler", getMethod("turnOn"), true, false)); addTask(new ApplianceTask("TurnOffBoiler", getMethod("turnOff"), true, true)); } @Override public String getType() { return ApplianceType.BOILER.asString(); } @Override protected UtilityType[] getAllowedConsumption() { return DEFAULT_ALLOWED_CONSUMPTION; } }
true
a9022a4f5f0532be7645af29507cc871468276d3
Java
WF1683497569/Keng
/app/src/main/java/com/example/wf/keng/Size.java
UTF-8
6,844
2.21875
2
[ "Apache-2.0" ]
permissive
package com.example.wf.keng; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.hardware.Camera; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; public class Size extends Activity implements SensorEventListener{ private CameraPreview mPreview; // Z轴暂不需要,已先行注释 private SensorManager sensorManager = null; private Sensor gyroSensor = null; private TextView vX; private TextView vY; // private TextView vZ; private TextView re; private TextView value1; private TextView value2; private Button first_record; private Button second_record; private Button result; private static double vX1; private static double vY1; // private static double vZ1; private static double vX2; private static double vY2; // private static double vZ2; public static double X; public static double Y; // public static double Z; private static Double h; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21) { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE ); getWindow().setStatusBarColor(Color.TRANSPARENT); } setContentView(R.layout.activity_size); // vX = (TextView) findViewById(R.id.vx); // vY = (TextView) findViewById(R.id.vy); // vZ = (TextView) findViewById(R.id.vz); re = (TextView) findViewById(R.id.re); value1 = (TextView) findViewById(R.id.value1); value2 = (TextView) findViewById(R.id.value2); first_record = (Button) findViewById(R.id.first); second_record = (Button) findViewById(R.id.second); result = (Button) findViewById(R.id.result); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); gyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); Intent intent = getIntent(); String data = intent.getStringExtra("data"); h = Double.parseDouble(data); //点击按钮1记录A点数据 first_record.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //test数据 // vX1 = 227; // vY1 = 66.98; vX1 = X; vY1 = Y; // vZ1 = Z; value1.setText("第一次记录:" + vX1 + "/" + vY1 + ""); Toast.makeText(Size.this, "已记录第一次位置!", Toast.LENGTH_SHORT).show(); } }); //点击按钮2记录B点数据 second_record.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //test数据 // vX2 = 279; // vY2 = 72.00; vX2 = X; vY2 = Y; // vZ2 = Z; value2.setText("第二次记录:" + vX2 + "/" + vY2 + ""); Toast.makeText(Size.this, "已记录第二次位置!", Toast.LENGTH_SHORT).show(); } }); //点击按钮求尺寸 result.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { double result = getAB(vY1,vY2,vX2-vX1,h); Toast.makeText(Size.this, "正在计算...", Toast.LENGTH_SHORT).show(); re.setText("此道路坑洞的尺寸为:" + result +""); Toast.makeText(Size.this, "计算成功...", Toast.LENGTH_SHORT).show(); } }); initCamera(); final ImageView mediaPreview = (ImageView) findViewById(R.id.media_preview); final Button buttonCapturePhoto = (Button) findViewById(R.id.button_capture_photo); final TextView zhunxin = (TextView) findViewById(R.id.zhunxin) ; zhunxin.bringToFront(); buttonCapturePhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPreview.takePicture(mediaPreview); } }); mediaPreview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Size.this, ShowPhoto.class); intent.setDataAndType(mPreview.getOutputMediaFileUri(), mPreview.getOutputMediaFileType()); startActivityForResult(intent, 0); } }); } private void initCamera() { mPreview = new CameraPreview(this); RelativeLayout preview = (RelativeLayout) findViewById(R.id.camera_preview); preview.addView(mPreview); } @Override protected void onPause() { super.onPause(); sensorManager.unregisterListener(this); // 解除监听器注册 mPreview = null; } @Override protected void onResume() { super.onResume(); sensorManager.registerListener(this, gyroSensor, SensorManager.SENSOR_DELAY_NORMAL); //为传感器注册监听器 if (mPreview == null) { initCamera(); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { // vX.setText("Orientation X: " + event.values[0]); // vY.setText("Orientation Y: " + event.values[1]); // vZ.setText("Orientation Z: " + event.values[2]); X = event.values[0]; Y = event.values[1]; // Z = event.values[2]; } //计算尺寸方法 public double getAB(double a,double b,double c,double h) { double a0 = Math.toRadians(a); double b0 = Math.toRadians(b); double c0 = Math.toRadians(c); double AB = h*Math.sqrt((Math.tan(a0))*(Math.tan(a0))+(Math.tan(b0))*(Math.tan(b0))-2*(Math.tan(a0)*Math.tan(b0)*Math.cos(c0))); return AB; } }
true