blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4d364138e832dd0bd5f722c035bfa1a34696ef98 | f2fe84871c1f458164c6f419f27c18d1ff246c4e | /app/src/main/java/com/android/camera/PIPCustomization.java | a0f94ccf001a23f0ad0f59d9f5ea67f938e6fbc1 | [] | no_license | luoran-gaolili/MTK-CAMERA1 | 6f7285336020e181790c77935e8db9de96b8ce77 | 14ea4d9192f493a56d6516cec13e15c2bc1d6d26 | refs/heads/master | 2020-07-08T21:17:59.155969 | 2019-09-03T07:12:21 | 2019-09-03T07:12:21 | 203,777,915 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,791 | java | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2014. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
package com.android.camera;
public class PIPCustomization {
private static final String TAG = "PIPCustomization";
public static final String MAIN_CAMERA = "main_camera";
public static final String SUB_CAMERA = "sub_camera";
// scale
public static final float TOP_GRAPHIC_MAX_SCALE_VALUE = 1.8f;
public static final float TOP_GRAPHIC_MIN_SCALE_VALUE = 0.6f;
// rotate
public static final float TOP_GRAPHIC_MAX_ROTATE_VALUE = 180f;
// top graphic edge, default is min(width, height) / 2
public static final float TOP_GRAPHIC_DEFAULT_EDGE_RELATIVE_VALUE = 1f / 2;
// edit button edge, default is min(width, height) / 10
public static final int TOP_GRAPHIC_EDIT_BUTTON_RELATIVE_VALUE = 10;
public static final float TOP_GRAPHIC_LEFT_TOP_RELATIVE_VALUE =
TOP_GRAPHIC_DEFAULT_EDGE_RELATIVE_VALUE - 1f / TOP_GRAPHIC_EDIT_BUTTON_RELATIVE_VALUE;
// top graphic crop preview position
public static final float TOP_GRAPHIC_CROP_RELATIVE_POSITION_VALUE = 3f / 4;
// which camera enable FD, default is main camera support fd
public static final String ENABLE_FACE_DETECTION = MAIN_CAMERA;
// when take picture, whether sub camera need mirror
public static final boolean SUB_CAMERA_NEED_HORIZONTAL_FLIP = true;
private PIPCustomization() {
}
public static boolean isMainCameraEnableFD() {
boolean enable = false;
enable = ENABLE_FACE_DETECTION.endsWith(MAIN_CAMERA);
Log.i(TAG, "isMainCameraEnableFD enable = " + enable);
return enable;
}
}
| [
"[email protected]"
] | |
d0e0c5c8dfe17c2e5207208b8f0bf05f9664f50c | ca030864a3a1c24be6b9d1802c2353da4ca0d441 | /classes6.dex_source_from_JADX/com/facebook/ui/flyout/IFlyoutInterface.java | 67ecc933aca7735efeead977eb891bbf2faa43fc | [] | no_license | pxson001/facebook-app | 87aa51e29195eeaae69adeb30219547f83a5b7b1 | 640630f078980f9818049625ebc42569c67c69f7 | refs/heads/master | 2020-04-07T20:36:45.758523 | 2018-03-07T09:04:57 | 2018-03-07T09:04:57 | 124,208,458 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 131 | java | package com.facebook.ui.flyout;
/* compiled from: creator_product */
public interface IFlyoutInterface {
boolean m26966a();
}
| [
"[email protected]"
] | |
42f02c42cf92e9a8d603c3214c6bf82d37c08716 | 44b8f0874ac3d3638acbe4ec0fa89141417582b8 | /ProjProduto/src/visao/Menu.java | bae15fbbf67a3091cb2be6ef7600e16b31433092 | [
"MIT"
] | permissive | ComPacto/Java-2 | aa50277f670755b55452ab407273ce2a28430667 | 43f8392b4ea86136cac338843e82da81a274ea69 | refs/heads/master | 2020-04-05T18:46:08.658806 | 2018-11-11T19:14:20 | 2018-11-11T19:15:14 | 157,112,065 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,883 | java | package visao;
import com.sun.glass.events.KeyEvent;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
/**
*
* @author Alunos
*/
public class Menu extends javax.swing.JFrame implements InternalFrameListener {
private boolean flagCadProduto = false;
private boolean flagCadCliente = false;
/**
* Creates new form Menu
*/
public Menu() {
initComponents();
setExtendedState(MAXIMIZED_BOTH);
}
/**
* 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() {
jAreaTrabalho = new javax.swing.JDesktopPane();
jmbMenu = new javax.swing.JMenuBar();
jmCadastro = new javax.swing.JMenu();
jmiProduto = new javax.swing.JMenuItem();
jmiCliente = new javax.swing.JMenuItem();
jmSair = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout jAreaTrabalhoLayout = new javax.swing.GroupLayout(jAreaTrabalho);
jAreaTrabalho.setLayout(jAreaTrabalhoLayout);
jAreaTrabalhoLayout.setHorizontalGroup(
jAreaTrabalhoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 508, Short.MAX_VALUE)
);
jAreaTrabalhoLayout.setVerticalGroup(
jAreaTrabalhoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 369, Short.MAX_VALUE)
);
jmCadastro.setText("Cadastro");
jmiProduto.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
jmiProduto.setText("Produto");
jmiProduto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jmiProdutoActionPerformed(evt);
}
});
jmiProduto.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jmiProdutoKeyPressed(evt);
}
});
jmCadastro.add(jmiProduto);
jmiCliente.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
jmiCliente.setText("Cliente");
jmiCliente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jmiClienteActionPerformed(evt);
}
});
jmiCliente.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jmiClienteKeyPressed(evt);
}
});
jmCadastro.add(jmiCliente);
jmbMenu.add(jmCadastro);
jmSair.setText("Sair");
jmSair.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jmSairMouseClicked(evt);
}
});
jmbMenu.add(jmSair);
setJMenuBar(jmbMenu);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jAreaTrabalho)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jAreaTrabalho)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void abrirCadastroProduto() {
if(!flagCadProduto){
UiCadProduto objCadProduto = new UiCadProduto();
jAreaTrabalho.add(objCadProduto);
objCadProduto.setVisible(true);
flagCadProduto = true;
objCadProduto.addInternalFrameListener(this);
}
}
private void abrirCadastroCliente() {
if(!flagCadProduto){
UiCadCliente objCadCliente = new UiCadCliente();
jAreaTrabalho.add(objCadCliente);
objCadCliente.setVisible(true);
flagCadProduto = true;
objCadCliente.addInternalFrameListener(this);
}
}
private void jmiProdutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiProdutoActionPerformed
abrirCadastroProduto();
}//GEN-LAST:event_jmiProdutoActionPerformed
private void jmiClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiClienteActionPerformed
abrirCadastroCliente();
}//GEN-LAST:event_jmiClienteActionPerformed
private void jmSairMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jmSairMouseClicked
System.exit(0);
}//GEN-LAST:event_jmSairMouseClicked
private void jmiProdutoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jmiProdutoKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
abrirCadastroProduto();
}
}//GEN-LAST:event_jmiProdutoKeyPressed
private void jmiClienteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jmiClienteKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
abrirCadastroCliente();
}
}//GEN-LAST:event_jmiClienteKeyPressed
/**
* @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(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Menu().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JDesktopPane jAreaTrabalho;
private javax.swing.JMenu jmCadastro;
private javax.swing.JMenu jmSair;
private javax.swing.JMenuBar jmbMenu;
private javax.swing.JMenuItem jmiCliente;
private javax.swing.JMenuItem jmiProduto;
// End of variables declaration//GEN-END:variables
@Override
public void internalFrameOpened(InternalFrameEvent ife) {
}
@Override
public void internalFrameClosing(InternalFrameEvent ife) {
}
@Override
public void internalFrameClosed(InternalFrameEvent ife) {
if (ife.getInternalFrame() instanceof UiCadProduto) {
flagCadProduto = false;
} else {
flagCadCliente = false;
}
}
@Override
public void internalFrameIconified(InternalFrameEvent ife) {
}
@Override
public void internalFrameDeiconified(InternalFrameEvent ife) {
}
@Override
public void internalFrameActivated(InternalFrameEvent ife) {
}
@Override
public void internalFrameDeactivated(InternalFrameEvent ife) {
}
}
| [
"[email protected]"
] | |
b25796d60c3bba65af2b65d9a31e499af7445fdb | 79042fe29a12f6b3ec27aedfb74ccd6ab67f8257 | /src/main/java/org/mthree/vendingmachine/service/VendingMachineServiceLayerImpl.java | 6e54d9e2e421e388dd26d0648339713b0b7b6315 | [] | no_license | hagabor94/VendingMachine | bac36fc5c4a196f3c6df66087999145e2b7f1542 | 0c38f298dc428e07fb7560db35fa0503ca24db6b | refs/heads/main | 2023-06-24T10:54:40.872042 | 2021-07-14T07:44:46 | 2021-07-14T07:44:46 | 385,687,016 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,561 | java | package org.mthree.vendingmachine.service;
import org.mthree.vendingmachine.dao.VendingMachineAuditDao;
import org.mthree.vendingmachine.dao.VendingMachineDao;
import org.mthree.vendingmachine.dao.VendingMachinePersistenceException;
import org.mthree.vendingmachine.dto.Item;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class VendingMachineServiceLayerImpl implements VendingMachineServiceLayer{
private VendingMachineDao dao;
private VendingMachineAuditDao auditDao;
public VendingMachineServiceLayerImpl(VendingMachineDao dao, VendingMachineAuditDao auditDao){
this.dao = dao;
this.auditDao = auditDao;
}
@Override
public List<Item> getAllItems() throws VendingMachinePersistenceException {
return dao.getAllItems();
}
@Override
public BigDecimal getItem(int id, BigDecimal funds) throws VendingMachinePersistenceException, VendingMachineIsufficientFundsException, VendingMachineNoItemInventoryException, VendingMachineNoSuchItemException {
Item requestedItem = dao.getItem(id);
if(requestedItem == null){
throw new VendingMachineNoSuchItemException("NO SUCH ITEM");
}
if(requestedItem.getQuantity() == 0){
throw new VendingMachineNoItemInventoryException("REQUESTED ITEM IS EMPTY");
}
if(funds.compareTo(requestedItem.getPrice()) == -1){
throw new VendingMachineIsufficientFundsException("REQUESTED ITEM COSTS MORE");
}
auditDao.writeAuditEntry("ITEM REQUESTED : "+requestedItem.getName());
editItem(id);
return funds.subtract(requestedItem.getPrice());
}
@Override
public Item editItem(int id) throws VendingMachinePersistenceException {
Item editedItem = dao.editItem(id);
auditDao.writeAuditEntry("ITEM SERVED : "+editedItem.getName()+" QUANTITY : "+editedItem.getQuantity());
return editedItem;
}
@Override
public Map<Coins, Integer> changeToCoins(BigDecimal change) {
BigDecimal remainingChange = new BigDecimal(String.valueOf(change));
Map<Coins, Integer> coins = new HashMap<>();
int coinCounter = 0;
while( !(BigDecimal.valueOf(1).compareTo(remainingChange.divide(Coins.QUARTER.getValue())) == 1)){
coinCounter++;
remainingChange = remainingChange.subtract(Coins.QUARTER.getValue());
}
if(coinCounter > 0)
coins.put(Coins.QUARTER, coinCounter);
coinCounter = 0;
while( !(BigDecimal.valueOf(1).compareTo(remainingChange.divide(Coins.DIME.getValue())) == 1)){
coinCounter++;
remainingChange = remainingChange.subtract(Coins.DIME.getValue());
}
if(coinCounter > 0)
coins.put(Coins.DIME, coinCounter);
coinCounter = 0;
while( !(BigDecimal.valueOf(1).compareTo(remainingChange.divide(Coins.NICKEL.getValue())) == 1)){
coinCounter++;
remainingChange = remainingChange.subtract(Coins.NICKEL.getValue());
}
if(coinCounter > 0)
coins.put(Coins.NICKEL, coinCounter);
coinCounter = 0;
while( !(BigDecimal.valueOf(1).compareTo(remainingChange.divide(Coins.PENNY.getValue())) == 1)){
coinCounter++;
remainingChange = remainingChange.subtract(Coins.PENNY.getValue());
}
if(coinCounter > 0)
coins.put(Coins.PENNY, coinCounter);
return coins;
}
}
| [
"[email protected]"
] | |
f9bdd1deedfc8646d2b4812af72b085bc63c9a64 | 9f5a99f13ddb142a7cb4ec9727a417c51b92e3e5 | /android/app/src/Onekey/java/org/haobtc/onekey/business/update/AutoCheckUpdate.java | 4ac71f119881c3f9ef7a2d92d40ff56ed63dfa4e | [
"MIT"
] | permissive | peterQin0826/electrum | 10dcfb9d117c2a6d1a815d4dd442de62ef0680a3 | 5a4fff3d7ec91e36748a59f52f4ba3b8f73a41d4 | refs/heads/bixin_dev | 2023-04-03T16:28:39.814524 | 2021-03-10T08:13:07 | 2021-03-10T08:13:28 | 320,548,023 | 0 | 1 | MIT | 2021-03-17T12:02:39 | 2020-12-11T10:57:26 | Python | UTF-8 | Java | false | false | 5,610 | java | package org.haobtc.onekey.business.update;
import static org.haobtc.onekey.constant.Constant.ONE_KEY_WEBSITE;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;
import com.azhon.appupdate.config.UpdateConfiguration;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.azhon.appupdate.utils.ApkUtil;
import java.io.File;
import org.haobtc.onekey.R;
import org.haobtc.onekey.business.language.LanguageManager;
import org.haobtc.onekey.business.version.VersionManager;
import org.haobtc.onekey.ui.dialog.AppUpdateDialog;
/**
* 检查更新,并自动更新
*
* @author Onekey@QuincySx
* @create 2021-01-20 5:21 PM
*/
public class AutoCheckUpdate implements OnDownloadListener {
private final Handler mHandler = new Handler(Looper.getMainLooper());
private final DownloadManager manager;
private AppUpdateDialog updateDialog;
private final Context mContext;
private final UpdateConfiguration mConfiguration;
private static volatile AutoCheckUpdate AUTOCHECKUPDATE;
private VersionManager mVersionManager;
public static AutoCheckUpdate getInstance(Context context) {
if (AUTOCHECKUPDATE == null) {
synchronized (AutoCheckUpdate.class) {
if (AUTOCHECKUPDATE == null) {
AUTOCHECKUPDATE = new AutoCheckUpdate(context.getApplicationContext());
}
}
}
return AUTOCHECKUPDATE;
}
private AutoCheckUpdate(Context context) {
mContext = context;
manager = DownloadManager.getInstance(mContext);
mConfiguration =
new UpdateConfiguration()
.setEnableLog(true)
.setJumpInstallPage(true)
.setShowNotification(true)
.setForcedUpgrade(false)
.setOnDownloadListener(this);
mVersionManager = new VersionManager();
}
public void checkUpdate(@NonNull FragmentManager manager, boolean showHint) {
mVersionManager.getVersionData(
updateInfo -> {
String locate = LanguageManager.getInstance().getLocalLanguage(mContext);
String url = updateInfo.getAPK().getUrl();
String versionName = updateInfo.getAPK().getVersionName();
int versionCode = updateInfo.getAPK().getVersionCode();
String size = updateInfo.getAPK().getSize().replace("M", "");
String description =
"English".equals(locate)
? updateInfo.getAPK().getChangelogEn()
: updateInfo.getAPK().getChangelogCn();
mVersionManager.saveVersionInfo(mContext, updateInfo);
mHandler.post(
() ->
attemptUpdate(
manager,
url,
versionCode,
versionName,
size,
description,
showHint));
return null;
});
}
private void attemptUpdate(
@NonNull FragmentManager fragmentManager,
String uri,
int versionCode,
String versionName,
String size,
String description,
boolean showHint) {
int versionCodeLocal = ApkUtil.getVersionCode(mContext);
if (versionCodeLocal >= versionCode) {
if (showHint) {
Toast.makeText(mContext, R.string.is_new, Toast.LENGTH_SHORT).show();
}
return;
}
String url;
if (uri.startsWith("https")) {
url = uri;
} else {
url = ONE_KEY_WEBSITE + uri;
}
if (!manager.isDownloading()) {
manager.setApkName("oneKey.apk")
.setApkUrl(url)
.setSmallIcon(R.drawable.logo_square)
.setConfiguration(mConfiguration);
}
if (updateDialog != null) {
updateDialog.dismiss();
}
updateDialog = new AppUpdateDialog(manager, versionName, description);
try {
updateDialog.show(fragmentManager, "");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void start() {
if (updateDialog.progressBar != null) {
updateDialog.progressBar.setIndeterminate(false);
}
}
@Override
public void downloading(int max, int progress) {
if (updateDialog.progressBar != null) {
updateDialog.progressBar.setProgress((int) (((float) progress / max) * 100));
}
}
@Override
public void done(File apk) {
updateDialog.dismiss();
manager.release();
}
@Override
public void cancel() {}
@Override
public void error(Exception e) {}
public void onDestroy() {
try {
if (updateDialog != null) {
updateDialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
1b63ce12cb9016a6fdffad12b71cc5c77a316f6a | 3aa96bd2717db1ab965e1dd7987d782c8a4c3b59 | /src/com/vaani/algo/ds/algos/tree/binary/BalancedBinaryTree.java | e1687ffb4f24da5e9c7f76acd070666a8355c800 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | sjl421/AlgorithmUtil | 1121683fcb7f40fea96af6bb83a73980156b4ca4 | edc3bcdd648a3e6981e8b1f0ae74f0f349225081 | refs/heads/master | 2020-04-15T20:56:27.872900 | 2018-09-01T07:00:00 | 2018-09-25T07:00:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 867 | java | package com.vaani.algo.ds.algos.tree.binary;
import com.vaani.algo.ds.core.tree.BinaryTreeNode;
/**
* Given a binary tree, determine if it is height-balanced.
* <p>
* For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
* <p>
* Created by Xiaomeng on 8/11/2014.
*/
public class BalancedBinaryTree {
public boolean isBalanced(BinaryTreeNode root) {
return getBalance(root) != -1;
}
public int getBalance(BinaryTreeNode root) {
if (root == null) return 0;
int left = getBalance(root.left);
if (left == -1) return -1;
int right = getBalance(root.right);
if (right == -1) return -1;
if (Math.abs(left - right) > 1) return -1;
return left > right ? left + 1 : right + 1;
}
}
| [
"[email protected]"
] | |
139670894ef7ba39c4b392936611a230dc4052d7 | 957ff5a8f07716240e453cc2ecf38ba30211abed | /Interfaz/src/Main.java | 7c1639362cec9fb9ec4d28c79fe07fb192073ad2 | [
"MIT"
] | permissive | shirosweets/Proyectos_Eclipse | 3ae312b75b12cbeb09408e5dc5699b23adf55394 | f125a3ec5992d68628fc9876f0d1b2f72070e585 | refs/heads/master | 2022-06-02T23:45:39.714729 | 2020-05-01T16:12:25 | 2020-05-01T16:12:25 | 260,500,813 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 1,633 | java | import java.awt.Container; // vieja
import javax.swing.JFrame; // nueva
/*public class Main extends JFrame {
//public
private Container contenedor;
public static void main (String[] args) {
public Main() { // Constructor
contenedor = getContentPane();
contenedor.setLayout(null);
setTitle("Esta es mi ventana");
setSize(400, 200); // Alto x Ancho
setLocationRelativeTo(null);
}
}
}*/
public class Main{
public static void main (String[] args) {
JFrame miVentana = new JFrame("Título extraordinario");
miVentana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Agrega _ [] X
miVentana.setSize(300, 200); // Fija tamaño (Horizontal x Vertical)(Altura x Ancho) se mide en pixeles
miVentana.setVisible(true); // Lo muestra
JFrame miVentana2 = new JFrame("Título triste");
miVentana2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Cierra TODO
miVentana2.setSize(300, 200);
miVentana2.setVisible(true);
miVentana2.setLocationRelativeTo(null); // Posición por default (centro)
JFrame miVentana3 = new JFrame("Título imposible");
miVentana3.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // Impide cerrarla
miVentana3.setSize(300, 200);
miVentana3.setVisible(true);
miVentana3.setLocationRelativeTo(null); // Posición por default (centro)
JFrame miVentana4 = new JFrame("Título disvariando");
miVentana4.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); // La esconde
miVentana4.setSize(300, 200);
miVentana4.setVisible(true);
miVentana4.setLocationRelativeTo(null); // Posición por default (centro)
}
} | [
"[email protected]"
] | |
dce84565629d7970c260b5f69ec985f8ba1f7b2e | 4756d2644d004efb98408df810ce5af4afd0110f | /3.JavaMultithreading/src/com/javarush/task/task29/task2909/car/Truck.java | 5dc03bd535f3deee61259594798c03080e8a4711 | [] | no_license | PavelSmirnoff/JavaRushTask | 0266ba4e02ba2774d1584788529a2025c55996d5 | e8a4152369147d3dc77797a78f62ee6b2cfff47b | refs/heads/main | 2023-07-25T06:10:37.199999 | 2021-09-09T13:23:06 | 2021-09-09T13:23:06 | 327,271,121 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 251 | java | package com.javarush.task.task29.task2909.car;
public class Truck extends Car{
@Override
public int getMaxSpeed() {
return MAX_TRUCK_SPEED;
}
public Truck(int numberOfPassengers) {
super( numberOfPassengers);
}
}
| [
"[email protected]"
] | |
4328586a44064388b9129cb8f496bc5c6007e8f1 | 8d9bcc58cbe0fb32578efa7b9aef5c5e203b82a4 | /Projects/PixelsCamp_netorkinghostnameverifier/app/src/main/java/pt/claudio/security/pixelscamp_netorkinghostnameverifier/MainActivity.java | 06adec8f14c6085085c994ce496c0f8723f3c9f3 | [] | no_license | clviper/pixelscamp_talk_resources | 1e5822a8610879b2750f9ea1d9a367936d93d5a9 | 1174de2f9aaa6e6c200dc298e405af9ea89ce064 | refs/heads/master | 2020-05-23T06:26:29.794641 | 2016-10-07T01:16:48 | 2016-10-07T01:16:48 | 70,205,150 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,291 | java | package pt.claudio.security.pixelscamp_netorkinghostnameverifier;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import org.xml.sax.InputSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.io.Reader;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.xml.parsers.SAXParserFactory;
class loadURL extends AsyncTask<String, Void, String> {
private Exception exception;
protected String doInBackground(String... urls) {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
String data;
URL url = new URL("https://wrong.host.badssl.com/");
URLConnection urlConnection = url.openConnection();
InputStream in = urlConnection.getInputStream();
BufferedReader reader =new BufferedReader(new InputStreamReader(in, "UTF-8"));
while ((data = reader.readLine()) != null) {
Log.d("px", data);
}
return "";
} catch (Exception e) {
Log.d("px ",e.toString());
return "";
}
}
protected void onPostExecute() {
// TODO: check this.exception
// TODO: do something with the feed
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new loadURL().execute();
}
}
| [
"[email protected]"
] | |
6f5b8a96e5ae42382ff48119db7af022c2f266fe | 404338f4ba6f48ecda1c3cd6138a7aa33aff8659 | /test/com/company/MainTest.java | eaeb9963ebd69afd45606e91aa93854f598e065e | [] | no_license | VeryBarry/ForumWeb | 0fc8ecab433d2aaa08cc384450635f535c8acaf5 | e31392fbfed6275694956a86baad1c7b320a6068 | refs/heads/master | 2021-01-10T23:29:01.945678 | 2016-10-13T16:13:38 | 2016-10-13T16:13:38 | 70,604,510 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,841 | java | package com.company;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import static org.junit.Assert.*;
/**
* Created by VeryBarry on 10/13/16.
*/
public class MainTest {
public Connection startConnection() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:h2:mem:test");
Main.createTables(conn);
return conn;
}
@Test
public void testUser() throws SQLException {
Connection conn = startConnection();
Main.insertUser(conn, "Alice", "pass");
User user = Main.selectUser(conn, "Alice");
conn.close();
assertTrue(user != null);
}
@Test
public void testMessage() throws SQLException {
Connection conn = startConnection();
Main.insertUser(conn, "Alice", "pass");
User user = Main.selectUser(conn, "Alice");
Main.insertMessage(conn, -1, "Hello, world.", user.id);
Message message = Main.selectMessage(conn, 1);
conn.close();
assertTrue(message != null);
assertTrue(message.author.equals("Alice"));
}
@Test
public void testReplies() throws SQLException {
Connection conn = startConnection();
Main.insertUser(conn, "Alice", "pass");
Main.insertUser(conn, "Bob", "pass");
User alice = Main.selectUser(conn, "Alice");
User bob = Main.selectUser(conn, "Bob");
Main.insertMessage(conn, -1, "Hello, world.", alice.id);
Main.insertMessage(conn, 1, "Hey Alice.", bob.id);
Main.insertMessage(conn, 1, "Hey again, Alice.", bob.id);
ArrayList<Message> replies = Main.selectReplies(conn, 1);
conn.close();
assertTrue(replies.size() == 2);
}
} | [
"[email protected]"
] | |
5bf5fef7c8b820518bf06dda0522e3cbc0d549c8 | 3a2732011a802e5e105e610b48608a1dfc8b94c0 | /library/src/main/java/com/milton/common/widget/swipetoloadlayout/SwipeLoadMoreFooterLayout.java | 0d44029f84236785e42d6ee7d2bd3ff94ebaf136 | [] | no_license | suiyuan0/MiltonAndroidCommon | 6beddca00b09d48238ad01e2141a3a25fa5fa756 | 9e765ec6f9cb35733fead4f726c0010a7616b836 | refs/heads/master | 2021-01-19T02:07:22.642470 | 2016-12-19T03:32:13 | 2016-12-19T03:32:13 | 57,343,248 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,011 | java | package com.milton.common.widget.swipetoloadlayout;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;
/**
* Created by Aspsine on 2015/8/13.
*/
public class SwipeLoadMoreFooterLayout extends FrameLayout implements SwipeLoadMoreTrigger, SwipeTrigger {
public SwipeLoadMoreFooterLayout(Context context) {
this(context, null);
}
public SwipeLoadMoreFooterLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SwipeLoadMoreFooterLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void onLoadMore() {
}
@Override
public void onPrepare() {
}
@Override
public void onMove(int y, boolean isComplete, boolean automatic) {
}
@Override
public void onRelease() {
}
@Override
public void onComplete() {
}
@Override
public void onReset() {
}
}
| [
"[[email protected]]"
] | |
9ad9249a9a326a7b73f0e6cbf07fb16bbc19693b | 592bad48cf799b68869a4c500674df3a4c3df35f | /lab/40-security-solution/src/test/java/accounts/client/AccountClientTests.java | c9ff2863d85d15e516755588485fbc8a994f72c7 | [] | no_license | VHelpYou/Spring | 066b2404f923b1b715550ba132985e7ed0435b6d | a78e6c0a2127e8ee7b14e9f9de0edfcb4714c8a8 | refs/heads/master | 2020-04-24T04:03:57.604369 | 2019-02-20T14:49:47 | 2019-02-20T14:49:47 | 171,690,792 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,154 | java | package accounts.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Random;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import accounts.client.AccountClientTests.TestClientConfig;
import common.money.Percentage;
import config.Constants;
import rewards.internal.account.Account;
import rewards.internal.account.Beneficiary;
/**
* In this scenario, the test is the OAuth2 client.
* <p>
* This is basically the same test-client as the REST lab used. But it uses
* OAuth2 validation because the {@link RestTemplate} it uses is a
* {@link OAuth2RestTemplate}.
* <p>
* <b>Note 1:</b> This client does not need to be secure so security
* auto-configuration is disabled.
* <p>
* <b>Note 2:</b> This is not a Web application and we do not want to pick up
* any additional configuration so we specify our own configuration class to
* initialize from. This sets this application up as an OAuth2 client and
* creates the {@link OAuth2RestTemplate} we need.
* <p>
* <b>Note 3:</b> This test has its own Spring Boot properties defined in
* "<code>client-oauth2.properties<code>".
*/
@ExtendWith(SpringExtension.class)
@RunWith(JUnitPlatform.class) // For JUnit 4 backwards compatibility only
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE, classes = TestClientConfig.class)
@TestPropertySource("classpath:client-oauth2.properties")
public class AccountClientTests {
/**
* When the account-server starts up and runs data.sql, 21 accounts are created.
*/
public static final int ORIGINAL_NUMBER_OF_ACCOUNTS = 21;
/**
* OAuth2 name for this client - defined in client-oauth2.properties.
*/
public static final String CLIENT_NAME = Constants.ACCOUNT_TESTER_CLIENT;
/**
* Spring Boot property for setting application name (in this case the client
* name).
*/
public static final String SPRING_APPLICATION_NAME_PROPERTY = "spring.application.name";
/**
* Account server URL.
*/
private static final String BASE_URL = "http://localhost:8080";
@Autowired
private RestTemplate restTemplate;
private Random random = new Random(); // Random number for new Accounts
/**
* Additional configuration for this test - make this test an OAuth2 client and
* create an OAuth2 aware RestTemplate.
*/
@Configuration
@EnableOAuth2Client
public static class TestClientConfig {
@Bean
public RestTemplate restTemplate(OAuth2ProtectedResourceDetails details) {
return new OAuth2RestTemplate(details);
}
}
@BeforeEach
public void setup(@Autowired Environment env) {
// Sanity check - did this test pick up client-oauth2.properties?
String appName = env.getProperty(SPRING_APPLICATION_NAME_PROPERTY);
Assert.assertEquals(CLIENT_NAME, appName);
}
@Test
public void listAccounts() {
String url = BASE_URL + "/accounts";
// We have to use Account[] instead of List<Account>, or Jackson won't know what
// type to unmarshal to (because List<Account>.class doesn't parse).
Account[] accounts = restTemplate.getForObject(url, Account[].class);
// Number of accounts may be greater if you have run multiple tests without
// restarting the server.
assertTrue(accounts.length >= ORIGINAL_NUMBER_OF_ACCOUNTS);
assertEquals("Keith and Keri Donald", accounts[0].getName());
assertEquals(2, accounts[0].getBeneficiaries().size());
assertEquals(Percentage.valueOf("50%"), //
accounts[0].getBeneficiary("Annabelle").getAllocationPercentage());
}
@Test
public void getAccount() {
String url = BASE_URL + "/accounts/{accountId}";
Account account = restTemplate.getForObject(url, Account.class, 0);
assertEquals("Keith and Keri Donald", account.getName());
assertEquals(2, account.getBeneficiaries().size());
assertEquals(Percentage.valueOf("50%"), account.getBeneficiary("Annabelle").getAllocationPercentage());
}
@Test
public void createAccount() throws URISyntaxException {
String url = BASE_URL + "/accounts";
// use a unique number to avoid conflicts
String number = String.format("12345%4d", random.nextInt(10000));
Account account = new Account(number, "John Doe");
account.addBeneficiary("Jane Doe");
URI newAccountLocation = restTemplate.postForLocation(url, account);
Account retrievedAccount = restTemplate.getForObject(newAccountLocation, Account.class);
assertEquals(account.getNumber(), retrievedAccount.getNumber());
Beneficiary accountBeneficiary = account.getBeneficiaries().iterator().next();
Beneficiary retrievedAccountBeneficiary = retrievedAccount.getBeneficiaries().iterator().next();
assertEquals(accountBeneficiary.getName(), retrievedAccountBeneficiary.getName());
assertNotNull(retrievedAccount.getEntityId());
}
@Test
public void addAndDeleteBeneficiary() {
// perform both add and delete to avoid issues with side effects
String addUrl = BASE_URL + "/accounts/{accountId}/beneficiaries";
URI newBeneficiaryLocation = restTemplate.postForLocation(addUrl, "David", 1);
Beneficiary newBeneficiary = restTemplate.getForObject(newBeneficiaryLocation, Beneficiary.class);
assertEquals("David", newBeneficiary.getName());
restTemplate.delete(newBeneficiaryLocation);
try {
System.out.println("You SHOULD get the exception \"No such beneficiary with name 'David'\" in the server.");
restTemplate.getForObject(newBeneficiaryLocation, Beneficiary.class);
fail("Should have received 404 Not Found after deleting beneficiary at " + newBeneficiaryLocation);
} catch (HttpClientErrorException e) {
assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode());
}
}
}
| [
"[email protected]"
] | |
01bbc311136d1d381c7339892995af525a576bf1 | eb9f655206c43c12b497c667ba56a0d358b6bc3a | /platform/core-nio-fs/src/com/intellij/platform/core/nio/fs/CorePath.java | da372fec5fc4192b7f700a00ee3bee1c4507f8ee | [
"Apache-2.0"
] | permissive | JetBrains/intellij-community | 2ed226e200ecc17c037dcddd4a006de56cd43941 | 05dbd4575d01a213f3f4d69aa4968473f2536142 | refs/heads/master | 2023-09-03T17:06:37.560889 | 2023-09-03T11:51:00 | 2023-09-03T12:12:27 | 2,489,216 | 16,288 | 6,635 | Apache-2.0 | 2023-09-12T07:41:58 | 2011-09-30T13:33:05 | null | UTF-8 | Java | false | false | 4,786 | java | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.platform.core.nio.fs;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.Iterator;
import java.util.Objects;
import static com.intellij.platform.core.nio.fs.CoreRoutingFileSystemProvider.unwrap;
public class CorePath implements Path {
private final Path myDelegate;
private final CoreRoutingFileSystem myFileSystem;
private static volatile String ourMountedDelegateClassName;
public CorePath(CoreRoutingFileSystem fileSystem, Path delegate) {
myDelegate = delegate;
myFileSystem = fileSystem;
}
public Path getDelegate() {
return myDelegate;
}
@Override
public FileSystem getFileSystem() {
return myFileSystem;
}
@Override
public boolean isAbsolute() {
return myDelegate.isAbsolute();
}
@Override
public Path getRoot() {
return wrap(myDelegate.getRoot());
}
@Override
public Path getFileName() {
return wrap(myDelegate.getFileName());
}
@Override
public Path getParent() {
return wrap(myDelegate.getParent());
}
@Override
public int getNameCount() {
return myDelegate.getNameCount();
}
@Override
public Path getName(int index) {
return wrap(myDelegate.getName(index));
}
@Override
public Path subpath(int beginIndex, int endIndex) {
return wrap(myDelegate.subpath(beginIndex, endIndex));
}
@Override
public boolean startsWith(Path other) {
if (!(other instanceof CorePath))return false;
return myDelegate.startsWith(unwrap(other));
}
@Override
public boolean startsWith(String other) {
return myDelegate.startsWith(other);
}
@Override
public boolean endsWith(Path other) {
if (!(other instanceof CorePath))return false;
return myDelegate.endsWith(unwrap(other));
}
@Override
public boolean endsWith(String other) {
return myDelegate.endsWith(other);
}
@Override
public Path normalize() {
return wrap(myDelegate.normalize());
}
@Override
public Path resolve(Path other) {
return wrap(myDelegate.resolve(unwrap(other)));
}
@Override
public Path resolve(String other) {
return wrap(myDelegate.resolve(other));
}
@Override
public Path resolveSibling(Path other) {
return wrap(myDelegate.resolveSibling(unwrap(other)));
}
@Override
public Path resolveSibling(String other) {
return wrap(myDelegate.resolveSibling(other));
}
@Override
public Path relativize(Path other) {
return wrap(myDelegate.relativize(unwrap(other)));
}
@Override
public URI toUri() {
return myDelegate.toUri();
}
@Override
public Path toAbsolutePath() {
return wrap(myDelegate.toAbsolutePath());
}
@Override
public Path toRealPath(LinkOption... options) throws IOException {
return wrap(myDelegate.toRealPath(options));
}
@Override
public File toFile() {
return isMountedFS() ? myDelegate.toFile() : new File(myDelegate.toString());
}
@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException {
return myDelegate.register(watcher, events, modifiers);
}
@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) throws IOException {
return myDelegate.register(watcher, events);
}
@Override
public Iterator<Path> iterator() {
Iterator<Path> iterator = myDelegate.iterator();
return new Iterator<Path>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Path next() {
return wrap(iterator.next());
}
};
}
@Override
public int compareTo(Path other) {
return myDelegate.compareTo(unwrap(other));
}
@Override
public String toString() {
return myDelegate.toString();
}
private Path wrap(Path path) {
return path == null ? null : CoreRoutingFileSystemProvider.path(myFileSystem, path);
}
static void setMountedDelegateClassName(String mountedDelegateClassName) {
ourMountedDelegateClassName = mountedDelegateClassName;
}
public boolean isMountedFS() {
return myDelegate.getClass().getSimpleName().equals(ourMountedDelegateClassName);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CorePath paths = (CorePath)o;
return Objects.equals(myDelegate, paths.myDelegate) &&
Objects.equals(myFileSystem, paths.myFileSystem);
}
@Override
public int hashCode() {
return Objects.hash(myDelegate, myFileSystem);
}
}
| [
"[email protected]"
] | |
e1dcc176b359c7fa3c29f329dfd74b40bd659e39 | 7a935a47f61828fd6fadb563c4c06a8010194751 | /src/test/java/io/vertx/test/codegen/testjsonmapper/nonpublicfunctionmapper/APIInterfaceWithZonedDateTime.java | 82deedf3e726b2b3cfd82d961bd2f82b5ab00bce | [
"Apache-2.0"
] | permissive | nileshborole/vertx-codegen | 7051c07fbc317ff790d23ce23bb652a19cff03f4 | fd62520da09887998bc4244c31c2a763accf0ffb | refs/heads/master | 2021-02-23T06:23:33.917756 | 2020-03-02T16:15:02 | 2020-03-02T16:15:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 386 | java | package io.vertx.test.codegen.testjsonmapper.nonpublicfunctionmapper;
import java.time.ZonedDateTime;
import java.util.function.Function;
/**
* @author <a href="mailto:[email protected]">Julien Viet</a>
*/
public class APIInterfaceWithZonedDateTime {
static Function<String, ZonedDateTime> deserializer = null;
static Function<ZonedDateTime, String> serializer = null;
}
| [
"[email protected]"
] | |
b77a28eed9dd351a706d83cca5a45edf0ad9673a | c6b994fd200a1bb3ac64d766fb57e8675ad85ef6 | /ProyectoLibreria/app/src/main/java/com/example/proyectolibreria/BD/DataBaseHelper.java | c1a661cc7d2b8f247f535c7b264753acbc227396 | [] | no_license | sandra1036/PMDM | e719ea446127703fb52b1602ba749879877c8cbc | 83f5f0c4a6a3ee653fce2655c6f7d58fc80cd495 | refs/heads/master | 2020-07-28T01:52:06.870004 | 2020-02-21T10:41:56 | 2020-02-21T10:41:56 | 209,273,258 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,964 | java | package com.example.proyectolibreria.BD;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.proyectolibreria.Activitys.Libros;
import com.example.proyectolibreria.Activitys.Usuarios;
public class DataBaseHelper {
private Context context=null;
private static DataBaseHelperInternal dataBaseHelper=null;
public static SQLiteDatabase liteDatabase=null;
private DataBaseHelperInternal dataBaseHelpelibros=null;
public static final int DATABASE_VERSION=2;
public static final String DATABASE_NAME= "Dbproyecto";
public static final String DATABASE_TABLE_USUARIOS="Usuarios";
public static final String USUARIOS_ID="id";
public static final String USUARIOS_NOMBRE="nombre";
public static final String USUARIOS_Contrasenya="contrasenya";
public static final String DATABASE_CREATE_USUARIO= "create table "+DATABASE_TABLE_USUARIOS +"("
+USUARIOS_ID+" integer primary key autoincrement,"
+USUARIOS_NOMBRE+ " text not null,"
+USUARIOS_Contrasenya+" text not null)";
public static final String DATABASE_TABLE_LIBROS="Libros";
public static final String LIBROS_ID="id";
public static final String LIBROS_TITULO="titulo";
public static final String LIBROS_ANYO="anyos";
public static final String LIBROS_SINOPSIS="sinopsis";
public static final String LIBROS_AUTOR="autor";
public static final String LIBROS_GENERO="genero";
public static final String USUARIO_ID="usuario_id";
public static final String DATABASE_CREATE_LIBROS="create table "+DATABASE_TABLE_LIBROS+"("
+LIBROS_ID+" integer primary key autoincrement,"
+LIBROS_TITULO+" text not null,"
+LIBROS_ANYO+" text not null,"
+LIBROS_SINOPSIS+" text not null,"
+LIBROS_AUTOR+" text not null,"
+LIBROS_GENERO+" text not null,"
+USUARIO_ID+" integer not null,"
+"FOREIGN KEY ("+USUARIO_ID+") REFERENCES "+DATABASE_TABLE_USUARIOS+" ("+USUARIOS_ID+"))";
public DataBaseHelper(Context context){
this.context=context;
}
public DataBaseHelper open(){
dataBaseHelper= new DataBaseHelperInternal(context);
liteDatabase=dataBaseHelper.getWritableDatabase();
return this;
}
public void close(){
dataBaseHelper.close();
}
public Cursor getItemsUsuarios(){
return liteDatabase.query(DATABASE_TABLE_USUARIOS,new String[] {USUARIOS_ID, USUARIOS_NOMBRE, USUARIOS_Contrasenya},
null,null,null,null,USUARIOS_NOMBRE);
}
public Cursor getItemsLibros(){
return liteDatabase.query(DATABASE_TABLE_LIBROS,new String[] {LIBROS_ID, LIBROS_TITULO, LIBROS_ANYO,LIBROS_SINOPSIS,LIBROS_AUTOR,LIBROS_GENERO},
null,null,null,null,LIBROS_ID);
}
public long insertItemUsuario(String nombre, String contrasenya){
ContentValues contentValues=new ContentValues();
contentValues.put(USUARIOS_NOMBRE,nombre);
contentValues.put(USUARIOS_Contrasenya,contrasenya);
return liteDatabase.insert(DATABASE_TABLE_USUARIOS,null,contentValues);
}
public long insertItemLibros(String titulo, String anyo, String sinopsis, String autor, String genero,int U){
ContentValues contentValues=new ContentValues();
contentValues.put(LIBROS_TITULO ,titulo);
contentValues.put(LIBROS_ANYO,anyo);
contentValues.put(LIBROS_SINOPSIS,sinopsis);
contentValues.put(LIBROS_AUTOR,autor);
contentValues.put(LIBROS_GENERO,genero);
contentValues.put(USUARIO_ID,U+1);
return liteDatabase.insert(DATABASE_TABLE_LIBROS,null,contentValues);
}
public int delete(int row){
return liteDatabase.delete(DATABASE_TABLE_LIBROS,LIBROS_ID+"=?",new String[]{Integer.toString(row)});
}
}
| [
"[email protected]"
] | |
faf37f026e0c040424d4044789943e2e5c306bbd | c6cd955ce7c0672dcccdd4146af3aad0dc3fb403 | /settergeetter/src/Abstract/shape.java | c3b0ead26bbbfea4e3de492e67ea321cf1aac784 | [] | no_license | Nanda27/Leavemanagement | f44f7c1cef28aaeffb52e20c447a51d8bcc36217 | ef730f3a4cae28c3a5989c218e61e32da6f98ef1 | refs/heads/master | 2020-03-30T16:27:51.345782 | 2018-10-04T10:48:42 | 2018-10-04T10:48:42 | 151,410,182 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 71 | java | package Abstract;
abstract class shape {
abstract void draw();
}
| [
"[email protected]"
] | |
df6de84d34987eb162d2b5fc894391f966c0547e | 717edd8d64d78ae7d6c6cb2f08adcbdb4909e7e4 | /src/main/java/local/alberto/tp2/controller/ProdutoController.java | 75ae34e0df6ecc7a05c21fde32b5621bdb3a5888 | [] | no_license | albertoelias123/TP_POO | 8a69ce78445f8f26d957dd78c2f4bb04cf31a661 | 21028f330d9f9006f607111ddac40a097216927b | refs/heads/master | 2023-06-23T08:09:35.795324 | 2019-10-10T19:37:47 | 2019-10-10T19:37:47 | 211,938,565 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 971 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package local.alberto.tp2.controller;
import java.util.ArrayList;
import local.alberto.tp2.model.Produto;
/**
*
* @author alber
*/
public class ProdutoController {
private static ArrayList<Produto> produtosVendidos;
public static void inicializa(){
produtosVendidos = new ArrayList();
}
public static void cadastrarProduto(int id, String descricao, int qtdEstoque, String categoria, double preco, String nome) throws Exception{
Produto produtoAdd = new Produto(id, descricao, qtdEstoque, categoria, preco, nome);
produtosVendidos.add(produtoAdd);
}
public static ArrayList<Produto> getAllProduto()throws Exception{
return produtosVendidos;
}
}
| [
"[email protected]"
] | |
ec5eeb8473bb4848237c9770ad5bfd65a9d346ca | c93deeb4acb17328991c2a9aa76b931d9e7e4769 | /m1-12_Polymorphism-exercises/src/main/java/com/techelevator/FourDaySPU.java | f8f3d9c4e3a0a6d63a0e0c0e73eb74bd954060f3 | [] | no_license | DanielSaltzman/Tech-Elevator-Exercises | 7712e60275e8b65697b8003640cb533f00a96b3d | 7e726fec989e5226e278df5710ef46cefd8167fc | refs/heads/master | 2020-05-15T13:05:39.780657 | 2019-04-19T16:57:34 | 2019-04-19T16:57:34 | 182,288,115 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,080 | java | package com.techelevator;
public class FourDaySPU implements DeliveryDriver {
private int weightInOunces;
private int distanceInMiles;
private int mailClass;
public FourDaySPU (int distanceInMiles, int weightInOunces, int mailClass) {
this.distanceInMiles = distanceInMiles;
this.weightInOunces = weightInOunces;
this.mailClass = mailClass;
}
public String toString() {
String formatted = String.format("$%.2f", calculateRate(distanceInMiles, weightInOunces));
String mailClassType = "SPU ";
if (mailClass == 3) {
mailClassType += "(4-day Ground)";
}
return String.format("%1$-31s %2$s", mailClassType, formatted);
}
@Override
public double calculateRate(int distance, double weight) {
double rate = 0.0;
double weightInPounds = (double) weightInOunces / 16;
if(mailClass == 3) {
rate = 0.0050;
}
return weightInPounds * rate * distanceInMiles;
}
public int getWeightInOunces() {
return weightInOunces;
}
public int getDistanceInMiles() {
return distanceInMiles;
}
public int getMailClass() {
return mailClass;
}
}
| [
"[email protected]"
] | |
13e56269959a095b6202d239815e578f98f5df37 | 6a1c5c04a4fa430a1bb454b120e8114eca437d72 | /app_servlet/src/main/java/com/zhiyun/servlets/FailServlet.java | 40c80f780caceddf0ca4f35c2d22bf6eb0fe9355 | [] | no_license | yanyuanyun/apps_repository | 9b9f5a917d634606ab242858e1642a9a3e358925 | f5da743a3a2cc7c9f889b43319749ac92252d506 | refs/heads/master | 2022-12-21T19:37:36.593733 | 2020-02-22T15:12:45 | 2020-02-22T15:12:45 | 242,341,567 | 0 | 0 | null | 2022-12-16T04:24:29 | 2020-02-22T12:55:38 | Java | UTF-8 | Java | false | false | 853 | java | package com.zhiyun.servlets;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class FailServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write("<div style='center'><h1>用户名或密码错误,<a href='/web/htmls/login.html'>点此重新登录</a></h1></div>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
| [
"[email protected]"
] | |
917fc4610a41cabfd554398cbecfdc2d37fda341 | 4323cd6ad8a440f8645ce6a413ea7ff688dcf8ce | /COFBase.java | 301a31c5fb65b736c7e98f86a37ea849e6250e55 | [] | no_license | rulkens/MagicCircleOfFifths | be9cff720f1a705ae3884ff7659badbc16971fb5 | 3acb289da9ac93750f4c251b4521df90c2364916 | refs/heads/master | 2020-04-19T21:17:43.732390 | 2015-02-16T17:48:16 | 2015-02-16T17:48:16 | 30,880,120 | 3 | 3 | null | null | null | null | UTF-8 | Java | false | false | 474 | java | /**
circle of fifths - creates an interactive circle of fifths in processing
Required
------------------------
the rwmidi library (http://ruinwesen.com/support-files/rwmidi.zip)
code by Alexander Rulkens
[email protected]
http://alexrulkens.com/
please give me credit if you use this code for something
Base file (to be used for all important functions)
**/
/**
COFBase.class ; the circle of fifths base class
**/
class COFBase {
}
| [
"[email protected]"
] | |
1b10fdf4268e09ca1a4597d74336c79725432888 | a8304b18788b8989702f0980c760db84fb0b0de1 | /ProgramaImprenta/src/entidades/PoliticaCalidad.java | 8f693df3bcb7942006231b4f4764d3ceb7a652aa | [] | no_license | romangs84/repositoriogrupo2 | a1f299f6925eac44d64da7de9f19f777f62b5153 | 6a089b80fddef19c10a3549f4e11d46bc2b6b216 | refs/heads/main | 2023-08-26T13:03:27.149670 | 2021-11-07T16:13:31 | 2021-11-07T16:13:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,503 | java | package entidades;
import java.time.LocalDate;
import java.util.Arrays;
public class PoliticaCalidad {
private static int numPol = 0;
private long NombrePolitica;
private LocalDate FechaVig;
private String Descripcion;
private OpCalidad[] operarios;
public PoliticaCalidad() {
numPol = numPol + 1;
this.NombrePolitica = numPol;
}
public PoliticaCalidad(long idPol, LocalDate FechaVig, String Descripcion, String Resultado) {
numPol = numPol + 1;
this.NombrePolitica = numPol;
this.FechaVig = FechaVig;
this.Descripcion = Descripcion;
}
public long getNombrePolitica() {
return NombrePolitica;
}
public void setNombrePolitica(long NombrePolitica) {
this.NombrePolitica = NombrePolitica;
}
public LocalDate getFechaVig() {
return FechaVig;
}
public void setFechaVig(LocalDate fechaVig) {
FechaVig = fechaVig;
}
public String getDescripcion() {
return Descripcion;
}
public void setDescripcion(String descripcion) {
Descripcion = descripcion;
}
public static int getNumPol() {
return numPol;
}
public static void setNumPol(int numPol) {
PoliticaCalidad.numPol = numPol;
}
public OpCalidad[] getOperarios() {
return operarios;
}
public void setOperarios(OpCalidad[] operarios) {
this.operarios = operarios;
}
@Override
public String toString() {
return "PoliticaCalidad [NombrePolitica=" + NombrePolitica + ", FechaVig=" + FechaVig + ", Descripcion=" + Descripcion
+ ", operarios=" + Arrays.toString(operarios) + "]";
}
}
| [
"hugoa@DESKTOP-TL19H9R"
] | hugoa@DESKTOP-TL19H9R |
00c1613bb7ae5b466e4e41d8a1bc809559b892f6 | efd80600387ef16e2f102422daafcead03aa2e1d | /oopexample/src/oopexample/Main.java | c0ed5ff36a3618470e351164202b8a9667da11a4 | [] | no_license | dilaranuraltiparmak/oopexample | 93424959debb3df7114e8b1f3d4815b673de312f | e887da92c2df09ef0bed4a3cfcd5eace9654c5b9 | refs/heads/main | 2023-04-22T05:19:09.010793 | 2021-05-07T11:27:26 | 2021-05-07T11:27:26 | 365,211,272 | 0 | 0 | null | null | null | null | ISO-8859-9 | Java | false | false | 1,489 | java | package oopexample;
public class Main {
public static void main(String[] args) {
//objelerle çalışmaya başlamak
Student student1=new Student(10,"Dilara Nur",23456,"c# bilgisi çok kötü");//örnek oluşturma,referans oluşturma,intance oluşturma
/*Student student1=new Student();//örnek oluşturma,referans oluşturma,intance oluşturma
student1.id=10;
student1.name="Dilara Nur";
student1.detail="c# bilgisi çok kötü";
student1.studentnumber=23456;*/
Student student2=new Student();//örnek oluşturma,referans oluşturma,intance oluşturma
student2.id=20;
student2.name="Ayşe";
student2.detail="java bilgisi lazım";
student2.studentnumber=15050;
Student student3=new Student();//örnek oluşturma,referans oluşturma,intance oluşturma
student3.id=30;
student3.name="Fatıma";
student3.detail="react lazım projesi için";
student3.studentnumber=189560;
Student[]students= {student1,student2,student3};//getproduct veritabanındaki verileri gider okur
for (Student student:students) {
System.out.println(student.name);
}
System.out.println(students.length);
Course course1=new Course();
course1.name="c#";
course1.id=1;
Course course2=new Course();
course2.name="java";
course2.id=2;
CourseManager CourseManager=new CourseManager();
CourseManager.addToList(course1);
CourseManager.addToList(course2);
}
}
| [
"[email protected]"
] | |
2d5e71e949735b99237ae81f1ce772adf3e981f2 | 3ae44a42c030188b97dae6f628c34bafa0ed39dd | /app/src/main/java/com/example/adrin/detectorappsinseguras/controlador/ConnectionDetected.java | db3788c68f9eda7c71fa22a01cf26d92912ae35f | [] | no_license | A-Garrido5/DetectorAppsRiesgosas | d5243c26b3ef861b6d9b546f1ac19d7fa1f7d136 | 1c99d88130a4982cc2b41434a8fb926ccbd22d4a | refs/heads/master | 2021-01-13T00:41:11.930043 | 2016-03-11T15:56:23 | 2016-03-11T15:56:23 | 49,735,457 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,615 | java | package com.example.adrin.detectorappsinseguras.controlador;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import com.example.adrin.detectorappsinseguras.Bienvenida;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class ConnectionDetected {
public static boolean hasActiveInternetConnection(Context c)
{
ConnectivityManager connectivityManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public static int isNetworkAvailable(Context context)
{
if (hasActiveInternetConnection(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
if(urlc.getResponseCode() == 200)
return 1;
} catch (IOException e) {
System.out.println("No internet disponible");
return -1;
}
} else {
System.out.println("No internet disponible");
return -1;
}
return 0;
}
} | [
"[email protected]"
] | |
cdf119e3c7315f25cf36566f7bbde59d52429ae2 | 4e5867d9eb86262c8d340c7e53ea286dd56c4ff7 | /persistence/src/main/java/io/github/gnupinguin/tlgscraper/db/repository/MessageRepositoryImpl.java | d7f9a0bf01a2d11795785c34929f37980eabff89 | [
"BSD-2-Clause"
] | permissive | securityigi/telegram-scraper | c9289d528c5f9aa4e59a12f0f251bce4eab443bd | 6d5bc7e379c835a2380ecc3ccb8946e7d423c081 | refs/heads/main | 2023-05-31T13:02:51.803923 | 2021-06-14T21:46:43 | 2021-06-14T21:46:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,151 | java | package io.github.gnupinguin.tlgscraper.db.repository;
import io.github.gnupinguin.tlgscraper.db.mappers.SqlEntityMapper;
import io.github.gnupinguin.tlgscraper.db.orm.QueryExecutor;
import io.github.gnupinguin.tlgscraper.model.db.Message;
import org.springframework.stereotype.Component;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.List;
import static io.github.gnupinguin.tlgscraper.db.repository.DbTools.questionMarks;
@Component
public class MessageRepositoryImpl extends AbstractRepository<Message> implements MessageRepository {
private static final String INSERT_QUERY = "INSERT INTO message " +
"(chat_id, " +
"message_id, " +
"type, " +
"text_content, " +
"publish_date, " +
"load_date, " +
"views) VALUES (?, ?, ?, ?, ?, ?, ?);";
private static final String DELETE_QUERY = "DELETE FROM message WHERE internal_id = ?;";
private static final String DELETE_ALL = "DELETE FROM message;";
public MessageRepositoryImpl(QueryExecutor queryExecutor, SqlEntityMapper<Message> mapper) {
super(queryExecutor, mapper);
}
@Override
public boolean save(Collection<Message> objects) {
return saveWithIdGeneration(INSERT_QUERY, (id, e) -> e.setInternalId(id), objects);
}
@Override
public @Nonnull List<Message> get(Collection<Long> ids) {
String query = "SELECT internal_id, chat_id, message_id, type, text_content, publish_date, load_date, views FROM message WHERE internal_id IN " + questionMarks(ids.size()) + ";";
return getInternal(query, ids);
}
@Override
public boolean delete(Collection<Long> ids) {
return deleteInternal(DELETE_QUERY, ids);
}
@Override
public boolean delete() {
return deleteInternal(DELETE_ALL);
}
@Override
public @Nonnull List<Message> getForChat(Long chatId) {
String query = "SELECT internal_id, chat_id, message_id, type, text_content, publish_date, load_date, views FROM message WHERE chat_id = ?;";
return getInternal(query, List.of(chatId));
}
}
| [
"[email protected]"
] | |
23f66cca9fa331be8c51384273d06804d87c7e36 | 37aee617ceb3ca828248309a4db28ede200d4c1a | /src/main/java/org/openlmis/ao/reports/dto/RequisitionReportDto.java | 7ad3dc1c5a515aacc035b0162c5be04e17c46b87 | [] | no_license | OpenLMIS-Angola/angola-reports | 6aa04eb90c60b63043397780f44bbb3e43ea5fd0 | ecf8d5278f870aee6b922d1a7ad7353e529b1a20 | refs/heads/master | 2023-09-02T00:15:28.235525 | 2023-08-18T11:10:28 | 2023-08-18T11:10:28 | 177,607,321 | 0 | 1 | null | 2023-08-18T11:10:29 | 2019-03-25T14:53:29 | Java | UTF-8 | Java | false | false | 968 | java | package org.openlmis.ao.reports.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.joda.money.Money;
import org.openlmis.ao.reports.dto.external.RequisitionDto;
import org.openlmis.ao.reports.dto.external.RequisitionLineItemDto;
import org.openlmis.ao.reports.dto.external.UserDto;
import java.time.ZonedDateTime;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class RequisitionReportDto {
private RequisitionDto requisition;
private List<RequisitionLineItemDto> fullSupply;
private List<RequisitionLineItemDto> nonFullSupply;
private Money fullSupplyTotalCost;
private Money nonFullSupplyTotalCost;
private Money totalCost;
private UserDto initiatedBy;
private ZonedDateTime initiatedDate;
private UserDto submittedBy;
private ZonedDateTime submittedDate;
private UserDto authorizedBy;
private ZonedDateTime authorizedDate;
}
| [
"[email protected]"
] | |
60cd0830b720f563780405cbf45fb3a8a4119562 | bae34dd33e983d07faf75d8041a2eb797580dc1c | /src/main/java/org/startinglineup/simulator/HomeTeam.java | 18dca6d389d4193b6e432eec4c15a1443763c1ef | [] | no_license | mdarretta/StartingLineup | a078feb88982ecef4bdbccf42e38c0a8894203f7 | 2c1bf43eb649e8d5394e248b4a2c9e1c51f1b051 | refs/heads/main | 2023-07-16T13:23:22.984880 | 2023-06-30T13:36:16 | 2023-06-30T13:36:16 | 194,145,283 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 230 | java | package org.startinglineup.simulator;
public class HomeTeam extends Team {
public HomeTeam(org.startinglineup.component.Team team) {
super(team);
}
public boolean isHomeTeam() {
return true;
}
}
| [
"[email protected]"
] | |
bbca495819ad17f93cf36ba414a476d83693633e | 38f9b2dcf9de85005a58417847face7b95a9c67d | /src/Domain.java | 082a0b62d89527696bdac6eaf980220f60e5ff39 | [] | no_license | qindezhen/test | e75be30085b4fbfac8ebeb1922e4e0e01676729d | 43118b7d670857de1ea95b73f7347769a051aa2a | refs/heads/master | 2020-09-03T16:06:14.337355 | 2019-11-04T12:22:28 | 2019-11-04T12:22:28 | 219,490,603 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 171 | java |
public class Domain {
private String demo="";
public String getDemo() {
return demo;
}
public void setDemo(String demo) {
this.demo = demo;
}
}
| [
"[email protected]"
] | |
c0e6d84bc852beb589b07a4448e4640b7cd203d4 | 45cbf4213e178994963ec018d3344d11ab7e8d03 | /SkynetEye/src/main/java/com/skynet/system/dao/RoleMenuDao.java | 80f1be1ab02401b8b25acc953995e32b0dfef72c | [] | no_license | skynet-auxo/skynet-auxo | 412f88e65d9f2eb08acfeef3230251f3670de4e8 | cdab50c63b0124f77d777df00677bff49fe54674 | refs/heads/master | 2022-11-01T08:13:47.681341 | 2019-06-17T01:10:21 | 2019-06-17T01:10:21 | 192,259,296 | 0 | 0 | null | 2022-10-12T20:28:02 | 2019-06-17T02:09:26 | JavaScript | UTF-8 | Java | false | false | 722 | java | package com.skynet.system.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import com.skynet.system.domain.RoleMenuDO;
/**
* 角色与菜单对应关系
* @author chglee
* @email [email protected]
* @date 2017-10-03 11:08:59
*/
@Mapper
public interface RoleMenuDao {
RoleMenuDO get(Long id);
List<RoleMenuDO> list(Map<String,Object> map);
int count(Map<String,Object> map);
int save(RoleMenuDO roleMenu);
int update(RoleMenuDO roleMenu);
int remove(Long id);
int batchRemove(Long[] ids);
List<Long> listMenuIdByRoleId(Long roleId);
int removeByRoleId(Long roleId);
int removeByMenuId(Long menuId);
int batchSave(List<RoleMenuDO> list);
}
| [
"[email protected]"
] | |
2fa555025e40c5ce68af13e96a7baf6eae47c207 | 2c2f909055d963f96c715bc36bce20e2089ce47e | /src/behavioural/chainofreponsibility/Manager.java | 62492911af2944e4baa8d5764a4d1e506c3d8e6d | [
"MIT"
] | permissive | webdude21/DesignPatterns | 84fd5ace069dbac421dce3e91b7dec1de41c8b9d | 9b678c9aaf070f6df0f3f3597a245d730884aee2 | refs/heads/master | 2021-01-10T01:38:41.265474 | 2017-02-27T18:29:31 | 2017-02-27T18:29:31 | 47,060,026 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 181 | java | package behavioural.chainofreponsibility;
class Manager extends Approver {
Manager(Approver superior, int maxAmount) {
super(superior);
setMaxAmountToApprove(maxAmount);
}
}
| [
"[email protected]"
] | |
992f6968d9c26b707c772a76e397e6d21bc45c76 | 89a64f4b674a24823cbae7899945f115417fea13 | /jcip-lab/src/main/java/com/saturn/lab/jcip/ApplyingThreadPools/ThreadDeadlock.java | 97edecb825b433a92632149ac39618178f3cb130 | [] | no_license | Tbdgithub/nettylab | 29ad08bd528fce8848e5d3ae20c3cd340d509e28 | fcd7f9feea92d30e798698e00ca0210a1bf08adc | refs/heads/master | 2020-03-29T07:14:36.603398 | 2018-08-21T01:22:18 | 2018-08-21T01:22:18 | 94,661,125 | 0 | 0 | null | 2017-08-14T01:40:17 | 2017-06-18T02:47:59 | Java | UTF-8 | Java | false | false | 1,980 | java | package com.saturn.lab.jcip.ApplyingThreadPools;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadDeadlock {
ExecutorService exec = Executors.newSingleThreadExecutor();
//ExecutorService exec = Executors.newFixedThreadPool(1);
public static void main(String[] args) {
ThreadDeadlock example = new ThreadDeadlock();
example.start();
}
public void start() {
try {
RenderPageTask task = new RenderPageTask();
Future<String> page = exec.submit(task);
// String resp = task.call();
System.out.println("resp:" + page.get());
} catch (Exception e) {
e.printStackTrace();
}
}
public class LoadFileTask implements Callable<String> {
private final String fileName;
public LoadFileTask(String fileName) {
this.fileName = fileName;
}
public String call() throws Exception {
// Here's where we would actually read the file
return "load file call.file:" + fileName;
}
}
public class RenderPageTask implements Callable<String> {
public String call() throws Exception {
Future<String> header, footer;
System.out.println("begin submit header");
header = exec.submit(new LoadFileTask("header.html"));
System.out.println("begin submit footer");
footer = exec.submit(new LoadFileTask("footer.html"));
String page = renderBody();
System.out.println("wait for page");
// Will deadlock -- task waiting for result of subtask
return header.get() + page + footer.get();
}
private String renderBody() {
// Here's where we would actually render the page
return "here is body";
}
}
} | [
"[email protected]"
] | |
1df0df81db9603cd8c9757e1aa0bd3b313449465 | 2a9b4debec5a9f96f221a9fb5f8aef54fdeda847 | /src/main/java/epam/demo/libraryservice/LibraryServiceApplication.java | 2d8e6509aa4fc70a4dc779740c32830f08e130e5 | [] | no_license | sumitdubey89/library-service | 1536845969e52603ca14ab745a048ca217ed5acc | 49b09508c165da7af92b8db24bf50a40a3a9e031 | refs/heads/master | 2023-05-18T14:55:38.180382 | 2021-06-03T08:14:32 | 2021-06-03T08:14:32 | 373,430,701 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 333 | java | package epam.demo.libraryservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LibraryServiceApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryServiceApplication.class, args);
}
}
| [
"[email protected]"
] | |
25208838924de12aec43a27187293c35e4d05164 | 8136b4f138f6dfbee2dc4dfac49ae63017b13cbe | /app/src/main/java/app/nutrimeat/meat/org/nutrimeat/CommonFunctions.java | 0a1448dc7ed55c0c0cb08e43aff3db7b58bb9cf3 | [] | no_license | sandeepkumbam123/NutrimeatUpdate | 0f4a1afaa3697bfb945c0f6cdad06ffd78e9e2c0 | 3b91cb8fee5d34d0ef0d54b297effba0551b16a0 | refs/heads/master | 2021-06-16T06:59:17.385155 | 2020-03-17T17:39:06 | 2020-03-17T17:39:06 | 101,791,762 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,348 | java | package app.nutrimeat.meat.org.nutrimeat;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import app.nutrimeat.meat.org.nutrimeat.product.ModelCart;
public class CommonFunctions {
public static void setSharedPreferenceStringList(Context pContext, String pKey, List<String> pData) {
SharedPreferences.Editor editor = pContext.getSharedPreferences(PrefManager.PREF_NAME, Activity.MODE_PRIVATE).edit();
editor.putInt(pKey + "size", pData.size());
editor.commit();
for (int i = 0; i < pData.size(); i++) {
SharedPreferences.Editor editor1 = pContext.getSharedPreferences(PrefManager.PREF_NAME, Activity.MODE_PRIVATE).edit();
editor1.putString(pKey + i, (pData.get(i)));
editor1.commit();
}
}
public static List<String> getSharedPreferenceStringList(Context pContext, String pKey) {
int size = pContext.getSharedPreferences(PrefManager.PREF_NAME, Activity.MODE_PRIVATE).getInt(pKey + "size", 0);
List<String> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(pContext.getSharedPreferences(PrefManager.PREF_NAME, Activity.MODE_PRIVATE).getString(pKey + i, ""));
}
return list;
}
public static void setSharedPreferenceProductList(Context pContext, String pKey, List<ModelCart> pData) {
SharedPreferences.Editor editor = pContext.getSharedPreferences(PrefManager.PREF_NAME, Activity.MODE_PRIVATE).edit();
Gson gson = new Gson();
String jsonProduct = gson.toJson(pData);
editor.putString(pKey, jsonProduct);
editor.commit();
}
public static List<ModelCart> getSharedPreferenceProductList(Context pContext, String pKey) {
String json_string = pContext.getSharedPreferences(PrefManager.PREF_NAME, Activity.MODE_PRIVATE).getString(pKey,"");
Gson gson = new Gson();
Type type = new TypeToken<List<ModelCart>>(){}.getType();
List<ModelCart> products= gson.fromJson(json_string, type);
if(products==null){
products=new ArrayList<>();
}
return products;
}
}
| [
"[email protected]"
] | |
0f67bf56c0dc77f35edc78168fdbba1491d2822f | 08643706f5ce40a863fb03c3bd5d0e9550848a9b | /src/java/controller/ControllerCartBean.java | d15d90075ab63f1acb84042189ad06574a87c275 | [
"MIT"
] | permissive | trollsad125/nhatnvps05367 | 0226eed0955d883cb38582abd217b374fa99beaf | b23056b03ed66fcda3ffc1c2cc679b631348ea7b | refs/heads/master | 2020-03-10T02:36:14.165593 | 2018-04-11T19:12:44 | 2018-04-11T19:12:44 | 129,140,479 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,625 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import cart.CartBean;
import cart.ProductDTO;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Product;
/**
*
* @author Nizis
*/
public class ControllerCartBean extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
/* TODO output your page here. You may use following sample code. */
try {
String action = request.getParameter("action");
if (action.equals("Add to Cart")) {
HttpSession session = request.getSession();
CartBean shop = (CartBean) session.getAttribute("SHOP");
if (shop == null) {
shop = new CartBean();
}
String code = request.getParameter("txtCode");
String name = request.getParameter("txtName");
String price = request.getParameter("txtPrice");
Float fprice = Float.parseFloat(price);
Product s = new Product(code, name, fprice);
ProductDTO ss = new ProductDTO(s);
shop.addSanPham(ss);
session.setAttribute("SHOP", shop);
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response);
} else if (action.equals("View Cart")) {
RequestDispatcher rd = request.getRequestDispatcher("showcart.jsp");
rd.forward(request, response);
} else if (action.equals("AddMore")) {
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response);
} else if (action.equals("Remove")) {
String[] list = request.getParameterValues("rmv");
if (list != null) {
HttpSession session = request.getSession();
if (session != null) {
CartBean shop = (CartBean) session.getAttribute("SHOP");
if (shop != null) {
for (int i = 0; i < list.length; i++) {
shop.remove(list[i]);
}
session.setAttribute("SHOP", shop);
}
}
}
if (request.getParameterValues("codes") == null) {
RequestDispatcher rd = request.getRequestDispatcher("empty.jsp");
rd.forward(request, response);
} else {
String url = "ControllerCartBean?action=View Cart";
RequestDispatcher rd = request.getRequestDispatcher(url);
rd.forward(request, response);
}
} else if (action.equals("Product Details")) {
RequestDispatcher rd = request.getRequestDispatcher("error_1.jsp");
rd.forward(request, response);
} else if (action.equals("Product Details ")) {
RequestDispatcher rd = request.getRequestDispatcher("error_1_1.jsp");
rd.forward(request, response);
} else if (action.equals("Update")) {
String[] list = request.getParameterValues("codes");
String[] sll = request.getParameterValues("sl");
HttpSession session = request.getSession();
if (session != null) {
CartBean shop = (CartBean) session.getAttribute("SHOP");
if (shop != null) {
for (int i = 0; i < list.length; i++) {
int tt = Integer.parseInt(sll[i]);
shop.updateSP(list[i], tt);
}
session.setAttribute("SHOP", shop);
}
}
String url = "ControllerCartBean?action=View Cart";
RequestDispatcher rd = request.getRequestDispatcher(url);
rd.forward(request, response);
}
else if (action.equals("Check out")) {
RequestDispatcher rd = request.getRequestDispatcher("error_1_1.jsp");
rd.forward(request, response);
}
} catch (Exception e) {
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| [
"[email protected]"
] | |
359ae717f1e24e04e32ee35b146d754dd8de3e5b | ab742e9780e21a6393fab9fecd078204451f0f74 | /新建文件夹/AnnoDemo1.java | 92442e253e58ce0fbddb36b3f0fc676ee69ef0de | [] | no_license | AllenXueKY/JavaWeb | ce46dd89bf6afbd9373b414b61065c7d5807fa90 | 03733dde57f61b00ba057414cb0d44b5dbdffea6 | refs/heads/master | 2022-12-22T11:21:55.166718 | 2020-06-17T11:20:08 | 2020-06-17T11:20:08 | 241,346,340 | 0 | 0 | null | 2022-12-16T04:24:09 | 2020-02-18T11:41:09 | TSQL | GB18030 | Java | false | false | 303 | java |
/**
* 注解javadoc演示
* @author Allen
* @version 1.0
* @since 1.5
*/
public class AnnoDemo1 {
/**
* 计算两数的和
* @param a 整数
* @param b 整数
* @return 两数的和
*/
public int add(int a,int b){
return a + b;
}
}
| [
"[email protected]"
] | |
029ccc44a30f1cac66a5f56b57ea16a3d8026785 | 449cc92656d1f55bd7e58692657cd24792847353 | /member/src/test/java/com/lj/business/member/service/impl/BranchCompanyServiceImplTest.java | cfa7046f82d6befa9ff8ed2426075d77ae22e300 | [] | no_license | cansou/HLM | f80ae1c71d0ce8ead95c00044a318796820a8c1e | 69d859700bfc074b5948b6f2c11734ea2e030327 | refs/heads/master | 2022-08-27T16:40:17.206566 | 2019-12-18T06:48:10 | 2019-12-18T06:48:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,944 | java | package com.lj.business.member.service.impl;
/**
* Copyright © 2017-2020 All rights reserved.
*
* Licensed under the 深圳市扬恩科技 License, Version 1.0 (the "License");
*
*/
import javax.annotation.Resource;
import org.junit.Assert;
import org.junit.Test;
import com.lj.base.core.pagination.Page;
import com.lj.base.exception.TsfaServiceException;
import com.lj.base.mvc.web.test.SpringTestCase;
import com.lj.business.member.dto.company.AddBranchCompany;
import com.lj.business.member.dto.company.DelBranchCompany;
import com.lj.business.member.dto.company.FindBranchCompany;
import com.lj.business.member.dto.company.FindBranchCompanyPage;
import com.lj.business.member.dto.company.FindBranchCompanyPageReturn;
import com.lj.business.member.dto.company.UpdateBranchCompany;
import com.lj.business.member.emus.CompanyType;
import com.lj.business.member.service.IBranchCompanyService;
/**
*
*
* 类说明:分公司测试类
*
*
* <p>
* 详细描述:
*
* @Company: 扬恩科技有限公司
* @author 曾垂瑜
*
* CreateDate: 2018年03月22日
*/
public class BranchCompanyServiceImplTest extends SpringTestCase{
@Resource
private IBranchCompanyService branchCompanyService;
/**
*
*
* 方法说明:添加分公司信息
*
* @throws TsfaServiceException
*
* @author 曾垂瑜 CreateDate: 2018年03月22日
*
*/
@Test
public void addBranchCompany() throws TsfaServiceException{
AddBranchCompany addBranchCompany = new AddBranchCompany();
//add数据录入
addBranchCompany.setCompanyNo("06f6e4e4405f48a498d477f682c9c3b6");
addBranchCompany.setCompanyName("深圳分公司");
addBranchCompany.setCompanyType(CompanyType.DEALER);
addBranchCompany.setMerchantNo("96f4d5ddad504998af92bbfda6dd4153");
Assert.assertNotNull(branchCompanyService.addBranchCompany(addBranchCompany ));
}
/**
*
*
* 方法说明:修改分公司信息
*
* @throws TsfaServiceException
*
* @author 曾垂瑜 CreateDate: 2018年03月22日
*
*/
@Test
public void updateBranchCompany() throws TsfaServiceException{
UpdateBranchCompany updateBranchCompany = new UpdateBranchCompany();
//update数据录入
updateBranchCompany.setCode("Code");
updateBranchCompany.setCompanyNo("CompanyNo");
updateBranchCompany.setCompanyName("CompanyName");
updateBranchCompany.setStatus("Status");
updateBranchCompany.setCompanyType(CompanyType.BRANCH);
updateBranchCompany.setRemark("Remark");
updateBranchCompany.setRemark2("Remark2");
updateBranchCompany.setRemark3("Remark3");
updateBranchCompany.setRemark4("Remark4");
branchCompanyService.updateBranchCompany(updateBranchCompany );
}
/**
*
*
* 方法说明:查找分公司信息
*
* @throws TsfaServiceException
*
* @author 曾垂瑜 CreateDate: 2018年03月22日
*
*/
@Test
public void findBranchCompany() throws TsfaServiceException{
FindBranchCompany findBranchCompany = new FindBranchCompany();
findBranchCompany.setCode("");
branchCompanyService.findBranchCompany(findBranchCompany);
}
/**
*
*
* 方法说明:查找分公司信息
*
* @throws TsfaServiceException
*
* @author 曾垂瑜 CreateDate: 2018年03月22日
*
*/
@Test
public void findBranchCompanyPage() throws TsfaServiceException{
FindBranchCompanyPage findBranchCompanyPage = new FindBranchCompanyPage();
Page<FindBranchCompanyPageReturn> page = branchCompanyService.findBranchCompanyPage(findBranchCompanyPage);
Assert.assertNotNull(page);
}
/**
*
*
* 方法说明:删除分公司信息
*
* @throws TsfaServiceException
*
* @author 曾垂瑜 CreateDate: 2018年03月22日
*
*/
@Test
public void delBranchCompany() throws TsfaServiceException{
DelBranchCompany delBranchCompany = new DelBranchCompany();
delBranchCompany.setCode("");
Assert.assertNotNull(branchCompanyService.delBranchCompany(delBranchCompany));
}
}
| [
"[email protected]"
] | |
bd8e915939fdf4d66275ebce7efff3b1f3c5c275 | 377b28173527ad0426721b8877a90454d593c455 | /Hello.java | 8f53869cdf413effd68a1de8421fabe96833627c | [] | no_license | akshesh1988/Jenkins | d08d330810a1e5283037ad6435fd15742e4bdea0 | 3467b45e7980b576cae961f7670d316387fff3e4 | refs/heads/master | 2022-09-28T17:33:30.094056 | 2020-05-30T11:48:11 | 2020-05-30T11:48:11 | 267,852,074 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 190 | java | public class Hello{
public static void main(String[] args){
for(int i=1;i<=10;i++){
System.out.println("Hello world...."+i);
}
}
}
| [
"[email protected]"
] | |
4fe9e752bdb32a0807c1b3bd825a3a5d52c68ea8 | 1591f1ab8330a5fd7b53ccea5073791a105dd853 | /Exerc_02b/src/exerc_02b/Exerc_02b.java | b31a55a8eeadddd48d2421b38f8c0a047f7036ad | [] | no_license | Jownath/PWII-Heranca-e-Polimorfismo | 997a0003ceb01e14ecedeaa4d366416518f7740b | 4137743697a94ee4d48261b477671e840ef0bbc9 | refs/heads/master | 2022-11-22T19:06:12.579837 | 2020-07-16T17:37:28 | 2020-07-16T17:37:28 | 280,215,839 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,114 | java | package exerc_02b;
public class Exerc_02b {
public static void main(String[] args) {
Rica rich = new Rica();
rich.setNome("Daniela");
rich.setIdade(32);
rich.setDinheiro(333750);
System.out.println(rich.toString());
rich.fazCompras();
System.out.println("----------------------------------");
Pobre poor = new Pobre();
poor.setNome("Antônio");
poor.setIdade(47);
System.out.println(poor.toString());
poor.trabalha();
System.out.println("----------------------------------");
Miseravel miserable = new Miseravel();
miserable.setNome("Cleisson");
miserable.setIdade(26);
System.out.println(miserable.toString());
miserable.mendiga();
System.out.println("----------------------------------");
Pessoa people = new Pessoa();
people.setNome("Maria");
people.setIdade(19);
System.out.println(people.toString());
}
}
| [
"[email protected]"
] | |
71384d5029b0d316a53bb658c6653dd53e56f7cf | 2f5f4f69a2b560cc312ca8cf91576e8aa13f7868 | /app/src/main/java/tamps/cinvestav/continuousgpsreadings/LectorBateria.java | f344faaf32c2be1d8b89519fc7b534fc3de10a19 | [] | no_license | s0lver/Continuous-GPS-Readings | b27934db3fcad5057c399a812a0b29e72ebca124 | c9125489b099520cd18b5b51cf7239171f94ebe3 | refs/heads/master | 2021-01-19T21:29:30.539514 | 2015-01-12T21:22:38 | 2015-01-12T21:22:38 | 29,157,189 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,725 | java | package tamps.cinvestav.continuousgpsreadings;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
public class LectorBateria {
private static final String STRING_BATT_LEVEL = "level";
private static final String STRING_BATT_SCALE = "scale";
private static final String STRING_BATT_STATUS = "status";
private Context contexto;
public LectorBateria(Context contexto) {
this.contexto = contexto;
}
public String obtenerNivelBateria() {
Intent batteryIntent = contexto.registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int rawlevel = batteryIntent.getIntExtra(STRING_BATT_LEVEL, -1);
double scale = batteryIntent.getIntExtra(STRING_BATT_SCALE, -1);
double level = -1;
if (rawlevel >= 0 && scale > 0) {
level = rawlevel / scale;
}
int status = batteryIntent.getIntExtra(STRING_BATT_STATUS, 0);
StringBuilder sb = new StringBuilder();
sb.append(level).append(',');
switch (status) {
case BatteryManager.BATTERY_STATUS_CHARGING:
sb.append("charging");
break;
case BatteryManager.BATTERY_STATUS_DISCHARGING:
sb.append("discharging");
break;
case BatteryManager.BATTERY_STATUS_FULL:
sb.append("full");
break;
case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
sb.append("not-charging");
break;
default:
sb.append("unknown");
}
return sb.toString();
}
}
| [
"[email protected]"
] | |
83d1e254a87c73dbbbb52c4115ff4916640c1110 | 2ba0a4ef73c5a0eea897e0be8a1e01ca8309559f | /Observer/src/main/java/com/observer/ObserverA.java | edc667e87dfc1d4322d03405c2309e84c81f0088 | [] | no_license | VincentCeoi/GOF23 | fa2b0ef5d24ffdb793a7fcc433ac8a43b9248e5f | 89198b6b8e627d29bfb29aef4f4bb691a89ecbd2 | refs/heads/master | 2021-01-13T08:58:13.858685 | 2016-06-06T14:30:58 | 2016-06-06T14:30:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 516 | java | package com.observer;
/**
* @description
* @authoor lengchuan
* @date 16-6-6
*/
public class ObserverA implements Observer{
private int mystate;//mystate需要跟目标对象的state的值一致
public void update(Subject subject) {
mystate=((ConcreteSubject)subject).getState();
System.out.println("观察者更新状态!"+mystate);
}
public int getMystate() {
return mystate;
}
public void setMystate(int mystate) {
this.mystate = mystate;
}
}
| [
"[email protected]"
] | |
03da2ea334c8c40c925d4f8cce1ff5c680623483 | 9ae8c29d2e1c7a12dd4cc61f36e3813f8616c9bc | /src/main/java/com/jong/admin/config/auth/SecurityConfig.java | d28afb99bc4f5f3186d950681b52e5e5e81e9260 | [] | no_license | oen142/Study-Jpa-SpringBoot-SpringSecurity | d04aa82370ef33464ff694d8b3fabbbb31f0d716 | b200de856cf7517e02c01b7257f57835759981ad | refs/heads/master | 2022-11-15T19:32:09.298949 | 2020-07-10T01:52:42 | 2020-07-10T01:52:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,277 | java | package com.jong.admin.config.auth;
import com.jong.admin.domain.user.Role;
import lombok.RequiredArgsConstructor;
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;
@RequiredArgsConstructor
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final CustomOAuth2UserService customOAuth2UserService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.headers().frameOptions().disable()
.and()
.authorizeRequests()
.antMatchers("/", "/css/**", "/images/**", "/js/**", "/h2-console/**", "/profile").permitAll()
.antMatchers("/api/v1/**").hasRole(Role.USER.name())
.anyRequest().authenticated()
.and()
.logout()
.logoutSuccessUrl("/")
.and()
.oauth2Login()
.userInfoEndpoint()
.userService(customOAuth2UserService);
}
} | [
"[email protected]"
] | |
c1665e65c42df2d6806b74e70ae9950d620a14f3 | 873f09f51d1df256f0f17c50e7dc8ce303414457 | /slow-donkey-server/src/main/java/io/bumble/slowdonkey/server/persistence/Snapshot.java | 3b7e88347db79f52105fa107dce2d9bfa036bab0 | [
"Apache-2.0"
] | permissive | io-bumble/slow-donkey | 810ecbd0a88c7c9fd54e136f40cce6c1d771fd86 | d04be72972365f63e6ae13bcf3e0739995ff106d | refs/heads/master | 2021-05-22T02:20:44.959481 | 2020-04-13T15:55:44 | 2020-04-13T15:55:44 | 252,926,005 | 0 | 2 | Apache-2.0 | 2020-10-13T20:54:17 | 2020-04-04T06:27:00 | Java | UTF-8 | Java | false | false | 5,407 | java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.bumble.slowdonkey.server.persistence;
import io.bumble.slowdonkey.common.util.SingletonUtil;
import io.bumble.slowdonkey.server.data.DataTree;
import io.bumble.slowdonkey.server.property.SlowDonkeyServerPropertyHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* The snapshot file name is as `snapshot-{timestamp}.dat`.
* The {timestamp} is the create time of the file generated by {@code System.currentTimeMillis()}.
*
* @author shenxiangyu on 2020/03/31
*/
public class Snapshot {
private Logger logger = LoggerFactory.getLogger(Snapshot.class);
private String md5;
private long lastTxnId;
public static Snapshot getInstance() {
return SingletonUtil.getInstance(Snapshot.class);
}
/**
* Load snapshot from files, and recover the data tree from the snapshot file content.
*
* @param dataTree data tree which will be recovered
* @return true for success
*/
public boolean loadDataTreeFromSnapshotFile(DataTree dataTree) {
List<File> snapshotFiles = getSnapshotFiles();
for (File snapshotFile : snapshotFiles) {
if (loadDataTreeFromSnapshotFile(dataTree, snapshotFile.getAbsolutePath())) {
return true;
}
}
return false;
}
/**
* Save the data tree to snapshot file.
* File name is composed by last transaction id and term e.g. {txnId}-{term}.dat
*
* @param dataTree data tree
* @return true for success
*/
public boolean saveDataTreeToSnapshotFile(DataTree dataTree) {
String snapshotFileName = dataTree.getLastTxnId() + '-' + dataTree.getTerm() + ".dat";
String snapshotFullPathFileName = SlowDonkeyServerPropertyHolder.getInstance().getSnapshotFilePath().getValue() +
'/' + snapshotFileName;
try (OutputStream outputStream = new FileOutputStream(snapshotFullPathFileName);
DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
// TODO checksum
byte[] bytes = dataTree.toBytes();
int dataLen = bytes.length;
// Write data tree length
dataOutputStream.writeInt(dataLen);
// Write data tree bytes
dataOutputStream.write(bytes);
lastTxnId = dataTree.getLastTxnId();
return true;
} catch (IOException e) {
logger.error("Save data tree to snapshot file failed.", e);
}
return false;
}
public String getMd5() {
return null;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public long getLastTxnId() {
return lastTxnId;
}
public void setLastTxnId(long lastTxnId) {
this.lastTxnId = lastTxnId;
}
/**
* Load data tree from snapshot file
*
* @param dataTree data tree model
* @param fullPathFileName snapshot file path
* @return true on success
*/
private boolean loadDataTreeFromSnapshotFile(DataTree dataTree, String fullPathFileName) {
try (InputStream inputStream = new FileInputStream(fullPathFileName);
DataInputStream dataInputStream = new DataInputStream(inputStream)) {
// Read last transaction id
this.lastTxnId = dataInputStream.readLong();
// Read data tree length
int dataLen = dataInputStream.readInt();
byte[] bytes = new byte[dataLen];
// Read data tree bytes
int dataRead = dataInputStream.read(bytes);
if (dataRead != dataLen) {
logger.error("Data read failed, the data length read is invalid.");
return false;
}
return dataTree.fromBytes(bytes);
} catch (IOException e) {
logger.error("Load snapshot failed.", e);
}
return false;
}
/**
* Get snapshot files order by the transaction id, the newest the snapshot file will be at the first place.
*
* @return snapshot file list
*/
private List<File> getSnapshotFiles() {
String path = SlowDonkeyServerPropertyHolder.getInstance().getSnapshotFilePath().getValue();
File fileDirectory = new File(path);
File[] files = fileDirectory.listFiles();
if (files == null) {
return Collections.emptyList();
}
// TODO order by transaction id
return Arrays.asList(files);
}
}
| [
"[email protected]"
] | |
e7bb7ac92ffb15ce2a81e2c9e2fda6c7db5bad25 | d97ce71e200958fe0a1e60f0663527f7b19167ee | /src/server/src/main/groovy/com/perfectcomputersolutions/pos/security/JwtAuthorizationTokenFilter.java | 512d8624c4af2592b7a660f5ce05491e1374d316 | [] | no_license | PerfectComputerSolutionsNP/pos | 141fa79af85f4469d18b9357af6dedd744cb7f1b | e683ba806cac49c4add4ea4ace550d2ba0d32faa | refs/heads/master | 2020-04-08T14:22:16.892316 | 2018-11-27T06:10:26 | 2018-11-27T06:10:26 | 150,139,439 | 1 | 2 | null | 2018-10-23T10:48:42 | 2018-09-24T17:11:53 | Groovy | UTF-8 | Java | false | false | 3,851 | java | package com.perfectcomputersolutions.pos.security;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final UserDetailsService userDetailsService;
private final JwtTokenUtil jwtTokenUtil;
private final String tokenHeader;
public JwtAuthorizationTokenFilter(UserDetailsService userDetailsService, JwtTokenUtil jwtTokenUtil, @Value("${jwt.header}") String tokenHeader) {
this.userDetailsService = userDetailsService;
this.jwtTokenUtil = jwtTokenUtil;
this.tokenHeader = tokenHeader;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
logger.debug("processing authentication for '{}'", request.getRequestURL());
final String requestHeader = request.getHeader(this.tokenHeader);
String username = null;
String authToken = null;
if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
authToken = requestHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(authToken);
} catch (IllegalArgumentException e) {
logger.error("an error occurred during getting username from token", e);
} catch (ExpiredJwtException e) {
logger.warn("the token is expired and not valid anymore", e);
}
} else {
logger.warn("couldn't find bearer string, will ignore the header");
}
logger.debug("checking authentication for user '{}'", username);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
logger.debug("security context was null, so authorizating user");
// It is not compelling necessary to load the use details from the database. You could also store the information
// in the token and read it from it. It's up to you ;)
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
// For simple validation it is completely sufficient to just check the token integrity. You don't have to call
// the database compellingly. Again it's up to you ;)
if (jwtTokenUtil.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
logger.info("authorizated user '{}', setting security context", username);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(request, response);
}
} | [
"[email protected]"
] | |
3071ae9d2a4293a575ea0841e5b2d81a3ca58f26 | 63d319fbd88e49701d8dcc2919c8f3a6013e90d0 | /Applications/CIM/plugins/es.tid.cim.diagram/src/es/tid/cim/diagram/edit/parts/LANSegmentEditPart.java | 259448bca6e03f723696f3ebf9081b3b6ef12f22 | [] | no_license | DevBoost/Reuseware | 2e6b3626c0d434bb435fcf688e3a3c570714d980 | 4c2f0170df52f110c77ee8cffd2705af69b66506 | refs/heads/master | 2021-01-19T21:28:13.184309 | 2019-06-09T20:39:41 | 2019-06-09T20:48:34 | 5,324,741 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 7,835 | java | package es.tid.cim.diagram.edit.parts;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.RoundedRectangle;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.ToolbarLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ITextAwareEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.ConstrainedToolbarLayoutEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.notation.View;
import es.tid.cim.diagram.edit.policies.CIMLevelZeroTextSelectionEditPolicy;
import es.tid.cim.diagram.edit.policies.LANSegmentCanonicalEditPolicy;
import es.tid.cim.diagram.edit.policies.LANSegmentItemSemanticEditPolicy;
import es.tid.cim.diagram.part.CIMLevelZeroVisualIDRegistry;
/**
* @generated
*/
public class LANSegmentEditPart extends ShapeNodeEditPart {
/**
* @generated
*/
public static final int VISUAL_ID = 2084;
/**
* @generated
*/
protected IFigure contentPane;
/**
* @generated
*/
protected IFigure primaryShape;
/**
* @generated
*/
public LANSegmentEditPart(View view) {
super(view);
}
/**
* @generated
*/
protected void createDefaultEditPolicies() {
super.createDefaultEditPolicies();
installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
new LANSegmentItemSemanticEditPolicy());
installEditPolicy(EditPolicyRoles.CANONICAL_ROLE,
new LANSegmentCanonicalEditPolicy());
installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy());
// XXX need an SCR to runtime to have another abstract superclass that would let children add reasonable editpolicies
// removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE);
}
/**
* @generated
*/
protected LayoutEditPolicy createLayoutEditPolicy() {
ConstrainedToolbarLayoutEditPolicy lep = new ConstrainedToolbarLayoutEditPolicy() {
protected EditPolicy createChildEditPolicy(EditPart child) {
if (child.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE) == null) {
if (child instanceof ITextAwareEditPart) {
return new CIMLevelZeroTextSelectionEditPolicy();
}
}
return super.createChildEditPolicy(child);
}
};
return lep;
}
/**
* @generated
*/
protected IFigure createNodeShape() {
LANSegmentFigure figure = new LANSegmentFigure();
return primaryShape = figure;
}
/**
* @generated
*/
public LANSegmentFigure getPrimaryShape() {
return (LANSegmentFigure) primaryShape;
}
/**
* @generated
*/
protected boolean addFixedChild(EditPart childEditPart) {
if (childEditPart instanceof LANSegmentElementNameEditPart) {
((LANSegmentElementNameEditPart) childEditPart)
.setLabel(getPrimaryShape()
.getFigureLANSegmentElementNameFigure());
return true;
}
if (childEditPart instanceof WrappingLabel84EditPart) {
((WrappingLabel84EditPart) childEditPart)
.setLabel(getPrimaryShape().getFigureLANSegmentNameFigure());
return true;
}
return false;
}
/**
* @generated
*/
protected boolean removeFixedChild(EditPart childEditPart) {
return false;
}
/**
* @generated
*/
protected void addChildVisual(EditPart childEditPart, int index) {
if (addFixedChild(childEditPart)) {
return;
}
super.addChildVisual(childEditPart, -1);
}
/**
* @generated
*/
protected void removeChildVisual(EditPart childEditPart) {
if (removeFixedChild(childEditPart)) {
return;
}
super.removeChildVisual(childEditPart);
}
/**
* @generated
*/
protected IFigure getContentPaneFor(IGraphicalEditPart editPart) {
return super.getContentPaneFor(editPart);
}
/**
* @generated
*/
protected NodeFigure createNodePlate() {
DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(getMapMode()
.DPtoLP(40), getMapMode().DPtoLP(40));
return result;
}
/**
* Creates figure for this edit part.
*
* Body of this method does not depend on settings in generation model
* so you may safely remove <i>generated</i> tag and modify it.
*
* @generated
*/
protected NodeFigure createNodeFigure() {
NodeFigure figure = createNodePlate();
figure.setLayoutManager(new StackLayout());
IFigure shape = createNodeShape();
figure.add(shape);
contentPane = setupContentPane(shape);
return figure;
}
/**
* Default implementation treats passed figure as content pane.
* Respects layout one may have set for generated figure.
* @param nodeShape instance of generated figure class
* @generated
*/
protected IFigure setupContentPane(IFigure nodeShape) {
if (nodeShape.getLayoutManager() == null) {
ConstrainedToolbarLayout layout = new ConstrainedToolbarLayout();
layout.setSpacing(getMapMode().DPtoLP(5));
nodeShape.setLayoutManager(layout);
}
return nodeShape; // use nodeShape itself as contentPane
}
/**
* @generated
*/
public IFigure getContentPane() {
if (contentPane != null) {
return contentPane;
}
return super.getContentPane();
}
/**
* @generated
*/
public EditPart getPrimaryChildEditPart() {
return getChildBySemanticHint(CIMLevelZeroVisualIDRegistry
.getType(LANSegmentElementNameEditPart.VISUAL_ID));
}
/**
* @generated
*/
public class LANSegmentFigure extends RoundedRectangle {
/**
* @generated
*/
private WrappingLabel fFigureLANSegmentNameFigure;
/**
* @generated
*/
private WrappingLabel fFigureLANSegmentElementNameFigure;
/**
* @generated
*/
public LANSegmentFigure() {
ToolbarLayout layoutThis = new ToolbarLayout();
layoutThis.setStretchMinorAxis(false);
layoutThis.setMinorAlignment(ToolbarLayout.ALIGN_CENTER);
layoutThis.setSpacing(5);
layoutThis.setVertical(true);
this.setLayoutManager(layoutThis);
this.setCornerDimensions(new Dimension(getMapMode().DPtoLP(8),
getMapMode().DPtoLP(8)));
this.setMaximumSize(new Dimension(getMapMode().DPtoLP(100),
getMapMode().DPtoLP(135)));
createContents();
}
/**
* @generated
*/
private void createContents() {
fFigureLANSegmentNameFigure = new WrappingLabel();
fFigureLANSegmentNameFigure.setText("< LANSegment >");
this.add(fFigureLANSegmentNameFigure);
fFigureLANSegmentElementNameFigure = new WrappingLabel();
fFigureLANSegmentElementNameFigure.setText("");
this.add(fFigureLANSegmentElementNameFigure);
}
/**
* @generated
*/
private boolean myUseLocalCoordinates = false;
/**
* @generated
*/
protected boolean useLocalCoordinates() {
return myUseLocalCoordinates;
}
/**
* @generated
*/
protected void setUseLocalCoordinates(boolean useLocalCoordinates) {
myUseLocalCoordinates = useLocalCoordinates;
}
/**
* @generated
*/
public WrappingLabel getFigureLANSegmentNameFigure() {
return fFigureLANSegmentNameFigure;
}
/**
* @generated
*/
public WrappingLabel getFigureLANSegmentElementNameFigure() {
return fFigureLANSegmentElementNameFigure;
}
}
}
| [
"[email protected]"
] | |
0c5ef171144f28d9dcc6afd12407dae0792d1527 | b23fa335dd90ba80714175f98404903c7c18a902 | /src/main/java/brussels/formation/application/DeviceAction.java | 49c53ac38bcd73fe0a781142130c14e8666b8837 | [
"Apache-2.0"
] | permissive | tareqhb/Becarful | 3f0a0e2c05193fd32e12ab38db8a0ee780b4ff51 | 2c6e7356da6c884df916109137137e1368afed32 | refs/heads/master | 2020-03-29T22:56:12.274183 | 2018-09-26T15:28:47 | 2018-09-26T15:28:47 | 150,448,635 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,339 | java | package brussels.formation.application;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import brussels.formation.model.Device;
import brussels.formation.model.DeviceRepository;
@Component
public class DeviceAction {
// -----------------------------------------------------------------------------Property(ies)---
private DeviceRepository deviceRepository;
// ----------------------------------------------------------------------------Constructor(s)---
@Autowired
public DeviceAction(DeviceRepository deviceRepository) {
this.deviceRepository = deviceRepository;
}
// -------------------------------------------------------------------------------Override(s)---
// ---------------------------------------------------------------------------------Method(s)---
public List<Device> getDevice(String id) {
return deviceRepository.getDevice(id);
}
public List<Device> getLastDevice(String id,String id2) {
return deviceRepository.getLastDevice(id,id2);
}
public List<Device> getAll() {
return deviceRepository.getAll();
}
// -----------------------------------------------------------------------Getter(s)/Setter(s)---
}
| [
"[email protected]"
] | |
a0b99b0111991f00da173e1ee91665c68934a3c7 | a08c6ebc5af12842ae7db2fa5cc24f75d4c02e73 | /src/main/java/manager/ExcelReaderManager.java | 6d4889b6d682a52a2e3b83724ab3202b8891c5a7 | [] | no_license | shenbengit/Language | f4d210f047730d5cd34050ff32284504d532ae6a | 382e672b8496ff0775c89d26e7f872413acf179c | refs/heads/master | 2020-03-16T21:28:39.025926 | 2018-09-12T05:11:56 | 2018-09-12T05:11:56 | 133,000,452 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,674 | java | package manager;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* excel表格读取
*/
public class ExcelReaderManager {
/**
* excel表路径
*/
private String excelPath;
/**
* id所在列号
* 默认:0
*/
private int idColumn = 0;
/**
* 选择拼接语言的所在列号,在isAnalysedAll为false时有效
*/
private int targetColumn = 0;
/**
* 解析完生成结果路径
*/
private String saveFilePath;
/**
* 是否解析所有
* 默认只解析一个
*/
private boolean isAnalysedAll = false;
/**
* 设置读取信息配置,必须调用的方法
*
* @param excelPath excel表路径
* @param saveFilePath 解析完生成结果路径
*/
public void setReaderConfig(String excelPath, String saveFilePath) {
this.excelPath = excelPath;
this.saveFilePath = saveFilePath;
}
/**
* 设置id所在列号
*
* @param idColumn id所在列号
*/
public void setIdColumn(int idColumn) {
this.idColumn = idColumn;
}
/**
* 设置拼接语言的所在列号
*
* @param targetColumn 选择拼接语言的所在列号
*/
public void setTargetColumn(int targetColumn) {
this.targetColumn = targetColumn;
}
/**
* 是否解析所有
*
* @param analysedAll true: 会使设置的targetColumn无效
*/
public void setAnalysedAll(boolean analysedAll) {
isAnalysedAll = analysedAll;
}
/**
* 开始解析
*/
public void analyse() {
if (isEmpty(excelPath) || isEmpty(saveFilePath)) {
System.out.println("请先设置setReaderConfig(String excelPath,String saveFilePath)");
return;
}
final List<String> list = new ArrayList<String>();
final List<String> list1 = new ArrayList<String>();
final List<String> list2 = new ArrayList<String>();
final List<String> list3 = new ArrayList<String>();
final List<String> list4 = new ArrayList<String>();
final List<List<String>> mList = new ArrayList<List<String>>();
mList.add(list1);
mList.add(list2);
mList.add(list3);
mList.add(list4);
final List<Integer> integers = new ArrayList<Integer>();
InputStream is = null;
try {
//本地国际化文件地址
is = new FileInputStream(excelPath);
/*
*第二个参数excelTypeEnum,是根据excel表后缀选的 分别为:ExcelTypeEnum.XLS | ExcelTypeEnum.XLSX
*最好选用ExcelTypeEnum.XLS,经测试,选用ExcelTypeEnum.XLSX会出现解析错误的现象。可以将.xlsx转为.xls后进行解析
*/
ExcelReader reader = new ExcelReader(is, ExcelTypeEnum.XLS, null, new AnalysisEventListener<List<String>>() {
public void invoke(List<String> strings, AnalysisContext analysisContext) {
if (!isAnalysedAll) {
list.add("<string name=\"" + strings.get(idColumn) + "\">" + strings.get(targetColumn) + "</string>");
} else {
integers.clear();
//除id所在的列号,其他列号全部添加到integers
for (int i = 0; i < strings.size(); i++) {
if (i != idColumn) {
integers.add(i);
}
}
//如果列号太多,可以自行添加List<String>至mList中
if (integers.size() > 4) {
System.out.println("列数已超过5,请单独解析");
return;
}
//根据不同的列拼接,拼接的字符串存放至不同的集合中
for (int i = 0; i < integers.size(); i++) {
mList.get(i).add("<string name=\"" + strings.get(idColumn) + "\">" + strings.get(integers.get(i)) + "</string>");
}
}
}
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
if (!list.isEmpty()) {
//移除标题
list.remove(0);
} else {
list.clear();
//所有数据添加到list里
for (List<String> l : mList) {
if (!l.isEmpty()) {
//移除标题
l.remove(0);
list.addAll(l);
list.add("\n************************************************************************\n");
}
}
}
if (list.isEmpty()) {
return;
}
//list数据写入到文件里
FileOutputStream fileOutputStream;
BufferedWriter bufferedWriter;
File file = new File(saveFilePath);
try {
if (!file.exists()) {
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file, false);
bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
for (String str : list) {
bufferedWriter.write(str + "\n");
}
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("list: " + list.size());
}
});
reader.read();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
}
| [
"[email protected]"
] | |
16d9eb5dabee15c83f4b864372318e7c42056722 | 944c0092e8a643c87f7cae58f5f2bd729442af65 | /LOOKID/src/main/java/lookid/server/service/UserSESService.java | 4676f6912b08b1d0956d61b15854669e3a1e0a4d | [] | no_license | lookiesmu/LOOKID_BACK | 64ee99281e593a2962f17d08fc0c6b1826c6c96a | eb52a31ba7d87d1d399823ddb5d31c098d74111c | refs/heads/release | 2022-12-22T17:30:09.300071 | 2020-01-17T14:13:32 | 2020-01-17T14:13:32 | 197,785,794 | 0 | 2 | null | 2022-12-16T00:58:19 | 2019-07-19T14:21:51 | Java | UTF-8 | Java | false | false | 176 | java | package lookid.server.service;
import lookid.server.dto.SuccessDTO;
public interface UserSESService {
public SuccessDTO find_pw(String id, String mail) throws Exception;
}
| [
"[email protected]"
] | |
034978dd22722b06bb7c88afaf59f0d800b1072c | 661e800e319522826075c367ed385ec4f90cc439 | /src/utils/src/main/java/org/tio/utils/qr/scheme/IEvent.java | 1f55972575fb2e0704f54440b69fca1e58ebd305 | [
"Apache-2.0"
] | permissive | nuoyanliao/t-io | e91c715431552a2a009550dd9ac64d035869a9f9 | a1a79a553132923bedc554e06b600393cf452ab4 | refs/heads/master | 2022-01-19T12:26:14.092283 | 2018-05-31T03:18:50 | 2018-05-31T03:18:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,383 | java | package org.tio.utils.qr.scheme;
import static org.tio.utils.qr.scheme.SchemeUtil.LINE_FEED;
import static org.tio.utils.qr.scheme.SchemeUtil.getParameters;
import java.util.Map;
/**
* A simple wrapper for iEvent data to use with ZXing QR Code generator.
*
* <code>
* BEGIN:VEVENT
* UID:[email protected]
* DTSTAMP:19970714T170000Z
* ORGANIZER;CN=John Doe:MAILTO:[email protected]
* DTSTART:19970714T170000Z
* DTEND:19970715T035959Z
* SUMMARY:Bastille Day Party
* END:VEVENT
* </code>
*
*/
public class IEvent extends SubSchema {
public static final String NAME = "VEVENT";
private static final String BEGIN_EVENT = "BEGIN:VEVENT";
private static final String UID = "UID";
private static final String STAMP = "DTSTAMP";
private static final String ORGANIZER = "ORGANIZER";
private static final String START = "DTSTART";
private static final String END = "DTEND";
private static final String SUMMARY = "SUMMARY";
private String uid;
private String stamp;
private String organizer;
private String start;
private String end;
private String summary;
public IEvent() {
super();
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getStamp() {
return stamp;
}
public void setStamp(String stamp) {
this.stamp = stamp;
}
public String getOrganizer() {
return organizer;
}
public void setOrganizer(String organizer) {
this.organizer = organizer;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
@Override
public SubSchema parseSchema(Map<String, String> parameters, String code) {
if (parameters.containsKey(UID)) {
setUid(parameters.get(UID));
}
if (parameters.containsKey(STAMP)) {
setStamp(parameters.get(STAMP));
}
if (parameters.containsKey(START)) {
setStart(parameters.get(START));
}
if (parameters.containsKey(END)) {
setEnd(parameters.get(END));
}
if (parameters.containsKey(SUMMARY)) {
setSummary(parameters.get(SUMMARY));
}
Map<String, String> param = getParameters(code);
// TODO
return this;
}
@Override
public String generateString() {
StringBuilder sb = new StringBuilder();
sb.append(BEGIN_EVENT).append(LINE_FEED);
if (uid != null) {
sb.append(UID).append(":").append(uid).append(LINE_FEED);
} else if (stamp != null) {
sb.append(STAMP).append(":").append(stamp).append(LINE_FEED);
} else if (organizer != null) {
sb.append(ORGANIZER).append(";").append(organizer).append(LINE_FEED);
} else if (start != null) {
sb.append(START).append(":").append(start).append(LINE_FEED);
} else if (end != null) {
sb.append(END).append(":").append(end).append(LINE_FEED);
} else if (summary != null) {
sb.append(SUMMARY).append(":").append(summary).append(LINE_FEED);
}
sb.append(LINE_FEED).append("END:VEVENT");
return sb.toString();
}
@Override
public String toString() {
return generateString();
}
public static IEvent parse(Map<String, String> parameters, final String code) {
IEvent event = new IEvent();
event.parseSchema(parameters, code);
return event;
}
}
| [
"[email protected]"
] | |
9865e16a570dc557daab5542b00907048037330b | de24c449b32306f83b294b28cafb1adf9b1e4b14 | /app-toucai/src/flag_toucai/java/com/desheng/app/toucai/global/ConfigTouCai.java | c0e7bd2eff594443c76f427e888d9931c3cb08ae | [] | no_license | hnbn78/android-hq | a54a6faaa7226b3a0861c5b87556cd54f07f7b4b | 9787f3800512276cfffdb9b817df2538175e100e | refs/heads/main | 2023-04-07T22:54:47.660376 | 2021-04-07T18:07:43 | 2021-04-07T18:07:43 | 345,937,048 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,210 | java | package com.desheng.app.toucai.global;
import com.ab.global.Config;
import com.desheng.base.global.BaseConfig;
/**
* Created by lee on 2017/4/6 0006.
*/
public class ConfigTouCai extends BaseConfig {
static {
//TODO 正式
env = Config.ENV_PUBLISH;
HOST_PUBLISH = "http://tc.xsj280.com";
// //TODO 测试
// env = Config.ENV_DEVELOP;
// HOST_TEST = "http://test.tc508.com";
isSelfMonitor = !isPublish();
Config.DEFAULT_DB_NAME = "green-dao3.db";
//网络地址访问
HOST_LOCAL = "http://127.0.0.1:8080";
HOST_USER_PREFIX = "yx";
isUsePush = true;
isNetBanner = true;
isFloatBtnEnabled = true;//TODO 正式打包需求改成 true
if (isPublish()) {
ForceHost = HOST_PUBLISH;
//TODO 正式
SWITCH_LINE = HOST_PUBLISH + "/upload/json/app3.json";
} else {
//TODO 验收
ForceHost = HOST_TEST;
SWITCH_LINE = HOST_TEST + "/upload/json/app3.json";
}
CustomServiceLink = "https://v88.live800.com/live800/chatClient/chatbox.jsp?companyID=925834&configID=8015&jid=8547731414&s=1";
}
}
| [
"[email protected]"
] | |
e7dd7daa4bc53d8e25757638397d62179e278e20 | cc65cc30d1321439b21211710eee9265e72e46c2 | /Aplikasi_Pelayanan_Parkir_Baru/src/popup/popup_perusahaan.java | 036b3dce409f861a1db098e9b308170d4348aa78 | [] | no_license | opiktaopik20/Aplikasi_Pelayanan_Parkir | 2f61724bc214d18e68ca35f98af0d8b8caecc5cb | 331031f9f28dd0ac9cc8424ac93262b04ff78b96 | refs/heads/master | 2023-03-07T16:34:07.826496 | 2021-02-24T18:56:46 | 2021-02-24T18:56:46 | 341,995,393 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,337 | java | package popup;
import com.sun.glass.events.KeyEvent;
import transaksi.form_penjualan_kartu;
import java.sql.*;
import javax.swing.JOptionPane;
import koneksi.koneksi;
import javax.swing.table.DefaultTableModel;
public class popup_perusahaan extends javax.swing.JFrame {
private Connection conn = new koneksi().connect();
private DefaultTableModel tabmod;
public form_penjualan_kartu fa_perusahaan = null;
public popup_perusahaan() {
initComponents();
data_table();
txt_cari.requestFocus();
}
protected void data_table() {
Object[] Baris = {"Id Perusahaan", "Nama Perusahaan"};
tabmod = new DefaultTableModel (null, Baris);
tabel_perusahaan.setModel(tabmod);
tabel_perusahaan.setDefaultEditor(Object.class, null);
String sql = "SELECT * FROM data_perusahaan";
try {
java.sql.Statement stat = conn.createStatement();
ResultSet hasil = stat.executeQuery(sql);
while (hasil.next()) {
String a = hasil.getString("id_perusahaan");
String b = hasil.getString("nama_perusahaan");
String[] data = {a, b};
tabmod.addRow(data);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Database Tidak Terhubung " + e);
}
}
/**
* 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() {
jButton2 = new javax.swing.JButton();
cont_header = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
cont_isi = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
tabel_perusahaan = new javax.swing.JTable();
jPanel10 = new javax.swing.JPanel();
bcari = new javax.swing.JButton();
txt_cari = new javax.swing.JTextField();
brefresh = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jButton2.setText("jButton2");
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Data Karyawan");
setMinimumSize(new java.awt.Dimension(800, 400));
setName(""); // NOI18N
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
});
cont_header.setBackground(new java.awt.Color(0, 153, 153));
jLabel12.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel12.setForeground(new java.awt.Color(255, 255, 255));
jLabel12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gambar/staff - icon.png"))); // NOI18N
jLabel12.setText("Perusahaan");
javax.swing.GroupLayout cont_headerLayout = new javax.swing.GroupLayout(cont_header);
cont_header.setLayout(cont_headerLayout);
cont_headerLayout.setHorizontalGroup(
cont_headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(cont_headerLayout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jLabel12)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
cont_headerLayout.setVerticalGroup(
cont_headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, cont_headerLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
tabel_perusahaan.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tabel_perusahaan.getTableHeader().setReorderingAllowed(false);
tabel_perusahaan.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tabel_perusahaanMouseClicked(evt);
}
});
jScrollPane3.setViewportView(tabel_perusahaan);
bcari.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
bcari.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gambar/btn_search.png"))); // NOI18N
bcari.setText("Cari");
bcari.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bcariActionPerformed(evt);
}
});
txt_cari.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_cariKeyPressed(evt);
}
});
brefresh.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
brefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gambar/btn_refresh.png"))); // NOI18N
brefresh.setText("Refresh");
brefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
brefreshActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(57, 42, 42));
jLabel3.setText("Data Perusahaan");
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(brefresh)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_cari, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bcari)
.addGap(0, 0, 0))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bcari, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_cari, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(brefresh)
.addComponent(jLabel3)))
);
javax.swing.GroupLayout cont_isiLayout = new javax.swing.GroupLayout(cont_isi);
cont_isi.setLayout(cont_isiLayout);
cont_isiLayout.setHorizontalGroup(
cont_isiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(cont_isiLayout.createSequentialGroup()
.addContainerGap()
.addGroup(cont_isiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel10, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 760, Short.MAX_VALUE))
.addContainerGap())
);
cont_isiLayout.setVerticalGroup(
cont_isiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(cont_isiLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cont_header, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(cont_isi, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(cont_header, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cont_isi, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void tabel_perusahaanMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabel_perusahaanMouseClicked
try {
int tablepilih = tabel_perusahaan.getSelectedRow();
fa_perusahaan.str_id_perusahaan= tabel_perusahaan.getValueAt(tablepilih, 0).toString();
fa_perusahaan.str_nama_perusahaan = tabel_perusahaan.getValueAt(tablepilih, 1).toString();
fa_perusahaan.itemTerpilih_perusahaan();
this.setVisible(false);
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Data Tidak Tersimpan " + e);
}
}//GEN-LAST:event_tabel_perusahaanMouseClicked
private void brefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_brefreshActionPerformed
// TODO add your handling code here:
data_table();
txt_cari.setText("");
}//GEN-LAST:event_brefreshActionPerformed
private void bcariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bcariActionPerformed
Object[] Baris = {"Id Perusahaan", "Nama Perusahaan"};
tabmod = new DefaultTableModel (null, Baris);
tabel_perusahaan.setModel(tabmod);
tabel_perusahaan.setDefaultEditor(Object.class, null);
String sql = "select * from data_perusahaan where id_perusahaan like '%" + txt_cari.getText() + "%' or nama_perusahaan like '%" + txt_cari.getText() + "%'";
try {
java.sql.Statement stat = conn.createStatement();
ResultSet hasil = stat.executeQuery(sql);
while (hasil.next()) {
String a = hasil.getString("id_perusahaan");
String b = hasil.getString("nama_perusahaan");
String[] data = {a, b};
tabmod.addRow(data);
}
int cek_hasil = tabel_perusahaan.getRowCount();
if (cek_hasil == 0) {
JOptionPane.showMessageDialog(null, "Data Tidak Ditemukan");
data_table();
} else {
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Database Tidak Terhubung" + e);
}
}//GEN-LAST:event_bcariActionPerformed
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
// TODO add your handling code here:
//fa_driver.dispose_popup = true;
fa_perusahaan.itemTidakTerpilih();
}//GEN-LAST:event_formWindowClosed
private void txt_cariKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_cariKeyPressed
// TODO add your handling code here:
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
btn_search_driverActionPerformed(null);
}
}//GEN-LAST:event_txt_cariKeyPressed
/**//**/
/**
* @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(popup_perusahaan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(popup_perusahaan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(popup_perusahaan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(popup_perusahaan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new popup_perusahaan().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bcari;
private javax.swing.JButton brefresh;
private javax.swing.JPanel cont_header;
private javax.swing.JPanel cont_isi;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel10;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTable tabel_perusahaan;
private javax.swing.JTextField txt_cari;
// End of variables declaration//GEN-END:variables
private void btn_search_driverActionPerformed(Object object) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| [
"[email protected]"
] | |
3024c62bbb04e3898878be99fbb979d1babac403 | 5ae3676f1c878e1428a4eb87fa02eb56e0db93b0 | /Algorithm/src/others/ReOrderArray.java | e95dbb461b95dd4ff5b5f67ef290bf7ac5827be2 | [] | no_license | xmsx/Algorithm | f8eb54a3608afc71a813090578b9a25d29122c25 | 4bac6586c3832db1509bafe239aeaddf432b7230 | refs/heads/master | 2020-12-30T18:03:00.809170 | 2017-10-25T04:48:18 | 2017-10-25T04:48:18 | 90,947,555 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 603 | java | package others;
public class ReOrderArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = {1,2,3,4,5,6,7,8};
reOrderArray(array);
System.out.println(array[4]);
}
private static void reOrderArray(int[] array) {
// TODO Auto-generated method stub
for(int i=0;i<array.length-1;i++){
for(int j=0;j<array.length-1-i;j++){
if(array[j]%2==0&&array[j+1]%2==1){
int temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
}
}
| [
"[email protected]"
] | |
643227b560cb29af7d7b18a407c95933a6e1cacb | ac50f300ec505bf93a908d861a7c8e7cff3e0c0d | /ConnectionPoolingExp/src/com/learn/dbcp/conn/pool/DBCPConnProvider.java | 1e732a002247568c07a6ab6978c873a47d430c36 | [] | no_license | RishikeshShukla/DSConnectionPoolingExample | 97d7b51f25b07f4a050caed0194b8d221d5f03cc | d7587fe00bb3558f4f334a08275e54bd9d7187f6 | refs/heads/master | 2021-01-16T21:21:55.021732 | 2016-11-10T05:42:22 | 2016-11-10T05:42:22 | 62,583,642 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 493 | java | package com.learn.dbcp.conn.pool;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
public class DBCPConnProvider {
DBCPDataSource dbcpDS;
public DBCPConnProvider() {
try {
dbcpDS = DBCPDataSource.getInstance();
} catch (IOException | SQLException | PropertyVetoException e) {
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException {
return dbcpDS.getConnection();
}
}
| [
"[email protected]"
] | |
86e8a8fb0f0d811f96be63993830eac0962313f1 | 195737906d2b06d21c5395df2d3df01c8c0043a3 | /src/main/java/org/restaurant/repository/RoleRepository.java | e9f2355e0f234ddef2c62dd9d0d0ae7cd3a497ca | [] | no_license | thewolf25/Restaurent | e3c08b1cff1b801d00aa7318ef37e5718a212cd2 | 6ca694bccb9e88f977d2aab1bb5e6a487fa72b11 | refs/heads/master | 2023-02-27T08:55:29.759828 | 2021-02-03T16:12:04 | 2021-02-03T16:12:04 | 326,482,859 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 207 | java | package org.restaurant.repository;
import org.restaurant.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, Integer>{
}
| [
"[email protected]"
] | |
3efba61bc3a722a3c382d1f56a7776d72a0653bd | b57550ca3e3d5083a717b3fbb74175402fa42db5 | /ScapeRoom.java | 0dcef8aa49198447ab1091977a80dd844c89b254 | [] | no_license | MeloAguilar/ElEnteViviente | 334eb472105146caaef8cf6036a8a2a4e229cd2b | 7b843358639f887d797d037c65b3cc4a0b618118 | refs/heads/main | 2023-02-15T06:43:04.061107 | 2020-12-12T20:42:24 | 2020-12-12T20:42:24 | 316,324,902 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 31,846 | java | import java.util.Scanner;
public class ScapeRoom {
public static void main(String[] args) {
String eleccionEntrada;
boolean pistola = false, linterna = false, llavePequeña = false, llaveFinal = false, palanca = false, fotoLavabo = false,
llaveEscalera = false, pastillaCordura = false, llavesCoche = false, finDelJuego = false;
int habitacion = 0;
Scanner sc = new Scanner(System.in);
int pilasLinterna = 10, cordura = 100;
//En este juego responderas por teclado con las opciones expuestas en los corchetes.
//Hay varios requisitos. Para poder llegar a la planta de arriba tendrás que encontrar 3 objetos.
//La linterna, las llaves del coche y la llave de la segunda planta.
//Para terminar el juego deberás encontrar como abrir la puertade la izquierda.
//La llave pequeña y la palanca.
//No hay un único final. Cuando abras la puerta final existen 6 finales malos y uno no tan malo.
System.out.println("Estás en clase y te llega un Whatsapp de tu mejor amigo: es un audio donde \n" +
" se escuchan gritos. Segundos después, te envía su ubicación en tiempo real. En el mapa \n" +
" consigues ver que se encuentra en una casa a las afueras del pueblo, que parece abandonada. \n" +
"Preocupado, llamas a la policía sin suerte pues, al no haber pasado 72 horas desde su desaparición, \n" +
"te dicen que intentes ponerte en contacto con él o vayas a verle a casa antes de lanzar la alarma. \n" +
"Llamas a sus padres pero no contestan al teléfono así que decides ir a aquella casa que aparecía \n" +
"en su ubicación. Puede que esté en problemas \n" +
"\n" +
"Abres la puerta y entras. Esta se cierra tras de ti con un portazo\n" +
"......\n" +
"...");
System.out.println("-¿Qué haría Josh aquí?");
System.out.println("*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*");
//Comenzaremos el juego con una pequeña introduccion
System.out.println("INICIO DEL JUEGO\n" +
"*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*");
System.out.println("*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*");
System.out.println("Instrucciones");
System.out.println("-Tu vitalidad va guiada por la cordura.");
System.out.println("-Comienzas con 100 puntos de cordura.");
System.out.println("-Para decidir el camino escribe en pantalla cualquiera de las opciones entre corchetes.");
System.out.println("-La linterna es un item MUY importante.");
System.out.println("-La linterna funciona a pilas, comenzarás con 10 que se irán gastando mediante avances por la casa.");
System.out.println("-Podrás encontrar pilas para la linterna por la casa.");
System.out.println("-Hay al menos 10 finales diferentes.");
System.out.println("-Elige con lógica tus opciones si no quieres morir antes de tiempo.");
System.out.println("*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*");
System.out.println("*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*");
String inicio;
System.out.println("¿Quieres comenzar?");
System.out.println("[si] [no]");
inicio = sc.nextLine();
if (inicio.equals("si") || inicio.equals("no")) {
switch (inicio) {
case "no":
System.out.println("Esperamos que vuelvas pronto!!");
System.out.println("Created by Carmelo Aguilar & Pedro Cornejo");
break;
case "si":
System.out.println("La bicicleta resbala en el asfalto debido a la lluvia, que no podría haber empezado en un momento peor. \n" +
"Siguiendo las indicaciones que te da tu teléfono, giras a la izquierda y te sales de la carretera, pasando por un camino de tierra para llegar a una humilde casa de dos plantas y lo que parece ser un garaje. \n" +
"Está rodeada de árboles, lo que, junto al viento y la lluvia, crean la ilusión de que aquella casa cobrase vida.\n" +
"\n" +
"El jardín descuidado y las vallas llenas de óxido le dan un aspecto aún más desaliñado. Sin embargo, recuerdas por qué estás allí, te animas de valor y entras, arrepintiéndote prácticamente al instante.\n");
System.out.println("La casa no está mucho mejor por dentro de lo que está por fuera. Intentas respirar hondo, pero el olor a humedad hace que prefieras mantener tus respiraciones cortas. \n" +
"Justo enfrente, tienes las escaleras que acaban en una puerta, a la izquierda tienes una doble puerta cerrada que parece dirigir al salón y, a la derecha, \n" +
"una puerta algo más pequeña que seguramente irá al garaje, según la disposición que has visto desde fuera.");
while (pilasLinterna > 0 && cordura > 0) {
System.out.println("¿Dónde quieres ir? \n" +
"[salon] [garaje] [escaleras]\n" +
"Inventario [cosas]");
eleccionEntrada = sc.nextLine();
//Aquí encontraremos el inventario
if (eleccionEntrada.equals("cosas")) {
System.out.println("pilas: " + pilasLinterna);
System.out.println("cordura: " + cordura);
if (linterna == true) {
System.out.println("linterna");
}
if (llavesCoche == true) {
System.out.println("llave coche");
}
if (llaveEscalera == true) {
System.out.println("llave escalera");
}
if (llavePequeña == true) {
System.out.println("llave pequeña");
}
if (pistola == true) {
System.out.println("pistola");
}
if (pastillaCordura == true) {
char usarAdrenalina;
System.out.println("adrenalina");
System.out.println("¿usar?");
System.out.println("[si] [no]");
usarAdrenalina = sc.nextLine().charAt(0);
switch (usarAdrenalina) {
case 's':
if (cordura < 80) {
pilasLinterna--;
cordura = 100;
System.out.println("Recuperaste la cordura al máximo");
pastillaCordura = false;
} else {
System.out.println("En realidad no creo que lo necesite ahora");
}
break;
case 'n':
System.out.println("Sí, en verdad debería dejarlo para cuando lo necesite");
break;
}
}
} else if (eleccionEntrada.equals("salon") || eleccionEntrada.equals("garaje") || eleccionEntrada.equals("escaleras")) {
switch (eleccionEntrada) {
case "salon":
String eleccionesSalon;
System.out.println("Abres ambas puertas y crees poder " +
"ver el polvo revolotear por el aire,\n " +
"además de nuevamente ese olor a humedad y a " +
"cerrado insoportable. Intentas aclarar la vista, \n" +
"ya que está muy oscuro. Puedes distinguir unos cuadros en la " +
"pared del fondo, en el centro de la sala.\n " +
"En otra pared puedes ver un corcho con distintos papeles colgados.\n " +
"Por otro lado, Hay varios documentos esparcidos por " +
"la mesa y el sofá, están todos arrugados.");
pilasLinterna--;
boolean token = false;
while (!token) {
System.out.println("¿A qué quieres acercarte?");
System.out.println("[cuadros] [mesa] [dibujos] [salir]");
eleccionesSalon = sc.nextLine();
if (eleccionesSalon.equals("cuadros") || eleccionesSalon.equals("mesa") || eleccionesSalon.equals("dibujos")) {
switch (eleccionesSalon) {
case "cuadros":
System.out.println("Al acercarte, puedes ver que son unas fotos de cinco niños. " +
"Están llenos de polvo, tanto que casi no se pueden visualizar bien los rostros infantiles.\n " +
"Además, el cuadro del centro parece a punto de caerse. \n" +
"En un intento de acercar tu mano el cuadro cae al suelo sin darte tiempo para reaccionar, \n" +
"por lo que el marco se rompe. Delante de ti se descubre una caja fuerte \n" +
"con un código de cinco dígitos, tal vez haya algo que pueda servirte. \n" +
"De todas formas, te agachas para recoger el cuadro.");
System.out.println("(tú) Ahora puedo ver mejor la foto...\n" +
"¿Por qué me suena este chico?...");
System.out.println("¿Debería sonarme?");
System.out.println("Detrás de la foto puedes ver una fecha escrita: 1995");
System.out.println("¿Quieres probar o prefieres seguir buscando?");
System.out.println("[probar] [pasar]");
String cajaFuerte;
cajaFuerte = sc.nextLine();
if (cajaFuerte.equals("probar")) {
System.out.println("Hay una caja fuerte tras el cuadro central\n" +
"Parece que es un código numérico.");
System.out.println("(tú)Probaré con...");
String numeroSecreto = "9585", contraseña;
contraseña = sc.nextLine();
if (contraseña.equals(numeroSecreto)) {
System.out.println("Pones el código en la caja fuerte y " +
"se escucha un chasquido que indica que está abierta, \n" +
"Abres despacio la puerta para asegurarte de que no " +
"se levante más polvo del que ya hay en la habitación\n" +
"Metes la mano y sacas una linterna, suspirando agradecido. Ves un bulto al fondo\n" +
"Intentas alcanzarlo y cuando lo sacas puedes ver que es una especie de muñeca hecha con ramas. " +
"...como si fuera para algún tipo de ritual...");
System.out.println("La puerta de la caja fuerte tiene el número 7 grabado en su interior");
System.out.println("Inexplicable... La muñeca se resbala de tus manos y cae al suelo\n" +
"a la vez que escuchas un estruendoso golpe que parece venir de arriba.");
System.out.println("(Tú)Ni siquiera sé si debería subir, pero algo me llama a hacerlo");
linterna = true;
pilasLinterna--;
token = true;
} else {
System.out.println("Parece que no se abre, seguiré buscando por aquí");
pilasLinterna--;
}
} else if (cajaFuerte.equals("pasar")) {
System.out.println("seguiré buscando");
pilasLinterna--;
} else {
System.out.println("no creo que valga con eso");
}
break;
case "mesa":
System.out.println("Das unos pasos y te agachas junto a la mesa, " +
"estirando los papeles para intentar leer algo");
System.out.println("(tú)- son fotocopias de un anuncio de venta de la casa… \n" +
"pero en todas aparecen tachones y frases como “Bienvenido al infierno”. \n" +
"Un escalofrío te recorre mientras lo lees y te levantas con rapidez. \n" +
"Antes de alejarte, ves un post-it pegado a la mesa, en el que pone “+17590”");
pilasLinterna--;
break;
case "dibujos":
System.out.println("Te acercas a los dibujos que hay colgados en el corcho. \n" +
"Puedes ver animales y arcoíris dibujados de forma infantil, \n" +
"sin embargo, hay un dibujo que te llama la atención: \n" +
"Uno de un niño que va de la mano de un borrón negro con ojos, \n" +
"además se puede ver escrito J + A. En el borde del corcho \n" +
"se encuentra algo grabado: -10000");
pilasLinterna--;
break;
}
} else if (eleccionesSalon.equals("salir")) {
pilasLinterna--;
break;
}
}
break;
case "garaje":
if (llavesCoche && llaveEscalera) {
System.out.println("Hace demasiado frío aquí... mejor será seguir buscando.");
}
String eleccionGaraje1, eleccionGaraje2;
System.out.println("Entras y ves el coche y unas taquillas que están bastante alejadas \n" +
"de la puerta, totalmente sumidas en la oscuridad \n" +
",¿Quieres acercarte a las taquillas o prefieres investigar el coche?");
boolean tokenGaraje = false;
while (!tokenGaraje && cordura>0 && pilasLinterna>0) {
System.out.println("[coche] [taquillas] [salir]");
pilasLinterna--;
eleccionGaraje1 = sc.nextLine();
while (eleccionGaraje1.equals("coche") || eleccionGaraje1.equals("taquillas")) {
switch (eleccionGaraje1) {
case "coche":
if (!llavesCoche) {
System.out.println("Te asomas a la ventanilla del coche e intentas ver el interior. \n" +
"Los asientos están destrozados y parece que una colonia de bichos han conquistado el coche como nuevo hábitat.");
} else if (llavesCoche) {
tokenGaraje=false;
String libreta;
System.out.println("Pruebas a introducirla en la cerradura y, aunque el coche no reacciona de ninguna forma, la puerta se abre.\n " +
"Al tirar de ella para asomarte en su interior, escuchas como algunos bichos se esconden entre los recovecos del coche. \n" +
"Te armas de valor y coges la libreta del asiento del copiloto, esperando que no haya nada raro dentro. \n" +
"Justo antes de incorporarte, ves unas llaves en el suelo del coche, las cuales coges con velocidad.");
System.out.println("¿Quieres abrir la libreta?");
System.out.println("[si] [no]");
libreta = sc.nextLine();
switch (libreta) {
case "si":
System.out.println("Abres la libreta con cuidado, pues parece que se va a deshacer en cualquier momento. \n " +
"En la portada se puede leer “J. Howarthson”. Al pasar lentamente las páginas, ves que en todas aparece una fecha diferente,\n " +
"lo que te hace entender que puede ser una especie de diario. Te diriges a la última página \n" +
"y ves que la fecha corresponde a hace poco más de un año. En ella puedes leer:\n" +
"\n" +
"“Otra noche más en la que no me siento seguro en esta casa. \n" +
"Mis hijos han dejado de venir a verme porque temen que a sus hijos les pase algo.\n" +
"¿Qué va a pasarles si están con sus abuelos? No permitiría que nada les hiciera daño.\n " +
"Sin embargo… Linda cada vez está más perdida… ha perdido aquella sonrisa de la que me enamoré\n " +
"y también parece que está perdiendo las ganas de vivir. \n" +
"El pequeño Josh es el único que no sale llorando cada vez que viene.\n " +
"Más bien, parece que disfruta mucho de estar aquí, pero no entiendo por qué.\n" +
"Estoy perdiendo a toda mi familia por culpa de esta casa, debo venderla como sea”.");
break;
case "no":
System.out.println("(tú)No tengo tiempo para leer esto...");
break;
}
}
break;
case "taquillas":
System.out.println("Te acercas a las taquillas con cuidado de no resbalar con el aceite\n" +
"ha derramado el coche por todo el suelo. \n" +
"Cuando estás lo suficientemente cerca como para poder para poder leer,\n" +
"descubres que está escrito en la taquilla izquierda LUCIFER y en la derecha LUCIEL.\n" +
"\n" +
"¿Cuál prefieres abrir?\n" +
"[izq] [der]");
eleccionGaraje2 = sc.nextLine();
if(eleccionGaraje2.equals("izq") || eleccionGaraje2.equals("der")){
switch (eleccionGaraje2){
case "izq":
if (!linterna) {
System.out.println("Al tocar la taquilla sientes como el frío recorre tu cuerpo,\n " +
"y un olor a azufre sale del interior. Respirar hondo y coges con \n" +
"firmeza la puerta para abrirla pero una fuerza desconocida comienza a \n" +
"tirar de tu mano hacia adentro de la misma y tú, \n" +
"desesperado, intentas alejarte cuanto antes de la taquilla. \n" +
"Te acabas cayendo al suelo cuando la puerta se abre de par en par.\n " +
"Jurarías haber visto un rostro en la oscuridad de la taquilla, \n" +
"pero intentas pensar que tu imaginación te está jugando una mala pasada");
cordura -= 100;
pilasLinterna--;
} else if (linterna) {
System.out.println("Sintiéndote seguro de tu elección abres la " +
"taquilla y el fuerte olor que desprende te hace toser. \n" +
"No te apetece demasiado meter la mano ahí dentro, \n" +
"pero puedes divisar algo en el interior de la misma. \n" +
"Al meter la mano, sacas las llaves de un coche algo \n" +
"oxidadas que llevan un llavero colgado con distintos nombres:\n " +
"Molly, Robbie, Anna, Lilly y… ¿Josh?");
System.out.println("Hay muchos Josh en este mundo pero, con todo lo que está pasando,\n" +
"seguro que se refiere al Josh que yo conozco.\n" +
"Sin embargo...¿Quiénes son el resto de personas?\n" +
"Josh no tiene hermanos... Esto es muy extraño...");
cordura -= 25;
pilasLinterna--;
System.out.println("cordura-->"+cordura);
}
break;
case "der":
if (!linterna) {
System.out.println("Sintiéndote seguro de tu elección abres la taquilla \n" +
"y el fuerte olor que desprende te hace toser. \n" +
"No te apetece demasiado meter la mano ahí dentro, \n" +
"pero puedes divisar algo en el interior de la misma. \n" +
"Al meter la mano, sacas las llaves de un coche algo oxidadas \n" +
"que llevan un llavero colgado con distintos nombres: \n" +
"Molly, Robbie, Anna, Lilly y… ¿Josh? ");
cordura -= 90;
llavesCoche = true;
System.out.println(cordura);
pilasLinterna--;
} else if (linterna) {
System.out.println("Has encontrado las llaves del coche dentro de la taquilla \n" +
"mmmm... Parece que hay un numero escrito en la puerta [9]");
llavesCoche = true;
pilasLinterna--;
}
break;
}
}
break;
}
break;
}if (eleccionGaraje1.equals("salir")){
tokenGaraje = true;
}
}
break;
case "escaleras":
break;
}
}
}if (pilasLinterna <= 0 ){
System.out.println("te quedaste sin pilas en la linterna...");
System.out.println("FIN");
finDelJuego = true;
}else if( cordura <= 0) {
System.out.println("Tu cordura está a cero");
System.out.println("FIN");
finDelJuego = true;
}
break;//break del si inicial
}
}
}
}
| [
"[email protected]"
] | |
504a65ebc5fbbb2624cdc0fbfe2fde8cf6107b2e | 7e3141a25612ec2defd11e4c9cc4aae9e0a7116b | /src/main/java/com/altimetrik/greetingservice/config/Constants.java | 25d6ab7db1d63dd773f23a5b90d4d1e0c99a7389 | [] | no_license | sonirahul/altimetrik-greeting-service | 0c6f71dd12d9ca490132813485c85fdcbea98a50 | e3dec54a5e33513fc88d1faf985f4bf1f4ce9b65 | refs/heads/master | 2020-12-05T15:49:50.493907 | 2020-01-06T19:30:21 | 2020-01-06T19:30:21 | 232,161,606 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,606 | java | package com.altimetrik.greetingservice.config;
public final class Constants {
public static final int ZERO = 0;
public static final int ONE = 1;
public static final int TWO = 2;
public static final int THREE = 3;
public static final int FOUR = 4;
public static final int FIVE = 5;
public static final int SIX = 6;
public static final int SEVEN = 7;
public static final int EIGHT = 8;
public static final int NINE = 9;
public static final int TEN = 10;
public static final int TWENTY = 20;
public static final int INFINITE = 1000000000;
public static final String DEFAULT_INCLUDE_PATTERN = "/api/.*";
public static final String JWT = "JWT";
public static final String HEADER = "header";
public static final String BEARER = "Bearer ";
public static final String AUTHORIZATION = "Authorization";
public static final String AUTHORITIES_KEY = "auth";
public static final String USER_ID_KEY = "userId";
public static final String COMMA = ",";
public static final String EMPTY = "";
public static final String JWT_EXCEPTION = "JwtException";
public static final String EXPIRED_JWT_EXCEPTION = "ExpiredJwtException";
public static final String SIGNATURE_EXCEPTION = "SignatureException";
public static final String MALFORMED_JWT_EXCEPTION = "MalformedJwtException";
public static final String UNSUPPORTED_JWT_EXCEPTION = "UnsupportedJwtException";
public static final String ILLEGAL_ARGUMENT_EXCEPTION = "IllegalArgumentException";
public static final String ACCESS_DENIED = "Access Denied";
}
| [
"[email protected]"
] | |
3bc1bbaf1205e8dae57240743d8722c96e4c3156 | a8aac8b2f966c5171bbf6cfa5be264e0875d58e4 | /src/proxy/virtual/ImageComponent.java | a0f8540c19b05f3a57f97984bdd54f36c17fdc39 | [] | no_license | puzzledPublic/designPatternEx | fa3449a5be83f2dc95807255ae10ace2ac962de0 | 4ddba19c62628ae18aa97d8da73fa3624def2c31 | refs/heads/master | 2021-03-26T14:28:48.925938 | 2020-03-23T12:33:21 | 2020-03-23T12:33:21 | 247,712,555 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 535 | java | package proxy.virtual;
import java.awt.Graphics;
import javax.swing.JComponent;
public class ImageComponent extends JComponent {
private Icon icon;
public ImageComponent(Icon icon) {
this.icon = icon;
}
public void setIcon(Icon icon) {
this.icon = icon;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = icon.getIconWidth();
int h = icon.getIconHeight();
int x = (800 - w) / 2;
int y = (600 - h) / 2;
icon.paintIcon(this, g, x, y);
}
}
| [
"[email protected]"
] | |
6f1788c3c2e486d2e6ceb1c1db261a8aa4f9a83e | 9e319f4ec990d56e9f8b104a98e37e66ecbdc02b | /Core_Java_Programs/Address.java | 4c8a6bb6b0ca847fab36f905f0ebcc3702e5ea9f | [] | no_license | bhagya314/MKPITS_Bhagyashri_Lalsare_Java_Mar_2021 | d4e680a00c654792da98947c655b9f0d1a0d9be6 | 218e8f604b4fe9c9480a558b263e47ffb813f225 | refs/heads/main | 2023-07-13T12:37:51.188075 | 2021-08-20T14:53:39 | 2021-08-20T14:53:39 | 347,282,013 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,020 | java | package Com.mkpits.java.Aggregation;
public class Address
{
String city;
String state;
String country;
public Address(String city,String state,String country)
{
this.city=city;
this.state=state;
this.country=country;
}
}
class employee
{
int id;
String name;
Address address;
public employee(int id,String name,Address address)
{
this.id=id;
this.name=name;
this.address=address;
}
void display()
{
System.out.println(id + " : " +name);
System.out.println(address.city+":" +address.state +":" +address.country);
}
}
class aggregation {
public static void main(String[] arg)
{
Address adr = new Address("Chandrapur", "Maharashtra", "India");
Address adr1 = new Address("Chandigar", "Panjab", "India");
employee emp = new employee(11, "Bhagya", adr);
employee emp1 = new employee(12, "Vicky", adr1);
emp.display();
emp1.display();
}
} | [
"[email protected]"
] | |
e4f7c9c1587988e3c7f34853541dcc9115089880 | cb73a4919c09adfc7ee768c56c67b811130f7166 | /src/com/hxlm/health/web/interceptor/MemberInterceptor.java | 99b93c6d6a39fc471c146f68b2c0bcf433026035 | [] | no_license | wangyalanbao/zwtx | fcf9a7ea373efdbd5398c25c5664aae1f86f0b34 | 0dcb43015f76490aa163551eeeec33eded35a008 | refs/heads/master | 2021-04-09T13:01:40.935918 | 2018-03-14T02:49:51 | 2018-03-14T02:49:51 | 124,730,821 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,201 | java | /*
*
*
*
*/
package com.hxlm.health.web.interceptor;
import java.io.Writer;
import java.net.URLEncoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.hxlm.health.web.ErrorMsg;
import com.hxlm.health.web.Status;
import com.hxlm.health.web.service.MemberService;
import com.hxlm.health.web.Principal;
import com.hxlm.health.web.entity.Member;
import com.hxlm.health.web.util.WebUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* Interceptor - 会员权限
*
*
*
*/
public class MemberInterceptor extends HandlerInterceptorAdapter {
/** 重定向视图名称前缀 */
private static final String REDIRECT_VIEW_NAME_PREFIX = "redirect:";
/** "重定向URL"参数名称 */
private static final String REDIRECT_URL_PARAMETER_NAME = "redirectUrl";
/** "会员"属性名称 */
private static final String MEMBER_ATTRIBUTE_NAME = "member";
/** 区分请求来源属性名称 */
public static final String VERSION_NAME = "version";
/** 默认登录URL */
private static final String DEFAULT_LOGIN_URL = "/login.jhtml";
/** 默认登录URL */
private static final String MOBILE_LOGIN_URL = "/mobile/logins.jhtml";
/** 登录URL */
private String loginUrl = DEFAULT_LOGIN_URL;
@Value("${url_escaping_charset}")
private String urlEscapingCharset;
@Resource(name = "memberServiceImpl")
private MemberService memberService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Principal principal = (Principal) session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
if (principal != null) {
return true;
} else {
String version = request.getHeader(VERSION_NAME);
if (version != null) {
ErrorMsg errorMsg = new ErrorMsg();
errorMsg.setCode(Status.UNLOGIN);
errorMsg.setMessage("请先登录后在进行相关操作!");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
Writer writer = response.getWriter();
JSONObject json = JSONObject.fromObject(errorMsg);
writer.write(json.toString());
writer.flush();
writer.close();
return false;
} else {
if (request.getRequestURI().contains("/mobile/")) {
String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
response.sendRedirect(request.getContextPath() + MOBILE_LOGIN_URL + "?" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(redirectUrl, urlEscapingCharset));
return false;
} else {
String requestType = request.getHeader("X-Requested-With");
if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
response.addHeader("loginStatus", "accessDenied");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
} else {
if (request.getMethod().equalsIgnoreCase("GET")) {
String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
response.sendRedirect(request.getContextPath() + loginUrl + "?" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(redirectUrl, urlEscapingCharset));
} else {
response.sendRedirect(request.getContextPath() + loginUrl);
}
return false;
}
}
}
// String requestType = request.getHeader("X-Requested-With");
// if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
// response.addHeader("loginStatus", "accessDenied");
// response.sendError(HttpServletResponse.SC_FORBIDDEN);
// return false;
// } else {
// if (request.getMethod().equalsIgnoreCase("GET")) {
// String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
// response.sendRedirect(request.getContextPath() + loginUrl + "?" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(redirectUrl, urlEscapingCharset));
// } else {
// response.sendRedirect(request.getContextPath() + loginUrl);
// }
// return false;
// }
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
String viewName = modelAndView.getViewName();
if (!StringUtils.startsWith(viewName, REDIRECT_VIEW_NAME_PREFIX)) {
modelAndView.addObject(MEMBER_ATTRIBUTE_NAME, memberService.getCurrent());
}
}
}
/**
* 获取登录URL
*
* @return 登录URL
*/
public String getLoginUrl() {
return loginUrl;
}
/**
* 设置登录URL
*
* @param loginUrl
* 登录URL
*/
public void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
} | [
"[email protected]"
] | |
3dc6fe0afa83637e3c68206e60e9149976bd3a6d | 19fe992d84ce81061ec9ae796bbdaf046d4f6d7d | /src/main/java/com/dimple/project/system/domain/vo/RouterVo.java | 0f785e24af1066b1aad6196af0e8685cbb1d0cda | [
"Apache-2.0"
] | permissive | tchigher/DimpleBlog | 503c170396e0a2c2a89289ca87d5b5686714b766 | f81747236f6f80601945a7b797a0b11744bbab79 | refs/heads/master | 2022-03-29T22:33:23.535437 | 2019-12-30T10:55:30 | 2019-12-30T10:55:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,098 | java | package com.dimple.project.system.domain.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.util.List;
/**
* @className: RouterVo
* @description: 路由配置信息
* @author: Dimple
* @date: 10/22/19
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Data
public class RouterVo {
/**
* 路由名字
*/
private String name;
/**
* 路由地址
*/
private String path;
/**
* 是否隐藏路由,当设置 true 的时候该路由不会再侧边栏出现
*/
private String hidden;
/**
* 重定向地址,当设置 noRedirect 的时候该路由在面包屑导航中不可被点击
*/
private String redirect;
/**
* 组件地址
*/
private String component;
/**
* 当你一个路由下面的 children 声明的路由大于1个时,自动会变成嵌套的模式--如组件页面
*/
private Boolean alwaysShow;
/**
* 其他元素
*/
private MetaVo meta;
/**
* 子路由
*/
private List<RouterVo> children;
}
| [
"[email protected]"
] | |
5a84303f1e2175ab8089715e0264c080af93bbcb | 2b21bd735f9df96010787d1276af0ce918f54b83 | /src/network/Node.java | 97a7611de8e63c7ee8084607dd865b586fdcfd82 | [
"BSD-3-Clause"
] | permissive | oakamel/blockchain-simulation | e9ad812f0611a5b8b2965337f7b571871169b44e | 2ff09f3457ef9c638b11342537fc0ca57e10d112 | refs/heads/master | 2020-04-06T23:33:18.625559 | 2018-11-16T13:47:12 | 2018-11-16T13:47:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 24,476 | java | package network;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import blocks.Block;
import blocks.ChainedHashMap;
import transactions.PeerToPeerTransaction;
import transactions.RewardTransaction;
import transactions.Transaction;
import transactions.TransactionBufferInputs;
import transactions.Trindex;
import transactions.UTXOReward;
public class Node {
// For printing only
String displayName;
private PublicKey publicKey;
private PrivateKey privateKey;
public ArrayList<Node> connectedNeighbors;
public ArrayList<Transaction> transactionsNotInABlock;
public ArrayList<Trindex> UTXOSet;
public ArrayList<ChainedHashMap> forks;
public ChainedHashMap blockChain;
public ArrayList<TransactionBufferInputs> myTransactionsBuffer;
int pendingTransactionIndex;
private PrintStream stream;
public ArrayList<ChainedHashMap> allForks;
public Node(String displayName) {
this.displayName = displayName;
OutputStream out;
try {
out = new FileOutputStream(this.displayName + ".txt");
this.stream = new PrintStream(out);
stream.println("Logging for Node: " + this.displayName);
stream.println();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
intializeKeys();
intializeStructures();
}
public void fancyPrint(String s) {
System.out.println(s);
stream.println(s);
}
public void fancyPrint(String s,boolean error) {
System.err.println(s);
stream.println(s);
}
public void fancyPrint() {
System.out.println();
stream.println();
}
private void intializeStructures() {
this.UTXOSet = new ArrayList<Trindex>();
this.connectedNeighbors = new ArrayList<Node>();
this.transactionsNotInABlock = new ArrayList<Transaction>();
this.forks = new ArrayList<ChainedHashMap>();
this.blockChain = new ChainedHashMap();
this.myTransactionsBuffer = new ArrayList<TransactionBufferInputs>();
this.allForks = new ArrayList<ChainedHashMap>();
pendingTransactionIndex = 0;
}
public void intializeKeys() {
KeyPairGenerator keyGen;
try {
keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(1024, new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
privateKey = pair.getPrivate();
publicKey = pair.getPublic();
} catch (NoSuchAlgorithmException e) {
System.err.println(e.getMessage());
}
}
public ArrayList<Node> getConnectedNeighbors() {
return connectedNeighbors;
}
public void addNeighbor(Node n) {
if (!this.connectedNeighbors.contains(n))
this.connectedNeighbors.add(n);
}
public int getNeighborsSize() {
return this.connectedNeighbors.size();
}
public void setConnectedNeighbors(ArrayList<Node> connectedNeighbors) {
this.connectedNeighbors = connectedNeighbors;
}
public String getDisplayName() {
return this.displayName;
}
public PublicKey getPublicKey() {
return publicKey;
}
public void bootstrap(ChainedHashMap blocks) {
for (int i = 0; i < blocks.size(); i++) {
this.blockChain.put(blocks.get(i).getThisBlockHashPointer(), blocks.get(i));
for (Transaction trans : blocks.get(i).getTransactions()) {
if (trans instanceof PeerToPeerTransaction) {
for (Trindex trin : ((PeerToPeerTransaction) trans).getInputs()) {
if (this.UTXOSet.contains(trin))
UTXOSet.remove(trin);
}
UTXOSet.add(new Trindex(trans.clone(), 0));
if (((PeerToPeerTransaction) trans).getChange().getAmount() != 0)
UTXOSet.add(new Trindex(trans.clone(), 1));
} else
UTXOSet.add(new Trindex(trans.clone(), 0));
}
}
}
public void printBlockChainsAndForks() {
fancyPrint("Node: " + this.displayName);
fancyPrint("Blockchain's ");
fancyPrint(this.blockChain.toString());
fancyPrint("forks: ");
fancyPrint(this.forks.toString());
// fancyPrint("all forks: ");
// fancyPrint(this.allForks.toString());
}
public void recieveTransaction(Transaction transaction, Node sender) {
//TODO
if (!this.transactionsNotInABlock.contains(transaction) && validateTransactionOrigin(transaction)
&& validateTransactionIntegrity(transaction)
)
{
fancyPrint("--------------------------- Transactions Recieved ----------------");
fancyPrint("Node: " + this.displayName);
fancyPrint("Recieved Transaction: " + "\n" + transaction);
fancyPrint("From: " + sender.displayName);
fancyPrint("Timestamp: " + ((System.currentTimeMillis() - Network.startTime)));
fancyPrint("-------------------------------------------------------------------");
fancyPrint();
this.addTransactionToTransactionsNotInABlock(transaction);
this.gossip(transaction);
} else {
fancyPrint("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Transactions Ignored ");
fancyPrint("Node: " + this.displayName);
fancyPrint("Ignored Transaction: " + transaction.getId());
fancyPrint("From: " + sender.displayName);
fancyPrint("Timestamp: " + ((System.currentTimeMillis() - Network.startTime)));
fancyPrint("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
fancyPrint();
}
}
public void runMyTransactionBuffer() {
if(pendingTransactionIndex<=myTransactionsBuffer.size() && myTransactionsBuffer.size()>0) {
ArrayList<Transaction> transactionsInBlockChain = new ArrayList<Transaction>();
for (int i = 0; i < blockChain.size(); i++) {
Block currentBlock = blockChain.get(i);
for (Transaction trans : currentBlock.getTransactions()) {
transactionsInBlockChain.add(trans);
}
}
if(pendingTransactionIndex == 0) {
System.err.println("ruuuuuuuuuning traaaaaaaaans");
runTransaction(myTransactionsBuffer.get(pendingTransactionIndex));
pendingTransactionIndex++;
}else {
if(transactionsInBlockChain.contains(myTransactionsBuffer.get(pendingTransactionIndex - 1).createdTransaction)) {
runTransaction(myTransactionsBuffer.get(pendingTransactionIndex));
pendingTransactionIndex++;
}
}
}
}
public void makeTransaction(PublicKey recieverNPublickKey, String recieverDisplayName, double amount, double fees) {
// myTransactionsBuffer.add(new TransactionBufferInputs(recieverNPublickKey, recieverDisplayName, amount, fees));
// runMyTransactionBuffer();
//TODO
ArrayList<Trindex> inputs = this.findTransactionsToSatisfyAmount(amount + fees);
fancyPrint("In node: " + this.displayName);
fancyPrint("Making a transaction: ");
fancyPrint("Inputs are: " + inputs);
PeerToPeerTransaction trans = new PeerToPeerTransaction(this.publicKey, recieverNPublickKey, this.displayName,
recieverDisplayName, amount, fees, inputs);
if (trans.isCreated()) {
// trans.id = this.displayName + " " + amount + " " + recieverDisplayName;
//fancyPrint(trans.toString());
this.signTransaction(trans);
this.addTransactionToTransactionsNotInABlock(trans);
this.gossip(trans);
}
}
public void makeTransaction(PublicKey recieverNPublickKey, String recieverDisplayName, double amount, double fees,ArrayList<Trindex> inputs) {
// myTransactionsBuffer.add(new TransactionBufferInputs(recieverNPublickKey, recieverDisplayName, amount, fees));
// runMyTransactionBuffer();
//TODO
fancyPrint("In node: " + this.displayName);
fancyPrint("Making a transaction: ");
fancyPrint("Inputs are: " + inputs);
PeerToPeerTransaction trans = new PeerToPeerTransaction(this.publicKey, recieverNPublickKey, this.displayName,
recieverDisplayName, amount, fees, inputs);
if (trans.isCreated()) {
// trans.id = this.displayName + " " + amount + " " + recieverDisplayName;
fancyPrint(trans.toString());
this.signTransaction(trans);
this.addTransactionToTransactionsNotInABlock(trans);
this.gossip(trans);
}
}
public void runTransaction(TransactionBufferInputs transactionBufferInputs) {
PublicKey recieverNPublickKey = transactionBufferInputs.recieverNPublickKey;
String recieverDisplayName = transactionBufferInputs.recieverDisplayName;
double amount = transactionBufferInputs.amount;
double fees = transactionBufferInputs.fees;
ArrayList<Trindex> inputs = this.findTransactionsToSatisfyAmount(amount + fees);
fancyPrint("In node: " + this.displayName);
fancyPrint("Making a transaction: ");
fancyPrint("Inputs are: " + inputs);
PeerToPeerTransaction trans = new PeerToPeerTransaction(this.publicKey, recieverNPublickKey, this.displayName,
recieverDisplayName, amount, fees, inputs);
if (trans.isCreated()) {
// trans.id = this.displayName + " " + amount + " " + recieverDisplayName;
fancyPrint(trans.toString());
this.signTransaction(trans);
transactionBufferInputs.createdTransaction = trans;
this.addTransactionToTransactionsNotInABlock(trans);
this.gossip(trans);
}
}
public ArrayList<Trindex> findTransactionsToSatisfyAmount(double amount) {
ArrayList<Trindex> myTransactions = new ArrayList<Trindex>();
ArrayList<Trindex> result = new ArrayList<Trindex>();
for (Trindex trin : this.UTXOSet) {
Transaction trans = trin.getTransaction();
int index = trin.getIndex();
if (trans.getOutput(index).getRecieverPublicKey().equals(this.getPublicKey()))
myTransactions.add(trin);
}
Collections.sort(myTransactions, new Comparator<Trindex>() {
public int compare(Trindex o1, Trindex o2) {
if (o1.getTransaction().getOutput(o1.getIndex()).getAmount() == o2.getTransaction()
.getOutput(o2.getIndex()).getAmount())
return 0;
if (o1.getTransaction().getOutput(o1.getIndex()).getAmount() < o2.getTransaction()
.getOutput(o2.getIndex()).getAmount())
return -1;
return 1;
}
});
double totalAggregatedAmount = 0;
for (Trindex trin : myTransactions) {
totalAggregatedAmount += trin.getTransaction().getOutput(trin.getIndex()).getAmount();
if (totalAggregatedAmount >= amount) {
result.add(trin);
break;
}
}
return result;
}
public void addTransactionToTransactionsNotInABlock(Transaction transaction) {
this.transactionsNotInABlock.add(transaction);
if (this.transactionsNotInABlock.size() >= Network.numberOfTransactionsInABlock)
mine();
}
public void mine() {
fancyPrint("");
fancyPrint("Node: " + this.displayName + " Started mining");
fancyPrint();
Transaction[] transactionsToBeAddedToBlock = new Transaction[Network.numberOfTransactionsInABlock + 1];
for (int i = 1; i < transactionsToBeAddedToBlock.length; i++)
transactionsToBeAddedToBlock[i] = transactionsNotInABlock.remove(0).clone();
UTXOReward reward = new UTXOReward(this.publicKey, this.displayName, Network.baseReward);
Transaction trans = new RewardTransaction(reward);
transactionsToBeAddedToBlock[0] = trans;
int indexOfLongestChain = getIndexOfLongestChain();
String previousHashPointer = "";
int number = 0;
if (indexOfLongestChain == -1) {
previousHashPointer = this.blockChain.last().getThisBlockHashPointer();
indexOfLongestChain = 0;
number = this.blockChain.last().getNumber() + 1;
} else {
previousHashPointer = this.forks.get(indexOfLongestChain).last().getThisBlockHashPointer();
number = this.forks.get(indexOfLongestChain).last().getNumber() + 1;
}
String allTransactionsAndPreviousHash = this.findAllStringsToBeHashed(transactionsToBeAddedToBlock,
previousHashPointer);
Long nonce = findNonce(allTransactionsAndPreviousHash, Network.nonceTarget);
String thisBlockHashPointer = Network.sha256(nonce + allTransactionsAndPreviousHash);
java.sql.Timestamp createdAt = new java.sql.Timestamp(System.currentTimeMillis());
Block newBlock = new Block(transactionsToBeAddedToBlock, previousHashPointer, thisBlockHashPointer, nonce,
createdAt, this, number);
//TODO
fancyPrint("---------------------------------------");
fancyPrint("Node: " + this.displayName);
fancyPrint("submitted block to network");
fancyPrint(newBlock.toString());
fancyPrint("---------------------------------------");
fancyPrint();
Network.addBlockToNetwork(this, newBlock);
}
public int getIndexOfLongestChain() {
if (this.forks.size() != 0) {
int sizeOfLongestChain = this.forks.get(0).size();
int indexOfLongestChain = 0;
for (int i = 1; i < this.forks.size(); i++) {
if (this.forks.get(i).size() > sizeOfLongestChain) {
sizeOfLongestChain = this.forks.get(i).size();
indexOfLongestChain = i;
}
}
return indexOfLongestChain;
} else {
return -1;
}
}
public void gossip(Transaction transaction) {
//TODO
int random = (int) (this.connectedNeighbors.size() * Math.random());
Collections.shuffle(connectedNeighbors);
for (int i = 0; i < random; i++)
this.connectedNeighbors.get(i).recieveTransaction(transaction.clone(), this);
// for(Node node:this.connectedNeighbors)
// node.recieveTransaction(transaction, this);
}
public void gossip(Block block) {
// if (block.getMiner().equals(this)) {
// addBlockToItsPlaceInTheFork(block);
// }
//TODO
int random = (int) (this.connectedNeighbors.size() * Math.random());
Collections.shuffle(connectedNeighbors);
for (int i = 0; i < random; i++)
this.connectedNeighbors.get(i).recieveBlock(block.clone(), this);
// for(Node node:this.connectedNeighbors)
// node.recieveBlock(block, this);
}
public void recieveBlock(Block block, Node sender) {
if (!recievedThisBlockBefore(block)) {
if (allTransactionsInThisBlockHaveValidInputs(block)) {
if (noCommonInputsBetweenTransactionsInThisBlock(block)) {
fancyPrint("--------------------------- Block Recieved -----------------------");
fancyPrint("Node: " + this.displayName);
fancyPrint("Recieved Block: " + block.getThisBlockHashPointer());
fancyPrint("Recieved Block: " + "\n" + block);
fancyPrint("From: " + sender.displayName);
fancyPrint("Timestamp: " + ((System.currentTimeMillis() - Network.startTime)));
fancyPrint("------------------------------------------------------------------");
fancyPrint();
if(addBlockToItsPlaceInTheFork(block))
{
checkConsensus();
gossip(block);
}
} else {
fancyPrint("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Block Ignored",true);
fancyPrint("Node: " + this.displayName,true);
fancyPrint("Fraud block: " + block.getThisBlockHashPointer(),true);
fancyPrint("From: " + sender.displayName,true);
fancyPrint("Timestamp: " + ((System.currentTimeMillis() - Network.startTime)),true);
fancyPrint("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
fancyPrint();
}
} else {
fancyPrint("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Block Ignored",true);
fancyPrint("Node: " + this.displayName,true);
fancyPrint("Block contains faulty transactions: " + block.getThisBlockHashPointer(),true);
fancyPrint("From: " + sender.displayName,true);
fancyPrint("Timestamp: " + ((System.currentTimeMillis() - Network.startTime)),true);
fancyPrint("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",true);
fancyPrint();
}
} else {
fancyPrint("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Block Ignored");
fancyPrint("Node: " + this.displayName);
fancyPrint("Recieved block before: " + block.getThisBlockHashPointer());
fancyPrint("From: " + sender.displayName);
fancyPrint("Timestamp: " + ((System.currentTimeMillis() - Network.startTime)));
fancyPrint("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
fancyPrint();
}
}
public boolean noCommonInputsBetweenTransactionsInThisBlock(Block block) {
ArrayList<Trindex> inputs = new ArrayList<Trindex>();
for (Transaction trans : block.getTransactions())
if (trans instanceof PeerToPeerTransaction)
for (Trindex trin : ((PeerToPeerTransaction) trans).getInputs())
if (!inputs.contains(trin))
inputs.add(trin);
else
return false;
return true;
}
public boolean addBlockToItsPlaceInTheFork(Block block) {
String previousBlockHashPointer = block.getPreviousBlockHashPointer();
if (this.blockChain.last().getThisBlockHashPointer().equals(previousBlockHashPointer)) {
ChainedHashMap newFork = new ChainedHashMap();
newFork.put(block.getThisBlockHashPointer(), block.clone());
this.forks.add(newFork);
} else {
for (ChainedHashMap fork : this.forks) {
if (fork.last().getThisBlockHashPointer().equals(previousBlockHashPointer)) {
if (checkCommonPreviousTransactionsBetweenBlockAndFrok(block, fork)) {
fork.put(block.getThisBlockHashPointer(), block.clone());
} else {
fancyPrint("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Block Ignored");
fancyPrint("Node: " + this.displayName);
fancyPrint(
"Block contains transactions from previous blocks: " + block.getThisBlockHashPointer());
fancyPrint("Timestamp: " + ((System.currentTimeMillis() - Network.startTime)));
fancyPrint("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
fancyPrint();
return false;
}
break;
}
}
}
return true;
}
public boolean checkCommonPreviousTransactionsBetweenBlockAndFrok(Block block, ChainedHashMap fork) {
ArrayList<Transaction> transactionsInFork = new ArrayList<Transaction>();
for (int i = 0; i < fork.size(); i++) {
Block currentBlock = fork.get(i);
for (Transaction trans : currentBlock.getTransactions()) {
transactionsInFork.add(trans);
}
}
for (Transaction trans : block.getTransactions()) {
if (transactionsInFork.contains(trans))
return false;
}
return true;
}
public void checkConsensus() {
int longest = 0;
int indexOfLongestChain = 0;
int secondLongest = 0;
for (int i = 0; i < this.forks.size(); i++) {
int newSize = forks.get(i).size();
if (newSize > longest) {
longest = newSize;
indexOfLongestChain = i;
}
}
for (int i = 0; i < this.forks.size(); i++) {
int newSize = forks.get(i).size();
if (newSize <= longest && i != indexOfLongestChain) {
if (newSize > secondLongest) {
secondLongest = newSize;
}
}
}
if (longest - secondLongest >= Network.numberOfBlocksToReachConsensus) {
ChainedHashMap longestChain = this.forks.get(indexOfLongestChain);
int startingIndex = this.blockChain.size();
for (int i = 0; i < longestChain.size() - Network.numberOfBlocksToReachConsensus; i++) {
this.blockChain.put(longestChain.get(i).getThisBlockHashPointer(), longestChain.get(i).clone());
}
int stopAt = longestChain.size() - Network.numberOfBlocksToReachConsensus;
for (int i = 0; i < stopAt; i++) {
longestChain.remove(0);
}
ArrayList<Transaction> transactionsInBlocksMinedByMeButDropped = new ArrayList<Transaction>();
for (int i = 0; i < this.forks.size(); i++) {
if (i != indexOfLongestChain) {
ChainedHashMap currentChain = this.forks.get(i);
for (int j = 0; j < currentChain.size(); j++) {
if (currentChain.get(j).getMiner().equals(this)) {
for (Transaction trans : currentChain.get(j).getTransactions())
transactionsInBlocksMinedByMeButDropped.add(trans);
}
}
}
}
this.forks.clear();
if(longestChain.size()!=0)
this.forks.add(longestChain);
updateUTXOSet(startingIndex, transactionsInBlocksMinedByMeButDropped);
//runMyTransactionBuffer();
}
}
public void updateUTXOSet(int startingIndex, ArrayList<Transaction> transactionsInBlocksMinedByMeButDropped) {
System.out.println("UPDATING UTXO SET!");
System.out.println("transactions in a block to mined by me: " +
transactionsInBlocksMinedByMeButDropped);
System.out.println("starting index: " + startingIndex);
System.out.println("OLD UTXO");
System.out.println(this.UTXOSet);
System.out.println("Traversing the blockchain");
for (int i = startingIndex; i < this.blockChain.size(); i++) {
Block currentBlock = this.blockChain.get(i);
// System.out.println("current block is: " + currentBlock);
for (Transaction trans : currentBlock.getTransactions()) {
// System.out.println("current trans is: " + trans);
if (transactionsInBlocksMinedByMeButDropped.contains(trans))
transactionsInBlocksMinedByMeButDropped.remove(trans);
if (trans instanceof PeerToPeerTransaction) {
for (Trindex trin : ((PeerToPeerTransaction) trans).getInputs()) {
// System.out.println("current trindex is: " + trin);
if (this.UTXOSet.contains(trin)) {
// System.out.println("Removing trindex: " + trin);
UTXOSet.remove(trin);
}
}
UTXOSet.add(new Trindex(trans.clone(), 0));
if (((PeerToPeerTransaction) trans).getChange().getAmount() != 0)
UTXOSet.add(new Trindex(trans.clone(), 1));
} else
UTXOSet.add(new Trindex(trans.clone(), 0));
}
}
for (Transaction trans : transactionsInBlocksMinedByMeButDropped)
if (!this.transactionsNotInABlock.contains(trans))
this.transactionsNotInABlock.add(trans);
}
public boolean allTransactionsInThisBlockHaveValidInputs(Block block) {
//TODO
for (Transaction trans : block.getTransactions())
if (!(this.validateTransactionIntegrity(trans) && this.validateTransactionOrigin(trans)))
return false;
return true;
}
public boolean nonceOfBlockIsCorrect(Block block) {
return Network.firstNCharsEqualZero(block.getNonce() + Network.findAllStringsToBeHashed(block),
Network.nonceTarget);
}
public boolean recievedThisBlockBefore(Block block) {
for (ChainedHashMap possibleBlockChain : this.forks)
if (possibleBlockChain.get(block.getThisBlockHashPointer()) != null)
return true;
for (int i = 0; i < this.blockChain.size(); i++)
if (blockChain.get(block.getThisBlockHashPointer()) != null)
return true;
return false;
}
public void signTransaction(Transaction transaction) {
try {
byte[] data = transaction.getId().getBytes();
Signature dsa = Signature.getInstance("SHA/DSA");
dsa.initSign(privateKey);
dsa.update(data);
transaction.setSignature(dsa.sign());
} catch (InvalidKeyException e) {
System.err.println(e.getMessage());
} catch (NoSuchAlgorithmException e) {
System.err.println(e.getMessage());
} catch (SignatureException e) {
System.err.println(e.getMessage());
}
}
public boolean validateTransactionOrigin(Transaction transaction) {
// validating signature
try {
if (transaction instanceof PeerToPeerTransaction) {
byte[] data = transaction.getId().getBytes();
Signature dsa = Signature.getInstance("SHA/DSA");
dsa.initVerify(((PeerToPeerTransaction) transaction).getSenderPublicKey());
/* Update and verify the data */
dsa.update(data);
return dsa.verify(transaction.getSignature());
}
} catch (NoSuchAlgorithmException e) {
System.err.println(e.getMessage());
} catch (InvalidKeyException e) {
System.err.println(e.getMessage());
} catch (SignatureException e) {
System.err.println(e.getMessage());
}
return true;
}
public boolean validateTransactionIntegrity(Transaction transaction) {
if (transaction instanceof PeerToPeerTransaction) {
ArrayList<Trindex> inputs = ((PeerToPeerTransaction) transaction).getInputs();
for (Trindex trin : inputs) {
if (!UTXOSet.contains(trin))
return false;
}
}
return true;
}
public String findAllStringsToBeHashed(Transaction[] transactionsToBeAddedToABlock,
String previousBlockHashPointer) {
String res = "";
for (Transaction tran : transactionsToBeAddedToABlock)
res += tran.getId();
res += previousBlockHashPointer;
return res;
}
public Long findNonce(String input, int numberOfLeadingZeors) {
boolean found = false;
String hash = "";
Long nonce = 0L;
while (!found) {
hash = Network.sha256(nonce + input);
if (Network.firstNCharsEqualZero(hash, numberOfLeadingZeors)) {
found = true;
break;
}
nonce++;
}
return nonce;
}
public boolean equals(Object o) {
return this.publicKey.equals(((Node) o).publicKey);
}
@Override
public String toString() {
return this.displayName;
}
public static void main(String[] args) {
// Node n = new Node("test");
// fancyPrint(n.findNonce("first", 1));
// fancyPrint();
// fancyPrint(n.sha256("ammar"));
// fancyPrint(n.sha256("amma"));
// fancyPrint(n.sha256("ammr"));
// fancyPrint(n.sha256("ramma"));
}
}
| [
"[email protected]"
] | |
6372c4754931f4218f21c513d263e722d2c060cf | ef0c1514e9af6de3ba4a20e0d01de7cc3a915188 | /sdk/purview/azure-resourcemanager-purview/src/main/java/com/azure/resourcemanager/purview/models/PrivateEndpointConnection.java | 17ddc45dc7d51edfe95e261f2bfe209c481f0878 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"CC0-1.0",
"BSD-3-Clause",
"UPL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | Azure/azure-sdk-for-java | 0902d584b42d3654b4ce65b1dad8409f18ddf4bc | 789bdc6c065dc44ce9b8b630e2f2e5896b2a7616 | refs/heads/main | 2023-09-04T09:36:35.821969 | 2023-09-02T01:53:56 | 2023-09-02T01:53:56 | 2,928,948 | 2,027 | 2,084 | MIT | 2023-09-14T21:37:15 | 2011-12-06T23:33:56 | Java | UTF-8 | Java | false | false | 7,214 | java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.purview.models;
import com.azure.core.util.Context;
import com.azure.resourcemanager.purview.fluent.models.PrivateEndpointConnectionInner;
/** An immutable client-side representation of PrivateEndpointConnection. */
public interface PrivateEndpointConnection {
/**
* Gets the id property: Fully qualified resource Id for the resource.
*
* @return the id value.
*/
String id();
/**
* Gets the name property: The name of the resource.
*
* @return the name value.
*/
String name();
/**
* Gets the type property: The type of the resource.
*
* @return the type value.
*/
String type();
/**
* Gets the privateEndpoint property: The private endpoint information.
*
* @return the privateEndpoint value.
*/
PrivateEndpoint privateEndpoint();
/**
* Gets the privateLinkServiceConnectionState property: The private link service connection state.
*
* @return the privateLinkServiceConnectionState value.
*/
PrivateLinkServiceConnectionState privateLinkServiceConnectionState();
/**
* Gets the provisioningState property: The provisioning state.
*
* @return the provisioningState value.
*/
String provisioningState();
/**
* Gets the name of the resource group.
*
* @return the name of the resource group.
*/
String resourceGroupName();
/**
* Gets the inner com.azure.resourcemanager.purview.fluent.models.PrivateEndpointConnectionInner object.
*
* @return the inner object.
*/
PrivateEndpointConnectionInner innerModel();
/** The entirety of the PrivateEndpointConnection definition. */
interface Definition
extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate {
}
/** The PrivateEndpointConnection definition stages. */
interface DefinitionStages {
/** The first stage of the PrivateEndpointConnection definition. */
interface Blank extends WithParentResource {
}
/** The stage of the PrivateEndpointConnection definition allowing to specify parent resource. */
interface WithParentResource {
/**
* Specifies resourceGroupName, accountName.
*
* @param resourceGroupName The resource group name.
* @param accountName The name of the account.
* @return the next definition stage.
*/
WithCreate withExistingAccount(String resourceGroupName, String accountName);
}
/**
* The stage of the PrivateEndpointConnection definition which contains all the minimum required properties for
* the resource to be created, but also allows for any other optional properties to be specified.
*/
interface WithCreate
extends DefinitionStages.WithPrivateEndpoint, DefinitionStages.WithPrivateLinkServiceConnectionState {
/**
* Executes the create request.
*
* @return the created resource.
*/
PrivateEndpointConnection create();
/**
* Executes the create request.
*
* @param context The context to associate with this operation.
* @return the created resource.
*/
PrivateEndpointConnection create(Context context);
}
/** The stage of the PrivateEndpointConnection definition allowing to specify privateEndpoint. */
interface WithPrivateEndpoint {
/**
* Specifies the privateEndpoint property: The private endpoint information..
*
* @param privateEndpoint The private endpoint information.
* @return the next definition stage.
*/
WithCreate withPrivateEndpoint(PrivateEndpoint privateEndpoint);
}
/**
* The stage of the PrivateEndpointConnection definition allowing to specify privateLinkServiceConnectionState.
*/
interface WithPrivateLinkServiceConnectionState {
/**
* Specifies the privateLinkServiceConnectionState property: The private link service connection state..
*
* @param privateLinkServiceConnectionState The private link service connection state.
* @return the next definition stage.
*/
WithCreate withPrivateLinkServiceConnectionState(
PrivateLinkServiceConnectionState privateLinkServiceConnectionState);
}
}
/**
* Begins update for the PrivateEndpointConnection resource.
*
* @return the stage of resource update.
*/
PrivateEndpointConnection.Update update();
/** The template for PrivateEndpointConnection update. */
interface Update extends UpdateStages.WithPrivateEndpoint, UpdateStages.WithPrivateLinkServiceConnectionState {
/**
* Executes the update request.
*
* @return the updated resource.
*/
PrivateEndpointConnection apply();
/**
* Executes the update request.
*
* @param context The context to associate with this operation.
* @return the updated resource.
*/
PrivateEndpointConnection apply(Context context);
}
/** The PrivateEndpointConnection update stages. */
interface UpdateStages {
/** The stage of the PrivateEndpointConnection update allowing to specify privateEndpoint. */
interface WithPrivateEndpoint {
/**
* Specifies the privateEndpoint property: The private endpoint information..
*
* @param privateEndpoint The private endpoint information.
* @return the next definition stage.
*/
Update withPrivateEndpoint(PrivateEndpoint privateEndpoint);
}
/** The stage of the PrivateEndpointConnection update allowing to specify privateLinkServiceConnectionState. */
interface WithPrivateLinkServiceConnectionState {
/**
* Specifies the privateLinkServiceConnectionState property: The private link service connection state..
*
* @param privateLinkServiceConnectionState The private link service connection state.
* @return the next definition stage.
*/
Update withPrivateLinkServiceConnectionState(
PrivateLinkServiceConnectionState privateLinkServiceConnectionState);
}
}
/**
* Refreshes the resource to sync with Azure.
*
* @return the refreshed resource.
*/
PrivateEndpointConnection refresh();
/**
* Refreshes the resource to sync with Azure.
*
* @param context The context to associate with this operation.
* @return the refreshed resource.
*/
PrivateEndpointConnection refresh(Context context);
}
| [
"[email protected]"
] | |
41b5539ab68050ceff6b559aa4f781c3a2f45ad9 | 4d8dad421ce3785f0d6a6dcf9eaea601df5274c6 | /src/main/java/yunsheng/FInterface.java | 91fa09d6a0cc98cb849a1e5498bd93e2b56af47d | [] | no_license | jedyang/jdk8Learn | 72db370933735c426c9da0abe47609116a03517a | af6f5fac47b4b3fa934553fc61168726f2979346 | refs/heads/master | 2021-01-22T03:53:58.298150 | 2017-05-25T14:34:03 | 2017-05-25T14:34:03 | 92,412,087 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 469 | java | package yunsheng;
/**
* 函数接口是一种只有一个方法的接口,像这样地,函数接口可以隐式地转换成lambda表达式。
* Created by shengyun on 17/3/10.
*/
@FunctionalInterface
public interface FInterface {
void method1();
// deafault关键字,默认方法
default String method2(){
return "interface m2";
}
// 默认方法可以搞多个
default String method3(){
return "interface m3";
}
}
| [
"[email protected]"
] | |
88a6b1357a4d9bcd3c9b85a55291cbf693d0f256 | 101552846c1f866688b56cf68f84e5dfaf69b067 | /desktop/src/com/righteoushatred/moistanger/desktop/DesktopLauncher.java | 6235df5a1912b2d5e9bc8977e33f49e3759938fa | [] | no_license | epicbo/The-Moist-Anger | 1eb22223ec1aecd0ded12a5064094270f83d551d | 1152d3bac8baeefe5de97a77fef6f8fae0d95761 | refs/heads/master | 2021-01-20T20:24:14.648363 | 2016-07-23T16:13:19 | 2016-07-23T16:13:19 | 63,360,441 | 0 | 0 | null | 2016-07-23T15:43:57 | 2016-07-14T18:33:01 | Java | UTF-8 | Java | false | false | 515 | java | package com.righteoushatred.moistanger.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.righteoushatred.moistanger.MoistAngerGame;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.width = 1100;
config.height = 800;
config.resizable = false;
new LwjglApplication(new MoistAngerGame(), config);
}
}
| [
"[email protected]"
] | |
876290434674098f62f4c215a4da16c478b57a15 | 954899fa8a0171e0531ee78f485f11dadf1d33f4 | /app/src/main/java/com/example/myfirstapp/AuthFragment.java | 69473e5c732946128dbea87de919030c3de3aeee | [] | no_license | psvm/MyFirstApp | ca8db26c96ad903c083142d55b6fc32b45ef25cd | ef00cb42ee05a0a621446f995827e926525b66ee | refs/heads/master | 2020-03-23T18:27:38.228709 | 2018-07-30T13:23:11 | 2018-07-30T13:23:11 | 141,910,034 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,744 | java | package com.example.myfirstapp;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AuthFragment extends Fragment{
private EditText mLogin;
private EditText mPassword;
private Button mEnter;
private Button mRegister;
public static AuthFragment newInstance() {
Bundle args = new Bundle();
AuthFragment fragment = new AuthFragment();
fragment.setArguments(args);
return fragment;
}
private View.OnClickListener mOnEnterClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isEmailValid()&& isPasswordValid()){
Intent startProfileIntent = new Intent(getActivity(), ProfileActivity.class);
startProfileIntent.putExtra(ProfileActivity.USER_KEY,
new User(mLogin.getText().toString(), mPassword.getText().toString()));
startActivity(startProfileIntent);
}
else {
showMessage(R.string.login_input_error);
}
}
};
private View.OnClickListener mOnRegisterClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
// todo Обработка нажатий
}
};
private boolean isEmailValid(){
return !TextUtils.isEmpty(mLogin.getText())
&& Patterns.EMAIL_ADDRESS.matcher(mLogin.getText()).matches();
}
private boolean isPasswordValid() {
return !TextUtils.isEmpty(mPassword.getText());
}
private void showMessage(@StringRes int string){
Toast.makeText(getActivity(),string, Toast.LENGTH_LONG).show();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fr_auth, container, false);
mLogin = v.findViewById(R.id.etLogin);
mPassword = v.findViewById(R.id.etPassword);
mEnter = v.findViewById(R.id.buttonEnter);
mRegister = v.findViewById(R.id.buttonRegister);
mEnter.setOnClickListener(mOnEnterClickListener);
mRegister.setOnClickListener(mOnRegisterClickListener);
return v;
}
}
| [
"[email protected]"
] | |
91da82800908ac43c4ea9599979438f085954d82 | fea1538af64018769c91e2f65633123e80638bd6 | /app/src/main/java/com/example/android/leadermvprxdemo/activity/delicateView/ENSearchView.java | b123a4e459f4bc442c2f3e3837b5b2fa97a5c814 | [] | no_license | Leader0721/LeaderMVPRxDemo | 41848d9056ed5c327abe7f04b0af27ce79150c95 | 06aa45116f3471dbe623cc73ec7eeafa3bf9b8a3 | refs/heads/master | 2022-01-11T20:05:34.157348 | 2019-05-27T02:14:43 | 2019-05-27T02:14:43 | 110,673,831 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,719 | java | package com.example.android.leadermvprxdemo.activity.delicateView;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import com.example.android.leadermvprxdemo.R;
/**
* Created by codeest on 2016/11/14.
*
* 很Q 很弹 duang~ duang~ duang~
*/
public class ENSearchView extends View {
private static final int STATE_SEARCHING = 0;
private static final int STATE_WAIT = 1;
private static final int DEFAULT_LINE_COLOR = Color.WHITE;
private static final int DEFAULT_LINE_WIDTH = 9;
private static final int DEFAULT_DOT_SIZE = 3;
private static final int DEFAULT_DURATION = 3000;
private Paint mPaint, mArcPaint;
private float mFraction;
private int mCurrentState;
private Path mPath, mArcPath;
private PathMeasure mPathMeasure;
private RectF mRectF;
private float mWidth, mHeight;
private float mCenterX, mCenterY;
private float mPathLength, mCircleRadius;
private float mCurrentPos[], mCurrentTan[];
private boolean isDotShowing = true;
private int mDotSize, mDuration;
public ENSearchView(Context context) {
super(context);
}
public ENSearchView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.search);
int lineColor = ta.getColor(R.styleable.search_search_line_color, DEFAULT_LINE_COLOR);
int lineWidth = ta.getInteger(R.styleable.search_search_line_width, DEFAULT_LINE_WIDTH);
int dotSize = ta.getInteger(R.styleable.search_search_dot_size, DEFAULT_DOT_SIZE);
ta.recycle();
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(lineWidth);
mPaint.setColor(lineColor);
mArcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mArcPaint.setStyle(Paint.Style.FILL);
mArcPaint.setColor(Color.WHITE);
mDotSize = dotSize;
mDuration = DEFAULT_DURATION;
mCurrentState = STATE_WAIT;
mCurrentPos = new float[2];
mCurrentTan = new float[2];
mPath = new Path();
mArcPath = new Path();
mPathMeasure = new PathMeasure();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
mCenterX = mWidth / 2;
mCenterY = mHeight / 2;
mCircleRadius = mWidth / 4;
mRectF = new RectF(mCenterX - 0.95f * mCircleRadius,mCenterY - 0.95f * mCircleRadius,
mCenterX + 0.95f * mCircleRadius, mCenterY + 0.95f * mCircleRadius);
mPath.moveTo(mCenterX + 2.2f * mCircleRadius / (float) Math.sqrt(2), mCenterY + 2.2f * mCircleRadius / (float) Math.sqrt(2));
mPath.lineTo(mCenterX , mCenterY);
mPath.lineTo(mCenterX - 0.45f * mCircleRadius * (float) Math.sqrt(3), mCenterY + 0.45f * mCircleRadius);
mPath.lineTo(mCenterX - 0.45f * mCircleRadius * (float) Math.sqrt(3), mCenterY - 0.45f * mCircleRadius);
mPath.lineTo(mCenterX + 0.45f * mCircleRadius * (float) Math.sqrt(3), mCenterY);
mPath.lineTo(mCenterX, mCenterY);
mPath.lineTo(mCenterX + 2.2f * mCircleRadius / (float) Math.sqrt(2), mCenterY + 2.2f * mCircleRadius / (float) Math.sqrt(2));
mPathMeasure.setPath(mPath, false);
mPathLength = mPathMeasure.getLength();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mFraction <= 0.2) { //嗷~ 放大镜手柄收缩
canvas.drawCircle(mCenterX , mCenterY ,mCircleRadius - mCircleRadius * mFraction, mPaint);
canvas.drawLine(mCenterX + mCircleRadius / (float) Math.sqrt(2) + 1.2f * mCircleRadius / (float) Math.sqrt(2) / 0.2f * mFraction,
mCenterY + mCircleRadius / (float) Math.sqrt(2) + 1.2f * mCircleRadius / (float) Math.sqrt(2) / 0.2f * mFraction,
mCenterX + 2.2f * mCircleRadius / (float) Math.sqrt(2),
mCenterY + 2.2f * mCircleRadius / (float) Math.sqrt(2)
,mPaint);
} else if (mFraction <= 0.8) {
mPathMeasure.getPosTan(0 + mPathLength / 0.6f * (mFraction - 0.2f), mCurrentPos, mCurrentTan);
if (mCurrentPos[1] == mCenterY && mCurrentPos[0] <= mCenterX + mCircleRadius / 3 && mCurrentPos[0] >= mCenterX - mCircleRadius / 3) {
if (isDotShowing) {
isDotShowing = false;
} else {
canvas.drawCircle(mCurrentPos[0], mCurrentPos[1], mDotSize, mPaint); //嗷~ 轨迹中的小球
isDotShowing = true;
}
} else {
canvas.drawCircle(mCurrentPos[0], mCurrentPos[1], mDotSize, mPaint);
}
if (mFraction <= 0.3) { //嗷~ 内圈粘性部分
canvas.drawCircle(mCenterX , mCenterY ,0.8f * mCircleRadius + mCircleRadius * 2 * (mFraction - 0.2f), mPaint);
} else {
canvas.drawCircle(mCenterX , mCenterY ,mCircleRadius , mPaint);
}
if (mFraction <= 0.35 && mFraction > 0.3) {
canvas.drawArc(mRectF, 45 - 55 / 0.05f * (mFraction - 0.3f), 110 / 0.05f * (mFraction - 0.3f), false, mArcPaint);
} else if(mFraction <= 0.4 && mFraction > 0.35) {
canvas.drawArc(mRectF, 45 - 55 / 0.05f * (0.4f - mFraction), 110 / 0.05f * (0.4f - mFraction), false, mArcPaint);
}
if (mFraction <= 0.75 && mFraction > 0.7) { //嗷~ 外圈粘性部分
mArcPath.reset();
mArcPath.moveTo(mCenterX + mCircleRadius, mCenterY);
mArcPath.cubicTo(mCenterX + mCircleRadius + 8 / 0.05f * (mFraction - 0.7f), mCenterY + mCircleRadius / 2 + 8 / 0.05f * (mFraction - 0.7f),
mCenterX + mCircleRadius / 2 + 8 / 0.05f * (mFraction - 0.7f), mCenterY + mCircleRadius + 8 / 0.05f * (mFraction - 0.7f),
mCenterX, mCenterY + mCircleRadius);
canvas.drawPath(mArcPath, mPaint);
} else if(mFraction <= 0.8 && mFraction > 0.75) {
mArcPath.reset();
mArcPath.moveTo(mCenterX + mCircleRadius, mCenterY);
mArcPath.cubicTo(mCenterX + mCircleRadius + 8 / 0.05f * (0.8f - mFraction), mCenterY + mCircleRadius / 2 + 8 / 0.05f * (0.8f - mFraction),
mCenterX + mCircleRadius/ 2 + 8 / 0.05f * (0.8f - mFraction), mCenterY + mCircleRadius + 8 / 0.05f * (0.8f - mFraction),
mCenterX, mCenterY + mCircleRadius);
canvas.drawPath(mArcPath, mPaint);
}
} else { //嗷~ 放大镜手柄伸长
canvas.drawCircle(mCenterX , mCenterY ,mCircleRadius , mPaint);
canvas.drawLine(mCenterX + 2.2f *mCircleRadius / (float) Math.sqrt(2) - 1.2f * mCircleRadius / (float) Math.sqrt(2) / 0.2f * (mFraction - 0.8f),
mCenterY + 2.2f * mCircleRadius / (float) Math.sqrt(2) - 1.2f * mCircleRadius / (float) Math.sqrt(2) / 0.2f * (mFraction - 0.8f),
mCenterX + 2.2f * mCircleRadius / (float) Math.sqrt(2),
mCenterY + 2.2f * mCircleRadius / (float) Math.sqrt(2)
,mPaint);
}
}
public void start() {
if (mCurrentState == STATE_SEARCHING) {
return;
}
mCurrentState = STATE_SEARCHING;
ValueAnimator valueAnim = ValueAnimator.ofFloat(1.f, 100.f);
valueAnim.setDuration(mDuration);
valueAnim.setInterpolator(new LinearInterpolator());
valueAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
mFraction = valueAnimator.getAnimatedFraction();
invalidate();
}
});
valueAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mCurrentState = STATE_WAIT;
}
});
valueAnim.start();
}
}
| [
"[email protected]"
] | |
0547133102a12e786efef1b10d2510a6723fe21e | add343c3194537db4a3ae3bc478ed4e60f10b925 | /src/main/java/ac/td/core/action/contest/combat/CombatantResult.java | e64f0632bfcf89d11c24dae43d09bbb2bfef6ece | [] | no_license | alejoceballos/tellersdesk-core | 137125bb0c3d2c1a32a62237cee19563d1f7d698 | 58e1148df6a35237f83aa80e248c59a07e7ae0d0 | refs/heads/main | 2023-04-25T23:33:54.154243 | 2021-05-16T21:29:53 | 2021-05-16T21:29:53 | 358,774,988 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,719 | java | package ac.td.core.action.contest.combat;
import ac.td.core.action.contest.ContestException;
import ac.td.core.action.contest.ContestResultAlreadyApplied;
import java.util.HashMap;
import java.util.Map;
public class CombatantResult {
private final Combatant combatant;
private final StatusType statusType;
private final Map<String, Integer> effects = new HashMap<>();
private boolean applied = false;
private void validateNotNull(final Object... args) {
for (Object arg: args) {
if (arg == null) throw new NullPointerException("Argument cannot be null");
}
}
protected CombatantResult(final Combatant combatant, final StatusType statusType) {
validateNotNull(combatant, statusType);
this.combatant = combatant;
this.statusType = statusType;
}
protected CombatantResult(final Combatant combatant, final StatusType statusType, final Map<String, Integer> effects) {
this(combatant, statusType);
if (effects != null) {
this.effects.putAll(effects);
}
}
public Combatant getCombatant() {
return combatant;
}
public StatusType getStatus() {
return this.statusType;
}
public int getEffect(final String effect) {
final Integer effectResult = this.effects.get(effect);
return effectResult == null ? 0 : effectResult;
}
public void applyResultToCombatant() throws ContestException {
if (applied) throw new ContestResultAlreadyApplied("Combat result already applied to combatant");
this.effects.forEach((effect, value) -> combatant.set(effect, this.combatant.get(effect) + value));
applied = true;
}
}
| [
"[email protected]"
] | |
5c5133e80648e1fd1034058aad90caf3f7a19863 | 2ac09e1df530d7bd72a1b356b504ea2841851d2d | /java/net/sf/l2j/gameserver/handler/voicedcommandhandlers/stats.java | 0d07f15c10241878c8468befe71d8215598a92e0 | [] | no_license | DeMarko1984/leagueoflineage | 5d4470b5bed4e132a8e63555bd2581728117e864 | 7552026c310242723c884fe29bab503de9154ae3 | refs/heads/main | 2023-07-16T08:16:40.994221 | 2021-09-10T06:20:26 | 2021-09-10T06:20:26 | 403,709,649 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,351 | java | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* http://www.gnu.org/copyleft/gpl.html
*/
package net.sf.l2j.gameserver.handler.voicedcommandhandlers;
import java.util.Iterator;
import javolution.text.TextBuilder;
import net.sf.l2j.gameserver.handler.IVoicedCommandHandler;
import net.sf.l2j.gameserver.model.L2World;
import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
import net.sf.l2j.gameserver.serverpackets.NpcHtmlMessage;
/**
*
*
*/
public class stats implements IVoicedCommandHandler
{
private static final String[] VOICED_COMMANDS =
{
"stats"
};
@Override
public boolean useVoicedCommand(String command, L2PcInstance activeChar, String target)
{
if (command.equalsIgnoreCase("stats"))
{
L2PcInstance pc = L2World.getInstance().getPlayer(target);
if (pc != null)
{
NpcHtmlMessage adminReply = new NpcHtmlMessage(5);
TextBuilder replyMSG = new TextBuilder("<html><body>");
replyMSG.append("<center><font color=\"LEVEL\">[ L2J EVENT ENGINE ]</font></center><br>");
replyMSG.append("<br>Statistics for player <font color=\"LEVEL\">" + pc.getName() + "</font><br>");
replyMSG.append("Total kills <font color=\"FF0000\">" + pc.kills.size() + "</font><br>");
replyMSG.append("<br>Detailed list: <br>");
Iterator<String> it = pc.kills.iterator();
while (it.hasNext())
{
replyMSG.append("<font color=\"FF0000\">" + it.next() + "</font><br>");
}
replyMSG.append("</body></html>");
adminReply.setHtml(replyMSG.toString());
activeChar.sendPacket(adminReply);
}
}
return true;
}
@Override
public String[] getVoicedCommandList()
{
return VOICED_COMMANDS;
}
}
| [
"[email protected]"
] | |
bad602f4084a49b0f9792dba8e1882b37704d5f3 | 4dfc2d707434a6e14f9de0f08729f105808a9c3d | /src/main/java/com/dao/ProductDao.java | ceeaa314f730b924d30a4fbc8e96f7110742b6e8 | [] | no_license | starsibi/Clickart | 0bfd33fec6f8f9a2449430b03e4284dd75904bc7 | 2bc03988f794954b7701b400df3e10aed47324dd | refs/heads/master | 2020-04-19T03:09:07.917621 | 2016-08-18T13:56:46 | 2016-08-18T13:56:46 | 66,000,780 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 320 | java | package com.dao;
import java.util.List;
import com.model.Product;
public interface ProductDao {
public void add(Product product);
public void edit(Product product);
public void delete(int productId);
public Product getProduct(int productId);
public List getAllProduct();
public List getnikon(String brand);
}
| [
"[email protected]"
] | |
843704c3427bb374b655dcfb14caeda4fbb807a8 | c775e1e44451b4f4f6e1c18245c736aad3e9d595 | /src/question912/InsertionSort.java | 9e3c21ec957339bc1da54e4313cdfe78f4f876ba | [] | no_license | Jerrymouse1998/learning-record-of-leetcode | 690e00e7ed6954366e062490eea40deb82a07ed3 | 7b00f1af4e2409be52d8e1babe24787b101cd27f | refs/heads/master | 2020-12-04T21:46:33.624278 | 2020-05-30T02:06:12 | 2020-05-30T02:06:12 | 231,911,508 | 6 | 2 | null | null | null | null | UTF-8 | Java | false | false | 561 | java | package question912;
public class InsertionSort {
/*
插入排序
平均/最坏时间复杂度:O(n^2)
最好时间复杂度:O(n)
空间复杂度:O(1)
稳定
*/
public static void insertionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int curr = arr[i + 1], preIdx = i;
while (preIdx >= 0 && arr[preIdx] > curr) {
arr[preIdx + 1] = arr[preIdx];
preIdx--;
}
arr[preIdx + 1] = curr;
}
}
}
| [
"[email protected]"
] | |
04519cb581ea5ad7f34848293ea28b4a42558376 | 5735d6658b174bd220d3e7df8af4c4215da28e0f | /CatalogComponents/src/com/creocode/components/options/Serializator.java | fe12078cac6c7be2b6284ce966aaf9798b0b4954 | [
"BSD-3-Clause"
] | permissive | apolit/creomobile | b77df4db8be657ce9cd02e3f8b2b68517f7d62f2 | ea2f4bcdf13b53bdb7c08f96941488a99b27d2a1 | refs/heads/master | 2023-01-28T09:26:10.541499 | 2023-01-03T17:45:44 | 2023-01-03T17:45:44 | 2,680,047 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,115 | java | /*******************************************************************************
* Copyright 2010 Artur Polit
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Contributors:
* Artur Polit - code base
*******************************************************************************/
package com.creocode.components.options;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
/**
*
* @author artur
*/
public class Serializator {
private final int size;
public Serializator(int size) {
this.size = size;
try {
recordStore = RecordStore.openRecordStore(STORE_NAME, true);
if (recordStore.getNumRecords() == 0) {
initRecordStore();
}
recordStore.closeRecordStore();
} catch (RecordStoreException ex) {
System.err.print(ex.getMessage());
}
}
public static final String STORE_NAME = "SERIALIZATOR";
RecordStore recordStore = null;
public void serialize(int recordId, ISerializable serializable) throws RecordStoreNotOpenException, IOException, InvalidRecordIDException, RecordStoreException {
recordStore = RecordStore.openRecordStore(STORE_NAME, true);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
serializable.toDataStream(dout);
byte[] data = bout.toByteArray();
recordStore.setRecord(recordId, data, 0, data.length);
recordStore.closeRecordStore();
}
public void deserialize(int recordId, ISerializable serializable) throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException, IOException {
byte[] data;
recordStore = RecordStore.openRecordStore(STORE_NAME, true);
data = recordStore.getRecord(recordId);
if (data.length > 1) { //there is something
ByteArrayInputStream bin = new ByteArrayInputStream(data);
DataInputStream din = new DataInputStream(bin);
serializable.fromDataStream(din);
}
recordStore.closeRecordStore();
}
private void initRecordStore() throws RecordStoreNotOpenException, RecordStoreException {
int i;
for (i = 0; i < size; i++) {
byte[] data = new byte[100];
recordStore.addRecord(data, 0,data.length );
}
}
} | [
"[email protected]"
] | |
e140c16ac8227e6c1b0ad3008693fec778aff74b | 2ece187e205292a6fee7bbafb7e599bb1bfb45d9 | /Test/src/main/java/com/simon/concurrency/FileClock.java | 55cf54d5c1be49f51ede0d1cfcb7b43dd4afc492 | [] | no_license | kamismile/gzliRepo | 54a334d99e8f43eb313ba038c1f7520dcf58f5b7 | 321c87038153805b3d7c657da1188094f4c8b248 | refs/heads/master | 2020-03-17T16:50:29.915457 | 2015-05-20T06:53:39 | 2015-05-20T06:54:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 660 | java | package com.simon.concurrency;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class FileClock implements Runnable {
@Override
public void run() {
while (true) {
System.out.printf("%s\n", new Date());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.printf("The FileClock has been interrupted");
return;
}
}
}
public static void main(String[] args) {
FileClock clock = new FileClock();
Thread thread = new Thread(clock);
thread.start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
| [
"[email protected]"
] | |
0225db6000125724d7ab2723dfdcc059f5785430 | 7543eb6be4db4124084b6eac0b26131bcdfea563 | /sources/com/google/android/gms/auth/GoogleAuthUtil.java | 7138185815a0aa60a66582114a7fd4da1efb7b39 | [] | no_license | n0misain/6-1_source_from_JADX | bea3bc861ba84c62c27231e7bcff6df49e2f21c9 | e0e00915f0b376e7c1d0c162bf7d6697153ce7b1 | refs/heads/master | 2022-07-19T05:28:02.911308 | 2020-05-17T00:12:26 | 2020-05-17T00:12:26 | 264,563,027 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,989 | java | package com.google.android.gms.auth;
import android.accounts.Account;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.RequiresPermission;
import android.util.Log;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.internal.zzbo;
import com.google.android.gms.common.zzo;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
public final class GoogleAuthUtil extends zzd {
public static final int CHANGE_TYPE_ACCOUNT_ADDED = 1;
public static final int CHANGE_TYPE_ACCOUNT_REMOVED = 2;
public static final int CHANGE_TYPE_ACCOUNT_RENAMED_FROM = 3;
public static final int CHANGE_TYPE_ACCOUNT_RENAMED_TO = 4;
public static final String GOOGLE_ACCOUNT_TYPE = "com.google";
private static String KEY_ANDROID_PACKAGE_NAME = zzd.KEY_ANDROID_PACKAGE_NAME;
private static String KEY_CALLER_UID = zzd.KEY_CALLER_UID;
public static final String KEY_SUPPRESS_PROGRESS_SCREEN = "suppressProgressScreen";
public static final String WORK_ACCOUNT_TYPE = "com.google.work";
private GoogleAuthUtil() {
}
public static void clearToken(Context context, String str) throws GooglePlayServicesAvailabilityException, GoogleAuthException, IOException {
zzd.clearToken(context, str);
}
public static List<AccountChangeEvent> getAccountChangeEvents(Context context, int i, String str) throws GoogleAuthException, IOException {
return zzd.getAccountChangeEvents(context, i, str);
}
public static String getAccountId(Context context, String str) throws GoogleAuthException, IOException {
return zzd.getAccountId(context, str);
}
public static String getToken(Context context, Account account, String str) throws IOException, UserRecoverableAuthException, GoogleAuthException {
return zzd.getToken(context, account, str);
}
public static String getToken(Context context, Account account, String str, Bundle bundle) throws IOException, UserRecoverableAuthException, GoogleAuthException {
return zzd.getToken(context, account, str, bundle);
}
@Deprecated
public static String getToken(Context context, String str, String str2) throws IOException, UserRecoverableAuthException, GoogleAuthException {
return zzd.getToken(context, str, str2);
}
@Deprecated
public static String getToken(Context context, String str, String str2, Bundle bundle) throws IOException, UserRecoverableAuthException, GoogleAuthException {
return zzd.getToken(context, str, str2, bundle);
}
public static String getTokenWithNotification(Context context, Account account, String str, Bundle bundle) throws IOException, UserRecoverableNotifiedException, GoogleAuthException {
if (bundle == null) {
bundle = new Bundle();
}
bundle.putBoolean("handle_notification", true);
return zza(context, account, str, bundle).getToken();
}
public static String getTokenWithNotification(Context context, Account account, String str, Bundle bundle, Intent intent) throws IOException, UserRecoverableNotifiedException, GoogleAuthException {
if (intent == null) {
throw new IllegalArgumentException("Callback cannot be null.");
}
try {
Intent.parseUri(intent.toUri(1), 1);
if (bundle == null) {
bundle = new Bundle();
}
bundle.putParcelable("callback_intent", intent);
bundle.putBoolean("handle_notification", true);
return zza(context, account, str, bundle).getToken();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Parameter callback contains invalid data. It must be serializable using toUri() and parseUri().");
}
}
public static String getTokenWithNotification(Context context, Account account, String str, Bundle bundle, String str2, Bundle bundle2) throws IOException, UserRecoverableNotifiedException, GoogleAuthException {
zzbo.zzh(str2, "Authority cannot be empty or null.");
if (bundle == null) {
bundle = new Bundle();
}
if (bundle2 == null) {
bundle2 = new Bundle();
}
ContentResolver.validateSyncExtrasBundle(bundle2);
bundle.putString("authority", str2);
bundle.putBundle("sync_extras", bundle2);
bundle.putBoolean("handle_notification", true);
return zza(context, account, str, bundle).getToken();
}
@Deprecated
public static String getTokenWithNotification(Context context, String str, String str2, Bundle bundle) throws IOException, UserRecoverableNotifiedException, GoogleAuthException {
return getTokenWithNotification(context, new Account(str, "com.google"), str2, bundle);
}
@Deprecated
public static String getTokenWithNotification(Context context, String str, String str2, Bundle bundle, Intent intent) throws IOException, UserRecoverableNotifiedException, GoogleAuthException {
return getTokenWithNotification(context, new Account(str, "com.google"), str2, bundle, intent);
}
@Deprecated
public static String getTokenWithNotification(Context context, String str, String str2, Bundle bundle, String str3, Bundle bundle2) throws IOException, UserRecoverableNotifiedException, GoogleAuthException {
return getTokenWithNotification(context, new Account(str, "com.google"), str2, bundle, str3, bundle2);
}
@RequiresPermission("android.permission.MANAGE_ACCOUNTS")
@Deprecated
public static void invalidateToken(Context context, String str) {
zzd.invalidateToken(context, str);
}
@TargetApi(23)
public static Bundle removeAccount(Context context, Account account) throws GoogleAuthException, IOException {
return zzd.removeAccount(context, account);
}
private static TokenData zza(Context context, Account account, String str, Bundle bundle) throws IOException, GoogleAuthException {
if (bundle == null) {
bundle = new Bundle();
}
try {
TokenData zzb = zzd.zzb(context, account, str, bundle);
zzo.zzat(context);
return zzb;
} catch (Throwable e) {
GooglePlayServicesUtil.showErrorNotification(e.getConnectionStatusCode(), context);
Log.w("GoogleAuthUtil", "Error when getting token", e);
throw new UserRecoverableNotifiedException("User intervention required. Notification has been pushed.");
} catch (Throwable e2) {
zzo.zzat(context);
Log.w("GoogleAuthUtil", "Error when getting token", e2);
throw new UserRecoverableNotifiedException("User intervention required. Notification has been pushed.");
}
}
}
| [
"[email protected]"
] | |
e65a7814679c5477566523df94b40a61f5424073 | 957e17f54a0441c8c52baf1861df56e3eaf38bd6 | /src/main/java/com/ldap/auth/agent/ldap/mapper/GroupMappings.java | bf13194efa8d22bc3e6214f79c83e8a95fc5b06c | [] | no_license | tumakha/auth-agent | f0ec55a2dbd09716bb8b9387e29ce79a8deee2e2 | 49c957fee42307df2b0a6508f2d3a6f53490790f | refs/heads/master | 2021-01-10T02:26:25.737948 | 2020-07-07T09:54:21 | 2020-07-07T09:54:21 | 48,842,656 | 10 | 4 | null | 2020-07-07T09:55:07 | 2015-12-31T08:54:13 | Java | UTF-8 | Java | false | false | 1,968 | java | package com.ldap.auth.agent.ldap.mapper;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
/**
* @author Yuriy Tumakha
*/
public class GroupMappings {
private static final Logger LOG = LoggerFactory.getLogger(GroupMappings.class);
private String groupsDN;
private String groupsObjectFilter;
private SearchScope searchScope;
private String name;
private String description;
private String member;
public String getGroupsDN() {
return groupsDN;
}
public void setGroupsDN(String groupsDN) {
this.groupsDN = groupsDN;
}
public String getGroupsObjectFilter() {
return groupsObjectFilter;
}
public void setGroupsObjectFilter(String groupsObjectFilter) {
if (StringUtils.isEmpty(groupsObjectFilter)) {
groupsObjectFilter = "(objectclass=*)";
}
this.groupsObjectFilter = groupsObjectFilter;
}
public SearchScope getSearchScope() {
return searchScope;
}
public void setSearchScope(SearchScope searchScope) {
this.searchScope = searchScope;
}
public void setSearchScope(String searchScope) {
try {
this.searchScope = SearchScope.valueOf(searchScope);
} catch (Exception ex) {
LOG.warn("Wrong search scope name. " + ex.getMessage());
this.searchScope = SearchScope.ONELEVEL;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMember() {
return member;
}
public void setMember(String member) {
this.member = member;
}
} | [
"[email protected]"
] | |
9bc409d29bd3f1bc921da2d33e70dba84e929284 | 8d450fe88103b05b8b97bf4616254fce8c2cf013 | /Minimum Cost BST/OptimalBST.java | c6f3e11bab1df7dddc9b1fdb617fb785278aaa51 | [] | no_license | ShyamKumar1/Algorithms | 2d55ef7cee6ea8d926a2be8bb85bbd4ad5bd72e8 | 65f9413c90fa782f284c4e83d0f2bb375666d3e0 | refs/heads/main | 2023-02-07T20:03:27.044231 | 2021-01-02T05:58:54 | 2021-01-02T05:58:54 | 325,294,984 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,357 | java | import java.util.Scanner;
public class OptimalBST {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter No.of Nodes:");
int n = sc.nextInt();
int []keys = new int[n];
int []freq = new int[n];
System.out.println("Enter Keys:");
for (int i = 0; i < n; i++) {
keys[i]=sc.nextInt();
}
System.out.println("Enter Frequency of keys:");
for (int i = 0; i < n; i++) {
freq[i]=sc.nextInt();
}
System.out.println("Cost of Optimal BST is " + optimalSearchTree(keys, freq, n));
}
static int optimalSearchTree(int[] keys, int[] freq, int n) {
return optCost(freq, 0, n-1);
}
static int optCost(int[] freq, int i, int j) {
if (j < i) return 0;
if (j == i) return freq[i];
int fsum = sum(freq, i, j);
int min = Integer.MAX_VALUE;
for (int r = i; r <= j; ++r) {
int cost = optCost(freq, i, r-1) + optCost(freq, r+1, j);
if (cost < min)
min = cost;
}
return min + fsum;
}
static int sum(int[] freq, int i, int j) {
int s = 0;
for (int k = i; k <=j; k++)
s = s + freq[k];
return s;
}
} | [
"[email protected]"
] | |
ae69a40af76e5e1de7e6c310faf887adef7958ef | 4b0bf4787e89bcae7e4759bde6d7f3ab2c81f849 | /aliyun-java-sdk-cloudesl/src/main/java/com/aliyuncs/cloudesl/model/v20200201/QueryContainerListRequest.java | 69039f240e6b0204bfa43521ff6e43d1a23409d5 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-java-sdk | a263fa08e261f12d45586d1b3ad8a6609bba0e91 | e19239808ad2298d32dda77db29a6d809e4f7add | refs/heads/master | 2023-09-03T12:28:09.765286 | 2023-09-01T09:03:00 | 2023-09-01T09:03:00 | 39,555,898 | 1,542 | 1,317 | NOASSERTION | 2023-09-14T07:27:05 | 2015-07-23T08:41:13 | Java | UTF-8 | Java | false | false | 2,152 | java | /*
* 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.aliyuncs.cloudesl.model.v20200201;
import com.aliyuncs.RpcAcsRequest;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.cloudesl.Endpoint;
/**
* @author auto create
* @version
*/
public class QueryContainerListRequest extends RpcAcsRequest<QueryContainerListResponse> {
private String layoutId;
private Integer pageNumber;
private Integer pageSize;
public QueryContainerListRequest() {
super("cloudesl", "2020-02-01", "QueryContainerList");
setMethod(MethodType.POST);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public String getLayoutId() {
return this.layoutId;
}
public void setLayoutId(String layoutId) {
this.layoutId = layoutId;
if(layoutId != null){
putBodyParameter("LayoutId", layoutId);
}
}
public Integer getPageNumber() {
return this.pageNumber;
}
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
if(pageNumber != null){
putBodyParameter("PageNumber", pageNumber.toString());
}
}
public Integer getPageSize() {
return this.pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
if(pageSize != null){
putBodyParameter("PageSize", pageSize.toString());
}
}
@Override
public Class<QueryContainerListResponse> getResponseClass() {
return QueryContainerListResponse.class;
}
}
| [
"[email protected]"
] | |
5431e68f106b3dcde2c553fd679e2a7c15038f60 | b8118fe340cfe3417c005f3dbad0708e97da87de | /luyuni-ad-service/ad-sponsor/src/main/java/top/luyuni/ad/entity/unit_condition/CreativeUnit.java | 1bb081946c3e9417fdb3daa16f973beee1773d9e | [] | no_license | 1633/luyuni-ad | 98c238617bb27bba0e1dd31daae95d92714e4928 | 05b26c31bbdf83a5f6a3276212c9c3dfb3292aba | refs/heads/master | 2022-11-11T11:25:57.623134 | 2020-04-08T15:51:02 | 2020-04-08T15:51:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 928 | java | package top.luyuni.ad.entity.unit_condition;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "creative_unit")
public class CreativeUnit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Basic
@Column(name = "creative_id", nullable = false)
private Long creativeId;
@Basic
@Column(name = "unit_id", nullable = false)
private Long unitId;
public CreativeUnit(Long creativeId, Long unitId) {
this.creativeId = creativeId;
this.unitId = unitId;
}
}
| [
"[email protected]"
] | |
fbb7a2f77ddd0a7bbb029044195fbf77ce2b8dc4 | 5cfb22d7c2c8c96c2016daf1db6e5a26934ecb66 | /Check CoveredSum UncoveredSum Same OrNot.java | e965010ba6ab11b6673f6e1d01cedd4eaef5f3a1 | [] | no_license | golumall/Tree | 12065dc0ba1fc761d08f28935abc48a204f0ab17 | 425341491a2ddf7fbcfc922954f9f3ab152d04b5 | refs/heads/master | 2020-03-28T18:27:21.204480 | 2019-07-24T11:54:11 | 2019-07-24T11:54:11 | 148,882,733 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,960 | java | class Node
{
int data;
Node left;
Node right;
Node(int data)
{
this.data=data;
left=right=null;
}
}
class Check_CoveredSum_UncoveredSum_Same_OrNot
{
Node root;
int sum(Node node)
{
if(node==null)
return 0;
return node.data+sum(node.left)+sum(node.right);
}
int leftSum(Node node)
{
if(node.left==null&&node.right==null)
return node.data;
if(node.left!=null)
return node.data+leftSum(node.left);
else
return node.data+leftSum(node.right);
}
int rightSum(Node node)
{
if(node.left==null&&node.right==null)
return node.data;
if(node.right!=null)
return node.data+rightSum(node.right);
else
return node.data+rightSum(node.left);
}
int unCovered(Node node)
{
int l=0,r=0;
if(node.left!=null)
l=leftSum(node.left);
if(node.right!=null)
r=rightSum(node.right);
return node.data+l+r;
}
int covered(Node node)
{
return sum(node)-unCovered(node);
}
boolean check(Node node)
{
if(unCovered(node)==covered(node))
return true;
return false;
}
public static void main(String[] args) {
Check_CoveredSum_UncoveredSum_Same_OrNot tree=new Check_CoveredSum_UncoveredSum_Same_OrNot();
/*tree.root = new Node(8);
tree.root.left = new Node(3);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(6);
tree.root.left.right.left = new Node(4);
tree.root.left.right.right = new Node(7);
tree.root.right = new Node(10);
tree.root.right.right = new Node(14);
tree.root.right.right.left = new Node(13); */
tree.root=new Node(9);
tree.root.left=new Node(4);
tree.root.right=new Node(5);
tree.root.left.left=new Node(6);
tree.root.left.right=new Node(7);
tree.root.right.left=new Node(18);
tree.root.right.right=new Node(1);
if(tree.check(tree.root))
System.out.println("YES");
else
System.out.println("NO");
}
}
| [
"[email protected]"
] | |
94de1dc2ad5c14473ea0cca3436648cd4c581327 | 5dc352299a442c942cd647befd8064765991c3d7 | /src/main/java/com/viewol/web/info/vo/InfoResponse.java | c3e5e7099a37b04a0132842753f8429af34e3e6d | [] | no_license | viewolspace/viewol_web | d3a12add28c3eda735e155c8fdcc44481cf9d7aa | c0a6cd2904c515f3d657c734dda26b31846fd2c9 | refs/heads/master | 2021-06-04T00:35:04.435065 | 2019-05-08T08:24:51 | 2019-05-08T08:24:51 | 138,834,725 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,211 | java | package com.viewol.web.info.vo;
import com.alibaba.fastjson.JSON;
import com.viewol.web.common.Response;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
import java.util.List;
@ApiModel
public class InfoResponse extends Response {
private List<InfoVO> result;
public InfoResponse() {}
public InfoResponse(String status, String message) {
super(status, message);
}
public List<InfoVO> getResult() {
return result;
}
public void setResult(List<InfoVO> result) {
this.result = result;
}
@Override
public String toJSONString() {
return JSON.toJSONString(this);
}
public class InfoVO{
@ApiModelProperty(value = "新闻ID")
private int id;
@ApiModelProperty(value = "标题")
private String title;
@ApiModelProperty(value = "摘要")
private String summary;
@ApiModelProperty(value = "发布日期")
private String pubTime;
@ApiModelProperty(value = "图片地址")
private String picUrl;
@ApiModelProperty(value = "正文地址")
private String contentUrl;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getPubTime() {
return pubTime;
}
public void setPubTime(String pubTime) {
this.pubTime = pubTime;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getContentUrl() {
return contentUrl;
}
public void setContentUrl(String contentUrl) {
this.contentUrl = contentUrl;
}
}
}
| [
"[email protected]"
] | |
f2ad062aeb25fe6483f018b9a49a2892e38cb1ef | c2ab7eec35a9d5a616e07825a1880971bcf0d424 | /sina-domain/src/main/java/cc/pp/sina/domain/users/SinaUserInfo.java | 2b0297ad3a3e2a98846149625728136f6b12d3d4 | [] | no_license | xt-coder/sina-services | 7476a0569ad7000e55b1bb5cd1e7c1376a503f3d | d7b2b995d067c6b641a2b92f3dbb5b811a8ec433 | refs/heads/master | 2021-01-20T23:33:12.486603 | 2014-03-18T08:44:02 | 2014-03-18T08:44:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,334 | java | package cc.pp.sina.domain.users;
public class SinaUserInfo {
private final long id; //1
private final String screen_name;//2
private final String name;
private final int province;//3
private final int city;//4
private final String location;//5
private final String description;//6
private final String url;//7
private final String profile_image_url;//8
private final String domain;//9
private final String gender;//10
private final int followers_count;//11
private final int friends_count;//12
private final int statuses_count;//13
private final int favourites_count;//14
private final Long created_at;//15
private final boolean verified;//16
private final int verified_type;//17
private final String avatar_large;//18
private final int bi_followers_count;//19
private final String remark;//20
private final String verified_reason;//21
private final String weihao;//22
public SinaUserInfo(Builder builder) {
this.id = builder.id;
this.screen_name = builder.screen_name;
this.name = builder.name;
this.province = builder.province;
this.city = builder.city;
this.location = builder.location;
this.description = builder.description;
this.url = builder.url;
this.profile_image_url = builder.profile_image_url;
this.domain = builder.domain;
this.gender = builder.gender;
this.followers_count = builder.followers_count;
this.friends_count = builder.friends_count;
this.statuses_count = builder.statuses_count;
this.favourites_count = builder.favourites_count;
this.created_at = builder.created_at;
this.verified = builder.verified;
this.verified_type = builder.verified_type;
this.avatar_large = builder.avatar_large;
this.bi_followers_count = builder.bi_followers_count;
this.remark = builder.remark;
this.verified_reason = builder.verified_reason;
this.weihao = builder.weihao;
}
public static class Builder {
private final long id;
private String screen_name = "";
private String name = "";
private int province;
private int city;
private String location = "";
private String description = "";
private String url = "";
private String profile_image_url = "";
private String domain = "";
private String gender = "";
private int followers_count;
private int friends_count;
private int statuses_count;
private int favourites_count;
private Long created_at;
private boolean verified;
private int verified_type;
private String avatar_large = "";
private int bi_followers_count;
private String remark = "";
private String verified_reason = "";
private String weihao = "";
public Builder(long id) {
this.id = id;
}
public Builder setScreen_name(String screen_name) {
this.screen_name = screen_name;
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setProvince(int province) {
this.province = province;
return this;
}
public Builder setCity(int city) {
this.city = city;
return this;
}
public Builder setLocation(String location) {
this.location = location;
return this;
}
public Builder setDescription(String description) {
this.description = description;
return this;
}
public Builder setUrl(String url) {
this.url = url;
return this;
}
public Builder setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
return this;
}
public Builder setDomain(String domain) {
this.domain = domain;
return this;
}
public Builder setGender(String gender) {
this.gender = gender;
return this;
}
public Builder setFollowers_count(int followers_count) {
this.followers_count = followers_count;
return this;
}
public Builder setFriends_count(int friends_count) {
this.friends_count = friends_count;
return this;
}
public Builder setStatuses_count(int statuses_count) {
this.statuses_count = statuses_count;
return this;
}
public Builder setFavourites_count(int favourites_count) {
this.favourites_count = favourites_count;
return this;
}
public Builder setCreated_at(Long created_at) {
this.created_at = created_at;
return this;
}
public Builder setVerified(boolean verified) {
this.verified = verified;
return this;
}
public Builder setVerified_type(int verified_type) {
this.verified_type = verified_type;
return this;
}
public Builder setAvatar_large(String avatar_large) {
this.avatar_large = avatar_large;
return this;
}
public Builder setBi_followers_count(int bi_followers_count) {
this.bi_followers_count = bi_followers_count;
return this;
}
public Builder setRemark(String remark) {
this.remark = remark;
return this;
}
public Builder setVerified_reason(String verified_reason) {
this.verified_reason = verified_reason;
return this;
}
public Builder setWeihao(String weihao) {
this.weihao = weihao;
return this;
}
public SinaUserInfo build() {
return new SinaUserInfo(this);
}
}
public long getId() {
return id;
}
public String getScreen_name() {
return screen_name;
}
public String getName() {
return name;
}
public int getProvince() {
return province;
}
public int getCity() {
return city;
}
public String getLocation() {
return location;
}
public String getDescription() {
return description;
}
public String getUrl() {
return url;
}
public String getProfile_image_url() {
return profile_image_url;
}
public String getDomain() {
return domain;
}
public String getGender() {
return gender;
}
public int getFollowers_count() {
return followers_count;
}
public int getFriends_count() {
return friends_count;
}
public int getStatuses_count() {
return statuses_count;
}
public int getFavourites_count() {
return favourites_count;
}
public Long getCreated_at() {
return created_at;
}
public boolean isVerified() {
return verified;
}
public int getVerified_type() {
return verified_type;
}
public String getAvatar_large() {
return avatar_large;
}
public int getBi_followers_count() {
return bi_followers_count;
}
public String getRemark() {
return remark;
}
public String getVerified_reason() {
return verified_reason;
}
public String getWeihao() {
return weihao;
}
}
| [
"[email protected]"
] | |
02406dddce9b8a718a7adddcd67c4d4c1067d037 | 873c5a9d27b0e9cd868bde81c7c44d693a747878 | /springboot-weapp-demo/src/test/java/com/weapp/ApplicationTest.java | 95541b77030e5ebfef014038508e98481b2e724c | [] | no_license | chenzhuoli/weixinopen | f48256c1aa8fdcf7d605fe86e54a04965e1589e7 | 8639081ab858941d78ae7fbf0aaf2ae173da8aa4 | refs/heads/master | 2021-06-14T06:25:15.426872 | 2021-01-18T11:29:36 | 2021-01-18T11:29:36 | 75,054,375 | 0 | 0 | null | 2016-11-29T07:20:48 | 2016-11-29T07:20:48 | null | UTF-8 | Java | false | false | 1,813 | java | package com.weapp;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.weapp.controller.AppUserController;
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MockServletContext.class)
@WebAppConfiguration
@TestPropertySource("classpath:application-test.properties")
public class ApplicationTest {
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new AppUserController()).build();
MockitoAnnotations.initMocks(this);
}
//测试获取数据接口
@Test
public void test() throws Exception{
RequestBuilder request = null;
request = MockMvcRequestBuilders.get("/api/v1/user/123123")
.param("appId", "test123").param("apiName", "GET_USER");
mvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().string(equalTo("{\"id\":\"123123\"}")));
}
}
| [
"[email protected]"
] | |
0fdb0f2197da40ff4e38683f746f4815b2c79546 | 2b229ce360fcff117bc02907ffc49169f177af5f | /src/main/java/parts/model/PartAmountConstraint.java | 150789b8917260beb283e577af209192283053b6 | [] | no_license | OlegDemura/javarush2019 | 87856aa683702fe8e0f449944d194e5de1352fc0 | 66cf6432afc8af94c1eafc13b96a615422faf8b0 | refs/heads/master | 2020-04-14T15:52:26.785882 | 2019-01-03T07:49:06 | 2019-01-03T07:49:06 | 163,939,129 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 620 | java | package parts.model;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PartAmountConstraintValidation.class)
public @interface PartAmountConstraint {
String message() default "Введите положительное число.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| [
"[email protected]"
] | |
fd67b5f157e1265cb08cd4c9e860b0d5d3a6efb1 | 8de7b4dd50789124c43ec69153fb28579f08a0de | /WEB-MAC-HACK-KI/src/main/java/com/amigotrip/domain/PartyGuest.java | c0fe40cf420fff75f31574d4e569b35f4244d334 | [] | no_license | Yongjai/2017-REAL-MAC-HACK-KI | c4080fb6e621f651a1a8c4918d6315e183624c0a | b6194e9a84f468646340667eb6f1988b1ae78234 | refs/heads/master | 2021-08-28T06:01:07.160360 | 2017-12-08T14:38:59 | 2017-12-08T14:38:59 | 106,879,176 | 0 | 0 | null | 2017-10-13T22:33:00 | 2017-10-13T22:33:00 | null | UTF-8 | Java | false | false | 702 | java | package com.amigotrip.domain;
import lombok.*;
import javax.persistence.*;
/**
* Created by Naver on 2017. 10. 17..
*/
@Entity
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class PartyGuest {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Setter
@Getter
private String name;
@Setter
@Getter
private String email;
@Setter
@Getter
private int age;
@Setter
@Getter
private String gender;
@Setter
@Getter
private String language;
@Getter
@Setter
private String date;
@Setter
@Getter
private String theme;
@Setter
@Getter
private String attraction;
}
| [
"[email protected]"
] | |
116fecff9ffa70e8b518077afff1402f320c1e1e | b599d5291b9fd1b52e9795e3e7acc21e3421f7fc | /src/testenovo/Empregado.java | 0a66085782bd8844fe368b0147a1600df40cc68f | [] | no_license | Shaiell/testenovo | fe192b06d9aad8c2e6334a4ceda070c0405bc457 | ac1cc3ea9c642e3cd7cfb5b68fb6d782262008b6 | refs/heads/master | 2020-05-21T01:02:05.352978 | 2019-05-09T17:32:40 | 2019-05-09T17:32:40 | 185,845,140 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 740 | java | package testenovo;
public abstract class Empregado {
private String nome;
private String email;
private String matricula;
public Empregado(String nome, String email, String matricula) {
this.nome = nome;
this.email = email;
this.matricula = matricula;
}
public abstract Double getValorAPagar();
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMatricula() {
return matricula;
}
public void setMatricula(String matricula) {
this.matricula = matricula;
}
@Override
public String toString() {
return "Empregado pai";
}
}
| [
"[email protected]"
] | |
0395dbd158bfac4e272485d081225bc2a4b90fde | af043b52b4f340a465918b92fdd867bbf4c21093 | /src/main/java/com/walmart/stm/transaction/Transaction.java | 274505fea23029e1c0e394c7101f31cefea5de13 | [
"Apache-2.0"
] | permissive | yuanmai/javastm | d94a9e2fd0efc2bc6704c972c1eb784523849a6f | 86c919eb5509247197a28709ad08f84dd5237e5d | refs/heads/master | 2021-04-15T12:51:23.185369 | 2016-01-06T19:45:32 | 2016-01-06T19:45:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,736 | java | package com.walmart.stm.transaction;
/**
* Created by grosal3 on 1/1/16.
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
public final class Transaction implements Context {
private HashMap<Ref, Object> inTxMap = new HashMap<>();
private HashSet<Ref> toUpdate = new HashSet<>();
private long revision;
private static AtomicLong transactionNum = new AtomicLong(0);
private Map<Ref, Long> version = new HashMap<>();
public Transaction() {
revision = transactionNum.incrementAndGet();
}
public <T> T get(Ref<T> ref) {
if (!inTxMap.containsKey(ref)) {
RefTuple<T, Long> tuple = ref.content;
inTxMap.put(ref, tuple.value);
if (!version.containsKey(ref)) {
version.put(ref, tuple.revision);
}
}
return (T) inTxMap.get(ref);
}
public <T> void set(Ref<T> ref, T value) {
inTxMap.put(ref, value);
toUpdate.add(ref);
if (!version.containsKey(ref)) {
RefTuple<T, Long> tuple = ref.content;
version.put(ref, tuple.revision);
}
}
public boolean commit() {
synchronized (STM.commitLock) {
boolean isValid = true;
for (Ref ref : inTxMap.keySet()) {
if (ref.content.revision != version.get(ref)) {
isValid = false;
break;
}
}
if (isValid) {
for (Ref ref : toUpdate) {
ref.content = RefTuple.get(inTxMap.get(ref), revision);
}
}
return isValid;
}
}
}
| [
"[email protected]"
] | |
c2c0bc5c81c0652cef893e93843b2fb10b103d62 | bf530b7bcbc4efa5ff4f6ef67cf0359117c85c70 | /src/org/apps8os/motivator/data/GoalDataHandler.java | 2ae507917871184b6a567557f5faa6642641263c | [
"MIT",
"Apache-2.0"
] | permissive | apps8os/motivator | 31696a1972dc4268ece7aad45e673b439cf672ce | 911083a5973afc4d1eb520190b60371c3a3fb75f | refs/heads/master | 2016-08-07T04:30:11.413044 | 2014-07-01T13:59:40 | 2014-07-01T13:59:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,954 | java | /*******************************************************************************
* Copyright (c) 2014 Helsingin Diakonissalaitos and the authors
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
package org.apps8os.motivator.data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import org.apps8os.motivator.R;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.SparseArray;
/**
* Handles the access for goal data.
* Goals not yet implemented in the applications
* @author Toni Järvinen
*
*/
public class GoalDataHandler extends MotivatorDatabaseHelper {
private SparseArray<Question> mQuestions;
public static final int GOAL_ACTIVE = 0;
public static final int GOAL_COMPLETE = 1;
public static final int GOAL_FAILED = 2;
public static final int QUESTION_ID_WHAT_TO_ACHIEVE = 3000;
public static final int QUESTION_ID_TIMEFRAME = 3001;
public static final String KEY_START_TIME = "start_time";
public static final String KEY_END_TIME = "end_time";
public static final String KEY_LENGTH_IN_DAYS = "length_in_days";
public static final String KEY_GOAL_ID = "goal_id";
public static final String KEY_GOAL_AS_TEXT = "goal_as_text";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_STATUS = "complete";
public static final String TABLE_NAME_GOALS = "goals";
public static final String CREATE_GOAL_TABLE =
"CREATE TABLE " + TABLE_NAME_GOALS + " (" +
KEY_ID + " INTEGER PRIMARY KEY, " +
KEY_START_TIME + " INTEGER, " +
KEY_END_TIME + " INTEGER, " +
KEY_LENGTH_IN_DAYS + " INTEGER, " +
KEY_GOAL_ID + " INTEGER, " +
KEY_AMOUNT + " INTEGER, " +
KEY_STATUS + " INTEGER, " +
KEY_TIMESTAMP + " INTEGER);";
private Context mContext;
public GoalDataHandler(Context context) {
super(context);
mContext = context;
mQuestions = new SparseArray<Question>();
Resources res = context.getResources();
// Inserting the questions to the SpareArrays.
String[] goalQuestionIds = res.getStringArray(R.array.goal_question_ids);
String[] requiredQuestionIds = res.getStringArray(R.array.goal_required_ids);
for (int i = 0; i < goalQuestionIds.length; i++) {
boolean required = Arrays.asList(requiredQuestionIds).contains(goalQuestionIds[i]);
// String array of questions
String[] questionAndAnswers = res.getStringArray(res.getIdentifier(goalQuestionIds[i], "array", context.getPackageName()));
// discard the "id" part of the question id
int id = Integer.parseInt(goalQuestionIds[i].substring(2));
// Creation of new Question object and inserting it to the array.
Question question = new Question(id, questionAndAnswers[0], Arrays.copyOfRange(questionAndAnswers, 1, questionAndAnswers.length), required);
mQuestions.put(id, question);
}
}
public void insertGoal(long startTime, int daysAnswer, int goalId, int amount) {
SQLiteDatabase db = super.open();
ContentValues values = new ContentValues();
values.put(KEY_START_TIME, startTime);
Calendar calendar = Calendar.getInstance();
switch (daysAnswer) {
case 0:
values.put(KEY_LENGTH_IN_DAYS, 7);
calendar.add(Calendar.DATE, 7);
values.put(KEY_END_TIME, calendar.getTimeInMillis());
break;
case 1:
values.put(KEY_LENGTH_IN_DAYS, 14);
calendar.add(Calendar.DATE, 14);
values.put(KEY_END_TIME, calendar.getTimeInMillis());
break;
case 2:
values.put(KEY_LENGTH_IN_DAYS, 28);
calendar.add(Calendar.DATE, 28);
values.put(KEY_END_TIME, calendar.getTimeInMillis());
break;
}
values.put(KEY_GOAL_ID, goalId);
values.put(KEY_AMOUNT, amount);
values.put(KEY_STATUS, GOAL_ACTIVE);
values.put(KEY_TIMESTAMP, System.currentTimeMillis());
db.insert(TABLE_NAME_GOALS, null, values);
db.close();
}
public ArrayList<Goal> getOngoingGoals() {
open();
ArrayList<Goal> result = new ArrayList<Goal>();
String selection = KEY_START_TIME + " < " + System.currentTimeMillis() + " AND " + KEY_END_TIME + " > " + System.currentTimeMillis();
Cursor query = mDb.query(TABLE_NAME_GOALS, null, selection, null, null, null, KEY_END_TIME);
addGoals(result, query);
query.close();
close();
return result;
}
private void addGoals(ArrayList<Goal> result, Cursor query) {
Goal goal;
if (query.moveToFirst()) {
for (int i = 0; i < query.getCount(); i++) {
int goalId = query.getInt(4);
int amount = query.getInt(5);
int days = query.getInt(3);
String goalAsText = getQuestion(QUESTION_ID_WHAT_TO_ACHIEVE).getAnswer(goalId);
switch(days) {
case 7:
if (goalId == 1) {
goalAsText = goalAsText.replaceAll("X", "" + amount);
goalAsText = goalAsText + " " + mContext.getString(R.string.in_a_week);
} else if (goalId == 0) {
goalAsText = goalAsText.replaceAll("X", "" + amount);
goalAsText = goalAsText + " " + mContext.getString(R.string.for_a_week);
} else {
goalAsText = goalAsText + " " + mContext.getString(R.string.for_a_week);
}
break;
case 14:
if (goalId == 1) {
goalAsText = goalAsText.replaceAll("X", "" + amount);
goalAsText = goalAsText + " " + mContext.getString(R.string.in_two_weeks);
} else if (goalId == 0) {
goalAsText = goalAsText.replaceAll("X", "" + amount);
goalAsText = goalAsText + " " + mContext.getString(R.string.for_two_weeks);
} else {
goalAsText = goalAsText + " " + mContext.getString(R.string.for_two_weeks);
}
break;
case 28:
if (goalId == 1) {
goalAsText = goalAsText.replaceAll("X", "" + amount);
goalAsText = goalAsText + " " + mContext.getString(R.string.in_four_weeks);
} else if (goalId == 0) {
goalAsText = goalAsText.replaceAll("X", "" + amount);
goalAsText = goalAsText + " " + mContext.getString(R.string.for_four_weeks);
} else {
goalAsText = goalAsText + " " + mContext.getString(R.string.for_four_weeks);
}
break;
}
goal = new Goal(query.getInt(0), query.getLong(1), days, query.getLong(2), goalId, goalAsText, query.getInt(6));
if (goalId < 2) {
goal.setTargetAmount(amount);
}
result.add(goal);
query.moveToNext();
}
}
}
public void updateGoalStatus(int id, int status) {
open();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, status);
String selection = KEY_ID + " = " + id;
mDb.update(TABLE_NAME_GOALS, values, selection, null);
close();
}
public Question getQuestion(int id) {
return mQuestions.get(id);
}
public int getAmountOfQuestions() {
return mQuestions.size();
}
public int getFirstQuestionId() {
return mQuestions.keyAt(0);
}
}
| [
"[email protected]"
] | |
28bb29ef8dbd794c2274ddcddbe14e7d172ed6c7 | 40d844c1c780cf3618979626282cf59be833907f | /src/testcases/CWE191_Integer_Underflow/s04/CWE191_Integer_Underflow__short_console_readLine_postdec_61b.java | 56aa0fb3e507cb1909769430df2d79207cf159a7 | [] | no_license | rubengomez97/juliet | f9566de7be198921113658f904b521b6bca4d262 | 13debb7a1cc801977b9371b8cc1a313cd1de3a0e | refs/heads/master | 2023-06-02T00:37:24.532638 | 2021-06-23T17:22:22 | 2021-06-23T17:22:22 | 379,676,259 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,955 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__short_console_readLine_postdec_61b.java
Label Definition File: CWE191_Integer_Underflow.label.xml
Template File: sources-sinks-61b.tmpl.java
*/
/*
* @description
* CWE: 191 Integer Underflow
* BadSource: console_readLine Read data from the console using readLine
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: decrement
* GoodSink: Ensure there will not be an underflow before decrementing data
* BadSink : Decrement data, which can cause an Underflow
* Flow Variant: 61 Data flow: data returned from one method to another in different classes in the same package
*
* */
package testcases.CWE191_Integer_Underflow.s04;
import testcasesupport.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.logging.Level;
public class CWE191_Integer_Underflow__short_console_readLine_postdec_61b
{
public short badSource() throws Throwable
{
short data;
/* init data */
data = -1;
/* POTENTIAL FLAW: Read data from console with readLine*/
BufferedReader readerBuffered = null;
InputStreamReader readerInputStream = null;
try
{
readerInputStream = new InputStreamReader(System.in, "UTF-8");
readerBuffered = new BufferedReader(readerInputStream);
String stringNumber = readerBuffered.readLine();
if (stringNumber != null)
{
data = Short.parseShort(stringNumber.trim());
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
catch (NumberFormatException exceptNumberFormat)
{
IO.logger.log(Level.WARNING, "Error with number parsing", exceptNumberFormat);
}
finally
{
/* clean up stream reading objects */
try
{
if (readerBuffered != null)
{
readerBuffered.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
finally
{
try
{
if (readerInputStream != null)
{
readerInputStream.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
}
}
return data;
}
/* goodG2B() - use goodsource and badsink */
public short goodG2BSource() throws Throwable
{
short data;
/* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
data = 2;
return data;
}
/* goodB2G() - use badsource and goodsink */
public short goodB2GSource() throws Throwable
{
short data;
/* init data */
data = -1;
/* POTENTIAL FLAW: Read data from console with readLine*/
BufferedReader readerBuffered = null;
InputStreamReader readerInputStream = null;
try
{
readerInputStream = new InputStreamReader(System.in, "UTF-8");
readerBuffered = new BufferedReader(readerInputStream);
String stringNumber = readerBuffered.readLine();
if (stringNumber != null)
{
data = Short.parseShort(stringNumber.trim());
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
catch (NumberFormatException exceptNumberFormat)
{
IO.logger.log(Level.WARNING, "Error with number parsing", exceptNumberFormat);
}
finally
{
/* clean up stream reading objects */
try
{
if (readerBuffered != null)
{
readerBuffered.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
finally
{
try
{
if (readerInputStream != null)
{
readerInputStream.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
}
}
return data;
}
}
| [
"[email protected]"
] | |
a774c39c87e39663fd4e6077390f6ea4f2ea9fb2 | 2b196cb1202937720eeaea17ff4bc370d0073997 | /09_Servlets/Day 06- 17.02.2019/00_Product app/src/jb/ProductsServlet.java | f277143b0f4ed6019b8764d6db66fc190c4b289a | [] | no_license | yalowe/Java-822.104-1 | 3db9fea0d1b19ec060478af6dd42cd692c9b74b8 | c6e43cc32eec651b955916b8c86adbaa513c6107 | refs/heads/master | 2020-05-06T13:24:43.188109 | 2019-03-03T17:30:20 | 2019-03-03T17:30:20 | 180,135,139 | 1 | 0 | null | 2019-04-08T11:32:15 | 2019-04-08T11:32:14 | null | UTF-8 | Java | false | false | 2,319 | java | package jb;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@WebServlet("/ProductsServlet")
public class ProductsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProductsServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pageParam=request.getParameter("page");
String itemParam=request.getParameter("item");
if(pageParam!=null) {
if(pageParam.equals("home")) {
JSONArray allProducts=new JSONArray();
for(Product p: ProductStock.products) {
JSONObject prod=new JSONObject();
prod.put("name", p.getName());
prod.put("price", p.getPrice());
allProducts.add(prod);
}
response.getWriter().append(allProducts.toString());
return;
}
else if(pageParam.equals("cart")) {
Object cart=request.getSession().getAttribute("cart");
if(cart!=null) {
ArrayList<Product> userProducts=(ArrayList<Product>)cart;
JSONArray allCartProducts=new JSONArray();
for(Product p: userProducts) {
JSONObject prod=new JSONObject();
prod.put("name", p.getName());
prod.put("price", p.getPrice());
allCartProducts.add(prod);
}
response.getWriter().append(allCartProducts.toString());
return;
}
}
}
if(itemParam!=null) {
Product selected=ProductStock.getItemByName(itemParam);
if(selected!=null) {
Object cart=request.getSession().getAttribute("cart");
ArrayList<Product> userProducts=(cart!=null)?(ArrayList<Product>)cart:new ArrayList<Product>();
userProducts.add(selected);
request.getSession().setAttribute("cart",userProducts);
response.getWriter().append("{\"res\": \"Added product successfully\"}");
return;
}
}
response.getWriter().append("Sorry - non supprted request");
}
}
| [
"[email protected]"
] | |
a72f8229a4dda6d7b38d5dbc75a14fa15f3068ce | 8ee37bccfff6a9240da62bd434cb6521879fd219 | /src/main/java/com/url/Url.java | cbe7d6d7954ac028cbd78e7ef04f8defd6886bff | [] | no_license | karthik-morab/ProjectGladiator | 6e6bd58ec1ece15bf5ed08308cceef06cb49d530 | d8dd26e29bfa4cf787819ef67e826272b1fd3c5f | refs/heads/master | 2023-08-24T00:05:45.463692 | 2021-10-20T09:34:58 | 2021-10-20T09:34:58 | 418,855,219 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 377 | java | package com.url;
import java.io.*;
import java.util.*;
public class Url {
public String getUrl() {
Properties prop = new Properties();
try {
prop.load(new FileInputStream("src/main/resources/credentials.property"));
}
catch (Exception e){
System.out.println("Error in file reading");
}
String weburl = prop.getProperty("url");
return weburl;
}
}
| [
"[email protected]"
] | |
828c52d0315ed6434d0946abcf27e28e35b2c2a7 | d305b692dcf287f276608081bdbf3a2352a4f4f8 | /1. Lectures/Asynchronous_Rest _Multithreading/app/src/main/java/com/example/rest_client/ListView.java | b2e36c5fad686bc701ea3375439bd68bbd512da9 | [] | no_license | dimitrov9812/MobileApps_Fundamentals_AndroidStudio | 182ada1ecd1be3223ee2deebd74d422d7c8b5d2c | b7cc1bea4c43f2b58ef9e368be646032fd55e56f | refs/heads/master | 2021-05-24T09:18:02.375174 | 2020-05-05T11:49:21 | 2020-05-05T11:49:21 | 253,491,086 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 506 | java | package com.example.rest_client;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class ListView extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
}
public void setAdapter(ArrayAdapter<String> arrayAdapter) {
}
public void clearChoices() {
}
}
| [
"[email protected]"
] | |
b08872c8a017d9264b6f7ad14d248ff978991700 | 337b91e9a56bd4ad7a20dcae74ba8a577eb940b0 | /BaseLib/src/main/java/core/base/views/statusbar/BuildProperties.java | 05102d84ffc1e5377dba5bb3b8f636a93784eb18 | [] | no_license | bumbleben2486/FlowChart | 4339c2fdaba32505276ecfa15f16cfdbbda3ce78 | aebbc6b091a0eb111bf102f5c881cad17800c4d2 | refs/heads/master | 2020-04-19T10:19:38.529054 | 2019-01-29T10:41:54 | 2019-01-29T10:41:54 | 168,127,557 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,612 | java | package core.base.views.statusbar;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class BuildProperties {
private final Properties properties;
private BuildProperties() throws IOException {
properties = new Properties();
properties.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
}
public boolean containsKey(final Object key) {
return properties.containsKey(key);
}
public boolean containsValue(final Object value) {
return properties.containsValue(value);
}
public Set<Map.Entry<Object, Object>> entrySet() {
return properties.entrySet();
}
public String getProperty(final String name) {
return properties.getProperty(name);
}
public String getProperty(final String name, final String defaultValue) {
return properties.getProperty(name, defaultValue);
}
public boolean isEmpty() {
return properties.isEmpty();
}
public Enumeration<Object> keys() {
return properties.keys();
}
public Set<Object> keySet() {
return properties.keySet();
}
public int size() {
return properties.size();
}
public Collection<Object> values() {
return properties.values();
}
public static BuildProperties newInstance() throws IOException {
return new BuildProperties();
}
}
| [
"[email protected]"
] | |
beb6f6e7f5b5efe6c8420164f76af248d1108763 | 7b2179458a414a86c8e7dafad5444acb3707c841 | /src/test/java/com/dongx/blog/InitializationApplication.java | a7e6ebf89caaf9c9c06423b9dd8c2cdab3fdaa78 | [] | no_license | MiracleDx/blog | 075ae3bfa184c94f7605328330063840a4486292 | ceb590d8d2ed5f99f6136bc27feea4b3dc6de956 | refs/heads/master | 2023-07-07T01:05:22.771248 | 2019-07-13T15:40:17 | 2019-07-13T15:40:17 | 135,419,693 | 0 | 0 | null | 2023-06-20T18:32:03 | 2018-05-30T09:25:32 | Java | UTF-8 | Java | false | false | 334 | java | package com.dongx.blog;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class InitializationApplication {
@Test
public void contextLoads() {
}
}
| [
"[email protected]"
] | |
c5c35569469ea9d0a8eb039fb7fb280ba031b38f | 65d3272a7c1250d09cdd043a23f46a4e85eb1dc8 | /src/br/com/cocodonto/framework/dao/DeleteDaoException.java | 9b4e5b7f8a79aa426fc95ebcddb81ca702aaf5e5 | [] | no_license | JacquesAlex0513/CocOdonto | dea002890850c177c000ab341ef90ecec13c00a9 | 9be66c089cbc18938272433bf473262f8b7a932e | refs/heads/master | 2021-01-23T02:34:25.841319 | 2017-03-23T22:43:30 | 2017-03-23T22:43:30 | 86,005,270 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 490 | java | /**
*
*/
package br.com.cocodonto.framework.dao;
/**
* @author Jacques_64
*
*/
public class DeleteDaoException extends RuntimeException {
//Criando construtores da classe
public DeleteDaoException() {
super();
}
public DeleteDaoException(String message, Throwable cause) {
super(message, cause);
}
public DeleteDaoException(String message) {
super(message);
}
public DeleteDaoException(Throwable cause) {
super(cause);
}
}
| [
"[email protected]"
] | |
8da7fce4029e19d72813023c26ebe7122682432a | 236f127285eff34b0d7ee308b0b4ec3ea5853e99 | /src/main/java/pageObjects/FiltersCatalog.java | 75abf84e3f1421c964015efbe3c66eee70ec5014 | [] | no_license | RamyaPalacharla/RamyaUniform | ffed0967a180082348d6492d5a033cd8201bd573 | 561c3435aa9f683894bee16fde6388b30bd7e5d1 | refs/heads/main | 2023-09-03T09:01:34.682531 | 2021-11-22T10:28:17 | 2021-11-22T10:28:17 | 430,659,183 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,420 | java | package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class FiltersCatalog
{
//declaring driver variable
public WebDriver driver;
//finding the locators of WebElements and storing in variables
By filterGroupName=By.xpath("//*[@name='filter_group_description[1][name]']");
By filterName=By.xpath("//*[@placeholder='Filter Name']");
By save=By.xpath("//*[@data-original-title='Save']");
By errorMsg=By.className("text-danger");
By addPlus=By.xpath("//a[@onclick='addFilterRow();']");
By success=By.xpath("//*[text()=' Success: You have modified filters! ']");
By page=By.xpath("//div[@class='col-sm-6 text-right']");
//defining the constructor
public FiltersCatalog(WebDriver driver)
{
//assigning driver to driver variable in this class
this.driver=driver;
}
public WebElement getFilterGroupName()
{
return driver.findElement(filterGroupName);
}
public WebElement getSave()
{
return driver.findElement(save);
}
public WebElement getErrorMsg()
{
return driver.findElement(errorMsg);
}
public WebElement getAddPlus()
{
return driver.findElement(addPlus);
}
public WebElement getFilterName()
{
return driver.findElement(filterName);
}
public WebElement getSuccess()
{
return driver.findElement(success);
}
public WebElement getPage()
{
return driver.findElement(page);
}
} | [
"[email protected]"
] | |
834ef42551c8f7ef21757f82f2611a25ef220274 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/1/1_7d82c553de54c6d94d47325ff9dd8f66d0695b79/YetiGUI/1_7d82c553de54c6d94d47325ff9dd8f66d0695b79_YetiGUI_t.java | e42414321985b44aea559b20efc9371e701dcf3d | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 4,358 | java | package yeti.monitoring;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import yeti.Yeti;
import yeti.YetiLog;
import yeti.YetiRoutine;
/**
* Class that represents the GUI for Yeti.
*
* @author Manuel Oriol ([email protected])
* @date Sep 3, 2009
*
*/
public class YetiGUI implements Runnable {
/**
* The sampler to update the samplable objects.
*/
public YetiSampler sampler = null;
/**
* Checks whether the update thread should be stopped or not.
*/
public boolean isToUpdate = true;
/**
* The timeout between updates.
*/
public long nMSBetweenUpdates;
/**
* Method to stop the update of the GUI.
*/
public void stopRoutine() {
this.isToUpdate = false;
this.sampler.setToUpdate(false);
}
/**
* All the components in the current GUI.
*/
public ArrayList<YetiUpdatable> allComponents= new ArrayList<YetiUpdatable>();
/**
* Simple creation procedure for YetiGUI.
*
* @param nMSBetweenUpdates the time in ms between 2 updates.
*/
public YetiGUI(long nMSBetweenUpdates) {
this.nMSBetweenUpdates = nMSBetweenUpdates;
sampler = new YetiSampler(nMSBetweenUpdates);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
p.setLayout(new GridLayout(0,3));
f.add(new JScrollPane(p),BorderLayout.CENTER);
int numberOfMethods = Yeti.testModule.routinesInModule.values().size();
p.setPreferredSize(new Dimension(300,10*numberOfMethods));
p.setBackground(Color.white);
// we add all routines to the panel of routines.
for (YetiRoutine r: Yeti.testModule.routinesInModule.values()) {
YetiRoutineGraph graph = new YetiRoutineGraph(r);
graph.setSize(50, 30);
p.add(graph);
this.allComponents.add(graph);
}
f.setSize(400,400);
f.setLocation(1000,200);
f.setVisible(true);
// we add the number of faults over time
JFrame f0 = new JFrame();
f0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
YetiGraph graph0 = new YetiGraphFaultsOverTime(YetiLog.proc,nMSBetweenUpdates);
sampler.addSamplable(graph0);
this.allComponents.add(graph0);
f0.add(graph0);
f0.setSize(400,200);
f0.setLocation(200,200);
f0.setVisible(true);
// we add the number of calls over time
JFrame f1 = new JFrame();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
YetiGraph graph1 = new YetiGraphNumberOfCallsOverTime(YetiLog.proc,nMSBetweenUpdates);
sampler.addSamplable(graph1);
this.allComponents.add(graph1);
f1.add(graph1);
f1.setSize(400,200);
f1.setLocation(600,200);
f1.setVisible(true);
// we add the number of failures over time
JFrame f2 = new JFrame();
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
YetiGraph graph2 = new YetiGraphNumberOfFailuresOverTime(YetiLog.proc,nMSBetweenUpdates);
sampler.addSamplable(graph2);
this.allComponents.add(graph2);
f2.add(graph2);
f2.setSize(400,200);
f2.setLocation(200,400);
f2.setVisible(true);
// we add the number of failures over time
JFrame f3 = new JFrame();
f3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
YetiGraph graph3 = new YetiGraphNumberOfVariablesOverTime(YetiLog.proc,nMSBetweenUpdates);
sampler.addSamplable(graph3);
this.allComponents.add(graph3);
f3.add(graph3);
f3.setSize(400,200);
f3.setLocation(600,400);
f3.setVisible(true);
new Thread(this).start();
new Thread(sampler).start();
}
/* (non-Javadoc)
* We use this method to actually update the values in real time.
*
* @see java.lang.Runnable#run()
*/
public void run() {
// We use these two points in time to set an interval up.
// It happens that the update takes more time than a cycle to proceed.
// Do not use this loop to sample values.
while (isToUpdate) {
for (YetiUpdatable u: allComponents) {
u.updateValues();
}
try {
Thread.sleep(nMSBetweenUpdates);
} catch (InterruptedException e) {
// Should never happen
// e.printStackTrace();
}
}
}
}
| [
"[email protected]"
] | |
1d0757701de7b59ea194b03f86094041baf3082f | 11fb3c4e56415b99eb2a387346da0f3ce33cb100 | /src/com/dp/CompositePattern/TestSongList.java | 21652b103770f649035b443e5526226b38dd350c | [] | no_license | somu84/DesignPatternsProject | 2c555ddf893b637ae5165974fe98fb861ef01748 | 104340dfca595cf4e138d89f4f3f8fd0aab5e313 | refs/heads/master | 2021-01-18T18:38:10.775318 | 2017-04-09T13:53:16 | 2017-04-09T13:53:16 | 86,283,599 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 442 | java | package com.dp.CompositePattern;
public class TestSongList {
public static void main(String[] args){
SongComponent ind = new SongGroup("Industrial", "");
SongComponent mtl = new SongGroup("Metal", "");
SongComponent everySong = new SongGroup("Song List", "All Songs");
everySong.add(ind);
ind.add(new Song("HQWEWE", "INI", 1990));
ind.add(mtl);
DiscJokey cJ = new DiscJokey(everySong);
cJ.getSongList();
}
}
| [
"[email protected]"
] | |
4087a805723722da42707c2dcd26039e995a16b8 | 414ce90ea643414a8e3b084f7482b9f9f3b0747c | /SpringMVC_transaction/src/com/dao/TeacherDao.java | a2d27ffb79c4ba3aa9b52f89e9cc81fc828cf7c3 | [] | no_license | ablepoe/spring_mvc | dcbe320f190dcfd121746246b0945c8dfbe47aec | 5cfff038ffc3c3e622ee1c1261067c206c88362b | refs/heads/master | 2020-04-06T06:59:03.663615 | 2016-06-13T02:50:56 | 2016-06-13T02:50:56 | 37,966,015 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 87 | java | package com.dao;
public interface TeacherDao {
public void addTeacher();
}
| [
"[email protected]"
] | |
58f3d2d265babaefd1dd3732ad0f40c25981194f | b70d5b3f7b97cde823973b8e8d284cebfffd3c75 | /BookListServlet.java | bc7fdbae3cc13162238afdfde29e7467ab4194b0 | [] | no_license | PlusPplus/BookList | 601c9ec8cc4ac79fadb3ffdaa04d90d8c399bed0 | 97881473bfb6b9603bc2a99663202456a0f7bad1 | refs/heads/master | 2020-07-06T00:16:17.297839 | 2019-08-17T13:36:33 | 2019-08-17T13:36:33 | 202,828,030 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,200 | java | package com.servlet;
import java.io.IOException;
import java.util.List;
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 com.Data.BookList;
import com.Data.BookListDao;
/**
* @author Plus
* @date 2019年7月18日
*/
@WebServlet("/BookListServlet")
public class BookListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public BookListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BookListDao booklistdao=new BookListDao();
List<BookList> list=booklistdao.queryAll();
//int a=booklistdao.showCount();
request.setAttribute("booklist", list);
request.getRequestDispatcher("ShowBookList.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| [
"[email protected]"
] | |
28b50b6464d9f0c7c9ad9c5e03688d23175ae398 | 7b65d709ef21ceff32515a9196833968b10f05b3 | /Javafundamentals/Methods/src/PalidromeIntiger.java | 1bf1c4c69122a00d4d0ffbb93f52f2105bacb35a | [] | no_license | chonochonovuk/SoftUni | 432f9c81958df78a459a38feb5eb42f8053e09b9 | c6d49a22edac61b83fe7fe5e0d5621986de09b84 | refs/heads/master | 2021-07-13T04:59:50.508849 | 2020-04-12T11:22:30 | 2020-04-12T11:22:30 | 211,654,543 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 715 | java | import java.util.Scanner;
public class PalidromeIntiger {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String tillEnd = scanner.nextLine();
while (!tillEnd.equals("END")){
String check = PN(tillEnd);
if (tillEnd.equals(check)){
System.out.printf("%s%n",true);
}else{
System.out.printf("%s%n",false);
}
tillEnd = scanner.nextLine();
}
}
static String PN(String match){
String Result1 = "";
for (int a = match.length() - 1; a >= 0; a-- ){
Result1 += match.charAt(a);
}
return Result1;
}
}
| [
"[email protected]"
] | |
b1cee0f0203af2873ce2b5f105d096c456f55151 | 350184750d4e7afa18afe2a13608e68b8a3ef2f2 | /filefront/src/main/java/com/global/adk/filefront/provider/invoker/FileInvokerSupport.java | 73b969c73ef17054523f4b756d0ca4b05da9c972 | [] | no_license | smallchen28/application-developer-kit | dbdef1fb6b4135a59f4b7a9ccf995d5314180dbe | f1e27c4d8adc28693bbb76f8c10eca725cb0c823 | refs/heads/master | 2021-04-08T00:43:09.395874 | 2018-05-09T07:24:18 | 2018-05-09T07:24:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,274 | java | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
/*
* 修订记录:
* [email protected] 2016-09-03 14:13 创建
*
*/
package com.global.adk.filefront.provider.invoker;
import com.global.adk.biz.executor.AbstractInvokeService;
import com.global.adk.biz.executor.ServiceContext;
import com.global.adk.filefront.dal.mapper.FileDbOperator;
import com.global.adk.filefront.listeners.FileEventBus;
import com.global.adk.filefront.schedule.task.FileTaskExecutor;
import com.yjf.common.lang.result.StandardResultInfo;
import com.yjf.common.log.Logger;
import com.yjf.common.log.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author karott
*/
public abstract class FileInvokerSupport<P, R extends StandardResultInfo> extends AbstractInvokeService<P, R> {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
protected FileEventBus fileEventBus;
@Autowired
protected FileDbOperator fileDbOperator;
@Autowired
protected FileTaskExecutor fileTaskExecutor;
@Override
public void before(ServiceContext<P, R> serviceContext) {
}
@Override
public void after(ServiceContext<P, R> serviceContext) {
}
@Override
public void end(ServiceContext<P, R> serviceContext) {
}
}
| [
"[email protected]"
] | |
49cb81b1495bdc0a1ec8ba6a456bf68b97ecd321 | f7b4030e8b1c602f358d8eea903b5e2b9a24a848 | /app/src/main/java/com/thenextbiggeek/scribblear/MainActivity.java | c3ba84be1987ac4ab158478928c97d797ec6167c | [
"MIT"
] | permissive | abilashsenth/InstaAR-Augmented-Reality | 44d1dab67d732f2205e0df4ddc25d46b3293ef0d | 9abc1fd870219b7479d9fb874d0a781ab990899c | refs/heads/main | 2023-04-07T07:11:16.522062 | 2021-04-06T15:46:29 | 2021-04-06T15:46:29 | 355,230,912 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 22,728 | java | package com.thenextbiggeek.scribblear;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.media.CamcorderProfile;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.google.ar.core.Anchor;
import com.google.ar.core.ArCoreApk;
import com.google.ar.core.Pose;
import com.google.ar.core.Session;
import com.google.ar.core.TrackingState;
import com.google.ar.core.exceptions.UnavailableDeviceNotCompatibleException;
import com.google.ar.core.exceptions.UnavailableUserDeclinedInstallationException;
import com.google.ar.sceneform.AnchorNode;
import com.google.ar.sceneform.ArSceneView;
import com.google.ar.sceneform.Camera;
import com.google.ar.sceneform.FrameTime;
import com.google.ar.sceneform.HitTestResult;
import com.google.ar.sceneform.Scene;
import com.google.ar.sceneform.collision.Ray;
import com.google.ar.sceneform.math.Vector3;
import com.google.ar.sceneform.rendering.Color;
import com.google.ar.sceneform.rendering.Material;
import com.google.ar.sceneform.rendering.MaterialFactory;
import com.google.ar.sceneform.rendering.ModelRenderable;
import com.google.ar.sceneform.rendering.ViewRenderable;
import com.google.ar.sceneform.ux.ArFragment;
import com.google.ar.sceneform.ux.TransformableNode;
import com.googlecode.mp4parser.authoring.Edit;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.concurrent.CompletionException;
import pl.droidsonroids.gif.GifImageView;
public class MainActivity extends AppCompatActivity implements Scene.OnPeekTouchListener, Scene.OnUpdateListener {
private static final int PICK_IMAGE_REQUEST = 27;
private static final int PICK_VIDEO_REQUEST = 72;
Context context;
Session mSession;
//considers that the user is ready to install the ARCore app by google
boolean USER_REQUESTED_INSTALL = true;
ArFragment mArFragment;
private ModelRenderable mModelRenderable;
private ViewRenderable textViewRenderable;
private ViewRenderable textViewRenderable2;
private ViewRenderable gifViewRenderable;
private ViewRenderable imageViewRenderable;
private ViewRenderable videoViewRenderable;
private ViewRenderable textBoxRenderable;
String textBoxText;
private String TAG ="MainActivity";
private final int STORAGE_PERMISSION_KEY=10;
private final int CAMERA_PERMISSION_KEY = 9;
private Material material;
private final LineSimplifier lineSimplifier = new LineSimplifier();
private static final Color WHITE = new Color(android.graphics.Color.WHITE);
private static final float DRAW_DISTANCE = 0.13f;
private static AnchorNode anchorNode;
private final ArrayList<Stroke> strokes = new ArrayList<>();
private Stroke currentStroke;
ImageView tester;
GifImageView mGifImageView;
RelativeLayout mainLayout, gifSelectorLayout;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
//hiding the actionBar
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
mainLayout = (RelativeLayout) findViewById(R.id.campreview_relative_layout);
gifSelectorLayout = (RelativeLayout) findViewById(R.id.gif_chooser_relative_layout);
//requesting permissions and checking necessary ARCore apk
requestPermissions();
int arCoreInstalled = checkIfArCoreInstalled();
if(arCoreInstalled == 1){
initUxFragment();
}else{
checkIfArCoreInstalled();
}
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void initUxFragment() {
/**
* initializes the arFragment, creates a model using modelbuilder. a node represents an AR scene entity
* hence the model is applied to the node and the node to the fragment
*/
//textviewrenderable is dummy
//viewrenderables are declared again in respective functions for some reason only then
//separate induvidual elements are allowed in s
mArFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment);
ViewRenderable.builder().
setView(this, R.layout.gif_box).
build().
thenAccept( viewRenderable -> textViewRenderable = viewRenderable).
exceptionally(throwable ->
{Log.e(TAG, "Unable to load Renderable.", throwable);
return null;});
ViewRenderable.builder().
setView(this, R.layout.image_box).
build().
thenAccept( viewRenderable -> textViewRenderable = viewRenderable).
exceptionally(throwable ->
{Log.e(TAG, "Unable to load Renderable.", throwable);
return null;});
ViewRenderable.builder().
setView(this, R.layout.video_box).
build().
thenAccept( viewRenderable -> videoViewRenderable = viewRenderable).
exceptionally(throwable ->
{Log.e(TAG, "Unable to load Renderable.", throwable);
return null;});
ViewRenderable.builder().
setView(this, R.layout.text_box).
build().
thenAccept( viewRenderable -> textViewRenderable2 = viewRenderable).
exceptionally(throwable ->
{Log.e(TAG, "Unable to load Renderable.", throwable);
return null;});
}
//once the required gif is selected from the layout
public void selectedGIFfromLayout(View view) {
//each of the gifs name and the GifImageView ID are hardcoded and same (not to follow in upcoming versions)
String resName = view.getResources().getResourceEntryName(view.getId());
Log.e("RESOURCES", "the name of the drawable selected is " + resName);
int drawableID = getResId(resName, R.drawable.class);
gifSelectorLayout.setVisibility(View.GONE);
mainLayout.setVisibility(View.VISIBLE);
changeGif(drawableID);
}
public static int getResId(String resName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public void changeGif(int resId) {
ViewRenderable.builder().
setView(this, R.layout.gif_box).
build().
thenAccept( viewRenderable -> gifViewRenderable = viewRenderable).
exceptionally(throwable ->
{Log.e(TAG, "Unable to load Renderable.", throwable);
return null;});
//onTapListener on the arFragment to put in the 3d model
mArFragment.setOnTapArPlaneListener(
((hitResult, plane, motionEvent) -> {
if(gifViewRenderable == null){
return;
}
Anchor anchor = hitResult.createAnchor();
AnchorNode anchorNode2 = new AnchorNode(anchor);
anchorNode2.setParent(mArFragment.getArSceneView().getScene());
TransformableNode node2 = new TransformableNode(mArFragment.getTransformationSystem());
node2.setParent(anchorNode2);
node2.setRenderable(gifViewRenderable);
node2.select();
mGifImageView = (GifImageView) gifViewRenderable.getView();
mGifImageView.setImageResource(resId);
//TODO create a dynamic limit such that only 2 or 3 gifs are allowed as nodes
})
);
}
//accessed when add gif button is clicked in the UI
public void selectGif(View view) {
mainLayout.setVisibility(View.GONE);
gifSelectorLayout.setVisibility(View.VISIBLE);
}
//back to the activity_main.xml
public void cancelGifSelection(View view) {
gifSelectorLayout.setVisibility(View.GONE);
mainLayout.setVisibility(View.VISIBLE);
}
public void selectTextView(View v){
String message = popUp();
}
private String popUp() {
final String[] m_Text = {""};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Text to display");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
ViewRenderable.builder().
setView(this, R.layout.text_box).
build().
thenAccept( viewRenderable -> textBoxRenderable = viewRenderable).
exceptionally(throwable ->
{Log.e(TAG, "Unable to load Renderable.", throwable);
return null;});
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
textBoxText = input.getText().toString();
Log.e("TEXT", textBoxText);
TextView tester = (TextView) textBoxRenderable.getView();
//onTapListener on the arFragment to put in the 3d model
mArFragment.setOnTapArPlaneListener(
((hitResult, plane, motionEvent) -> {
if(textBoxRenderable == null){
return;
}
Anchor anchor = hitResult.createAnchor();
AnchorNode anchorNode4 = new AnchorNode(anchor);
anchorNode4.setParent(mArFragment.getArSceneView().getScene());
TransformableNode node4= new TransformableNode(mArFragment.getTransformationSystem());
node4.setParent(anchorNode4);
node4.setRenderable(textBoxRenderable);
node4.select();
tester.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/helvetica.ttf"));
tester.setText(textBoxText);
})
);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return textBoxText;
}
@Override
public void onUpdate(FrameTime frameTime) {
com.google.ar.core.Camera camera = mArFragment.getArSceneView().getArFrame().getCamera();
if(camera.getTrackingState() == TrackingState.TRACKING){
mArFragment.getPlaneDiscoveryController().hide();
}
}
//accessed when image add button is clicked in the UI
public void startImage(View view) {
//passes an intent to get image URI
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//accessed when video add button is clicked in the UI
public void startVideo(View view) {
//passes an intent to get image URI
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_VIDEO_REQUEST);
}
//when the draw button is clicked
public void startDrawing(View view) {
//disable planeRenderer
mArFragment.getArSceneView().getPlaneRenderer().setEnabled(false);
mArFragment.getArSceneView().getScene().addOnPeekTouchListener(this);
mArFragment.getArSceneView().getScene().addOnUpdateListener(this);
//currently white
MaterialFactory.makeOpaqueWithColor(this, WHITE).
thenAccept(material1 -> material = material1.makeCopy()).
exceptionally(throwable -> {
//handle the throwable
throw new CompletionException(throwable);
});
}
//draws
@Override
public void onPeekTouch(HitTestResult hitTestResult, MotionEvent motionEvent) {
int action = motionEvent.getAction();
Camera camera = mArFragment.getArSceneView().getScene().getCamera();
Ray ray = camera.screenPointToRay(motionEvent.getX(), motionEvent.getY());
Vector3 drawPoint = ray.getPoint(DRAW_DISTANCE);
if(action == MotionEvent.ACTION_DOWN){
if(anchorNode == null){
ArSceneView arSceneView = mArFragment.getArSceneView();
com.google.ar.core.Camera coreCamera = arSceneView.getArFrame().getCamera();
if(coreCamera.getTrackingState() != TrackingState.TRACKING){
return;
}
Pose pose = coreCamera.getPose();
anchorNode = new AnchorNode((arSceneView.getSession().createAnchor(pose)));
anchorNode.setParent(arSceneView.getScene());
}
currentStroke = new Stroke(anchorNode, material);
strokes.add(currentStroke);
currentStroke.add(drawPoint);
}else if(action == MotionEvent.ACTION_MOVE && currentStroke != null){
currentStroke.add(drawPoint);
}
}
public void startRecording(View view) {
//uses VideoRecorder class
VideoRecorder mVideoRecorder = new VideoRecorder();
mVideoRecorder.setSceneView(mArFragment.getArSceneView());
int orientation = getResources().getConfiguration().orientation;
//TODO make quality changeable
mVideoRecorder.setVideoQuality(CamcorderProfile.QUALITY_720P, orientation);
boolean recording = mVideoRecorder.onToggleRecord();
//keeps a timer of 5 seconds and toggles the record stop
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
boolean recording = mVideoRecorder.onToggleRecord();
String videoPath = mVideoRecorder.getVideoPath().getAbsolutePath();
Intent intent = new Intent(MainActivity.this, VideoPreviewActivity.class);
intent.putExtra("VIDEOPATH", videoPath);
startActivity(intent);
}
}, 10000);
}
private int checkIfArCoreInstalled() {
if(mSession == null){
try {
switch(ArCoreApk.getInstance().requestInstall(this, USER_REQUESTED_INSTALL)){
case INSTALLED:
//ARCore installed already. Cool!
return 1;
case INSTALL_REQUESTED:
//Nope //TODO: make sure the user installs the apk for the app's usage
USER_REQUESTED_INSTALL = false;
break;
}
} catch (UnavailableDeviceNotCompatibleException e) {
Toast.makeText(this, "This smartphone does not support the ARcore APK.", Toast.LENGTH_LONG).show();
e.printStackTrace();
return 0;
} catch (UnavailableUserDeclinedInstallationException e) {
Toast.makeText(this, "This app requires the ARcore APK to work", Toast.LENGTH_LONG).show();
e.printStackTrace();
return 0;
}
}
//returns 0 also when there is an mSession already running
return 0;
}
private void requestPermissions() {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
//request for camera permission
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.CAMERA}, CAMERA_PERMISSION_KEY);
}
if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
//request for the storage permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION_KEY);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,int[] resultCode ){
switch(requestCode){
case CAMERA_PERMISSION_KEY:
if(resultCode.length >0 ){
if(resultCode[0] == PackageManager.PERMISSION_GRANTED){
//permission granted
//TODO make sure the storage permission is also enabled. needed before the final version
checkIfArCoreInstalled();
}else{
//nope
Toast.makeText(this, "Camera Permission is required for AR",
Toast.LENGTH_SHORT).show();
requestPermissions();
}
}
break;
case STORAGE_PERMISSION_KEY:
if(resultCode.length >0){
if(resultCode[0] == PackageManager.PERMISSION_GRANTED){
//permissiongranted
//TODO make sure the camera permission is also enabled. needed before the final version
}else{
//nope
Toast.makeText(this, "Storage Permission is required for VideoReording",
Toast.LENGTH_SHORT).show();
requestPermissions();
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
ViewRenderable.builder().
setView(this, R.layout.image_box).
build().
thenAccept( viewRenderable -> imageViewRenderable = viewRenderable).
exceptionally(throwable ->
{Log.e(TAG, "Unable to load Renderable.", throwable);
return null;});
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//TODO this is how you refer tothe view. gif or video or image or otherwise
//onTapListener on the arFragment to put in the 3d model
mArFragment.setOnTapArPlaneListener(
((hitResult, plane, motionEvent) -> {
if(imageViewRenderable == null){
return;
}
Anchor anchor = hitResult.createAnchor();
AnchorNode anchorNode3 = new AnchorNode(anchor);
anchorNode3.setParent(mArFragment.getArSceneView().getScene());
TransformableNode node3 = new TransformableNode(mArFragment.getTransformationSystem());
node3.setParent(anchorNode3);
node3.setRenderable(imageViewRenderable);
node3.select();
ImageView tester = (ImageView) imageViewRenderable.getView();
tester.setImageBitmap(bitmap);
})
);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == PICK_VIDEO_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
VideoView tester = (VideoView) videoViewRenderable.getView();
tester.setVideoURI(uri);
//onTapListener on the arFragment to put in the 3d model
mArFragment.setOnTapArPlaneListener(
((hitResult, plane, motionEvent) -> {
if(videoViewRenderable == null){
return;
}
Anchor anchor = hitResult.createAnchor();
AnchorNode anchorNode4 = new AnchorNode(anchor);
anchorNode4.setParent(mArFragment.getArSceneView().getScene());
TransformableNode node4 = new TransformableNode(mArFragment.getTransformationSystem());
node4.setParent(anchorNode4);
node4.setRenderable(videoViewRenderable);
node4.select();
})
);
}
}
}
| [
"[email protected]"
] | |
03b56af05bfd49191856199669094414d153c4d2 | 3328f6d29aba38a9e43186150c2faf4415908b55 | /src/Main.java | bf5a218d6d5c5e4c7fc12cce9991b3716739e3a0 | [] | no_license | BaturinaAnna/hello-world | 7003b649d1f040b85a1a26956c05a521021ca233 | 68a6a487c7ec7f38640c2e9580a613ae1ef17d9f | refs/heads/master | 2021-06-24T10:35:06.935481 | 2021-03-18T15:19:10 | 2021-03-18T15:19:10 | 209,101,602 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 190 | java | public class Main {
public static void main(String[] args) {
String hello = "Hello";
String world = "World";
System.out.println(hello + " " + world + "!");
}
}
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.