blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 410 | content_id stringlengths 40 40 | detected_licenses listlengths 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 listlengths 1 1 | author_id stringlengths 0 313 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1f1169b94bff92db16494936e254df82f0826758 | e6e79217b8c2529891a9ec3f955cc749c38c6366 | /src/main/java/nvminecraftbros/minecraftaddons/emerald/tabs/EmeraldTab.java | 17a5cbcc5b7360960ef9914bace8d9c7dfa708dd | [] | no_license | AlexTheGreat4000/MinecraftAddonsMod | 65978f853ed02e1c6d9760409662fbf3f24565c7 | 352ea8a3cffeaa76e0ec35d17de39036f86b3450 | refs/heads/master | 2020-06-29T22:34:19.740261 | 2019-08-05T11:51:22 | 2019-08-05T11:51:22 | 200,644,723 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 540 | java | package nvminecraftbros.minecraftaddons.emerald.tabs;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import nvminecraftbros.minecraftaddons.MinecraftAddonMod;
import nvminecraftbros.minecraftaddons.emerald.items.EmeraldItems;
public class EmeraldTab extends CreativeTabs {
public static final String TAB = "emerald";
public EmeraldTab()
{
super(EmeraldTab.TAB);
}
@Override
public ItemStack getTabIconItem()
{
return new ItemStack(Items.EMERALD);
}
}
| [
"AlexTheGreat4000@users.noreply.github.com"
] | AlexTheGreat4000@users.noreply.github.com |
608d9079a37657e3225bd3a46d0d76bc0453c125 | 178ef1239b7b188501395c4d3db3f0266b740289 | /android/animation/PathKeyframes.java | 4b40f5755fc71f7612061e56fe6a0a37b1802df3 | [] | no_license | kailashrs/5z_framework | b295e53d20de0b6d2e020ee5685eceeae8c0a7df | 1b7f76b1f06cfb6fb95d4dd41082a003d7005e5d | refs/heads/master | 2020-04-26T12:31:27.296125 | 2019-03-03T08:58:23 | 2019-03-03T08:58:23 | 173,552,503 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,415 | java | package android.animation;
import android.graphics.Path;
import android.graphics.PointF;
import java.util.ArrayList;
public class PathKeyframes
implements Keyframes
{
private static final ArrayList<Keyframe> EMPTY_KEYFRAMES = new ArrayList();
private static final int FRACTION_OFFSET = 0;
private static final int NUM_COMPONENTS = 3;
private static final int X_OFFSET = 1;
private static final int Y_OFFSET = 2;
private float[] mKeyframeData;
private PointF mTempPointF = new PointF();
public PathKeyframes(Path paramPath)
{
this(paramPath, 0.5F);
}
public PathKeyframes(Path paramPath, float paramFloat)
{
if ((paramPath != null) && (!paramPath.isEmpty()))
{
mKeyframeData = paramPath.approximate(paramFloat);
return;
}
throw new IllegalArgumentException("The path must not be null or empty");
}
private static float interpolate(float paramFloat1, float paramFloat2, float paramFloat3)
{
return (paramFloat3 - paramFloat2) * paramFloat1 + paramFloat2;
}
private PointF interpolateInRange(float paramFloat, int paramInt1, int paramInt2)
{
paramInt1 *= 3;
paramInt2 *= 3;
float f1 = mKeyframeData[(paramInt1 + 0)];
f1 = (paramFloat - f1) / (mKeyframeData[(paramInt2 + 0)] - f1);
float f2 = mKeyframeData[(paramInt1 + 1)];
float f3 = mKeyframeData[(paramInt2 + 1)];
float f4 = mKeyframeData[(paramInt1 + 2)];
paramFloat = mKeyframeData[(paramInt2 + 2)];
f3 = interpolate(f1, f2, f3);
paramFloat = interpolate(f1, f4, paramFloat);
mTempPointF.set(f3, paramFloat);
return mTempPointF;
}
private PointF pointForIndex(int paramInt)
{
paramInt *= 3;
mTempPointF.set(mKeyframeData[(paramInt + 1)], mKeyframeData[(paramInt + 2)]);
return mTempPointF;
}
public Keyframes clone()
{
Object localObject = null;
try
{
Keyframes localKeyframes = (Keyframes)super.clone();
localObject = localKeyframes;
}
catch (CloneNotSupportedException localCloneNotSupportedException) {}
return localObject;
}
public Keyframes.FloatKeyframes createXFloatKeyframes()
{
new FloatKeyframesBase()
{
public float getFloatValue(float paramAnonymousFloat)
{
return getValue(paramAnonymousFloat)).x;
}
};
}
public Keyframes.IntKeyframes createXIntKeyframes()
{
new IntKeyframesBase()
{
public int getIntValue(float paramAnonymousFloat)
{
return Math.round(getValue(paramAnonymousFloat)).x);
}
};
}
public Keyframes.FloatKeyframes createYFloatKeyframes()
{
new FloatKeyframesBase()
{
public float getFloatValue(float paramAnonymousFloat)
{
return getValue(paramAnonymousFloat)).y;
}
};
}
public Keyframes.IntKeyframes createYIntKeyframes()
{
new IntKeyframesBase()
{
public int getIntValue(float paramAnonymousFloat)
{
return Math.round(getValue(paramAnonymousFloat)).y);
}
};
}
public ArrayList<Keyframe> getKeyframes()
{
return EMPTY_KEYFRAMES;
}
public Class getType()
{
return PointF.class;
}
public Object getValue(float paramFloat)
{
int i = mKeyframeData.length / 3;
if (paramFloat < 0.0F) {
return interpolateInRange(paramFloat, 0, 1);
}
if (paramFloat > 1.0F) {
return interpolateInRange(paramFloat, i - 2, i - 1);
}
if (paramFloat == 0.0F) {
return pointForIndex(0);
}
if (paramFloat == 1.0F) {
return pointForIndex(i - 1);
}
int j = 0;
i--;
while (j <= i)
{
int k = (j + i) / 2;
float f = mKeyframeData[(k * 3 + 0)];
if (paramFloat < f)
{
i = k - 1;
}
else
{
if (paramFloat <= f) {
break label126;
}
j = k + 1;
}
continue;
label126:
return pointForIndex(k);
}
return interpolateInRange(paramFloat, i, j);
}
public void setEvaluator(TypeEvaluator paramTypeEvaluator) {}
static abstract class FloatKeyframesBase
extends PathKeyframes.SimpleKeyframes
implements Keyframes.FloatKeyframes
{
FloatKeyframesBase()
{
super();
}
public Class getType()
{
return Float.class;
}
public Object getValue(float paramFloat)
{
return Float.valueOf(getFloatValue(paramFloat));
}
}
static abstract class IntKeyframesBase
extends PathKeyframes.SimpleKeyframes
implements Keyframes.IntKeyframes
{
IntKeyframesBase()
{
super();
}
public Class getType()
{
return Integer.class;
}
public Object getValue(float paramFloat)
{
return Integer.valueOf(getIntValue(paramFloat));
}
}
private static abstract class SimpleKeyframes
implements Keyframes
{
private SimpleKeyframes() {}
public Keyframes clone()
{
Object localObject = null;
try
{
Keyframes localKeyframes = (Keyframes)super.clone();
localObject = localKeyframes;
}
catch (CloneNotSupportedException localCloneNotSupportedException) {}
return localObject;
}
public ArrayList<Keyframe> getKeyframes()
{
return PathKeyframes.EMPTY_KEYFRAMES;
}
public void setEvaluator(TypeEvaluator paramTypeEvaluator) {}
}
}
| [
"kailash.sudhakar@gmail.com"
] | kailash.sudhakar@gmail.com |
c9d91be0c7616605bfc07b90c20e6f166304f74c | b9dd59c1109b9f7c7404d75c3140050083433cee | /Semester 2 - 2017/Software Engineering/src/JUnitTestCases.java | 3f0a8f02f7faec9cb5557d9e2c3b40e477204a36 | [] | no_license | s3432636/University | e288b5d95542a5dc0727e1a9952231c23994e70d | 092695422d8298afb994c1fb9402ef9e90e1826b | refs/heads/master | 2020-05-07T16:28:07.746174 | 2018-11-22T21:11:32 | 2018-11-22T21:11:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,947 | java | import static org.junit.Assert.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Arrays;
import org.junit.Test;
public class JUnitTestCases {
// Users are unable to login with an incorrect username and password.
@Test
public void test() throws NumberFormatException, NoSuchAlgorithmException, IOException {
ShareMarketMain main = new ShareMarketMain();
ShareMarketMain.readAtStartUp();
assertEquals("Failure", main.Login("aa", "AA"));
assertEquals("Failure", main.Login("main", "MAIN23"));
assertEquals("Failure", main.Login("Jeff", "JEFFFFFFFF"));
}
// users is able to login with a correct username and password.
@Test
public void test2() throws NumberFormatException, NoSuchAlgorithmException, IOException {
ShareMarketMain main = new ShareMarketMain();
assertEquals("Success", main.Login("aa", "aa"));
assertEquals("Success", main.Login("admin", "admin"));
assertEquals("Success", main.Login("Jeff", "Jeff"));
}
// Able to see if number of shares is increased or decreased based on input.
@Test
public void test3() throws FileNotFoundException {
// users 3,4,5 are all trading accounts
((TradingAccount) ShareMarketMain.users.get(3)).setData(+0, +3, -2, +3, +7, +5);
((TradingAccount) ShareMarketMain.users.get(4)).setData(+0, +0, +0, +0, +0, +0);
((TradingAccount) ShareMarketMain.users.get(5)).setData(+100, +3, -50, +6, +9, +1);
assertEquals("[0, 3, -2, 3, 7, 5]",
(Arrays.toString(((TradingAccount) ShareMarketMain.users.get(3)).getData())));
assertEquals("[0, 0, 0, 0, 0, 0]",
(Arrays.toString(((TradingAccount) ShareMarketMain.users.get(4)).getData())));
assertEquals("[100, 3, -50, 6, 9, 1]",
(Arrays.toString(((TradingAccount) ShareMarketMain.users.get(5)).getData())));
}
// Checks if brokerage price is computed correctly for a Sale.
@Test
public void test4() throws FileNotFoundException {
ShareMarketMain.readAtStartUp();
assertEquals(75.0, QueuedItem.BrokeragPriceSale("a2", 10000), 0.0);
assertEquals(50.0, QueuedItem.BrokeragPriceSale("a2", 0), 0.0);
assertEquals(300, QueuedItem.BrokeragPriceSale("a2", 100000), 0.0);
}
// Checks if brokerage price is computed correctly for a Purchase.
@Test
public void test5() {
assertEquals(150, QueuedItem.BrokeragPricePurchase("a2", 10000), 0.0);
assertEquals(50.0, QueuedItem.BrokeragPricePurchase("a2", 0), 0.0);
assertEquals(1050, QueuedItem.BrokeragPricePurchase("a2", 100000), 0.0);
}
// Test whether average share price for existing share held by the customer
// is computed correctly based on three or more purchases.
@Test
public void test6() {
}
// Test whether an item queued can be removed successfully before
// transaction is done
@Test
public void test7() throws FileNotFoundException {
ShareMarketMain.readSettingsOnStartUP();
Boolean output = true;
int[] test = { 1, 2, 3, 4, 5, 6 };
QueuedItem.QueueStockPurchase("Jeff", test, 10000);
QueuedItem.QueueStockPurchase("Jeff", test, 12000);
assertEquals(output, QueuedItem.cancelQueue("Jeff", 1));
assertEquals(output, QueuedItem.cancelQueue("Jeff", 0));
}
// Test that an item cannot be removed from the queue after the transaction
// is done
@Test
public void test8() throws FileNotFoundException {
Boolean output = true;
assertNotEquals(output, QueuedItem.cancelQueue("Jeff", 1));
assertNotEquals(output, QueuedItem.cancelQueue("Jeff", 0));
}
// Test attempts to queue a purchase or sale for amounts exceeding $600,000
// are automatically rejected
@Test
public void test9() throws FileNotFoundException {
int[] test = { 1, 2, 3, 4, 5, 6 };
Boolean output = true;
assertNotEquals(output, QueuedItem.QueueStockPurchase("admin", test, 600001));
assertNotEquals(output, QueuedItem.QueueStockPurchase("admin", test, 750000));
assertNotEquals(output, QueuedItem.QueueStockPurchase("admin", test, 900000));
}
//share market price test
@Test
public void test10() throws IOException {
SharePriceInformation aa = new SharePriceInformation();
aa.saveToFileShareMarketInformation("AAPL");
aa.saveToFileShareMarketInformation("TSLA");
aa.saveToFileShareMarketInformation("MSFT");
aa.saveToFileShareMarketInformation("AMZN");
aa.saveToFileShareMarketInformation("NFLX");
aa.saveToFileShareMarketInformation("AMD");
System.out.println(aa.getAAPLSharePrice());
System.out.println(aa.getAMDSharePrice());
System.out.println(aa.getAMZNSharePrice());
System.out.println(aa.getMSFTSharePrice());
System.out.println(aa.getNFLXSharePrice());
System.out.println(aa.getTSLASharePrice());
}
//share market price test
@Test
public void test11() throws IOException, ParseException {
ShareMarketMain.readSettingsOnStartUP();
int[] test = { 1, 2, 3, 4, 5, 6 };
QueuedItem.QueueStockPurchase("Jeff", test, 10000);
}
}
| [
"s3658817@student.rmit.edu.au"
] | s3658817@student.rmit.edu.au |
fb4f74c5b1bfcfbe22c6c86a22e0b62016042c2e | fb1a0222d9acf0e594afdb9fac06f8e523e57e37 | /src/main/java/com/proyecto/restfulmarcas/repositorio/RepositorioPrototipo.java | c7b075cd73917bec3e21506f0212cf18cc618678 | [] | no_license | AMD031/harokuMarca | 54f63781ceaf7cde70b4df4c2fbf4d174ea1bf13 | 709f99b26d21093e3beba8e118a739a5fe13f434 | refs/heads/master | 2022-05-19T11:01:27.087489 | 2020-02-14T11:57:15 | 2020-02-14T11:57:15 | 240,497,429 | 0 | 0 | null | 2022-01-21T23:37:55 | 2020-02-14T11:53:32 | Java | UTF-8 | Java | false | false | 1,606 | 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 com.proyecto.restfulmarcas.repositorio;
import com.proyecto.restfulmarcas.interfaces.IIngeniero;
import com.proyecto.restfulmarcas.modelo.Prototipo;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
/**
*
* @author Samuel Hermosilla Aguilera
*/
public interface RepositorioPrototipo
extends JpaRepository<Prototipo, Long>{
@Query(value = "SELECT * FROM prototipo AS p WHERE p.nombreClave LIKE %?1%", nativeQuery = true)
public List<Prototipo> getPrototipoByName(String nombre);
@Query(value = "SELECT i.id_ingeniero, i.nombre, i.dni FROM prototipo p INNER JOIN ingeniero_prototipo ip on p.id_prototipo = ip.id_prototipo_fk INNER JOIN ingeniero i on i.id_ingeniero = ip.id_ingeniero_fk WHERE p.id_prototipo = ?", nativeQuery = true)
public List<IIngeniero> getIngenieroByIdPrototipo(Long id);
@Query(value = "SELECT i.id_ingeniero, i.nombre, i.dni FROM prototipo p INNER JOIN ingeniero_prototipo ip on p.id_prototipo = ip.id_prototipo_fk INNER JOIN\n" +
"ingeniero i on i.id_ingeniero = ip.id_ingeniero_fk WHERE p.nombreClave like %?1%", nativeQuery = true)
public List<IIngeniero> getIngenierosByNombreClavePrototipo(String nombreClave);
}
| [
"teclado1333@gmail.com"
] | teclado1333@gmail.com |
6c3de0cb809430e902072f85d08bba331e23b7d4 | 9894e10c66f441069d92e83124040a42800c3903 | /week-01/Day-4/src/loops/FizzBuzz.java | aa325aaec84f8985b243512176567d4bcd93369b | [] | no_license | green-fox-academy/Mosi013 | 5f276cbe7f127f6705cd02cbec869e7c79eb4e90 | 64464f37fe704119f0dd55076d3d1d1b32715728 | refs/heads/master | 2021-02-15T07:47:42.117932 | 2020-09-18T08:09:36 | 2020-09-18T08:09:36 | 279,622,847 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 659 | java | package loops;
public class FizzBuzz {
// Write a program that prints the numbers from 1 to 100.
// But for multiples of three print “Fizz” instead of the number
// and for the multiples of five print “Buzz”.
// For numbers which are multiples of both three and five print “FizzBuzz”.
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("buzz");
} else {
System.out.println(i);
}
}
}
}
| [
"mosonyi.mark95@gmail.com"
] | mosonyi.mark95@gmail.com |
b2b90d24dbda1d4de94f321b6b87819b17834678 | 5bda7f9159092996628bec84ab0d1f904ea5a173 | /app/src/main/java/cn/tties/energy/view/fragment/IdentityFragment.java | 8685a5d67c01990acac87947fef4cd5325ce50bb | [] | no_license | laolongs/energys | 84100ff24347d3957a609da4bab426d693c6cddb | 7811eb9ec0e235212f71536d2e65400eb0af09d0 | refs/heads/master | 2020-03-11T07:44:44.070248 | 2018-05-03T11:26:45 | 2018-05-03T11:26:45 | 129,865,392 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,797 | java | package cn.tties.energy.view.fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import java.util.List;
import cn.tties.energy.R;
import cn.tties.energy.base.BaseFragment;
import cn.tties.energy.common.Constants;
import cn.tties.energy.common.MyNoDoubleClickListener;
import cn.tties.energy.model.result.Loginbean;
import cn.tties.energy.model.result.OpsLoginbean;
import cn.tties.energy.presenter.IdentityFragmentPresenter;
import cn.tties.energy.utils.ACache;
import cn.tties.energy.utils.ToastUtil;
import cn.tties.energy.view.activity.AboutActivity;
import cn.tties.energy.view.activity.ChangeTableActivity;
import cn.tties.energy.view.activity.LoginActivity;
import cn.tties.energy.view.activity.PasswordActivity;
import cn.tties.energy.view.activity.UpdateActivity;
import cn.tties.energy.view.activity.VersionActivity;
import cn.tties.energy.view.dialog.ConfirmDialog;
import cn.tties.energy.view.dialog.CriProgressDialog;
import cn.tties.energy.view.iview.IIdentityFragmentView;
/**
* Created by li on 2018/3/21
* description:
* author:guojlli
*/
public class IdentityFragment extends BaseFragment<IdentityFragmentPresenter> implements View.OnClickListener, IIdentityFragmentView {
private static final String TAG = "IdentityFragment";
Toolbar identityToolbar;
TextView identityName;
TextView identityCompany;
TextView identityNumber;
LinearLayout layoutPassword;
LinearLayout layoutVersion;
LinearLayout identityAbout;
LinearLayout layoutLoginout;
TextView identitySwitchElectricity;
ImageView identityImg;
ImageView identitySwitchSelsect;
int num = 0;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View inflate = inflater.inflate(R.layout.fragment_identity, null);
initFindView(inflate);
return inflate;
}
private void initFindView(View inflate) {
identityToolbar = inflate.findViewById(R.id.identity_toolbar);
layoutPassword = inflate.findViewById(R.id.layout_password);
layoutVersion = inflate.findViewById(R.id.layout_version);
identityAbout = inflate.findViewById(R.id.identity_about);
layoutLoginout = inflate.findViewById(R.id.layout_loginout);
identityImg = inflate.findViewById(R.id.identity_img);
identityName = inflate.findViewById(R.id.identity_name);
identityNumber = inflate.findViewById(R.id.identity_number);
identityCompany = inflate.findViewById(R.id.identity_company);
identitySwitchSelsect = inflate.findViewById(R.id.identity_switch_selsect);
identitySwitchElectricity = inflate.findViewById(R.id.identity_switch_electricity);
layoutPassword.setOnClickListener(this);
layoutVersion.setOnClickListener(this);
identityAbout.setOnClickListener(this);
layoutLoginout.setOnClickListener(this);
}
@Override
public void onResume() {
super.onResume();
mPresenter.getOpsloginData();//1502183891109
}
@Override
protected void createPresenter() {
mPresenter = new IdentityFragmentPresenter(this,getActivity());
}
@Override
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
//切换表号
// case R.id.layout_tablenumber:
// intent = new Intent(getActivity(), TablenNumberActivity.class);
// startActivity(intent);
// break;
//修改密码
case R.id.layout_password:
if(MyNoDoubleClickListener.isFastClick()){
intent = new Intent(getActivity(), PasswordActivity.class);
startActivity(intent);
}
break;
//版本更新
case R.id.layout_version:
if(MyNoDoubleClickListener.isFastClick()){
intent = new Intent(getActivity(), UpdateActivity.class);
startActivity(intent);
}
break;
//关于我们
case R.id.identity_about:
ToastUtil.showShort(getActivity(),"暂无关于我们!");
// intent = new Intent(getActivity(), AboutActivity.class);
// startActivity(intent);
break;
//设置
case R.id.layout_loginout:
ConfirmDialog dialog = new ConfirmDialog(getActivity());
dialog.loadDialog("退出登录", "", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToastUtil.showLong(getActivity(), "已退出登录");
ACache.getInstance().put(Constants.CACHE_LOGIN_STATUS_TWO, false);
final Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
getActivity().finish();
}
});
break;
}
}
@Override
public void getOpsLoginData(final OpsLoginbean opsLoginbean) {
OpsLoginbean loginbean = ACache.getInstance().getAsObject(Constants.CACHE_OPSLOGIN_USERINFO);
List<OpsLoginbean.ResultBean.EnergyLedgerListBean> energyLedgerList = opsLoginbean.getResult().getEnergyLedgerList();
identityName.setText(opsLoginbean.getResult().getMaintUser().getStaffName());
identityCompany.setText(opsLoginbean.getResult().getCompanyName() + "");
if (opsLoginbean.getResult().getEnergyLedgerList().size() > 0) {
String ischeck = ACache.getInstance().getAsString(Constants.CACHE_ISCHECK);
int postion = Integer.parseInt(ischeck);
for (int i = 0; i < energyLedgerList.size(); i++) {
if (i == postion) {
long energyLedgerId = loginbean.getResult().getEnergyLedgerList().get(postion).getEnergyLedgerId();
identityNumber.setText(energyLedgerId + "");
Log.i(TAG, "getOpsLoginData: " + energyLedgerId);
}
}
num = opsLoginbean.getResult().getEnergyLedgerList().size();
if (num > 0 && num == 1) {
identitySwitchSelsect.setVisibility(View.INVISIBLE);
identitySwitchElectricity.setText("仅有1个电表");
} else {
identitySwitchSelsect.setVisibility(View.VISIBLE);
identitySwitchElectricity.setText("共有" + num + "个电表 切换电表");
identitySwitchElectricity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(MyNoDoubleClickListener.isFastClick()){
Intent intent1 = new Intent(getActivity(), ChangeTableActivity.class);
intent1.putExtra("bean", opsLoginbean);
startActivity(intent1);
}
}
});
}
} else {
Log.i(TAG, "getOpsLoginData: " + "当前运维无信息");
}
}
}
| [
"https://github.com/laolongs/energy.git"
] | https://github.com/laolongs/energy.git |
e043a18c96c885ef3bf840019ca10578df83a5b3 | c885ef92397be9d54b87741f01557f61d3f794f3 | /results/Math-6/org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer/BBC-F0-opt-40/tests/15/org/apache/commons/math3/optim/nonlinear/scalar/noderiv/SimplexOptimizer_ESTest.java | d4f88162a61293f3536f52f4bf8adf475eba8042 | [
"CC-BY-4.0",
"MIT"
] | permissive | pderakhshanfar/EMSE-BBC-experiment | f60ac5f7664dd9a85f755a00a57ec12c7551e8c6 | fea1a92c2e7ba7080b8529e2052259c9b697bbda | refs/heads/main | 2022-11-25T00:39:58.983828 | 2022-04-12T16:04:26 | 2022-04-12T16:04:26 | 309,335,889 | 0 | 1 | null | 2021-11-05T11:18:43 | 2020-11-02T10:30:38 | null | UTF-8 | Java | false | false | 12,571 | java | /*
* This file was automatically generated by EvoSuite
* Thu Oct 21 10:54:49 GMT 2021
*/
package org.apache.commons.math3.optim.nonlinear.scalar.noderiv;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import org.apache.commons.math3.exception.MathUnsupportedOperationException;
import org.apache.commons.math3.optim.InitialGuess;
import org.apache.commons.math3.optim.OptimizationData;
import org.apache.commons.math3.optim.PointValuePair;
import org.apache.commons.math3.optim.SimpleBounds;
import org.apache.commons.math3.optim.SimplePointChecker;
import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.MultiDirectionalSimplex;
import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.NelderMeadSimplex;
import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true)
public class SimplexOptimizer_ESTest extends SimplexOptimizer_ESTest_scaffolding {
@Test(timeout = 4000)
public void test00() throws Throwable {
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer(34, 34);
OptimizationData[] optimizationDataArray0 = new OptimizationData[8];
double[] doubleArray0 = new double[6];
double[] doubleArray1 = new double[3];
SimpleBounds simpleBounds0 = new SimpleBounds(doubleArray0, doubleArray1);
optimizationDataArray0[1] = (OptimizationData) simpleBounds0;
InitialGuess initialGuess0 = new InitialGuess(doubleArray1);
optimizationDataArray0[3] = (OptimizationData) initialGuess0;
// Undeclared exception!
try {
simplexOptimizer0.parseOptimizationData(optimizationDataArray0);
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// 6 != 3
//
verifyException("org.apache.commons.math3.optim.BaseMultivariateOptimizer", e);
}
}
@Test(timeout = 4000)
public void test01() throws Throwable {
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer(1607.5299177275845, 1316.0);
// Undeclared exception!
try {
simplexOptimizer0.parseOptimizationData((OptimizationData[]) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.apache.commons.math3.optim.BaseOptimizer", e);
}
}
@Test(timeout = 4000)
public void test02() throws Throwable {
NelderMeadSimplex nelderMeadSimplex0 = new NelderMeadSimplex(7, (-0.7853981633974483));
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer(7, 7);
OptimizationData[] optimizationDataArray0 = new OptimizationData[9];
double[] doubleArray0 = new double[7];
SimpleBounds simpleBounds0 = new SimpleBounds(doubleArray0, doubleArray0);
optimizationDataArray0[0] = (OptimizationData) simpleBounds0;
optimizationDataArray0[1] = (OptimizationData) nelderMeadSimplex0;
// Undeclared exception!
try {
simplexOptimizer0.optimize(optimizationDataArray0);
fail("Expecting exception: MathUnsupportedOperationException");
} catch(MathUnsupportedOperationException e) {
//
// constraint
//
verifyException("org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer", e);
}
}
@Test(timeout = 4000)
public void test03() throws Throwable {
NelderMeadSimplex nelderMeadSimplex0 = new NelderMeadSimplex(7, (-0.7853981633974483));
double[] doubleArray0 = new double[2];
InitialGuess initialGuess0 = new InitialGuess(doubleArray0);
SimplePointChecker<PointValuePair> simplePointChecker0 = new SimplePointChecker<PointValuePair>(459.1, (-0.7853981633974483));
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer(simplePointChecker0);
OptimizationData[] optimizationDataArray0 = new OptimizationData[3];
optimizationDataArray0[0] = (OptimizationData) initialGuess0;
simplexOptimizer0.parseOptimizationData(optimizationDataArray0);
OptimizationData[] optimizationDataArray1 = new OptimizationData[7];
optimizationDataArray1[0] = (OptimizationData) nelderMeadSimplex0;
// Undeclared exception!
try {
simplexOptimizer0.optimize(optimizationDataArray1);
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// 7 != 2
//
verifyException("org.apache.commons.math3.optim.nonlinear.scalar.noderiv.AbstractSimplex", e);
}
}
@Test(timeout = 4000)
public void test04() throws Throwable {
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer(1.0, 1.0);
OptimizationData[] optimizationDataArray0 = new OptimizationData[6];
double[] doubleArray0 = new double[2];
doubleArray0[0] = (double) 3514;
doubleArray0[1] = 1.0;
InitialGuess initialGuess0 = new InitialGuess(doubleArray0);
optimizationDataArray0[1] = (OptimizationData) initialGuess0;
MultiDirectionalSimplex multiDirectionalSimplex0 = new MultiDirectionalSimplex(doubleArray0);
optimizationDataArray0[2] = (OptimizationData) multiDirectionalSimplex0;
simplexOptimizer0.parseOptimizationData(optimizationDataArray0);
// Undeclared exception!
try {
simplexOptimizer0.doOptimize();
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// illegal state: maximal count (0) exceeded: evaluations
//
verifyException("org.apache.commons.math3.optim.BaseOptimizer$MaxEvalCallback", e);
}
}
@Test(timeout = 4000)
public void test05() throws Throwable {
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer(28, 28);
OptimizationData[] optimizationDataArray0 = new OptimizationData[2];
NelderMeadSimplex nelderMeadSimplex0 = new NelderMeadSimplex(28, 28, 28, 28, 28);
optimizationDataArray0[0] = (OptimizationData) nelderMeadSimplex0;
double[] doubleArray0 = new double[5];
InitialGuess initialGuess0 = new InitialGuess(doubleArray0);
optimizationDataArray0[1] = (OptimizationData) initialGuess0;
simplexOptimizer0.parseOptimizationData(optimizationDataArray0);
// Undeclared exception!
try {
simplexOptimizer0.doOptimize();
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// 28 != 5
//
verifyException("org.apache.commons.math3.optim.nonlinear.scalar.noderiv.AbstractSimplex", e);
}
}
@Test(timeout = 4000)
public void test06() throws Throwable {
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer(1.0, 1.0);
// Undeclared exception!
try {
simplexOptimizer0.doOptimize();
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// null is not allowed
//
verifyException("org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer", e);
}
}
@Test(timeout = 4000)
public void test07() throws Throwable {
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer(2576.8744228493324, 2576.8744228493324);
OptimizationData[] optimizationDataArray0 = new OptimizationData[2];
double[] doubleArray0 = new double[4];
doubleArray0[0] = 2576.8744228493324;
doubleArray0[1] = 2576.8744228493324;
doubleArray0[2] = 2576.8744228493324;
doubleArray0[3] = 2576.8744228493324;
NelderMeadSimplex nelderMeadSimplex0 = new NelderMeadSimplex(doubleArray0, 2576.8744228493324, 2576.8744228493324, 2576.8744228493324, 2576.8744228493324);
optimizationDataArray0[0] = (OptimizationData) nelderMeadSimplex0;
simplexOptimizer0.parseOptimizationData(optimizationDataArray0);
// Undeclared exception!
try {
simplexOptimizer0.doOptimize();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.apache.commons.math3.optim.nonlinear.scalar.noderiv.AbstractSimplex", e);
}
}
@Test(timeout = 4000)
public void test08() throws Throwable {
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer((-1000.2625405548), (-1000.2625405548));
OptimizationData[] optimizationDataArray0 = new OptimizationData[2];
double[] doubleArray0 = new double[4];
doubleArray0[0] = (-1000.2625405548);
doubleArray0[1] = (-1000.2625405548);
doubleArray0[2] = (-1000.2625405548);
doubleArray0[3] = (-1000.2625405548);
NelderMeadSimplex nelderMeadSimplex0 = new NelderMeadSimplex(doubleArray0);
optimizationDataArray0[0] = (OptimizationData) nelderMeadSimplex0;
SimpleBounds simpleBounds0 = new SimpleBounds(doubleArray0, doubleArray0);
optimizationDataArray0[1] = (OptimizationData) simpleBounds0;
simplexOptimizer0.parseOptimizationData(optimizationDataArray0);
// Undeclared exception!
try {
simplexOptimizer0.doOptimize();
fail("Expecting exception: MathUnsupportedOperationException");
} catch(MathUnsupportedOperationException e) {
//
// constraint
//
verifyException("org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer", e);
}
}
@Test(timeout = 4000)
public void test09() throws Throwable {
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer(1.0, 1.0);
OptimizationData[] optimizationDataArray0 = new OptimizationData[6];
double[] doubleArray0 = new double[2];
doubleArray0[0] = (double) 3514;
doubleArray0[1] = 1.0;
InitialGuess initialGuess0 = new InitialGuess(doubleArray0);
optimizationDataArray0[1] = (OptimizationData) initialGuess0;
MultiDirectionalSimplex multiDirectionalSimplex0 = new MultiDirectionalSimplex(doubleArray0);
optimizationDataArray0[2] = (OptimizationData) multiDirectionalSimplex0;
// Undeclared exception!
try {
simplexOptimizer0.optimize(optimizationDataArray0);
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// illegal state: maximal count (0) exceeded: evaluations
//
verifyException("org.apache.commons.math3.optim.BaseOptimizer$MaxEvalCallback", e);
}
}
@Test(timeout = 4000)
public void test10() throws Throwable {
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer(1.0, 1.0);
OptimizationData[] optimizationDataArray0 = new OptimizationData[6];
double[] doubleArray0 = new double[2];
doubleArray0[0] = (double) 3514;
doubleArray0[1] = 1.0;
MultiDirectionalSimplex multiDirectionalSimplex0 = new MultiDirectionalSimplex(doubleArray0);
optimizationDataArray0[2] = (OptimizationData) multiDirectionalSimplex0;
// Undeclared exception!
try {
simplexOptimizer0.optimize(optimizationDataArray0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.apache.commons.math3.optim.nonlinear.scalar.noderiv.AbstractSimplex", e);
}
}
@Test(timeout = 4000)
public void test11() throws Throwable {
SimplexOptimizer simplexOptimizer0 = new SimplexOptimizer(1.0, 1.0);
OptimizationData[] optimizationDataArray0 = new OptimizationData[6];
// Undeclared exception!
try {
simplexOptimizer0.optimize(optimizationDataArray0);
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// null is not allowed
//
verifyException("org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer", e);
}
}
}
| [
"pderakhshanfar@serg2.ewi.tudelft.nl"
] | pderakhshanfar@serg2.ewi.tudelft.nl |
8bb8e7a88f6711de222dc00cdc5cfea4419e0533 | 67d29d8e55497555ce9c041f220501c89c88986a | /app/src/main/java/com/example/rodrigo/trukertrukersoft/activities/SignupActivity.java | 153d5c8e034cda90efd2d082e0ae3c3c4c2a8bef | [] | no_license | RodrigoRochaDiaz/Truker.TrukerSoft | f8a25ad6ddb53ea0f1729b99441e01e2ac381a77 | 58f704f03cc4c6187a65148e3d5e0101c710a589 | refs/heads/master | 2021-01-19T13:14:36.874308 | 2018-08-29T14:05:00 | 2018-08-29T14:05:00 | 88,074,006 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,172 | java | package com.example.rodrigo.trukertrukersoft.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.rodrigo.trukertrukersoft.R;
import com.example.rodrigo.trukertrukersoft.service.ITruckerSoftService;
import com.example.rodrigo.trukertrukersoft.service.request.UserRegistryRequest;
import com.example.rodrigo.trukertrukersoft.service.response.UserRegistryResponse;
import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "SignupActivity";
@InjectView(R.id.input_name) EditText _nameText;
@InjectView(R.id.input_age) EditText _ageText;
@InjectView(R.id.input_email) EditText _emailText;
@InjectView(R.id.input_phone) EditText _phoneText;
@InjectView(R.id.input_carnet) EditText _carnetText;
@InjectView(R.id.input_user) EditText _userText;
@InjectView(R.id.input_password) EditText _passwordText;
@InjectView(R.id.input_password_confirm) EditText _passwordConfirmText;
@InjectView(R.id.btn_signup) Button _signupButton;
@InjectView(R.id.link_login) TextView _loginLink;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
ButterKnife.inject(this);
_signupButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signup();
}
});
_loginLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Finish the registration screen and return to the LoginRequest activity
finish();
}
});
}
public void signup() {
Log.d(TAG, "Signup");
if (!validate()) {
onSignupFailed();
return;
}
_signupButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(SignupActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Creado cuenta...");
progressDialog.show();
String name = _nameText.getText().toString();
short age = Short.parseShort(_ageText.getText().toString());
String email = _emailText.getText().toString();
String phone = _phoneText.getText().toString();
String carnet = _carnetText.getText().toString();
String user = _userText.getText().toString();
String password = _passwordText.getText().toString();
//String passwordConfirm = _passwordConfirmText.getText().toString();
UserRegistryRequest userRegistryRequest = new UserRegistryRequest();
userRegistryRequest.setAge(age);
userRegistryRequest.setEmail(email);
userRegistryRequest.setFullName(name);
userRegistryRequest.setLadaId(2);
userRegistryRequest.setLicense(carnet);
userRegistryRequest.setPassword(password);
userRegistryRequest.setPhone(phone);
userRegistryRequest.setUsername(user);
// TODO: Implement your own signup logic here.
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://truckersoftservices.azurewebsites.net/api/").build();
ITruckerSoftService service = restAdapter.create(ITruckerSoftService.class);
service.UserRegistry(userRegistryRequest, new Callback<UserRegistryResponse>() {
@Override
public void success(UserRegistryResponse userRegistryResponse, Response response) {
Toast.makeText(getBaseContext(), userRegistryResponse.getMessage(), Toast.LENGTH_LONG).show();
if(userRegistryResponse.isSuccess()){
Intent intent = new Intent(SignupActivity.this, MainMenuActivity.class);
intent.putExtra("age", _ageText.getText().toString());
intent.putExtra("email", _emailText.getText().toString());
intent.putExtra("name", _nameText.getText().toString());
intent.putExtra("license", _carnetText.getText().toString());
intent.putExtra("password", _passwordText.getText().toString());
intent.putExtra("phone", _phoneText.getText().toString());
intent.putExtra("user", _userText.getText().toString());
intent.putExtra("userid", userRegistryResponse.getUserId());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
progressDialog.dismiss();
}
@Override
public void failure(RetrofitError error) {
Toast.makeText(getBaseContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void onSignupSuccess() {
_signupButton.setEnabled(true);
setResult(RESULT_OK, null);
finish();
}
public void onSignupFailed() {
Toast.makeText(getBaseContext(), "Falló inicio de sesión", Toast.LENGTH_LONG).show();
_signupButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String name = _nameText.getText().toString();
String age = _ageText.getText().toString();
String phone = _phoneText.getText().toString();
String license = _carnetText.getText().toString();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
String passwordconfirm = _passwordConfirmText.getText().toString();
String user = _userText.getText().toString();
if (user.isEmpty() || user.length() < 5) {
_userText.setError("Nombre de usuario incorrecto, debe de ser mayor a 5 caracteres");
valid = false;
} else {
_userText.setError(null);
}
if (name.isEmpty() || name.length() < 5) {
_nameText.setError("Nombre debe de ser mayor a 5 caracteres");
valid = false;
} else {
_nameText.setError(null);
}
if (age.isEmpty()) {
_ageText.setError("El campo edad es obligatorio");
valid = false;
} else {
_ageText.setError(null);
}
if (phone.isEmpty() && phone.length() < 10) {
_phoneText.setError("El campo teléfono es obligatorio, mayor de 10");
valid = false;
} else {
_phoneText.setError(null);
}
if (license.isEmpty()) {
_carnetText.setError("El campo carnet es obligatorio");
valid = false;
} else {
_carnetText.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("Ingresa un correo válido");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("La contraseña es incorrecta, mayor a 4 caracteres y menor de 10 caracteres");
valid = false;
} else {
_passwordText.setError(null);
}
if (passwordconfirm.isEmpty() || !password.equals(passwordconfirm)) {
_passwordConfirmText.setError("la confirmación de contraseña es incorrecta");
valid = false;
} else {
_passwordConfirmText.setError(null);
}
return valid;
}
}
| [
"rodrigo.rocha.diaz@gmail.com"
] | rodrigo.rocha.diaz@gmail.com |
641f8640ac4d742e64a908bc82cc23ab83985932 | 0be73ff9c1fb534afe17a05f1ed383cc1bfcab46 | /src/com/hrms/meetingmanagemnet/controller/MeetingInsertServlet.java | c45720cba77b7ada52d45f504558c63a2920e4c1 | [] | no_license | sltlindia/HRMS | 8fec6ede87cf077a832bbf56c61e7626208a0b3a | 1b4bce327bb552d4c0ac3bcf61d528d541ebc245 | refs/heads/master | 2021-01-16T06:31:14.722146 | 2018-02-23T09:34:55 | 2018-02-23T09:34:55 | 99,990,013 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,156 | java | package com.hrms.meetingmanagemnet.controller;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
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 com.hrms.meetingmanagemnet.bean.MeetingBookingDetailBean;
import com.hrms.meetingmanagemnet.bean.MeetingRoomDetailBean;
import com.hrms.meetingmanagemnet.dao.AllInsertMeetingDAO;
import com.hrms.pms.bean.DepartmentBean;
import com.hrms.pms.bean.EmployeeBean;
/**
* Servlet implementation class MeetingInsertServlet
*/
public class MeetingInsertServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
EmployeeBean user = (EmployeeBean) session.getAttribute("user");
AllInsertMeetingDAO allInsertMeetingDAO = new AllInsertMeetingDAO();
int emp_id = user.getEmployee_master_id();
String name = user.getFirstname() +" "+user.getLastname();
int dept_id = user.getDepartmentBean().getDepartment_id();
String meetingName = request.getParameter("name");
String purpose = request.getParameter("purpose");
int participant_no = Integer.parseInt(request.getParameter("participant_no"));
String date = request.getParameter("date");
int facility = Integer.parseInt(request.getParameter("facility"));
String starttime = request.getParameter("starttime");
String endtime = request.getParameter("endtime");
SimpleDateFormat yyyymmdd = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat HHmmaa = new SimpleDateFormat("hh:mm aa");
Date parseDate = null;
Date parseStartTime = null;
Date parseEndTime = null;
try {
parseDate = yyyymmdd.parse(date);
parseStartTime = HHmmaa.parse(starttime);
parseEndTime = HHmmaa.parse(endtime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(parseDate);
System.out.println(parseStartTime);
System.out.println(parseEndTime);
EmployeeBean employeeBean = new EmployeeBean();
DepartmentBean departmentBean = new DepartmentBean();
MeetingRoomDetailBean meetingRoomDetailBean = new MeetingRoomDetailBean();
employeeBean.setEmployee_master_id(emp_id);
departmentBean.setDepartment_id(dept_id);
meetingRoomDetailBean.setMeeting_room_detail_id(facility);
MeetingBookingDetailBean meetingBookingDetailBean = new MeetingBookingDetailBean(name, meetingName, purpose, participant_no, parseDate, parseStartTime, parseEndTime, employeeBean, departmentBean, meetingRoomDetailBean);
boolean result = allInsertMeetingDAO.bookingInsert(meetingBookingDetailBean);
if(result == true) {
response.getWriter().print("SUCCESS fully save data!!!");
}
}
}
| [
"30918642+sltlindia@users.noreply.github.com"
] | 30918642+sltlindia@users.noreply.github.com |
a25949ab69121be91eb5f114f3dea241d6830626 | 4d37505edab103fd2271623b85041033d225ebcc | /spring-core/src/main/java/org/springframework/core/type/classreading/SimpleMetadataReaderFactory.java | 821578e778e13a8a39f4179b167491429ce27bb9 | [
"Apache-2.0"
] | permissive | huifer/spring-framework-read | 1799f1f073b65fed78f06993e58879571cc4548f | 73528bd85adc306a620eedd82c218094daebe0ee | refs/heads/master | 2020-12-08T08:03:17.458500 | 2020-03-02T05:51:55 | 2020-03-02T05:51:55 | 232,931,630 | 6 | 2 | Apache-2.0 | 2020-03-02T05:51:57 | 2020-01-10T00:18:15 | Java | UTF-8 | Java | false | false | 4,147 | java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type.classreading;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Simple implementation of the {@link MetadataReaderFactory} interface,
* creating a new ASM {@link org.springframework.asm.ClassReader} for every request.
*
* @author Juergen Hoeller
* @since 2.5
*/
public class SimpleMetadataReaderFactory implements MetadataReaderFactory {
private final ResourceLoader resourceLoader;
/**
* Create a new SimpleMetadataReaderFactory for the default class loader.
*/
public SimpleMetadataReaderFactory() {
this.resourceLoader = new DefaultResourceLoader();
}
/**
* Create a new SimpleMetadataReaderFactory for the given resource loader.
*
* @param resourceLoader the Spring ResourceLoader to use
* (also determines the ClassLoader to use)
*/
public SimpleMetadataReaderFactory(@Nullable ResourceLoader resourceLoader) {
this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
}
/**
* Create a new SimpleMetadataReaderFactory for the given class loader.
*
* @param classLoader the ClassLoader to use
*/
public SimpleMetadataReaderFactory(@Nullable ClassLoader classLoader) {
this.resourceLoader =
(classLoader != null ? new DefaultResourceLoader(classLoader) : new DefaultResourceLoader());
}
/**
* Return the ResourceLoader that this MetadataReaderFactory has been
* constructed with.
*/
public final ResourceLoader getResourceLoader() {
return this.resourceLoader;
}
@Override
public MetadataReader getMetadataReader(String className) throws IOException {
try {
String resourcePath = ResourceLoader.CLASSPATH_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(className) + ClassUtils.CLASS_FILE_SUFFIX;
Resource resource = this.resourceLoader.getResource(resourcePath);
return getMetadataReader(resource);
}
catch (FileNotFoundException ex) {
// Maybe an inner class name using the dot name syntax? Need to use the dollar syntax here...
// ClassUtils.forName has an equivalent check for resolution into Class references later on.
int lastDotIndex = className.lastIndexOf('.');
if (lastDotIndex != -1) {
String innerClassName =
className.substring(0, lastDotIndex) + '$' + className.substring(lastDotIndex + 1);
String innerClassResourcePath = ResourceLoader.CLASSPATH_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(innerClassName) + ClassUtils.CLASS_FILE_SUFFIX;
Resource innerClassResource = this.resourceLoader.getResource(innerClassResourcePath);
if (innerClassResource.exists()) {
return getMetadataReader(innerClassResource);
}
}
throw ex;
}
}
@Override
public MetadataReader getMetadataReader(Resource resource) throws IOException {
return new SimpleMetadataReader(resource, this.resourceLoader.getClassLoader());
}
}
| [
"huifer97@163.com"
] | huifer97@163.com |
afb289bcef00ffa20f60315214ee0ab49750c799 | e353253c93b6bbc7c0d5a20b0ed5e002a7b3bb7a | /src/funlang/syntax/node/ANumTerm.java | efb5aaa0ccc9b69a59767d1cca6893f73f3c4b10 | [] | no_license | MathieuMathurin/INF5000-Debugger | da0b09d52f54d1035d54555de14412e286062fe6 | 5032fa9ada666ae9abe1ea4e4dab424bda49881d | refs/heads/master | 2021-01-16T18:36:22.628551 | 2016-04-30T03:15:21 | 2016-04-30T03:15:21 | 55,198,836 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,762 | java | /* This file was generated by SableCC (http://www.sablecc.org/). */
package funlang.syntax.node;
import funlang.syntax.analysis.*;
@SuppressWarnings("nls")
public final class ANumTerm extends PTerm
{
private TNum _num_;
public ANumTerm()
{
// Constructor
}
public ANumTerm(
@SuppressWarnings("hiding") TNum _num_)
{
// Constructor
setNum(_num_);
}
@Override
public Object clone()
{
return new ANumTerm(
cloneNode(this._num_));
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).caseANumTerm(this);
}
public TNum getNum()
{
return this._num_;
}
public void setNum(TNum node)
{
if(this._num_ != null)
{
this._num_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._num_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._num_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._num_ == child)
{
this._num_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._num_ == oldChild)
{
setNum((TNum) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
}
| [
"simondrouin4@gmail.com"
] | simondrouin4@gmail.com |
ef6591afaf6bc01184e933b1b2b5bf05de0cf718 | 5d3b2ec0d944a6ee868d94ab3b6e3d3520366bca | /web/09 Web application2/guestbook-방명록/GuestbookController.java | e498ccd8040244e29b851840a372636447c4db15 | [] | no_license | Wordbe/TIL | 68e89583a3814f6e552a766b06ffa47d9ba9317a | 52c80aff3f32483d434802cd100c150388f9b659 | refs/heads/master | 2022-11-24T08:22:29.565139 | 2022-09-20T16:44:32 | 2022-09-20T16:44:32 | 197,180,871 | 2 | 0 | null | 2022-11-16T03:15:28 | 2019-07-16T11:27:09 | Java | UTF-8 | Java | false | false | 2,975 | java | package kr.or.connect.guestbook.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import kr.or.connect.guestbook.dto.Guestbook;
import kr.or.connect.guestbook.service.GuestbookService;
@Controller
public class GuestbookController {
@Autowired
GuestbookService guestbookService;
@GetMapping(path="/list")
public String list(@RequestParam(name="start", required=false, defaultValue="0") int start,
ModelMap model,
@CookieValue(value="count", defaultValue="0", required=true) String value,
HttpServletResponse response) {
try {
int i = Integer.parseInt(value);
value = Integer.toString(++i);
} catch (Exception ex) {
value = "1";
}
Cookie cookie = new Cookie("count", value);
cookie.setMaxAge(60 * 60 * 24 * 365);
cookie.setPath("/"); // 경로 이하에 모두 쿠키 적용
response.addCookie(cookie);
List<Guestbook> list = guestbookService.getGuestbooks(start);
int count = guestbookService.getCount();
int pageCount = count / GuestbookService.LIMIT;
if (count % GuestbookService.LIMIT > 0)
pageCount++;
List<Integer> pageStartList = new ArrayList<>();
for (int i=0; i<pageCount; i++) {
pageStartList.add(i * GuestbookService.LIMIT);
}
model.addAttribute("list", list);
model.addAttribute("count", count);
model.addAttribute("pageStartList", pageStartList);
model.addAttribute("cookieCount", value);
return "list";
}
@PostMapping(path="/write")
public String wrtie(@ModelAttribute Guestbook guestbook,
HttpServletRequest request) {
String clientIp = request.getRemoteAddr();
System.out.println("clientIp: " + clientIp);
guestbookService.addGuestbook(guestbook, clientIp);
return "redirect:list";
}
@GetMapping(path="/delete")
public String delete(@RequestParam(name="id", required=true) Long id,
@SessionAttribute("isAdmin") String isAdmin,
HttpServletRequest request,
RedirectAttributes redirectAttr) {
if (isAdmin == null || !"true".equals(isAdmin)) {
redirectAttr.addFlashAttribute("errorMesaage", "로그인을 하지 않았습니다.");
return "redirect:loginform";
}
String clientIp = request.getRemoteAddr();
guestbookService.deleteGuestbook(id, clientIp);
return "redirect:list";
}
}
| [
"seonghojin3@gmail.com"
] | seonghojin3@gmail.com |
90e0764c28ba66b09373c175f0841feacda678a8 | c6c57b587bf770426e983f176efefef9fe85d5ce | /app/src/main/java/com/example/lord/engrisuru/japanese/Kanji.java | c62f491f4458af09bb4a4295da35454c0ab73055 | [] | no_license | altg0x0/Engrisuru | 2cdc9ec83df0e117b5ab3548060fea1d46224e37 | 68851aacb6cffec494a782771be54f32587ec8fd | refs/heads/master | 2021-04-03T05:31:18.228714 | 2019-09-20T11:37:04 | 2019-09-20T11:37:04 | 124,664,253 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 949 | java | package com.example.lord.engrisuru.japanese;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Index;
import androidx.room.PrimaryKey;
@Entity(indices = @Index(value = "grade"))
public class Kanji {
@PrimaryKey
@ColumnInfo(typeAffinity = ColumnInfo.TEXT)
public char character; // All kanji are supposedly 'non-astral' unicode
public int grade = 11; // 11 == ungraded
public String[] onyomiReadings = new String[]{"ソンザイシテイナイ"};
public String[] kunyomiReadings = new String[]{"そんざいしていない"};
public String[] englishMeanings;
public double weight;
// public WeightedStringArray onyomiReadings = new WeightedStringArray(new String[]{"ソンザイシテイナイ"}, 1);
// public WeightedStringArray kunyomiReadings = new WeightedStringArray(new String[]{"そんざいしていない"}, 1);
// public WeightedStringArray englishMeanings;
}
| [
"altg0x0@yandex.ru"
] | altg0x0@yandex.ru |
4c6ad3d45f75c94470e32a2c68090307c4ff5170 | 33f74fe7498e19eb578b7a063d1846c9b3b2fd87 | /PTN_Client(2015)/src/com/nms/ui/ptn/business/dialog/cespath/AddCesDialog.java | feaf930a58b43e6d1a98cd3a406e8ddbdb763ac6 | [] | no_license | pengchong1989/ptn-client | f489052f2a5b7a1d866dbc17bcb81464a6c11388 | 8b7e561ba725ba53b7f7fb5101c95932d866ba59 | refs/heads/master | 2021-08-23T20:37:04.331358 | 2017-12-06T12:44:22 | 2017-12-06T12:44:22 | 103,929,275 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 30,723 | java | package com.nms.ui.ptn.business.dialog.cespath;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import twaver.Element;
import twaver.Node;
import twaver.PopupMenuGenerator;
import twaver.TView;
import twaver.network.TNetwork;
import com.nms.db.bean.client.Client;
import com.nms.db.bean.equipment.port.PortInst;
import com.nms.db.bean.equipment.port.PortStmTimeslot;
import com.nms.db.bean.equipment.shelf.SiteInst;
import com.nms.db.bean.ptn.path.ces.CesInfo;
import com.nms.db.bean.ptn.path.pw.PwInfo;
import com.nms.db.bean.system.code.Code;
import com.nms.db.enums.EActiveStatus;
import com.nms.db.enums.ECesType;
import com.nms.db.enums.EPwType;
import com.nms.db.enums.EServiceType;
import com.nms.model.client.ClientService_MB;
import com.nms.model.equipment.port.PortService_MB;
import com.nms.model.equipment.shlef.SiteService_MB;
import com.nms.model.ptn.path.pw.PwInfoService_MB;
import com.nms.model.util.Services;
import com.nms.ui.frame.ViewDataTable;
import com.nms.ui.manager.ConstantUtil;
import com.nms.ui.manager.ControlKeyValue;
import com.nms.ui.manager.DateUtil;
import com.nms.ui.manager.ExceptionManage;
import com.nms.ui.manager.ListingFilter;
import com.nms.ui.manager.ResourceUtil;
import com.nms.ui.manager.UiUtil;
import com.nms.ui.manager.control.PtnButton;
import com.nms.ui.manager.control.PtnDialog;
import com.nms.ui.manager.control.PtnTextField;
import com.nms.ui.manager.keys.StringKeysBtn;
import com.nms.ui.manager.keys.StringKeysLbl;
import com.nms.ui.manager.keys.StringKeysMenu;
import com.nms.ui.manager.keys.StringKeysTip;
import com.nms.ui.manager.keys.StringKeysTitle;
import com.nms.ui.ptn.business.ces.CesBusinessPanel;
import com.nms.ui.ptn.business.dialog.cespath.controller.ChooseE1Controller;
import com.nms.ui.ptn.business.dialog.cespath.controller.ChooseTimeSlotController;
import com.nms.ui.ptn.business.dialog.cespath.modal.CesPortInfo;
import com.nms.ui.ptn.business.dialog.tunnel.TunnelTopoPanel;
import com.nms.ui.ptn.safety.roleManage.RootFactory;
/**
* 新建CES
* @author __USER__
*/
public class AddCesDialog extends PtnDialog {
/**
*
*/
private static final long serialVersionUID = 7365420009838403755L;
private CesBusinessPanel cesPathPanel;
private PtnButton submit;
private JCheckBox ckbActivity;
private JLabel lblName; // pw列表
private JLabel lblZPort;
private JLabel lblAPort;
private JLabel lblActivity;
private JLabel lblTunner;
private JPanel leftPanel;
private JSplitPane jSplitPane1;
private JTextField tfName;
private JScrollPane pwListJSP;
private JList pwList;
private JLabel selPwLabel;
private JScrollPane selPwListJSP;
private JList selPwList;
private JLabel serviceTypeJLabel;
private JComboBox serviceTypeCbox;
private PortInst portInst_a = null;
private PortInst portInst_z = null;
private PortStmTimeslot portStmTime_a = null;
private PortStmTimeslot portStmTime_z = null;
private CesInfo cesInfo;
private int siteId_a;
private int siteId_z;
private Vector<Object> pwVector = new Vector<Object>();
private final Vector<Object> selpwVector = new Vector<Object>();
private ViewDataTable<CesPortInfo> portTable_a;
private ViewDataTable<CesPortInfo> portTable_z;
private JScrollPane jscrollPane_portTable_a;
private JScrollPane jscrollPane_portTable_z;
private JButton leftBtn;
private JButton rightBtn;
private JLabel lblMessage;
private JLabel client;
public JComboBox clientComboBox;
private JButton autoNamingButton;
private TunnelTopoPanel tunnelTopoPanel=null;
public AddCesDialog(CesBusinessPanel cesPathPanel, boolean modal) {
try {
this.setModal(modal);
cesPathPanel.setDialog(this);
this.cesPathPanel = cesPathPanel;
initDialog();
clientComboxData(this.clientComboBox);
} catch (Exception e) {
ExceptionManage.dispose(e,this.getClass());
}
}
public AddCesDialog(CesBusinessPanel cesPathPanel, boolean modal, CesInfo cesInfo) {
try {
this.setModal(modal);
cesPathPanel.setDialog(this);
this.cesPathPanel = cesPathPanel;
this.cesInfo = cesInfo;
initDialog();
clientComboxData(this.clientComboBox);
if (this.cesInfo != null) {
initUpdate();
super.getComboBoxDataUtil().comboBoxSelect(this.clientComboBox, this.cesInfo.getClientId()+"");
}
} catch (Exception e) {
ExceptionManage.dispose(e,this.getClass());
}finally{
}
}
private void initUpdate() {
List<CesPortInfo> cesPortInfoList = null;
PortService_MB portService = null;
PortInst portinst=null;
List<PortInst> portList=null;
PwInfo pwInfo=null;
ControlKeyValue kv=null;
try {
pwInfo=new PwInfo();
cesPortInfoList = new ArrayList<CesPortInfo>();
portList=new ArrayList<PortInst>();
portService = (PortService_MB) ConstantUtil.serviceFactory.newService_MB(Services.PORT);
// 类型
// UiUtil.comboBoxSelect(serviceTypeCbox,String.valueOf(cesInfo.getCestype()));
super.getComboBoxDataUtil().comboBoxSelectByValue(serviceTypeCbox, String.valueOf(cesInfo.getCestype()));
//CES名称
tfName.setText(cesInfo.getName());
// 客户类型
if (cesInfo.getClientId() != 0) {
super.getComboBoxDataUtil().comboBoxSelect(clientComboBox, String.valueOf(cesInfo.getClientId()));
}
// 是否激活
ckbActivity.setSelected(EActiveStatus.ACTIVITY.getValue() == cesInfo.getActiveStatus() ? true : false);
// A端端口
int aAcId=cesInfo.getaAcId();
portinst = new PortInst();
portinst.setPortType("e1");
portinst.setPortId(aAcId);
portList = portService.select(portinst);
CesPortInfo cesPort = null;
for (PortInst e1 : portList) {
cesPort = new CesPortInfo();
cesPort.setE1PortInst(e1);
cesPortInfoList.add(cesPort);
}
if(portList!=null&&portList.size()>0){
this.siteId_a=portList.get(0).getSiteId();
this.loadPortTable_a(cesPortInfoList, siteId_a);
}
// Z端端口
portinst = new PortInst();
portinst.setPortType("e1");
portinst.setPortId(cesInfo.getzAcId());
portList = portService.select(portinst);
if(cesPortInfoList!=null){
cesPortInfoList.clear();
}
for (PortInst e1 : portList) {
cesPort = new CesPortInfo();
cesPort.setE1PortInst(e1);
cesPortInfoList.add(cesPort);
}
if(portList!=null&&portList.size()>0){
this.siteId_z=portList.get(0).getSiteId();
this.loadPortTable_z(cesPortInfoList, siteId_z);
}
//加载已经选择的PW列表
pwInfo=getPwNameById(cesInfo.getPwId());
kv = new ControlKeyValue("" + cesInfo.getPwId(), "NE:" + cesInfo.getASiteName() + "-NE:" + cesInfo.getZSiteName() + "/" + "pwName:" +pwInfo.getPwName(),pwInfo);
selpwVector.add(kv);
selPwList.setListData(selpwVector);
} catch (Exception e) {
ExceptionManage.dispose(e,this.getClass());
}finally{
cesPortInfoList=null;
portinst=null;
kv=null;
portinst=null;
pwInfo=null;
UiUtil.closeService_MB(portService);
}
}
/**
*
* @param cesPathPanel
* 父面板
* @param modal
* 当modal为true时,代表用户必须结束对话框才能回到原来所属的窗口。当modal为 false时,代表对话框与所属窗口可以互相切换,彼此之间在操作上没有顺序性。
* @param selectId
* 修改时,选中ces的主键id
* @throws Exception
*/
/*
* public AddCesDialog(CesBusinessPanel cesPathPanel, boolean modal, int selectId) { this.setModal(modal); this.cesPathPanel = cesPathPanel; setDefaultCesInfo(selectId); initDialog(); }
*/
public void initDialog() throws Exception {
initComponents();
this.addListener();
initDates();
}
public void initComponents() throws Exception {
createComponent();
setLayout();
}
/**
* 添加监听
*/
private void addListener() {
this.serviceTypeCbox.addItemListener(new java.awt.event.ItemListener() {
@Override
public void itemStateChanged(java.awt.event.ItemEvent evt) {
if (evt.getStateChange() == 1) {
try {
initTopo();
} catch (Exception e) {
ExceptionManage.dispose(e,this.getClass());
}
}
}
});
}
private void createComponent() throws Exception {
submit = new PtnButton(ResourceUtil.srcStr(StringKeysBtn.BTN_SAVE),true,RootFactory.COREMODU,this);
lblMessage = new JLabel();
jSplitPane1 = new JSplitPane();
leftPanel = new JPanel();
lblName = new JLabel(ResourceUtil.srcStr(StringKeysLbl.LBL_NAME));
tfName = new PtnTextField(true, PtnTextField.STRING_MAXLENGTH, this.lblMessage, this.submit, this);
lblZPort = new JLabel(ResourceUtil.srcStr(StringKeysLbl.LBL_Z_SIDE_PORT));
lblAPort = new JLabel(ResourceUtil.srcStr(StringKeysLbl.LBL_A_SIDE_PORT));
lblActivity = new JLabel(ResourceUtil.srcStr(StringKeysLbl.LBL_ACTIVITY_STATUS));
ckbActivity = new JCheckBox();
lblTunner = new JLabel(ResourceUtil.srcStr(StringKeysLbl.LBL_PW_LIST));
pwListJSP = new JScrollPane();
pwList = new JList();
pwListJSP.setViewportView(pwList);
selPwLabel = new JLabel(ResourceUtil.srcStr(StringKeysLbl.LBL_OPTED_PW_LIST));
selPwListJSP = new JScrollPane();
selPwList = new JList();
selPwListJSP.setViewportView(selPwList);
pwList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
serviceTypeJLabel = new JLabel(ResourceUtil.srcStr(StringKeysLbl.LBL_SERVICE_TYPE));
serviceTypeCbox = new JComboBox();
portTable_a = new ViewDataTable<CesPortInfo>("cesPortTable");
portTable_z = new ViewDataTable<CesPortInfo>("cesPortTable");
portTable_a.getTableHeader().setResizingAllowed(true);
portTable_a.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
portTable_a.setTableHeaderPopupMenuFactory(null);
portTable_a.setTableBodyPopupMenuFactory(null);
portTable_z.getTableHeader().setResizingAllowed(true);
portTable_z.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
portTable_z.setTableHeaderPopupMenuFactory(null);
portTable_z.setTableBodyPopupMenuFactory(null);
jscrollPane_portTable_a = new JScrollPane();
jscrollPane_portTable_z = new JScrollPane();
jscrollPane_portTable_a.setViewportView(portTable_a);
jscrollPane_portTable_z.setViewportView(portTable_z);
leftBtn = new JButton("▲");
rightBtn = new JButton("▼");
client = new javax.swing.JLabel(ResourceUtil.srcStr(StringKeysLbl.LBL_CLIENT_NAME));
clientComboBox = new javax.swing.JComboBox();
autoNamingButton = new JButton(ResourceUtil.srcStr(StringKeysLbl.LBL_AUTO_NAME));
}
public void initDates() {
try {
super.getComboBoxDataUtil().comboBoxData(serviceTypeCbox, "CESSERVICETYPE");
} catch (Exception e) {
ExceptionManage.dispose(e,this.getClass());
}
}
private void initTopo() {
TNetwork network = null;
try {
tunnelTopoPanel.boxDataByPws(this.getPwinfoList());
network =tunnelTopoPanel.getNetWork();
// network.doLayout(TWaverConst.LAYOUT_CIRCULAR);
network.setPopupMenuGenerator(new PopupMenuGenerator() {
@Override
public JPopupMenu generate(TView tview, MouseEvent mouseEvent) {
JPopupMenu menu = new JPopupMenu();
if (!tview.getDataBox().getSelectionModel().isEmpty()) {
final Element element = tview.getDataBox().getLastSelectedElement();
if (element instanceof Node) {
if (element.getBusinessObject() != null) {
JMenuItem ajMenuItem = new JMenuItem(ResourceUtil.srcStr(StringKeysMenu.MENU_SELECT_A_PORT));
ajMenuItem.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectPort("A", element);
}
});
JMenuItem zjMenuItem = new JMenuItem(ResourceUtil.srcStr(StringKeysMenu.MENU_SELECT_Z_PORT));
zjMenuItem.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectPort("Z", element);
}
});
menu.add(ajMenuItem);
menu.add(zjMenuItem);
} else {
return menu;
}
}
}
return menu;
}
});
} catch (Exception e) {
ExceptionManage.dispose(e,this.getClass());
} finally {
network = null;
}
}
/**
* 根据ces业务类型,获取不同的pw集合。用来刷新拓扑
*
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
private List<PwInfo> getPwinfoList() throws Exception {
List<PwInfo> pwInfoList = null;
PwInfoService_MB pwInfoService = null;
PwInfo pwInfo = null;
Code code_type = null;
List<PwInfo> pwInfoList_result = null;
ListingFilter filter=null;
try {
filter=new ListingFilter();
pwInfoList_result=new ArrayList<PwInfo>();
pwInfoService = (PwInfoService_MB) ConstantUtil.serviceFactory.newService_MB(Services.PwInfo);
code_type = (Code) ((ControlKeyValue) serviceTypeCbox.getSelectedItem()).getObject();
pwInfo = new PwInfo();
if(cesInfo==null){
pwInfo.setType(EPwType.forms(Integer.parseInt(code_type.getCodeValue())));
pwInfo.setPwStatus(EActiveStatus.ACTIVITY.getValue());//先显示激活的PW
pwInfoList = (List<PwInfo>) filter.filterList(pwInfoService.select(pwInfo));
for (PwInfo pwInfo_select : pwInfoList) {
if (pwInfo_select.getRelatedServiceId() == 0) {
pwInfoList_result.add(pwInfo_select);
}
}
}else{
pwInfo.setPwId(cesInfo.getPwId());
pwInfo.setType(EPwType.forms(cesInfo.getCestype()));
pwInfoList =(List<PwInfo>) filter.filterList( pwInfoService.select(pwInfo));
for (PwInfo pwInfo_select : pwInfoList) {
if (pwInfo_select.getRelatedServiceId()!=0) {
pwInfoList_result.add(pwInfo_select);
}
}
}
} catch (Exception e) {
throw e;
} finally{
UiUtil.closeService_MB(pwInfoService);
pwInfo = null;
filter=null;
code_type = null;
}
return pwInfoList_result;
}
private void selectPort(String type, Element element) {
Code code = (Code) ((ControlKeyValue) serviceTypeCbox.getSelectedItem()).getObject();
int cestype = Integer.parseInt(code.getCodeValue());
if (cestype == ECesType.SDHPDH.getValue()) {
if ("A".equals(type)) {
showStm1Dialog(element, type);
} else {
showE1Dialog(element, type);
}
} else if (cestype == ECesType.PDHSDH.getValue()) { // 弹出E1界面
if ("A".equals(type)) {
showE1Dialog(element, type);
} else {
showStm1Dialog(element, type);
}
} else if (cestype == ECesType.SDH.getValue()) {
showStm1Dialog(element, type);
} else if (cestype == ECesType.PDH.getValue()) {
showE1Dialog(element, type);
}
}
// 弹出E1界面
private void showE1Dialog(Element element, final String type) {
SiteInst siteInst = (SiteInst) element.getUserObject();
final ChooseE1Dialog dialog = new ChooseE1Dialog(this, true, type);
dialog.setTitle(ResourceUtil.srcStr(StringKeysTitle.TIT_SELECT_E1_PORT));
dialog.setSize(new Dimension(650, 450));
dialog.setLocation(UiUtil.getWindowWidth(dialog.getWidth()), UiUtil.getWindowHeight(dialog.getHeight()));
ChooseE1Controller CEcontroller = new ChooseE1Controller(dialog, siteInst, this);
CEcontroller.initData();
dialog.setVisible(true);
}
private void showStm1Dialog(Element element, final String type) {
SiteInst siteInst = (SiteInst) element.getUserObject();
ChooseTimeSlotDialog dialog = new ChooseTimeSlotDialog(this, true, type);
dialog.setTitle(ResourceUtil.srcStr(StringKeysTitle.TIT_SELECT_STM));
dialog.setSize(new Dimension(650, 450));
dialog.setLocation(UiUtil.getWindowWidth(dialog.getWidth()), UiUtil.getWindowHeight(dialog.getHeight()));
ChooseTimeSlotController CTScontroller = new ChooseTimeSlotController(dialog, siteInst);
CTScontroller.initData();
dialog.setVisible(true);
}
public void update(CesInfo obj) {
obj.setName(tfName.getText().trim());
obj.setActiveStatus(ckbActivity.isSelected() == true ? EActiveStatus.ACTIVITY.getValue() : EActiveStatus.UNACTIVITY.getValue());
}
public CesInfo get(PwInfo pw) throws Exception {
CesInfo cesInfo=null;
if(this.cesInfo!=null){
cesInfo=this.cesInfo;
}else{
cesInfo = new CesInfo();
}
ControlKeyValue client = null;
client = (ControlKeyValue) this.clientComboBox.getSelectedItem();
cesInfo.setName(tfName.getText().trim());
cesInfo.setServiceType(EServiceType.CES.getValue());
cesInfo.setActiveStatus(ckbActivity.isSelected() == true ? EActiveStatus.ACTIVITY.getValue() : EActiveStatus.UNACTIVITY.getValue());
cesInfo.setCreateUser(ConstantUtil.user.getUser_Name());
cesInfo.setCreateTime(DateUtil.getDate(DateUtil.FULLTIME));
cesInfo.setaSiteId(this.siteId_a);
cesInfo.setzSiteId(this.siteId_z);
cesInfo.setPwId(pw.getPwId());
cesInfo.setPwName(pw.getPwName());
if (!"".equals(client.getId()))
cesInfo.setClientId(Integer.parseInt(client.getId()));
if(((Client)client.getObject()) != null){
cesInfo.setClientName(((Client)client.getObject()).getName());
}
ControlKeyValue controlKeyValue = (ControlKeyValue) this.serviceTypeCbox.getSelectedItem();
Code code = (Code) controlKeyValue.getObject();
cesInfo.setCestype(Integer.parseInt(code.getCodeValue()));
return cesInfo;
}
private void setLayout() {
this.jSplitPane1.setLeftComponent(this.leftPanel);
this.leftPanel.setPreferredSize(new Dimension(280, 700));
tunnelTopoPanel=new TunnelTopoPanel();
this.jSplitPane1.setRightComponent(tunnelTopoPanel);
GridBagLayout layout = new GridBagLayout();
layout.columnWidths = new int[] { 50, 180, 50 };
layout.columnWeights = new double[] { 0, 0, 0 };
layout.rowHeights = new int[] { 25, 30, 30, 30, 100, 100, 30, 100, 30, 100, 15, 30, 30 };
layout.rowWeights = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2 };
this.leftPanel.setLayout(layout);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 1;
c.gridwidth = 3;
c.insets = new Insets(5, 10, 5, 5);
layout.setConstraints(this.lblMessage, c);
this.leftPanel.add(this.lblMessage);
/** 第一行 */
c.gridx = 0;
c.gridy = 1;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(5, 10, 5, 5);
layout.setConstraints(lblName, c);
this.leftPanel.add(lblName);
c.gridx = 1;
c.gridy = 1;
c.gridheight = 1;
c.gridwidth = 2;
c.insets = new Insets(5, 5, 5, 70);
layout.addLayoutComponent(tfName, c);
this.leftPanel.add(tfName);
c.gridx = 2;
c.gridy = 1;
c.gridheight = 1;
c.gridwidth = 2;
c.insets = new Insets(5, 5, 5, 5);
layout.addLayoutComponent(autoNamingButton, c);
this.leftPanel.add(autoNamingButton);
/** 第二行 */
c.gridx = 0;
c.gridy = 2;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(5, 10, 5, 5);
layout.setConstraints(this.serviceTypeJLabel, c);
this.leftPanel.add(this.serviceTypeJLabel);
c.gridx = 1;
c.gridy = 2;
c.gridheight = 1;
c.gridwidth = 2;
c.insets = new Insets(5, 5, 5, 5);
layout.addLayoutComponent(this.serviceTypeCbox, c);
this.leftPanel.add(this.serviceTypeCbox);
/** 第3行 */
c.gridx = 0;
c.gridy = 3;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(5, 10, 5, 5);
layout.setConstraints(this.client, c);
this.leftPanel.add(this.client);
c.gridx = 1;
c.gridy = 3;
c.gridheight = 1;
c.gridwidth = 2;
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.BOTH;
layout.addLayoutComponent(this.clientComboBox, c);
this.leftPanel.add(this.clientComboBox);
/** 第4行 */
c.gridx = 0;
c.gridy = 4;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(5, 10, 5, 5);
layout.setConstraints(this.lblAPort, c);
this.leftPanel.add(this.lblAPort);
c.gridx = 1;
c.gridy = 4;
c.gridheight = 1;
c.gridwidth = 2;
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.BOTH;
layout.addLayoutComponent(this.jscrollPane_portTable_a, c);
this.leftPanel.add(this.jscrollPane_portTable_a);
/** 第5行 */
c.gridx = 0;
c.gridy = 5;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(5, 10, 5, 5);
c.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(this.lblZPort, c);
this.leftPanel.add(this.lblZPort);
c.gridx = 1;
c.gridy = 5;
c.gridheight = 1;
c.gridwidth = 2;
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.BOTH;
layout.addLayoutComponent(this.jscrollPane_portTable_z, c);
this.leftPanel.add(this.jscrollPane_portTable_z);
/** 第6行 */
c.gridx = 0;
c.gridy = 6;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(5, 10, 5, 5);
c.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(this.lblActivity, c);
this.leftPanel.add(this.lblActivity);
c.gridx = 1;
c.gridy = 6;
c.gridheight = 1;
c.gridwidth = 2;
c.insets = new Insets(5, 5, 5, 5);
layout.setConstraints(this.ckbActivity, c);
this.leftPanel.add(this.ckbActivity);
/** 第7行 */
c.gridx = 0;
c.gridy = 7;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(5, 10, 5, 5);
layout.setConstraints(this.lblTunner, c);
this.leftPanel.add(this.lblTunner);
c.gridx = 1;
c.gridy = 7;
c.gridheight = 1;
c.gridwidth = 2;
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.BOTH;
layout.setConstraints(this.pwListJSP, c);
this.leftPanel.add(this.pwListJSP);
// 第8行
c.gridx = 1;
c.gridy = 8;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(5, 10, 5, 5);
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.EAST;
layout.setConstraints(this.leftBtn, c);
this.leftPanel.add(this.leftBtn);
c.gridx = 1;
c.gridy = 8;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(5, 5, 5, 5);
c.anchor = GridBagConstraints.WEST;
layout.setConstraints(this.rightBtn, c);
this.leftPanel.add(this.rightBtn);
// 第9行
c.gridx = 0;
c.gridy = 9;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(5, 10, 5, 5);
c.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(this.selPwLabel, c);
this.leftPanel.add(this.selPwLabel);
c.gridx = 1;
c.gridy = 9;
c.gridheight = 1;
c.gridwidth = 2;
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.BOTH;
layout.setConstraints(this.selPwListJSP, c);
this.leftPanel.add(this.selPwListJSP);
// 第10行
c.gridx = 2;
c.gridy = 11;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(5, 10, 5, 5);
c.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(this.submit, c);
this.leftPanel.add(this.submit);
this.setLayout(new BorderLayout());
// this.add(topPanel, BorderLayout.NORTH);
this.add(jSplitPane1, BorderLayout.CENTER);
}
/*
* public void setDefaultCesInfo(int selectId) { CesInfoService service = null; try { service = (CesInfoService) ConstantUtil.serviceFactory .newService(Services.CesInfo); this.cesInfo = service.select(new CesInfo(selectId)).get(0); } catch (Exception e) { ExceptionManage.dispose(e,this.getClass()); this.cesInfo = null; } finally { service = null; }
*
* }
*/
public void loadPortTable_a(List<CesPortInfo> cesPortInfoList, int siteId) {
getPortTable_a().clear();
setSiteId_a(siteId);
getPortTable_a().initData(cesPortInfoList);
}
public void loadPortTable_z(List<CesPortInfo> cesPortInfoList, int siteId) {
getPortTable_z().clear();
setSiteId_z(siteId);
getPortTable_z().initData(cesPortInfoList);
}
//用于显示PW列表的
public void loadPw(Collection<PwInfo> pwInfoCollection) {
this.selpwVector.removeAllElements();
getPwVector().removeAllElements();
// 界面a端和z端表中的端口
ControlKeyValue kv = null;
try {
// A表中端口和Z表中端口
for (PwInfo disPw : pwInfoCollection) {
kv = new ControlKeyValue(disPw.getPwId() + "", "NE:" + getSiteAdress(disPw.getASiteId()) + "-" + "NE:" + getSiteAdress(disPw.getZSiteId()) + "/" + "pwName:" + disPw.getPwName(), disPw);
getPwVector().add(kv);
}
this.pwList.setListData(this.pwVector);
} catch (Exception e) {
} finally {
kv = null;
}
}
//用于显示已近选择的PW列表
public void loadSelectPw(Collection<PwInfo> pwInfoCollection) {
getSelpwVector().removeAllElements();
// 界面a端和z端表中的端口
ControlKeyValue kv = null;
try {
// A表中端口和Z表中端口
for (PwInfo disPw : pwInfoCollection) {
kv = new ControlKeyValue(disPw.getPwId() + "", "NE:" + getSiteAdress(disPw.getASiteId()) + "-" + "NE:" + getSiteAdress(disPw.getZSiteId()) + "/" + "pwName:" + disPw.getPwName(), disPw);
getSelpwVector().add(kv);
}
this.selPwList.setListData(this.selpwVector);
} catch (Exception e) {
} finally {
kv = null;
}
}
/**
* 根据网元ID查询网元地址
*
* @param siteId
* @return
* @throws Exception
*/
public String getSiteAdress(int siteId) throws Exception {
SiteService_MB siteService = null;
SiteInst siteInst = null;
try {
siteService = (SiteService_MB) ConstantUtil.serviceFactory.newService_MB(Services.SITE);
siteInst = siteService.select(siteId);
if (siteInst != null) {
return siteInst.getCellId();
} else {
throw new Exception(ResourceUtil.srcStr(StringKeysTip.TIP_SELECT_SITEINST_ERROR));
}
} catch (Exception e) {
throw e;
} finally {
UiUtil.closeService_MB(siteService);
}
}
public List<Integer> getTablePortIdList() {
List<Integer> tableportIdList;
tableportIdList = new ArrayList<Integer>();
getAtablePortIdList(tableportIdList);
getZtablePortIdList(tableportIdList);
return tableportIdList;
}
@SuppressWarnings("unchecked")
public void getZtablePortIdList(List<Integer> tableportIdList) {
List<CesPortInfo> z_cesportInfoList = this.portTable_z.getDataBox().getAllElements();
for (CesPortInfo cesportInfo : z_cesportInfoList) {
if (cesportInfo.getPortStmTimeSlot() != null) {
tableportIdList.add(cesportInfo.getPortStmTimeSlot().getId());
}
if (cesportInfo.getE1PortInst() != null) {
tableportIdList.add(cesportInfo.getE1PortInst().getPortId());
}
}
}
@SuppressWarnings("unchecked")
public void getAtablePortIdList(List<Integer> tableportIdList) {
List<CesPortInfo> a_cesportInfoList = this.portTable_a.getDataBox().getAllElements();
for (CesPortInfo cesportInfo : a_cesportInfoList) {
if (cesportInfo.getPortStmTimeSlot() != null) {
tableportIdList.add(cesportInfo.getPortStmTimeSlot().getId());
}
if (cesportInfo.getE1PortInst() != null) {
tableportIdList.add(cesportInfo.getE1PortInst().getPortId());
}
}
}
/**
* 客户信息下拉列表
*
* @param jComboBox1
*/
public void clientComboxData(JComboBox jComboBox1) {
ClientService_MB service = null;
List<Client> clientList = null;
DefaultComboBoxModel defaultComboBoxModel = (DefaultComboBoxModel) clientComboBox.getModel();
try {
service = (ClientService_MB) ConstantUtil.serviceFactory.newService_MB(Services.CLIENTSERVICE);
clientList = service.refresh();
defaultComboBoxModel.addElement(new ControlKeyValue("0", "", null));
for (Client client : clientList) {
defaultComboBoxModel.addElement(new ControlKeyValue(client.getId() + "", client.getName(), client));
}
clientComboBox.setModel(defaultComboBoxModel);
} catch (Exception e) {
ExceptionManage.dispose(e,this.getClass());
} finally {
UiUtil.closeService_MB(service);
clientList = null;
}
}
public PtnButton getSubmit() {
return submit;
}
public JCheckBox getCkbActivity() {
return ckbActivity;
}
public JTextField getTfName() {
return tfName;
}
public JList getPwList() {
return pwList;
}
public JComboBox getServiceTypeCbox() {
return serviceTypeCbox;
}
public CesBusinessPanel getCesPathPanel() {
return cesPathPanel;
}
public CesInfo getCesInfo() {
return cesInfo;
}
public void setCesInfo(CesInfo cesInfo) {
this.cesInfo = cesInfo;
}
public PortInst getPortInst_a() {
return portInst_a;
}
public void setPortInst_a(PortInst portInst_a) {
this.portInst_a = portInst_a;
}
public PortInst getPortInst_z() {
return portInst_z;
}
public void setPortInst_z(PortInst portInst_z) {
this.portInst_z = portInst_z;
}
public PortStmTimeslot getPortStmTime_a() {
return portStmTime_a;
}
public void setPortStmTime_a(PortStmTimeslot portStmTimeA) {
portStmTime_a = portStmTimeA;
}
public PortStmTimeslot getPortStmTime_z() {
return portStmTime_z;
}
public void setPortStmTime_z(PortStmTimeslot portStmTimeZ) {
portStmTime_z = portStmTimeZ;
}
public int getSiteId_a() {
return siteId_a;
}
public void setSiteId_a(int siteIdA) {
siteId_a = siteIdA;
}
public int getSiteId_z() {
return siteId_z;
}
public void setSiteId_z(int siteIdZ) {
siteId_z = siteIdZ;
}
public Vector<Object> getPwVector() {
return pwVector;
}
public void setPwVector(Vector<Object> pwVector) {
this.pwVector = pwVector;
}
public ViewDataTable<CesPortInfo> getPortTable_a() {
return portTable_a;
}
public ViewDataTable<CesPortInfo> getPortTable_z() {
return portTable_z;
}
public JButton getLeftBtn() {
return leftBtn;
}
public JButton getRightBtn() {
return rightBtn;
}
public JList getSelPwList() {
return selPwList;
}
public Vector<Object> getSelpwVector() {
return selpwVector;
}
public JButton getAutoNamingButton() {
return autoNamingButton;
}
/**
* @param pwId
* 通过pwID 来获取PW的名称
* @return
*/
private PwInfo getPwNameById(int pwId) {
PwInfoService_MB pwService = null;
PwInfo pwinfo = null;
List<PwInfo> list = null;
try {
pwService = (PwInfoService_MB) ConstantUtil.serviceFactory.newService_MB(Services.PwInfo);
pwinfo = new PwInfo();
pwinfo.setPwId(pwId);
list = pwService.select(pwinfo);
if (list.size() > 0)
return list.get(0);
} catch (Exception e) {
ExceptionManage.dispose(e,this.getClass());
} finally {
UiUtil.closeService_MB(pwService);
pwinfo = null;
list = null;
}
return null;
}
public TunnelTopoPanel getTunnelTopoPanel() {
return tunnelTopoPanel;
}
public void setTunnelTopoPanel(TunnelTopoPanel tunnelTopoPanel) {
this.tunnelTopoPanel = tunnelTopoPanel;
}
} | [
"a18759149@qq.com"
] | a18759149@qq.com |
65c73d9e54065ad71a49bab36df928cb7c8f4fc7 | 304e78dbe7373c59ac9e2283be960e74015de2c1 | /asssignment_6/Heap.java | 78f8ec3f91e7e6caa00e79814c8e4f3c2bb5e922 | [] | no_license | musturuharitha/assignments | ed3bbc2620e42d66d4c79db561a4294ac30c594d | 22c33909ee4fa877fff37b5fbdad0b78ffc69eb7 | refs/heads/master | 2023-08-15T06:36:26.969288 | 2021-09-16T04:27:21 | 2021-09-16T04:27:21 | 404,608,383 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 571 | java | package assign_6;
import java.util.TreeMap;
public class Heap {
public static void main(String[] args) {
TreeMap<Long,String> map=new TreeMap<Long,String>();
map.put((long) 001, "hari");
map.put((long) 002, "appu");
map.put((long) 003, "chinnu");
System.out.println("all the keys: "+map.keySet());
System.out.println("all the values: "+map.values());
System.out.println("all key-value pairs: "+map.keySet()+map.values());
System.out.println("descendingMap: "+map.descendingMap());
}
}
| [
"noreply@github.com"
] | musturuharitha.noreply@github.com |
bcdd91717f1699a191402e159186e6cd79981af1 | a8dc0e22c1a15294eb0ecfe63e6d577a48ecd944 | /src/main/java/com/biz/office/service/order/OrderService.java | e526e0b3e2c4f9596813f33208f7b37b946a5aea | [] | no_license | kanadara13/biz-office | ce4c8878406d3e7af80e89edff8a96b817e09cc4 | 8f4a94df8637ce29f346a81963d8ea69a5b11beb | refs/heads/master | 2021-04-27T00:21:32.235361 | 2018-03-29T16:25:36 | 2018-03-29T16:25:36 | 123,799,117 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 869 | java | package com.biz.office.service.order;
import com.biz.office.domain.order.Order;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
@Service
public class OrderService {
private OrderGenerator generator;
private OrderCriteria criteria;
private OrderManager manager;
@Inject
public OrderService(OrderGenerator orderGenerator, OrderCriteria orderCriteria, OrderManager orderManager) {
this.generator = orderGenerator;
this.criteria = orderCriteria;
this.manager = orderManager;
}
public Order save(Order order) {
return generator.generate(order);
}
public Page<Order> find(OrderCriteria criteria, Pageable pageable) {
return criteria.find(criteria, pageable);
}
}
| [
"shin.jaehyeok@leisureq.co.kr"
] | shin.jaehyeok@leisureq.co.kr |
58813830bbddcbb7d2865551555b141883b2a4fa | 4e9c3e4311b15d02f4de76be989ee644ad71baf3 | /src/main/java/com/truck/deusemar/controller/DriverController.java | 42426d5b121b23877cb0ee406459ff4eec9052f8 | [] | no_license | deusemarjunior/truck-management | d4c1980e2ac667d875dbfea6118c50b96a38279e | 5e33393e77647a6e4e6091848509d975fea1322a | refs/heads/master | 2021-06-21T19:54:36.242766 | 2020-04-21T02:35:22 | 2020-04-21T02:35:22 | 177,205,712 | 0 | 0 | null | 2021-06-16T22:17:06 | 2019-03-22T20:34:32 | Java | UTF-8 | Java | false | false | 3,002 | java | package com.truck.deusemar.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.truck.deusemar.domain.Driver;
import com.truck.deusemar.repository.DriverRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/drivers")
@Api(value="Maintenance of drivers")
public class DriverController {
@Autowired
private DriverRepository driverRepository;
@GetMapping("/{id}")
public ResponseEntity<?> getId(@PathVariable(name="id", required=true) String id) {
Optional<Driver> driver = driverRepository.findById(id);
if(driver.isPresent())
return ResponseEntity.ok(driver.get());
else
return ResponseEntity.noContent().build();
}
@GetMapping
public ResponseEntity<?> list() {
return this.driverRepository.count() == 0L
? ResponseEntity.noContent().build()
: ResponseEntity.ok(this.driverRepository.findAll());
}
@GetMapping("/owners")
@ApiOperation("List of drivers owners of trucks")
public ResponseEntity<?> listDriverOwnerTruck() {
Driver example = new Driver();
example.setHasTruck(true);
List<Driver> drivers = driverRepository.findAll(Example.of(example));
return drivers == null
? ResponseEntity.noContent().build()
: ResponseEntity.ok(drivers);
}
@PostMapping
public ResponseEntity<?> create(@RequestBody Driver driver) {
try {
this.driverRepository.save(driver);
return ResponseEntity.status(HttpStatus.CREATED).body(driver);
} catch (Exception e) {
return ResponseEntity.badRequest().body("Errors");
}
}
@PutMapping
public ResponseEntity<?> update(@RequestBody Driver driver) {
try {
this.driverRepository.save(driver);
return ResponseEntity.status(HttpStatus.OK).body(driver);
} catch (Exception e) {
return ResponseEntity.badRequest().body("Errors");
}
}
@DeleteMapping("/{id}")
public ResponseEntity<?> delete(@PathVariable(name="id", required=true) String id) {
try {
Optional<Driver> drive = driverRepository.findById(id);
if(drive.isPresent()) {
this.driverRepository.delete(drive.get());
return ResponseEntity.status(HttpStatus.OK).body("");
}
return ResponseEntity.notFound().build();
} catch (Exception e) {
return ResponseEntity.badRequest().body("Errors");
}
}
}
| [
"deusemar@localhost.localdomain"
] | deusemar@localhost.localdomain |
867fbab65deb79feb66ea59ccb65d0914b8e0b8b | d4b1126b3a929b62beae534c204a2defb7fc7bcc | /app/src/main/java/com/hualianzb/sec/ui/adapters/PagerRecyclerAdapter.java | 0b359739dba8f4c4da13125f3c002c0c3eaa4871 | [] | no_license | crazytomaoto/sec_android | 2ed751e485de4ecbd17cf983e29ab95cf6494467 | 9cf88f93012c0041db04c70d6168dfcd343bc82a | refs/heads/main | 2020-04-11T21:05:44.334682 | 2019-03-26T07:54:59 | 2019-03-26T07:55:17 | 162,094,412 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,068 | java | package com.hualianzb.sec.ui.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hualianzb.sec.R;
import com.hualianzb.sec.models.RememberSEC;
import com.hualianzb.sec.utils.StringUtils;
import com.hualianzb.sec.utils.UiHelper;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Date:2018/10/22
* auther:wangtianyun
* describe:首页切卡的适配器
*/
public class PagerRecyclerAdapter extends RecyclerView.Adapter<PagerRecyclerAdapter.ViewHolder> {
private List<RememberSEC> rememberSecList;
private Context context;
private String money;
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public PagerRecyclerAdapter(Context context) {
rememberSecList = new ArrayList<>();
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_pager, parent, false);
ViewHolder vh = new ViewHolder(view);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
RememberSEC rememberSec = rememberSecList.get(position);
if (rememberSec != null) {
holder.tvName.setText(rememberSec.getWalletName());
if (rememberSec.getHowToCreate() == 1) {//创建的
if (rememberSec.isBackup()) {//已经保存了
holder.tvBack.setVisibility(View.GONE);
} else {
holder.tvBack.setVisibility(View.VISIBLE);
}
} else {
holder.tvBack.setVisibility(View.GONE);
}
holder.tvAddress.setText(rememberSec.getAddress().substring(0, 10) + "…" + (rememberSec.getAddress()).substring(32, 42));
money = getMoney();
if (!StringUtils.isEmpty(money)) {
holder.tvProperty.setText(money);
if (money.equals("0")) {
holder.tvProperty.setText(money);
return;
}
if (money.length() > 10) {
holder.tvProperty.setText((money + "").substring(0,10));
return;
}
if (Double.parseDouble(money) < 1) {
holder.tvProperty.setText(money);
return;
}
} else {
holder.tvProperty.setText("0");
}
}
holder.ivCode.setOnClickListener(v -> UiHelper.startMakeCodeActivity(context, rememberSecList.get(position).getAddress()));
holder.ll_base.setOnClickListener(v -> UiHelper.startManagerWalletActy(context));
}
@Override
public int getItemCount() {
return rememberSecList.size();
}
@Override
public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) {
super.onBindViewHolder(holder, position, payloads);
}
public void setData(List<RememberSEC> rememberSecList) {
this.rememberSecList = rememberSecList;
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tv_name)
TextView tvName;
@BindView(R.id.tvBack)
TextView tvBack;
@BindView(R.id.tv_address)
TextView tvAddress;
@BindView(R.id.iv_code)
ImageView ivCode;
@BindView(R.id.tv_property)
TextView tvProperty;
@BindView(R.id.ll_base)
LinearLayout ll_base;
ViewHolder(View view) {
super(view.getRootView());
ButterKnife.bind(this, view);
}
}
}
| [
"h15065349705"
] | h15065349705 |
538d0d6943f1003aa32dbfe46424760fe6c005a0 | c7322fd93a2b157d9af74e7dd10ef16c20d30758 | /library/src/main/java/pl/marchuck/stripedbottombar/StripedBottomBarTab.java | e1cd00e71cd04e251257eb3cc852a9a50e9dc78f | [
"Apache-2.0"
] | permissive | Marchuck/StripedBottomBar | 16887e0e1f652d6c2111beea3a7c19f0d64c1927 | 822597a5b617d91ffd13b9c4306dd67aae65c35b | refs/heads/master | 2021-09-05T22:19:22.262378 | 2018-01-31T09:52:28 | 2018-01-31T09:52:28 | 110,694,273 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 25,349 | java | package pl.marchuck.stripedbottombar;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorCompat;
import android.support.v7.widget.AppCompatImageView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.concurrent.Callable;
import pl.marchuck.stripebottombar.R;
/*
* BottomBar library for Android
* Copyright (c) 2016 Iiro Krankka (http://github.com/roughike).
*
* 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.
*/
public class StripedBottomBarTab extends LinearLayout {
@VisibleForTesting
static final String STATE_BADGE_COUNT = "STATE_BADGE_COUNT_FOR_TAB_";
private static final long ANIMATION_DURATION = 150;
private static final float ACTIVE_TITLE_SCALE = 1;
private static final float INACTIVE_FIXED_TITLE_SCALE = 0.86f;
private static final float ACTIVE_SHIFTING_TITLELESS_ICON_SCALE = 1.24f;
private static final float INACTIVE_SHIFTING_TITLELESS_ICON_SCALE = 1f;
private final int sixDps;
private final int eightDps;
private final int sixteenDps;
@VisibleForTesting
StripedBottomBarBadge badge;
private Type type = Type.FIXED;
private boolean isTitleless;
private int iconResId;
private String title;
private float inActiveAlpha;
private float activeAlpha;
private int inActiveColor;
private int activeColor;
private int barColorWhenSelected;
private int badgeBackgroundColor;
private boolean badgeHidesWhenActive;
private AppCompatImageView iconView;
private TextView titleView;
private boolean isActive;
private int indexInContainer;
private int titleTextAppearanceResId;
private Typeface titleTypeFace;
private View stripeView;
private int stripeViewColor = Color.TRANSPARENT;
private boolean stripeViewEnabled;
private ToggleVisibilityCallback toggleVisibilityCallback;
public static Callable<Integer> bottomBarHeightCallable = null;
StripedBottomBarTab(Context context) {
super(context);
sixDps = MiscUtils.dpToPixel(context, 6);
eightDps = MiscUtils.dpToPixel(context, 8);
sixteenDps = MiscUtils.dpToPixel(context, 16);
}
void setConfig(@NonNull Config config) {
setInActiveAlpha(config.inActiveTabAlpha);
setActiveAlpha(config.activeTabAlpha);
setInActiveColor(config.inActiveTabColor);
setActiveColor(config.activeTabColor);
setBarColorWhenSelected(config.barColorWhenSelected);
setBadgeBackgroundColor(config.badgeBackgroundColor);
setBadgeHidesWhenActive(config.badgeHidesWhenSelected);
setTitleTextAppearance(config.titleTextAppearance);
setTitleTypeface(config.titleTypeFace);
}
void prepareLayout() {
inflate(getContext(), getLayoutResource(), this);
setOrientation(VERTICAL);
setGravity(isTitleless ? Gravity.CENTER : Gravity.CENTER_HORIZONTAL);
setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
setBackgroundResource(MiscUtils.getDrawableRes(getContext(), R.attr.selectableItemBackgroundBorderless));
iconView = (AppCompatImageView) findViewById(R.id.bb_bottom_bar_icon);
iconView.setImageResource(iconResId);
if (type != Type.TABLET && !isTitleless) {
titleView = (TextView) findViewById(R.id.bb_bottom_bar_title);
titleView.setVisibility(VISIBLE);
if (type == Type.SHIFTING) {
findViewById(R.id.spacer).setVisibility(VISIBLE);
}
updateTitle();
}
updateCustomTextAppearance();
updateCustomTypeface();
prepareStripe();
}
private void prepareStripe() {
stripeView = new View(getContext());
stripeView.setBackgroundColor(stripeViewColor);
int stripeHeight = determineStripeHeight();
addView(stripeView, 0, new LinearLayout.LayoutParams(-1, stripeHeight));
if (!stripeViewEnabled) {
hideStripeView();
}
}
private int determineStripeHeight() {
int densityDpi = getResources().getDisplayMetrics().densityDpi;
// Log.d(TAG, "determineStripeHeight: " + densityDpi);
if (bottomBarHeightCallable != null) {
try {
return bottomBarHeightCallable.call();
} catch (Exception e) {
bottomBarHeightCallable = null;
return determineStripeHeight();
}
}
switch (densityDpi) {
case DisplayMetrics.DENSITY_LOW:
// LDPI
// System.out.println("DENSITY_LOW");
break;
case DisplayMetrics.DENSITY_MEDIUM:
// System.out.println("DENSITY_MEDIUM");
// MDPI
break;
case DisplayMetrics.DENSITY_TV:
case DisplayMetrics.DENSITY_HIGH:
// System.out.println("DENSITY_HIGH");
// HDPI
break;
case DisplayMetrics.DENSITY_XHIGH:
case DisplayMetrics.DENSITY_280:
// System.out.println("DENSITY_XHIGH");
return 5;
case DisplayMetrics.DENSITY_XXHIGH:
case DisplayMetrics.DENSITY_360:
case DisplayMetrics.DENSITY_400:
case DisplayMetrics.DENSITY_420:
// System.out.println("DENSITY_XXHIGH");
// XXHDPI
break;
case DisplayMetrics.DENSITY_XXXHIGH:
case DisplayMetrics.DENSITY_560:
//System.out.println("DENSITY_XXXHIGH");
// XXXHDPI
break;
}
if (densityDpi <= 320) {
return 10;
}
return 20;
}
@VisibleForTesting
int getLayoutResource() {
int layoutResource;
switch (type) {
case FIXED:
layoutResource = R.layout.bb_bottom_bar_item_fixed;
break;
case SHIFTING:
layoutResource = R.layout.bb_bottom_bar_item_shifting;
break;
case TABLET:
layoutResource = R.layout.bb_bottom_bar_item_fixed_tablet;
break;
default:
// should never happen
throw new RuntimeException("Unknown BottomBarTab type.");
}
return layoutResource;
}
private void updateTitle() {
if (titleView != null) {
titleView.setText(title);
}
}
@SuppressWarnings("deprecation")
private void updateCustomTextAppearance() {
if (titleView == null || titleTextAppearanceResId == 0) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
titleView.setTextAppearance(titleTextAppearanceResId);
} else {
titleView.setTextAppearance(getContext(), titleTextAppearanceResId);
}
titleView.setTag(R.id.bb_bottom_bar_appearance_id, titleTextAppearanceResId);
}
private void updateCustomTypeface() {
if (titleTypeFace != null && titleView != null) {
titleView.setTypeface(titleTypeFace);
}
}
Type getType() {
return type;
}
void setType(Type type) {
this.type = type;
}
boolean isTitleless() {
return isTitleless;
}
void setIsTitleless(boolean isTitleless) {
if (isTitleless && getIconResId() == 0) {
throw new IllegalStateException("This tab is supposed to be " +
"icon only, yet it has no icon specified. Index in " +
"container: " + getIndexInTabContainer());
}
this.isTitleless = isTitleless;
}
public ViewGroup getOuterView() {
return (ViewGroup) getParent();
}
AppCompatImageView getIconView() {
return iconView;
}
int getIconResId() {
return iconResId;
}
void setIconResId(int iconResId) {
this.iconResId = iconResId;
}
TextView getTitleView() {
return titleView;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
updateTitle();
}
public float getInActiveAlpha() {
return inActiveAlpha;
}
public void setInActiveAlpha(float inActiveAlpha) {
this.inActiveAlpha = inActiveAlpha;
if (!isActive) {
setAlphas(inActiveAlpha);
}
}
public float getActiveAlpha() {
return activeAlpha;
}
public void setStripeViewEnabled(boolean stripeViewEnabled) {
if (this.stripeViewEnabled && !stripeViewEnabled) {
setStripeViewColor(Color.TRANSPARENT);
}
this.stripeViewEnabled = stripeViewEnabled;
}
public void setStripeViewColor(int stripeViewColor) {
this.stripeViewColor = stripeViewColor;
if (stripeView != null) {
stripeView.setBackgroundColor(stripeViewColor);
}
}
public void setActiveAlpha(float activeAlpha) {
this.activeAlpha = activeAlpha;
if (isActive) {
setAlphas(activeAlpha);
}
}
public int getInActiveColor() {
return inActiveColor;
}
public void setInActiveColor(int inActiveColor) {
this.inActiveColor = inActiveColor;
if (!isActive) {
setColors(inActiveColor);
}
}
public int getActiveColor() {
return activeColor;
}
public void setActiveColor(int activeIconColor) {
this.activeColor = activeIconColor;
if (isActive) {
setColors(activeColor);
}
}
public int getBarColorWhenSelected() {
return barColorWhenSelected;
}
public void setBarColorWhenSelected(int barColorWhenSelected) {
this.barColorWhenSelected = barColorWhenSelected;
}
public int getBadgeBackgroundColor() {
return badgeBackgroundColor;
}
public void setBadgeBackgroundColor(int badgeBackgroundColor) {
this.badgeBackgroundColor = badgeBackgroundColor;
if (badge != null) {
badge.setColoredCircleBackground(badgeBackgroundColor);
}
}
public boolean getBadgeHidesWhenActive() {
return badgeHidesWhenActive;
}
public void setBadgeHidesWhenActive(boolean hideWhenActive) {
this.badgeHidesWhenActive = hideWhenActive;
}
int getCurrentDisplayedIconColor() {
Object tag = iconView.getTag(R.id.bb_bottom_bar_color_id);
if (tag instanceof Integer) {
return (int) tag;
}
return 0;
}
int getCurrentDisplayedTitleColor() {
if (titleView != null) {
return titleView.getCurrentTextColor();
}
return 0;
}
int getCurrentDisplayedTextAppearance() {
Object tag = titleView.getTag(R.id.bb_bottom_bar_appearance_id);
if (titleView != null && tag instanceof Integer) {
return (int) tag;
}
return 0;
}
public void setBadgeCount(int count) {
if (count <= 0) {
if (badge != null) {
badge.removeFromTab(this);
badge = null;
}
return;
}
if (badge == null) {
badge = new StripedBottomBarBadge(getContext());
badge.attachToTab(this, badgeBackgroundColor);
}
badge.setCount(count);
if (isActive && badgeHidesWhenActive) {
badge.hide();
}
}
public void removeBadge() {
setBadgeCount(0);
}
boolean isActive() {
return isActive;
}
boolean hasActiveBadge() {
return badge != null;
}
int getIndexInTabContainer() {
return indexInContainer;
}
void setIndexInContainer(int indexInContainer) {
this.indexInContainer = indexInContainer;
}
void setIconTint(int tint) {
iconView.setColorFilter(tint);
}
public int getTitleTextAppearance() {
return titleTextAppearanceResId;
}
@SuppressWarnings("deprecation")
void setTitleTextAppearance(int resId) {
this.titleTextAppearanceResId = resId;
updateCustomTextAppearance();
}
public void setTitleTypeface(Typeface typeface) {
this.titleTypeFace = typeface;
updateCustomTypeface();
}
public Typeface getTitleTypeFace() {
return titleTypeFace;
}
static String TAG = "TAG";
void select(boolean animate) {
Log.i(TAG, "select: " + animate);
isActive = true;
if (animate) {
animateIcon(activeAlpha, ACTIVE_SHIFTING_TITLELESS_ICON_SCALE);
animateTitle(sixDps, ACTIVE_TITLE_SCALE, activeAlpha);
animateColors(inActiveColor, activeColor);
} else {
setTitleScale(ACTIVE_TITLE_SCALE);
setTopPadding(sixDps);
setIconScale(ACTIVE_SHIFTING_TITLELESS_ICON_SCALE);
setColors(activeColor);
setAlphas(activeAlpha);
}
setSelected(true);
if (badge != null && badgeHidesWhenActive) {
badge.hide();
}
if (stripeViewEnabled) {
showStripeView();
}
}
void deselect(boolean animate) {
isActive = false;
boolean isShifting = type == Type.SHIFTING;
float titleScale = isShifting ? 0 : INACTIVE_FIXED_TITLE_SCALE;
int iconPaddingTop = isShifting ? sixteenDps : eightDps;
if (animate) {
animateTitle(iconPaddingTop, titleScale, inActiveAlpha);
animateIcon(inActiveAlpha, INACTIVE_SHIFTING_TITLELESS_ICON_SCALE);
animateColors(activeColor, inActiveColor);
} else {
setTitleScale(titleScale);
setTopPadding(iconPaddingTop);
setIconScale(INACTIVE_SHIFTING_TITLELESS_ICON_SCALE);
setColors(inActiveColor);
setAlphas(inActiveAlpha);
}
setSelected(false);
if (!isShifting && badge != null && !badge.isVisible()) {
badge.show();
}
if (stripeViewEnabled) {
hideStripeView();
}
}
private void animateColors(int previousColor, int color) {
ValueAnimator anim = new ValueAnimator();
anim.setIntValues(previousColor, color);
anim.setEvaluator(new ArgbEvaluator());
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
setColors((Integer) valueAnimator.getAnimatedValue());
}
});
anim.setDuration(150);
anim.start();
}
private void setColors(int color) {
if (iconView != null) {
iconView.setColorFilter(color);
iconView.setTag(R.id.bb_bottom_bar_color_id, color);
}
if (titleView != null) {
titleView.setTextColor(color);
}
}
private void setAlphas(float alpha) {
if (iconView != null) {
ViewCompat.setAlpha(iconView, alpha);
}
if (titleView != null) {
ViewCompat.setAlpha(titleView, alpha);
}
}
void updateWidth(float endWidth, boolean animated) {
if (!animated) {
getLayoutParams().width = (int) endWidth;
if (!isActive && badge != null) {
badge.adjustPositionAndSize(this);
badge.show();
}
return;
}
float start = getWidth();
ValueAnimator animator = ValueAnimator.ofFloat(start, endWidth);
animator.setDuration(150);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
ViewGroup.LayoutParams params = getLayoutParams();
if (params == null) return;
params.width = Math.round((float) animator.getAnimatedValue());
setLayoutParams(params);
}
});
// Workaround to avoid using faulty onAnimationEnd() listener
postDelayed(new Runnable() {
@Override
public void run() {
if (!isActive && badge != null) {
clearAnimation();
badge.adjustPositionAndSize(StripedBottomBarTab.this);
badge.show();
}
}
}, animator.getDuration());
animator.start();
}
private void updateBadgePosition() {
if (badge != null) {
badge.adjustPositionAndSize(this);
}
}
private void setTopPaddingAnimated(int start, int end) {
if (type == Type.TABLET || isTitleless) {
return;
}
ValueAnimator paddingAnimator = ValueAnimator.ofInt(start, end);
paddingAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
iconView.setPadding(
iconView.getPaddingLeft(),
(Integer) animation.getAnimatedValue(),
iconView.getPaddingRight(),
iconView.getPaddingBottom()
);
}
});
paddingAnimator.setDuration(ANIMATION_DURATION);
paddingAnimator.start();
}
private void animateTitle(int padding, float scale, float alpha) {
if (type == Type.TABLET && isTitleless) {
return;
}
setTopPaddingAnimated(iconView.getPaddingTop(), padding);
ViewPropertyAnimatorCompat titleAnimator = ViewCompat.animate(titleView)
.setDuration(ANIMATION_DURATION)
.scaleX(scale)
.scaleY(scale);
titleAnimator.alpha(alpha);
titleAnimator.start();
}
private void animateIconScale(float scale) {
ViewCompat.animate(iconView)
.setDuration(ANIMATION_DURATION)
.scaleX(scale)
.scaleY(scale)
.start();
}
private void animateIcon(float alpha, float scale) {
ViewCompat.animate(iconView)
.setDuration(ANIMATION_DURATION)
.alpha(alpha)
.start();
if (isTitleless && type == Type.SHIFTING) {
animateIconScale(scale);
}
}
private void setTopPadding(int topPadding) {
if (type == Type.TABLET || isTitleless) {
return;
}
iconView.setPadding(
iconView.getPaddingLeft(),
topPadding,
iconView.getPaddingRight(),
iconView.getPaddingBottom()
);
}
private void setTitleScale(float scale) {
if (type == Type.TABLET || isTitleless) {
return;
}
ViewCompat.setScaleX(titleView, scale);
ViewCompat.setScaleY(titleView, scale);
}
private void setIconScale(float scale) {
if (isTitleless && type == Type.SHIFTING) {
ViewCompat.setScaleX(iconView, scale);
ViewCompat.setScaleY(iconView, scale);
}
}
public void hideStripeView() {
stripeView.setVisibility(INVISIBLE);
if (toggleVisibilityCallback != null) {
toggleVisibilityCallback.onVisibleEnd(stripeView);
}
}
public void showStripeView() {
stripeView.setVisibility(VISIBLE);
if (toggleVisibilityCallback != null) {
toggleVisibilityCallback.onVisibleStart(stripeView);
}
}
public void setCustomStripeAnimation(@Nullable ToggleVisibilityCallback toggleVisibilityCallback) {
this.toggleVisibilityCallback = toggleVisibilityCallback;
}
@Override
public Parcelable onSaveInstanceState() {
if (badge != null) {
Bundle bundle = saveState();
bundle.putParcelable("superstate", super.onSaveInstanceState());
return bundle;
}
return super.onSaveInstanceState();
}
@VisibleForTesting
Bundle saveState() {
Bundle outState = new Bundle();
outState.putInt(STATE_BADGE_COUNT + getIndexInTabContainer(), badge.getCount());
return outState;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
restoreState(bundle);
state = bundle.getParcelable("superstate");
}
super.onRestoreInstanceState(state);
}
@VisibleForTesting
void restoreState(Bundle savedInstanceState) {
int previousBadgeCount = savedInstanceState.getInt(STATE_BADGE_COUNT + getIndexInTabContainer());
setBadgeCount(previousBadgeCount);
}
enum Type {
FIXED, SHIFTING, TABLET
}
public static class Config {
private final float inActiveTabAlpha;
private final float activeTabAlpha;
private final int inActiveTabColor;
private final int activeTabColor;
private final int barColorWhenSelected;
private final int badgeBackgroundColor;
private final int titleTextAppearance;
private final Typeface titleTypeFace;
private boolean badgeHidesWhenSelected = true;
private Config(Builder builder) {
this.inActiveTabAlpha = builder.inActiveTabAlpha;
this.activeTabAlpha = builder.activeTabAlpha;
this.inActiveTabColor = builder.inActiveTabColor;
this.activeTabColor = builder.activeTabColor;
this.barColorWhenSelected = builder.barColorWhenSelected;
this.badgeBackgroundColor = builder.badgeBackgroundColor;
this.badgeHidesWhenSelected = builder.hidesBadgeWhenSelected;
this.titleTextAppearance = builder.titleTextAppearance;
this.titleTypeFace = builder.titleTypeFace;
}
public static class Builder {
private float inActiveTabAlpha;
private float activeTabAlpha;
private int inActiveTabColor;
private int activeTabColor;
private int barColorWhenSelected;
private int badgeBackgroundColor;
private boolean hidesBadgeWhenSelected = true;
private int titleTextAppearance;
private Typeface titleTypeFace;
public Builder inActiveTabAlpha(float alpha) {
this.inActiveTabAlpha = alpha;
return this;
}
public Builder activeTabAlpha(float alpha) {
this.activeTabAlpha = alpha;
return this;
}
public Builder inActiveTabColor(@ColorInt int color) {
this.inActiveTabColor = color;
return this;
}
public Builder activeTabColor(@ColorInt int color) {
this.activeTabColor = color;
return this;
}
public Builder barColorWhenSelected(@ColorInt int color) {
this.barColorWhenSelected = color;
return this;
}
public Builder badgeBackgroundColor(@ColorInt int color) {
this.badgeBackgroundColor = color;
return this;
}
public Builder hideBadgeWhenSelected(boolean hide) {
this.hidesBadgeWhenSelected = hide;
return this;
}
public Builder titleTextAppearance(int titleTextAppearance) {
this.titleTextAppearance = titleTextAppearance;
return this;
}
public Builder titleTypeFace(Typeface titleTypeFace) {
this.titleTypeFace = titleTypeFace;
return this;
}
public Config build() {
return new Config(this);
}
}
}
}
| [
"lukasz.marczak@intive.com"
] | lukasz.marczak@intive.com |
79398fe1a4b8725a979a1051494ead0b211614ad | e0f7a481a3b055e857775ba98fcb5f1fc4ec0f1c | /ArqDeSisExecicicos/src/exercicio01/saque/SaqueController.java | b863e1941edeb918d0a52aa9d0494a549baebb6d | [] | no_license | jonasdias95/TesteEntrega | 9c50599f52a993795197aac2ab271467af5227e2 | d530ad88ae88242390fbdbf5899183febfac7133 | refs/heads/master | 2021-01-10T10:00:05.614903 | 2016-03-07T03:44:38 | 2016-03-07T03:44:38 | 53,274,549 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,163 | java | package exercicio01.saque;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;
import exercicio01.saque.beans.Conta;
import exercicio01.saque.ConexaoBD;
import exercicio01.saque.Log;
import exercicio01.saque.Notas;
import exercicio01.saque.Saque;
public class SaqueController implements ActionListener{
private Conta conta;
private Saque saque;
private Notas notas;
public ResourceBundle bundleParam;
public Log log;
public SaqueController(ResourceBundle bundleParam,final Conta conta) {
super();
this.conta = conta;
this.notas = new Notas();
this.bundleParam = bundleParam;
}
public Saque getSaque() {
return saque;
}
public void setSaque(int tipoMovimento, double valor) {
this.saque = new Saque(tipoMovimento, valor);
}
@Override
public void actionPerformed(ActionEvent ev) {
Connection conn = null;
double saldo = 0.0;
int qntNota =0;
double valor = saque.getValor();
//atributo para sair das opera��es logicas
// R$10 R$20 R$50
boolean[] vazio = {false,false,false};
String[] mensagens = {bundleParam.getString("mensagem.sim"),bundleParam.getString("mensagem.nao")};
// obtem conexao com o banco
ConexaoBD bd = new ConexaoBD() ;
try {
conn = bd.obtemConexao();
// *** For�a o uso de transa��o.
conn.setAutoCommit(false);
int opcao = JOptionPane.showOptionDialog(null, bundleParam.getString("tela.realizarSaque.confirma"), bundleParam.getString("tela.realizarSaque.titulo"),JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, mensagens, mensagens[1]);
if (opcao == 0) {
try {
Calendar cData= Calendar.getInstance();
String data = String.format("%tF", cData);
ArrayList<Notas> listaNotas = this.notas.carregarDados(conn);
int[] notasUsadas = new int[listaNotas.size()];
for(int i = 0; i < listaNotas.size();i++){
if(listaNotas.get(i).getQuantidade() == 0) vazio[i] = true;
}
while(vazio[2] == false && 50 <= valor){
qntNota = listaNotas.get(2).getQuantidade();
valor = valor - 50;
notasUsadas[2]++;
qntNota--;
if(qntNota == 0) vazio[2] = true;
}
while(vazio[1] == false && 20 <= valor){
qntNota = listaNotas.get(1).getQuantidade();
valor = valor - 20;
notasUsadas[1]++;
qntNota--;
if(qntNota == 0) vazio[1] = true;
}
while(vazio[0] == false && 10 <= valor){
qntNota = listaNotas.get(0).getQuantidade();
valor = valor - 10;
notasUsadas[0]++;
qntNota--;
if(qntNota == 0) vazio[0] = true;
}
for (int i = 0; i < listaNotas.size(); i++) {
int qntd =listaNotas.get(i).getQuantidade() - notasUsadas[i];
if(notasUsadas[i] != 0)notas.atualizarNota(conn, qntd, listaNotas.get(i).getNota());
}
if(valor==0){
//notas.atualizarNota(conn, qntdNota, nota);
conn.commit();
saldo = conta.consultaSaldo(conn, Integer.parseInt(conta.getNumConta()), conta.getAgencia().getNumAgencia(), conta.getBanco().getNumBanco());
if (saldo >= saque.getValor()){
conta.atualizarSaldo(conn, saldo - saque.getValor(), Integer.parseInt(conta.getNumConta()));
saque.inserirSaque(conn, saque.getTipoMovimento(), -saque.getValor(),Integer.parseInt(conta.getNumConta()), conta.getAgencia().getNumAgencia(), conta.getBanco().getNumBanco(), data);
if(saque.selectOperacao(conn, saque.getTipoMovimento(), data).equals(null)){
saque.insertOperacao(conn, saque.getTipoMovimento(), data, 1);
}else{
int quantidade = 1;
quantidade +=saque.selectQutddOperacao(conn, saque.getTipoMovimento(), data);
saque.updateOperacao(conn, saque.getTipoMovimento(), data, quantidade++);
log = new Log();
log.gravarLog(saque.getTipoMovimento()+" - "+saque.getValor());
}
conn.commit();
JOptionPane.showMessageDialog(null, bundleParam.getString("mensagem.msg01.saqueRealizado"));
}else{
JOptionPane.showMessageDialog(null, bundleParam.getString("tela.realizarSaque.sem.saldo"));
throw new Exception();
}
}else JOptionPane.showMessageDialog(null,bundleParam.getString("tela.realizarSaque.erro.nota"));
} catch (Exception e) {
conn.rollback();
JOptionPane.showMessageDialog(null,bundleParam.getString("tela.realizarSaque.erro.nota"));
e.printStackTrace();
}finally{
conn.close();
}
}else {
JOptionPane.showMessageDialog(null, bundleParam.getString("tela.realizarSaque.cancela") + "teste1");
throw new Exception();
}
}catch(Exception e1){
JOptionPane.showMessageDialog(null,bundleParam.getString("tela.realizarSaque.concela") + " " +
bundleParam.getString("tela.gerarCodigo.buttonCod") + " " +
bundleParam.getString("tela.realizarTransferencia.erro.nota"));
//e1.printStackTrace();
}
}
}
| [
"jonasdias95@gmail.com"
] | jonasdias95@gmail.com |
7fbf0782d0fc81d6fd3819f3b5e15aa65be409b2 | 588e229e5016e166518e23d66d671dc3be836f95 | /src/by/it/kanaplianik/jd01_04/TaskA.java | 2af77e174da1254b9865f8c72dd4caeb53703d8a | [] | no_license | MikKach/JD2021-10-06 | 3d3778ed0e540f2e1e258f15cbf5a53b2f83d491 | 29f86de44a4d7fc36999bc2c640fdfc98a44c08f | refs/heads/main | 2023-08-29T15:29:51.284472 | 2021-11-01T16:59:42 | 2021-11-01T16:59:42 | 419,403,417 | 0 | 0 | null | 2021-10-20T16:14:40 | 2021-10-20T16:14:39 | null | UTF-8 | Java | false | false | 1,302 | java | package by.it.kanaplianik.jd01_04;
import java.util.Arrays;
import java.util.Scanner;
public class TaskA {
public static void main(String[] args) {
printMulTable();
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
buildOneDimArray(string);
}
static void printMulTable() {
for (int a = 2; a <= 9; a++) {
for (int b = 2; b <= 9; b++) {
int c = a * b;
System.out.printf("%1d*%1d=%-2d ", a, b, c);
}
System.out.println();
}
}
static void buildOneDimArray(String line) {
double[] array = InOut.getArray(line);
double firstValue = array[0];
double lastValue = array[array.length - 1];
InOut.printArray(array, "V", 5);
Helper.sort(array);
InOut.printArray(array, "V", 4);
for (int i = 0; i < array.length; i++) {
if (array[i] == firstValue) {
System.out.println("Index of first element=" + i);
break;
}
}
for (int i = 0; i < array.length; i++) {
if (array[i] == lastValue) {
System.out.println("Index of last element=" + i);
break;
}
}
}
}
| [
"!kemer2020"
] | !kemer2020 |
c5cd16e4cf320ddd7907b7df027b67adb6139bde | f2314040ad2ae014df520b48d60d2c6d7b358f44 | /src/main/java/com/example/exchanger/controller/rest/OrderController.java | 194cbf64e0fe8e9bfe6fa1cd9ea585c91a162888 | [] | no_license | SemenNikolaenko/exchanger | e65a4ffee3618286fdfe06da97c56f442f2ca3b1 | 6249b5c0786e84a163ff1f0bf5252eb96ce3471f | refs/heads/main | 2023-03-22T18:10:30.911650 | 2021-03-14T08:09:24 | 2021-03-14T08:09:24 | 347,423,687 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,014 | java | package com.example.exchanger.controller.rest;
import com.example.exchanger.exception.NotEnoughMoneyException;
import com.example.exchanger.model.Account;
import com.example.exchanger.model.Order;
import com.example.exchanger.model.param.OrderRequestParam;
import com.example.exchanger.service.AccountService;
import com.example.exchanger.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/orders")
public class OrderController {
private OrderService orderService;
private AccountService accountService;
@Autowired
public OrderController(OrderService orderService, AccountService accountService) {
this.orderService = orderService;
this.accountService = accountService;
}
@PostMapping("/create")
public ResponseEntity createOrder(@RequestBody OrderRequestParam params, @RequestParam Long accountId) {
Order newOrder = null;
if (params.getExchangeAction().equalsIgnoreCase("BUY")) {
Account account = accountService.getAccountById(accountId);
newOrder = orderService.addOrderToBuy(params,account);
}
if (params.getExchangeAction().equalsIgnoreCase("SELL")) {
Account account = accountService.getAccountById(accountId);
newOrder = orderService.addOrderToSell(params, account);
}
if (newOrder != null) return ResponseEntity.ok().body(newOrder);
else return new ResponseEntity("Error with creating order", HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping
public ResponseEntity getAllOrders() {
List<Order> allOrders = orderService.getAllOrders();
return ResponseEntity.ok().body(allOrders);
}
@GetMapping("/finished")
public ResponseEntity getAllFinishedOrder() {
List<Order> allOrders = orderService.getAllFinishedOrders();
return ResponseEntity.ok().body(allOrders);
}
@GetMapping("/active")
public ResponseEntity getAllActiveOrder() {
List<Order> allOrders = orderService.getAllActiveOrders();
return ResponseEntity.ok().body(allOrders);
}
@GetMapping("/{id}")
public ResponseEntity executeOrder(@PathVariable("id") Long orderId, Long accountId) throws NotEnoughMoneyException {
double totalAmountMoneyFromOrder = orderService.executeOrder(orderId);
if (totalAmountMoneyFromOrder > 0) {
accountService.increaseBalance(totalAmountMoneyFromOrder, accountId);
return ResponseEntity.ok().body("Order executed success");
} else if (totalAmountMoneyFromOrder < 0) {
accountService.reduceBalance(totalAmountMoneyFromOrder, accountId);
return ResponseEntity.ok().body("Order executed success");
} else return ResponseEntity.badRequest().build();
}
}
| [
"nikolaenko.semen12@gmail.com"
] | nikolaenko.semen12@gmail.com |
4840f8fcd08c3e2056d1ef349437509207f30cc5 | 8e967502511934cabdde6c43b7dcabf7f9715565 | /src/test/java/lesson08/c_add_assertall/BaseTest.java | 582c2fd3682961bd5117cc9c08ecbf44b37190cf | [] | no_license | QA-automation-engineer/test-automation-4 | 1e2c1a3756787af70db3c0d6c1ddf95a635707c6 | 7ad3aadf78b193dada820540a6ee36db4f6e6e5f | refs/heads/master | 2020-04-27T00:47:04.919152 | 2019-04-01T22:01:34 | 2019-04-01T22:01:34 | 173,945,652 | 0 | 0 | null | 2019-03-26T12:11:56 | 2019-03-05T12:50:11 | Java | UTF-8 | Java | false | false | 2,573 | java | package lesson08.c_add_assertall;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.junit.AfterClass;
import org.junit.AssumptionViolatedException;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
public abstract class BaseTest extends SimpleAPI {
protected static WebDriver driver;
@Override
WebDriver getDriver() {
return driver;
}
@Rule
public TestWatcher testWatcher = new TestWatcher() {
@Override
protected void succeeded(Description description) {
System.out.println(String
.format("Test '%s' - PASSED", description.getMethodName()));
super.succeeded(description);
}
@Override
protected void failed(Throwable e, Description description) {
System.out.println(String
.format("Test '%s' - FAILED due to: %s",
description.getMethodName(),
e.getMessage()));
super.failed(e, description);
}
@Override
protected void skipped(AssumptionViolatedException e, Description description) {
System.out.println(String
.format("Test '%s' - SKIPPED", description.getMethodName()));
super.skipped(e, description);
}
@Override
protected void starting(Description description) {
System.out.println(String
.format("Test '%s' - is starting...", description.getMethodName()));
super.starting(description);
}
};
@BeforeClass
public static void setUp() {
driver = new ChromeDriver();
driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
@AfterClass
public static void tearDown() {
driver.quit();
}
void assertThat(ExpectedCondition<Boolean> condition) {
assertThat(condition, 10l);
}
void assertThat(ExpectedCondition<Boolean> condition, long timeout) {
waitFor(condition, timeout);
}
void assertAll(Assertion... assertions) {
List<Throwable> errors = new ArrayList<>();
for (Assertion assertion : assertions) {
try {
assertion.assertSmth();
} catch (Throwable throwable) {
errors.add(throwable);
}
}
if (!errors.isEmpty()) {
throw new AssertionError(errors
.stream()
.map(assertionError -> "\n Failed" + assertionError.getMessage())
.collect(Collectors.toList()).toString());
}
}
@FunctionalInterface
public interface Assertion {
void assertSmth();
}
}
| [
"trandafilov.vladimir@gmail.com"
] | trandafilov.vladimir@gmail.com |
66149c2471b92dd81dfc5f92e1e88b9ed3805007 | 31f609157ae46137cf96ce49e217ce7ae0008b1e | /bin/ext-accelerator/acceleratorfacades/src/de/hybris/platform/acceleratorfacades/csv/CsvFacade.java | 2cdba315ee31493f0b33cb288802ae1d2e19e7b6 | [] | no_license | natakolesnikova/hybrisCustomization | 91d56e964f96373781f91f4e2e7ca417297e1aad | b6f18503d406b65924c21eb6a414eb70d16d878c | refs/heads/master | 2020-05-23T07:16:39.311703 | 2019-05-15T15:08:38 | 2019-05-15T15:08:38 | 186,672,599 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,182 | java | /*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.acceleratorfacades.csv;
import de.hybris.platform.commercefacades.order.data.CartData;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
/**
* Facade for generating CSV content.
*/
public interface CsvFacade
{
/**
* Generate CSV content from CartData
*
* @param headers
* : list of text which is used as csv header; e.g Code,Name,Price
* @param includeHeader
* : flag to indicate whether header should be generated
* @param cartData
* @param writer
* : CSV content generated is written to the (buffered) writer
* @throws IOException
*/
void generateCsvFromCart(final List<String> headers, final boolean includeHeader, final CartData cartData, final Writer writer)
throws IOException;
}
| [
"nataliia@spadoom.com"
] | nataliia@spadoom.com |
8ea8b4e5231c62d8ea36e2905abb732bb3462459 | b4979b03a2c63ea72282999ba8932375c58009d5 | /JavaSource/com/intrigueit/myc2i/zipcode/ZipCodeUtil.java | 6c75a10e42c11b7ec545ba3da96f56844e424ce2 | [] | no_license | google-code-export/isnet | 9ae52952e91137e5efec9250ae0335596cc398cb | c63ac61d873cec9a99c2a3297867b3a65e890389 | refs/heads/master | 2020-04-30T19:27:56.265738 | 2014-03-18T23:57:24 | 2014-03-18T23:57:24 | 32,134,297 | 0 | 0 | null | null | null | null | WINDOWS-1252 | Java | false | false | 3,669 | java | package com.intrigueit.myc2i.zipcode;
import com.intrigueit.myc2i.zipcode.domain.ZipCode;
public class ZipCodeUtil {
/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: :*/
/*:: This routine calculates the distance between two points (given the :*/
/*:: latitude/longitude of those points). It is being used to calculate :*/
/*:: the distance between two ZIP Codes or Postal Codes using our :*/
/*:: ZIPCodeWorld(TM) and PostalCodeWorld(TM) products. :*/
/*:: :*/
/*:: Definitions: :*/
/*:: South latitudes are negative, east longitudes are positive :*/
/*:: :*/
/*:: Passed to function: :*/
/*:: lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees) :*/
/*:: lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees) :*/
/*:: unit = the unit you desire for results :*/
/*:: where: 'M' is statute miles :*/
/*:: 'K' is kilometers (default) :*/
/*:: 'N' is nautical miles :*/
/*:: United States ZIP Code/ Canadian Postal Code databases with latitude & :*/
/*:: longitude are available at http://www.zipcodeworld.com :*/
/*:: :*/
/*:: For enquiries, please contact sales@zipcodeworld.com :*/
/*:: :*/
/*:: Official Web site: http://www.zipcodeworld.com :*/
/*:: :*/
/*:: Hexa Software Development Center © All Rights Reserved 2004 :*/
/*:: :*/
/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
public double getDistance(ZipCode first,ZipCode second){
return this.distance(first.getLatitude(), first.getLongitude(), second.getLatitude(), second.getLongitude(), "M");
}
private double distance(double lat1, double lon1, double lat2, double lon2, String unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit.equals("K")) {
dist = dist * 1.609344;
} else if (unit.equals("N")) {
dist = dist * 0.8684;
}
return (dist);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts decimal degrees to radians :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts radians to decimal degrees :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
}
| [
"shamim71@1657e276-a2d9-11de-89ee-f3da9a46d971"
] | shamim71@1657e276-a2d9-11de-89ee-f3da9a46d971 |
138c39199218ed3618c0e5b5f3a6ee8da08f473d | 58a47ee4aeb15769f80cd31027dee757cf5e21ae | /gmall-manage-web/src/main/java/com/xliu/gmall/manage/controller/SkuController.java | b581684f7cd1499d0f4093c348a33ff296edefba | [] | no_license | HXACA/gmall | 074cbc6c3bf8adfc20a99d32a6da7920d20d4774 | 8f268b57af6a976ee323bbbb6b828ec35a57ba1e | refs/heads/master | 2022-09-27T01:51:00.005488 | 2020-03-16T08:26:23 | 2020-03-16T08:26:23 | 244,252,116 | 1 | 0 | null | 2022-09-01T23:21:00 | 2020-03-02T01:17:37 | CSS | UTF-8 | Java | false | false | 1,206 | java | package com.xliu.gmall.manage.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.xliu.gmall.bean.PmsSkuInfo;
import com.xliu.gmall.service.SkuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* @author liuxin
* @version 1.0
* @date 2020/3/5 9:12
*/
@Controller
@CrossOrigin
public class SkuController {
@Reference
SkuService skuService;
@RequestMapping("saveSkuInfo")
@ResponseBody
public String saveSkuInfo(@RequestBody PmsSkuInfo pmsSkuInfo){
pmsSkuInfo.setProductId(pmsSkuInfo.getSpuId());
/*处理无默认图像*/
if(StringUtils.isBlank(pmsSkuInfo.getSkuDefaultImg())){
pmsSkuInfo.setSkuDefaultImg(pmsSkuInfo.getSkuImageList().get(0).getImgUrl());
pmsSkuInfo.getSkuImageList().get(0).setIsDefault("1");
}
return skuService.saveSkuInfo(pmsSkuInfo);
}
}
| [
"718531794@qq.com"
] | 718531794@qq.com |
ef447ee7529eff57cf2fe46c37f94214e81ec25f | 3103d06f0286ddaee0c27711c26653d0aa408db0 | /spring-security-learn/src/test/java/com/ss/ssdemo/SsDemoApplicationTests.java | 9ca998108eb79036de89d1dc8f0bc70d0001c7ac | [] | no_license | mighto/spring-security-learn | 09a85c99745c0a7687e8442490c7aca5b97cc00f | 6c9203cf75b6b56fdaf2b0ac272a4d8c0e1fb69e | refs/heads/master | 2020-04-25T09:42:11.635401 | 2019-03-04T08:59:44 | 2019-03-04T08:59:44 | 172,683,670 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 339 | java | package com.ss.ssdemo;
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 SsDemoApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"2029635554@qq.com"
] | 2029635554@qq.com |
656015f519b006bd0a9f6733897ac54676ef296d | 2b256def9dad0581226cec012580b3ada1330c62 | /src/main/java/br/com/evertonsilvadev/recipesbookapi/business/AuthenticationBusiness.java | 678d412523a2062272d68af837e898662b24995c | [] | no_license | evertonpsilva/recipes-book-api | 8a97c5719b907c51c0bcb9bb61c20023707970a6 | 5a3e50a667d12cfda4f4899b293b52d3f5cb2c69 | refs/heads/master | 2023-06-16T16:42:59.213587 | 2021-07-12T18:50:15 | 2021-07-12T18:50:15 | 385,351,069 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,330 | java | package br.com.evertonsilvadev.recipesbookapi.business;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;
import br.com.evertonsilvadev.recipesbookapi.authentication.TokenAuthenticationService;
import br.com.evertonsilvadev.recipesbookapi.model.dto.LoginDTO;
@Service
public class AuthenticationBusiness {
@Autowired
private AuthenticationManager authManager;
@Autowired
private TokenAuthenticationService tokenService;
public String authenticaticateUser(LoginDTO credential) throws Exception {
UsernamePasswordAuthenticationToken dadosLogin = credential.toLoginToken();
try {
Authentication authentication = authManager.authenticate(dadosLogin);
String token = tokenService.generateToken(authentication);
return token;
} catch (AuthenticationException e) {
System.out.println(e.getLocalizedMessage());
throw new Exception("Teste");
}
}
}
| [
"everton.pereira@mv.com.br"
] | everton.pereira@mv.com.br |
056c358408959690da67a8fb747d4a327a42507a | 96412e1299b497c31f773d4cf2e0094ed07ca715 | /src/com/android/im/app/ChooseAccountActivity.java | f9e9ad7255b972cd1013284e4dcd4a7de037e3fa | [
"Apache-2.0"
] | permissive | android-nostalgic/platform_packages_apps_IM | 414d857ab207888b2a289fc90a09dee4aaa93a4d | 4879f9aa9a3ba8ea89fe31f8d765c4908d4fd53a | HEAD | 2016-09-07T05:25:05.512911 | 2008-10-21T14:00:00 | 2008-10-21T14:00:00 | 20,051,085 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 16,114 | java | /*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.im.app;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.RemoteException;
import android.provider.Im;
import android.util.Log;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.CursorAdapter;
import com.android.im.IImConnection;
import com.android.im.R;
import com.android.im.engine.ImConnection;
import com.android.im.plugin.BrandingResourceIDs;
import com.android.im.service.ImServiceConstants;
public class ChooseAccountActivity extends ListActivity implements
View.OnCreateContextMenuListener {
private static final int ID_SIGN_IN = Menu.FIRST + 1;
private static final int ID_SIGN_OUT = Menu.FIRST + 2;
private static final int ID_EDIT_ACCOUNT = Menu.FIRST + 3;
private static final int ID_REMOVE_ACCOUNT = Menu.FIRST + 4;
private static final int ID_SIGN_OUT_ALL = Menu.FIRST + 5;
private static final int ID_ADD_ACCOUNT = Menu.FIRST + 6;
private static final int ID_VIEW_CONTACT_LIST = Menu.FIRST + 7;
private static final int ID_SETTINGS = Menu.FIRST + 8;
ImApp mApp;
MyHandler mHandler;
private ProviderAdapter mAdapter;
private Cursor mProviderCursor;
private static final String[] PROVIDER_PROJECTION = {
Im.Provider._ID,
Im.Provider.NAME,
Im.Provider.FULLNAME,
Im.Provider.ACTIVE_ACCOUNT_ID,
Im.Provider.ACTIVE_ACCOUNT_USERNAME,
Im.Provider.ACTIVE_ACCOUNT_PW,
};
static final int PROVIDER_ID_COLUMN = 0;
static final int PROVIDER_NAME_COLUMN = 1;
static final int PROVIDER_FULLNAME_COLUMN = 2;
static final int ACTIVE_ACCOUNT_ID_COLUMN = 3;
static final int ACTIVE_ACCOUNT_USERNAME_COLUMN = 4;
static final int ACTIVE_ACCOUNT_PW_COLUMN = 5;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setTitle(R.string.choose_account_title);
mApp = ImApp.getApplication(this);
mHandler = new MyHandler();
mApp.registerForBroadcastEvent(ImApp.EVENT_SERVICE_CONNECTED, mHandler);
mApp.registerForConnEvents(mHandler);
mApp.startImServiceIfNeed();
// (for open source) for now exclude GTalk on the landing page until we can load
// it in an abstract way
String selection = "providers.name != ?";
String[] selectionArgs = new String[] { Im.ProviderNames.GTALK };
mProviderCursor = managedQuery(Im.Provider.CONTENT_URI_WITH_ACCOUNT,
PROVIDER_PROJECTION,
selection,
selectionArgs,
Im.Provider.DEFAULT_SORT_ORDER);
mAdapter = new ProviderAdapter(this, mProviderCursor);
mApp.callWhenServiceConnected(mHandler, new Runnable() {
public void run() {
setListAdapter(mAdapter);
}
});
registerForContextMenu(getListView());
}
private boolean allAccountsSignedOut() {
if (!mProviderCursor.moveToFirst()) return true;
do {
long accountId = mProviderCursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN);
if (isSignedIn(accountId)) return false;
} while (mProviderCursor.moveToNext()) ;
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(ID_SIGN_OUT_ALL).setVisible(!allAccountsSignedOut());
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, ID_SIGN_OUT_ALL, 0, R.string.menu_sign_out_all)
.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ID_SIGN_OUT_ALL:
// Sign out MSN/AIM/YAHOO account
if (mApp.serviceConnected()) {
for (IImConnection conn : mApp.getActiveConnections()) {
try {
conn.logout();
} catch (RemoteException e) {
}
}
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Log.e(ImApp.LOG_TAG, "bad menuInfo", e);
return;
}
Cursor providerCursor = (Cursor) getListAdapter().getItem(info.position);
menu.setHeaderTitle(providerCursor.getString(PROVIDER_FULLNAME_COLUMN));
if (providerCursor.isNull(ACTIVE_ACCOUNT_ID_COLUMN)) {
menu.add(0, ID_ADD_ACCOUNT, 0, R.string.menu_add_account);
return;
}
long providerId = providerCursor.getLong(PROVIDER_ID_COLUMN);
long accountId = providerCursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN);
boolean isLoggingIn = isSigningIn(accountId);
boolean isLoggedIn = isSignedIn(accountId);
if (!isLoggedIn) {
menu.add(0, ID_SIGN_IN, 0, R.string.sign_in)
.setIcon(R.drawable.ic_menu_login);
} else {
BrandingResources brandingRes = mApp.getBrandingResource(providerId);
menu.add(0, ID_VIEW_CONTACT_LIST, 0,
brandingRes.getString(BrandingResourceIDs.STRING_MENU_CONTACT_LIST));
menu.add(0, ID_SIGN_OUT, 0, R.string.menu_sign_out)
.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
}
if (!isLoggingIn && !isLoggedIn) {
menu.add(0, ID_EDIT_ACCOUNT, 0, R.string.menu_edit_account)
.setIcon(android.R.drawable.ic_menu_edit);
menu.add(0, ID_REMOVE_ACCOUNT, 0, R.string.menu_remove_account)
.setIcon(android.R.drawable.ic_menu_delete);
}
// always add a settings menu item
menu.add(0, ID_SETTINGS, 0, R.string.menu_settings);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.e(ImApp.LOG_TAG, "bad menuInfo", e);
return false;
}
int position = info.position;
long providerId = info.id;
switch (item.getItemId()) {
case ID_EDIT_ACCOUNT:
{
Cursor c = (Cursor)mAdapter.getItem(position);
if (c != null) {
Intent i = new Intent(ChooseAccountActivity.this, AccountActivity.class);
i.setAction(Intent.ACTION_EDIT);
i.setData(ContentUris.withAppendedId(Im.Account.CONTENT_URI,
c.getLong(ACTIVE_ACCOUNT_ID_COLUMN)));
c.close();
startActivity(i);
}
return true;
}
case ID_REMOVE_ACCOUNT:
{
Cursor c = (Cursor)mAdapter.getItem(position);
if (c != null) {
long accountId = c.getLong(ACTIVE_ACCOUNT_ID_COLUMN);
Uri accountUri = ContentUris.withAppendedId(Im.Account.CONTENT_URI, accountId);
getContentResolver().delete(accountUri, null, null);
// Requery the cursor to force refreshing screen
c.requery();
}
return true;
}
case ID_VIEW_CONTACT_LIST:
case ID_ADD_ACCOUNT:
case ID_SIGN_IN:
Intent i = mAdapter.intentForPosition(position);
if (i != null) {
startActivity(i);
}
return true;
case ID_SIGN_OUT:
// TODO: progress bar
IImConnection conn = mApp.getConnection(providerId);
if (conn != null) {
try {
conn.logout();
} catch (RemoteException e) {
}
}
return true;
case ID_SETTINGS:
Intent settingsIntent = mAdapter.settingsIntentForPosition(position);
if (settingsIntent != null) {
startActivity(settingsIntent);
}
return true;
}
return false;
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
startActivityAtPosition(position);
}
void startActivityAtPosition(int position) {
Intent i = mAdapter.intentForPosition(position);
if (i != null) {
startActivity(i);
}
}
static void log(String msg) {
Log.d(ImApp.LOG_TAG, "[ChooseAccount]" + msg);
}
@Override
protected void onRestart() {
super.onRestart();
mApp.startImServiceIfNeed();
mApp.registerForConnEvents(mHandler);
}
@Override
protected void onStop() {
super.onStop();
mApp.unregisterForConnEvents(mHandler);
mApp.unregisterForBroadcastEvent(ImApp.EVENT_SERVICE_CONNECTED, mHandler);
mApp.stopImServiceIfInactive();
}
boolean isSigningIn(long accountId) {
IImConnection conn = mApp.getConnectionByAccount(accountId);
try {
return (conn == null) ? false : (conn.getState() == ImConnection.LOGGING_IN);
} catch (RemoteException e) {
return false;
}
}
boolean isSignedIn(long accountId) {
try {
IImConnection conn = mApp.getConnectionByAccount(accountId);
if (conn == null) {
return false;
}
int state = conn.getState();
return state == ImConnection.LOGGED_IN || state == ImConnection.SUSPENDED;
} catch (RemoteException e) {
return false;
}
}
private final class MyHandler extends SimpleAlertHandler {
public MyHandler() {
super(ChooseAccountActivity.this);
}
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case ImApp.EVENT_CONNECTION_DISCONNECTED:
promptDisconnectedEvent(msg);
// fall through
case ImApp.EVENT_SERVICE_CONNECTED:
case ImApp.EVENT_CONNECTION_CREATED:
case ImApp.EVENT_CONNECTION_LOGGING_IN:
case ImApp.EVENT_CONNECTION_LOGGED_IN:
getListView().invalidateViews();
return;
}
super.handleMessage(msg);
}
}
private class ProviderListItemFactory implements LayoutInflater.Factory {
public View onCreateView(String name, Context context, AttributeSet attrs) {
if (name != null && name.equals(ProviderListItem.class.getName())) {
return new ProviderListItem(context, ChooseAccountActivity.this);
}
return null;
}
}
private final class ProviderAdapter extends CursorAdapter {
private LayoutInflater mInflater;
public ProviderAdapter(Context context, Cursor c) {
super(context, c);
mInflater = LayoutInflater.from(context).cloneInContext(context);
mInflater.setFactory(new ProviderListItemFactory());
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// create a custom view, so we can manage it ourselves. Mainly, we want to
// initialize the widget views (by calling getViewById()) in newView() instead of in
// bindView(), which can be called more often.
ProviderListItem view = (ProviderListItem) mInflater.inflate(
R.layout.account_view, parent, false);
view.init(cursor);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
((ProviderListItem) view).bindView(cursor);
}
public Intent intentForPosition(int position) {
Intent intent = null;
if (mCursor == null) {
return null;
}
mCursor.moveToPosition(position);
long providerId = mCursor.getLong(PROVIDER_ID_COLUMN);
if (mCursor.isNull(ACTIVE_ACCOUNT_ID_COLUMN)) {
// add account
intent = new Intent(ChooseAccountActivity.this, AccountActivity.class);
intent.setAction(Intent.ACTION_INSERT);
intent.setData(ContentUris.withAppendedId(Im.Provider.CONTENT_URI, providerId));
} else {
long accountId = mCursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN);
IImConnection conn = mApp.getConnection(providerId);
int state = getConnState(conn);
if (state < ImConnection.LOGGED_IN ) {
Uri accountUri = ContentUris.withAppendedId(Im.Account.CONTENT_URI, accountId);
if (mCursor.isNull(ACTIVE_ACCOUNT_PW_COLUMN)) {
// no password, edit the account
intent = new Intent(ChooseAccountActivity.this, AccountActivity.class);
intent.setAction(Intent.ACTION_EDIT);
intent.setData(accountUri);
} else {
// intent for sign in
intent = new Intent(ChooseAccountActivity.this, SigningInActivity.class);
intent.setData(accountUri);
}
} else if (state == ImConnection.LOGGED_IN || state == ImConnection.SUSPENDED) {
intent = new Intent(Intent.ACTION_VIEW);
intent.setClass(ChooseAccountActivity.this, ContactListActivity.class);
intent.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, accountId);
}
}
return intent;
}
public Intent settingsIntentForPosition(int position) {
Intent intent = null;
if (mCursor == null) {
return null;
}
mCursor.moveToPosition(position);
Long providerId = mCursor.getLong(PROVIDER_ID_COLUMN);
intent = new Intent(ChooseAccountActivity.this, SettingActivity.class);
intent.putExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, providerId);
return intent;
}
private int getConnState(IImConnection conn) {
try {
return conn == null ? ImConnection.DISCONNECTED : conn.getState();
} catch (RemoteException e) {
return ImConnection.DISCONNECTED;
}
}
}
}
| [
"initial-contribution@android.com"
] | initial-contribution@android.com |
15fb5e3a95ea44d5093d975f6df7fe26e069df39 | 6a70267cac0116f1eff942693c9880547d4999ad | /StoreProject/app/src/main/java/Adapter/AdapterRecyclerView2.java | 4ac9ba1fcc71ed7fbc9cd81b6a8c273f519b1502 | [] | no_license | ezgezl752000/fast-food | 85670c2679a62b581f8745ff2c8c66d1d499b19f | 7d107eee78e02a7c804283b6e80d01348015a61a | refs/heads/main | 2023-08-23T12:42:32.889135 | 2021-10-06T03:08:33 | 2021-10-06T03:08:33 | 414,027,947 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,873 | java | package Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.storeproject.R;
import com.squareup.picasso.Picasso;
import java.util.List;
import Activity.HomePage;
import Data.Food;
public class AdapterRecyclerView2 extends RecyclerView.Adapter<AdapterRecyclerView2.ViewHolder> {
List<Food> foodList;
List<String> mKeys;
Context _context;
private IProductSelectionListener iproductSelectionListener;
public AdapterRecyclerView2(List<Food> foodList,Context context, IProductSelectionListener productSelectionListener, List<String> mKeys) {
this.foodList = foodList;
this._context = context;
this.iproductSelectionListener = productSelectionListener;
this.mKeys = mKeys;
}
@NonNull
@Override
public AdapterRecyclerView2.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.items_recyclerview_square,parent,false);
ViewHolder viewHolder = new ViewHolder(view, iproductSelectionListener);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull AdapterRecyclerView2.ViewHolder holder, int position) {
Food food = foodList.get(position);
holder.key = mKeys.get(position);
holder.tvFood.setText(food.getName());
holder.tvRating.setText(food.getRating());
Picasso.with(this._context).load(food.getUrl()).into(holder.imageView);
}
@Override
public int getItemCount() {
return foodList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView tvFood,tvRating;
IProductSelectionListener selectionListener;
ImageView imageView;
String key;
public ViewHolder(View itemView, IProductSelectionListener selectionListener) {
super(itemView);
tvFood= itemView.findViewById(R.id.tvRyclerViewFoodName);
imageView = itemView.findViewById(R.id.imgRyclerViewFood);
tvRating = itemView.findViewById(R.id.tvRatingStarFood);
this.selectionListener = selectionListener;
this.key = key;
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
selectionListener.onProductSelected(getAdapterPosition(), foodList.get(getAdapterPosition()));
}
}
public interface IProductSelectionListener {
void onProductSelected(int position, Food food);
}
}
| [
"53049553+ezgezl752000@users.noreply.github.com"
] | 53049553+ezgezl752000@users.noreply.github.com |
b7ce8334599bfe35e1fc05625a753b4347add311 | 2f92dfff9b9929b64e645fdc254815d06bf2b8d2 | /src/test/test/lee/codetest/code_686__Repeated_String_Match/CodeTest.java | cdc2e417da8401f29e56d7ff336feaf53b56a726 | [
"MIT"
] | permissive | code543/leetcodequestions | fc5036d63e4c3e1b622fe73552fb33c039e63fb0 | 44cbfe6718ada04807b6600a5d62b9f0016d4ab2 | refs/heads/master | 2020-04-05T19:43:15.530768 | 2018-12-07T04:09:07 | 2018-12-07T04:09:07 | 157,147,529 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 851 | java |
package lee.codetest.code_686__Repeated_String_Match;
import org.junit.Test;
/**
testcase:"abcd"
"cdabcdab"
*/
public class CodeTest
{
@Test
public void testSolution() throws Exception
{
//new Solution()
lee.code.code_686__Repeated_String_Match.C686_MainClass.main(null);;
}
}
/**
*
*
* 686.Repeated String Match
*
* difficulty: Easy
* @see https://leetcode.com/problems/repeated-string-match/description/
* @see description_686.md
* @Similiar Topics
* -->String https://leetcode.com//tag/string
* @Similiar Problems
* -->Repeated Substring Pattern https://leetcode.com//problems/repeated-substring-pattern
* Run solution from Unit Test:
* @see lee.codetest.code_686__Repeated_String_Match.CodeTest
* Run solution from Main Judge Class:
* @see lee.code.code_686__Repeated_String_Match.C686_MainClass
*
*/
| [
"santoschenwbu@gmail.com"
] | santoschenwbu@gmail.com |
fb51c4237ad0ea851f4ce88cc852dd6c55fad473 | 71c12e8d46433bbec941fd167d83afa461459d38 | /app/src/main/java/com/example/a13834598889/lovepets/Fragments_Mine/Fragment_friends.java | 3c6fe75750b20f617cf018c2a6c2188043cc1081 | [] | no_license | xieyipeng/pet | 1456b6a5aebdaaa38255512b2828ba418ad56989 | ade53dd046e799b5475e790bde3af5c3d5a7e749 | refs/heads/master | 2020-03-25T01:16:05.781376 | 2018-08-05T11:10:39 | 2018-08-05T11:10:39 | 143,228,800 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,284 | java | package com.example.a13834598889.lovepets.Fragments_Mine;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.a13834598889.lovepets.JavaBean.DianZan;
import com.example.a13834598889.lovepets.JavaBean.User;
import com.example.a13834598889.lovepets.R;
import java.util.ArrayList;
import java.util.List;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by 13834598889 on 2018/5/3.
*/
public class Fragment_friends extends Fragment implements View.OnClickListener{
private RecyclerView recyclerView_friends;
private ContactsAdapter adapter;
private List<User> users = new ArrayList<>();
private CircleImageView circleImageView;
private ImageView imageView_back;
private View view;
private String picture_path;
private Integer max = 1;
private User administor = new User();
public static Fragment_friends newInstance(String path){
Fragment_friends fragment_friends = new Fragment_friends();
fragment_friends.picture_path = path;
return fragment_friends;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_friends,container,false);
administor = BmobUser.getCurrentUser(User.class);
preView();
return view;
}
public class ContactsHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView text_view_ni_cheng;
private TextView text_view_dian_zan_shu;
private TextView textView_qianming;
private CircleImageView imageView_TouXiang;
private ImageView imageView_dianzan;
private LinearLayout layout_caozuo;
private User user_friend;
private DianZan dianZan_friend;
private Integer dianzanshu_1 = 0;
private String path = "";
public ContactsHolder (View view){
super(view);
text_view_dian_zan_shu=(TextView)view.findViewById(R.id.dian_zan_shu_text_view);
text_view_ni_cheng=(TextView)view.findViewById(R.id.ni_cheng_text_view);
textView_qianming=(TextView)view.findViewById(R.id.ge_xing_qian_ming_text_view);
imageView_TouXiang=(CircleImageView)view.findViewById(R.id.tou_xiang_image_view);
imageView_dianzan = (ImageView)view.findViewById(R.id.dian_zan_button);
layout_caozuo = (LinearLayout)view.findViewById(R.id.layout_caozuo_friend);
imageView_dianzan.setOnClickListener(this);
layout_caozuo.setOnClickListener(this);
}
public void bindView(User user){
this.user_friend = user;
text_view_ni_cheng.setText(user.getNickName());
textView_qianming.setText(user.getSignature());
if(user.getPicture()!=null){
downloadFile_picture(user.getPicture(),imageView_TouXiang);
}
BmobQuery<DianZan> query=new BmobQuery<>();
query.getObject(user.getDianZan().getObjectId(), new QueryListener<DianZan>() {
@Override
public void done(DianZan dianZan, cn.bmob.v3.exception.BmobException e) {
if (e==null){
dianZan_friend = dianZan;
final int a=dianZan.getmDianZanShu().intValue();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
text_view_dian_zan_shu.setText(a+"");
}
});
}else{
Toast.makeText(getActivity(),""+e.getMessage()+e.getErrorCode(),Toast.LENGTH_LONG).show();
}
}
});
}
private void downloadFile_picture(BmobFile file, final CircleImageView view) {
file.download(new DownloadFileListener() {
@Override
public void done(final String s, cn.bmob.v3.exception.BmobException e) {
if(e==null){
if(s!=null){
try{
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try{
path = s;
Glide.with(getActivity().getApplication()).load(s).into(view);
}catch (Exception c){
c.printStackTrace();
}
}
});
}catch (Exception c){
c.printStackTrace();
}
}else {
}
}
}
@Override
public void onProgress(Integer integer, long l) {
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.dian_zan_button:
dianzanshu_1++;
if(max < dianzanshu_1 ){
Toast.makeText(getActivity(),"每次只能给此帖子点赞一次哦 !",Toast.LENGTH_SHORT).show();
break;
}
actionDaianzanCartoon(imageView_dianzan);
dianZan_friend.setmDianZanShu(dianZan_friend.getmDianZanShu()+1);
dianZan_friend.update(dianZan_friend.getObjectId(), new UpdateListener() {
@Override
public void done(cn.bmob.v3.exception.BmobException e) {
if(e==null){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try{
text_view_dian_zan_shu.setText(""+dianZan_friend.getmDianZanShu());
}catch (Exception c){
c.printStackTrace();
}
}
});
}else{
}
}
});
actionDaianzanCartoon(imageView_dianzan);
break;
case R.id.layout_caozuo_friend:
FragmentManager fragmentManager;
fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out)
.add(R.id.fragment_container,Fragment_im.newInstance(user_friend),"im_fragment")
.commit();
break;
}
}
private void actionDaianzanCartoon(View imageView){
ObjectAnimator button_dianzan0=ObjectAnimator.ofFloat(imageView,"scaleX",1f,1.7f,1f);
ObjectAnimator button_dianzan1=ObjectAnimator.ofFloat(imageView,"scaleY",1f,1.7f,1f);
ObjectAnimator button_dianzan2=ObjectAnimator.ofFloat(imageView,"rotation",0f,360f);
AnimatorSet animatorSet=new AnimatorSet();
animatorSet.setDuration(1000)
.play(button_dianzan0)
.with(button_dianzan1)
.with(button_dianzan2);
animatorSet.start();
}
}
public class ContactsAdapter extends RecyclerView.Adapter<ContactsHolder> {
private List<User> users;
public ContactsAdapter(List<User> users) {
this.users = users;
}
@Override
public ContactsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.friend_item, parent, false);
return new ContactsHolder(view);
}
@Override
public void onBindViewHolder(ContactsHolder holder, int position) {
User user = users.get(position);
holder.bindView(user);
}
@Override
public int getItemCount() {
return users.size();
}
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.fragment_friends_back:
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
if(fragmentManager.findFragmentByTag("friends_fragment") !=null){
fragmentManager.beginTransaction()
.hide(fragmentManager.findFragmentByTag("friends_fragment"))
.remove(fragmentManager.findFragmentByTag("friends_fragment"))
.show(fragmentManager.findFragmentByTag("fragment_account"))
.commit();
}
break;
default:
break;
}
}
//以下为测试代码
private void addData(){
BmobQuery<User> query = new BmobQuery<User>();
//likes是Post表中的字段,用来存储所有喜欢该帖子的用户
query.addWhereRelatedTo("friends", new BmobPointer(administor));
query.findObjects(new FindListener<User>() {
@Override
public void done(List<User> list, cn.bmob.v3.exception.BmobException e) {
if(e==null){
Toast.makeText(getActivity(),"您共有 "+list.size()+" 个朋友",Toast.LENGTH_LONG).show();
adapter.users = list;
adapter.notifyDataSetChanged();
}
}
});
}
private void preView(){
circleImageView = (CircleImageView)view.findViewById(R.id.circleImageView_mine88);
if(picture_path.equals("")){
Glide.with(getActivity().getApplication()).load(R.drawable.test_touxiang3).into(circleImageView);
}else{
Glide.with(getActivity().getApplication()).load(picture_path).into(circleImageView);
}
recyclerView_friends = (RecyclerView) view.findViewById(R.id.contacts_list_recycler_view);
imageView_back=(ImageView)view.findViewById(R.id.fragment_friends_back);
imageView_back.setOnClickListener(this);
addData();
adapter = new ContactsAdapter(users);
LinearLayoutManager layoutManager=new LinearLayoutManager(getActivity());
recyclerView_friends.setLayoutManager(layoutManager);
recyclerView_friends.setAdapter(adapter);
}
}
| [
"32957035+xieyipeng@users.noreply.github.com"
] | 32957035+xieyipeng@users.noreply.github.com |
7a8ef4b0222aeccd4d4a558d2eecdbf5adf52016 | 8ae100d7a3b27f23af28ca0e3373c76c057ca97e | /src/main/java/com/crxl/xllxj/module/login/sms/SmsLoginService.java | 20f176d0198ee7afffff57275c7571a8dd7909fc | [] | no_license | yuzelong620/xyxSocket | 592e9b75ff7d3c3a283b16c4b58e970ac782f5a2 | 375a769ca1c5a1a97f56e480ee5a771677a02266 | refs/heads/master | 2022-07-14T14:13:15.691725 | 2019-12-20T09:47:01 | 2019-12-20T09:47:01 | 229,236,317 | 0 | 0 | null | 2022-06-25T07:29:39 | 2019-12-20T09:46:12 | Java | UTF-8 | Java | false | false | 2,586 | java | package com.crxl.xllxj.module.login.sms;
import com.crxl.xllxj.module.common.enums.EnumConstant.IdentityId;
import com.crxl.xllxj.module.core.message.RequestMsg;
import com.crxl.xllxj.module.core.message.ResponseMsg;
import com.crxl.xllxj.module.core.service.BaseService;
import com.crxl.xllxj.module.core.thread.TaskManager;
import com.crxl.xllxj.module.login.bean.SmsLogin;
import com.crxl.xllxj.module.user.entity.UserEntity;
import com.crxl.xllxj.module.util.IdUtil;
/**
* 短信登录
*
* @author zxd
*
*/
public class SmsLoginService extends BaseService {
public void sendVerifyCode(String mobile, String areaCode) throws Exception {
smsService.sendVerifyCode(mobile, areaCode);
}
public void sendVerifyCode(RequestMsg req) {
SmsLogin smsLogin = req.getBody(SmsLogin.class);
String mobile = smsLogin.getMobile();
String areaCode = smsLogin.getAreaCode();
if (mobile == null || "".equals(mobile)) {
req. sendMessage(ResponseMsg.createInfoMessage("手机号不能为空。"));
return;
}
if (smsService.sendVerifyCode(mobile, areaCode)) {
req. sendMessage(ResponseMsg.createInfoMessage("发送成功。"));
} else {
req. sendMessage(ResponseMsg.createInfoMessage("失败,请稍后重试。"));
}
}
/**
* @param req
*/
public void smsLogin(RequestMsg req) {
SmsLogin smsLogin = req.getBody(SmsLogin.class);
String verifyCode = smsLogin.getVerifyCode();
String mobile = smsLogin.getMobile();
String areaCode = smsLogin.getAreaCode();
if (mobile == null || "".equals(mobile)) {
req. sendMessage(ResponseMsg.createInfoMessage("手机号不能为空。"));
return;
}
if (verifyCode == null || "".equals(verifyCode)) {
req. sendMessage( ResponseMsg.createInfoMessage("验证码不能为空。"));
return;
}
if (!smsService.validateVerifyCode(mobile, areaCode, verifyCode)) {
req. sendMessage( ResponseMsg.createInfoMessage("验证失败。"));
return;
}
UserEntity entity = userDao.findByPhone(mobile);
String nick = null;
if (entity == null) {
long identityId = identityDao.nextId(IdentityId.user);
if (nick == null) {
nick = loginService.createNick(identityId);
}
entity = new UserEntity(IdUtil.randomUUID(), smsLogin.getChannelId(), mobile, identityId);
// userDao.save(entity);
TaskManager.instance.putSaveTask(req.getChannel(), userDao.getAsynSaveTask(entity));
}
// SessionBean sessionBean=
// sessionService.createById(entity.getId(),req.getChannel(),nick);
// loginService.loginBySession(req.getChannel(), req.getCommand(),
// sessionBean);
}
} | [
"382981935@qq.com"
] | 382981935@qq.com |
34bb82a65e2c186c850dc09411e0feed336e1f95 | 046c765d9dd4c10a6bd46149b631d841b7dfa626 | /src/bean/PrototypeData.java | 25da5523fb631b7ed9ff08fe6aff26f6fb20c49e | [] | no_license | Alfystar/ISPW_Project | f4a3237a95e3ee22b41957782a99684f8bc35f89 | 217edd2a33310002f5c92090dffd501f87f8cb02 | refs/heads/master | 2020-04-17T22:10:52.319233 | 2019-02-18T11:59:13 | 2019-02-18T11:59:13 | 166,983,639 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 88 | java | package bean;
public interface PrototypeData extends Cloneable{
Object clone();
}
| [
"alfystar1701@gmail.com"
] | alfystar1701@gmail.com |
dea2d77966e05cef124e96aef1089a08bbe92869 | 9e1b64c34e6f7aa5354001b0c87d9f4048e44c91 | /common_lib/src/main/java/com/cdcompany/common_lib/utils/StringUtils.java | 9adf48d58c77cdba4f255be261bed9a2dc3414d0 | [] | no_license | wangjianchi/WeCooking | 66dfb290b64657f857183975ebd0e59ef90024b7 | f5091fa25cd182e56c71c8438e8785b546a1eefc | refs/heads/master | 2021-01-12T15:41:17.686338 | 2017-03-15T10:09:00 | 2017-03-15T10:09:00 | 71,851,806 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 16,156 | java | package com.cdcompany.common_lib.utils;
import android.text.TextUtils;
import android.text.format.Time;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
/**
* Created by wukewei on 16/7/25.
*/
public class StringUtils {
/**
* 空字符串常量
*/
public static final String EMPTY = "";
/**
* "不可用"字符串常量
*/
public static final String NOT_AVAILABLE = "N/A";
private static final int CACHE_SIZE = 4096;
/**
* 创建指定格式的时间格式化对象
*
* @param pattern 时间格式,形如"yyyy-MM-dd HH-mm-ss.SSS"
* @return Format 时间格式化对象
*/
public static SimpleDateFormat createDataFormat(String pattern) {
return new SimpleDateFormat(pattern);
}
/**
* 将s中字符用delimiter分割连接起来
*
* @param delimiter 分隔符
* @param segments 被连接的数据
* @return 返回连接号的字符串
* @see StringUtils#join(String, Object[])
*/
public static String join(String delimiter, Collection<?> segments) {
StringBuilder stringBuilder = new StringBuilder();
if (segments != null) {
appendCollectionObjectToStringBuilder(stringBuilder, delimiter, segments);
}
String outString = stringBuilder.toString();
if (outString.endsWith(delimiter)) {
return outString.substring(0, outString.length() - delimiter.length());
}
return outString;
}
/**
* 将对象链接成一个字符串,使用delimiter传入的字符串分割,
* <p><b>注意:</b>如果前一个片段为字符串且以delimiter结束或者为空(null获取为""),将不会重复添加此字符串</p>
* <p>字符串末尾不会自动添加delimiter字符串</p>
* <p>如果没有传入参数,返回一个<b>空字符串</b></p>
*
* @param delimiter 分割字符串
* @param segments 所有传入的部分
* @return 连接完毕后的字符串
*/
public static String join(String delimiter, Object... segments) {
StringBuilder stringBuilder = new StringBuilder();
if (segments != null) {
int size = segments.length;
if (size > 0) {
for (Object segment : segments) {
appendObjectToStringBuilder(stringBuilder, delimiter, segment);
}
}
}
String outString = stringBuilder.toString();
if (outString.endsWith(delimiter)) {
return outString.substring(0, outString.length() - delimiter.length());
}
return outString;
}
private static void appendArrayObjectToStringBuilder(StringBuilder stringBuilder, String delimiter, Object array) {
int length = Array.getLength(array);
for (int i = 0; i < length; i++) {
appendObjectToStringBuilder(stringBuilder, delimiter, Array.get(array, i));
}
}
private static void appendCollectionObjectToStringBuilder(StringBuilder stringBuilder, String delimiter, Collection<?> collection) {
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
appendObjectToStringBuilder(stringBuilder, delimiter, iterator.next());
}
}
private static void appendObjectToStringBuilder(StringBuilder stringBuilder, String delimiter, Object object) {
if (object == null) {
return;
}
if (object.getClass().isArray()) {
appendArrayObjectToStringBuilder(stringBuilder, delimiter, object);
} else if (object instanceof Collection) {
appendCollectionObjectToStringBuilder(stringBuilder, delimiter, (Collection) object);
} else {
String objectString = object.toString();
stringBuilder.append(objectString);
if (!isEmpty(objectString) && !objectString.endsWith(delimiter)) {
stringBuilder.append(delimiter);
}
}
}
/**
* 测试传入的字符串是否为空
*
* @param string 需要测试的字符串
* @return 如果字符串为空(包括不为空但其中为空白字符串的情况)返回true,否则返回false
*/
public static boolean isEmpty(String string) {
return string == null || string.trim().length() == 0;
}
/**
* 测试传入的字符串是否为空
*
* @param string 需要测试的字符串
* @return 如果字符串为空(包括不为空但其中为空白字符串的情况)返回false,否则返回true
*/
public static boolean isNotEmpty(String string) {
return string != null && string.trim().length() > 0;
}
/**
* 传入的字符串是否相等
*
* @param a a字符串
* @param b b字符串
* @return 如果字符串相等(值比较)返回true,否则返回false
*/
public static boolean equal(String a, String b) {
return a == b || (a != null && b != null && a.length() == b.length() && a.equals(b));
}
/**
* 将字符串用分隔符分割为long数组
* <p><b>只支持10进制的数值转换</b></p>
* <p><b>如果格式错误,将抛出NumberFormatException</b></p>
*
* @param string 字符串
* @param delimiter 分隔符
* @return 分割后的long数组.
*/
public static long[] splitToLongArray(String string, String delimiter) {
List<String> stringList = splitToStringList(string, delimiter);
long[] longArray = new long[stringList.size()];
int i = 0;
for (String str : stringList) {
longArray[i++] = Long.parseLong(str);
}
return longArray;
}
/**
* 将字符串用分隔符分割为Long列表
* <p><b>只支持10进制的数值转换</b></p>
* <p><b>如果格式错误,将抛出NumberFormatException</b></p>
*
* @param string 字符串
* @param delimiter 分隔符
* @return 分割后的Long列表.
*/
public static List<Long> splitToLongList(String string, String delimiter) {
List<String> stringList = splitToStringList(string, delimiter);
List<Long> longList = new ArrayList<Long>(stringList.size());
for (String str : stringList) {
longList.add(Long.parseLong(str));
}
return longList;
}
/**
* 将字符串用分隔符分割为字符串数组
*
* @param string 字符串
* @param delimiter 分隔符
* @return 分割后的字符串数组.
*/
public static String[] splitToStringArray(String string, String delimiter) {
List<String> stringList = splitToStringList(string, delimiter);
return stringList.toArray(new String[stringList.size()]);
}
/**
* 将字符串用分隔符分割为字符串列表
*
* @param string 字符串
* @param delimiter 分隔符
* @return 分割后的字符串数组.
*/
public static List<String> splitToStringList(String string, String delimiter) {
List<String> stringList = new ArrayList<String>();
if (!isEmpty(string)) {
int length = string.length();
int pos = 0;
do {
int end = string.indexOf(delimiter, pos);
if (end == -1) {
end = length;
}
stringList.add(string.substring(pos, end));
pos = end + 1; // skip the delimiter
} while (pos < length);
}
return stringList;
}
/**
* InputSteam 转换到 String,会把输入流关闭
*
* @param inputStream 输入流
* @return String 如果有异常则返回null
*/
public static String stringFromInputStream(InputStream inputStream) {
try {
byte[] readBuffer = new byte[CACHE_SIZE];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while (true) {
int readLen = inputStream.read(readBuffer, 0, CACHE_SIZE);
if (readLen <= 0) {
break;
}
byteArrayOutputStream.write(readBuffer, 0, readLen);
}
return byteArrayOutputStream.toString("UTF-8");
} catch (Exception e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* 测试是否为有效的注册电子邮件格式
*
* @param string 内容
* @return true if yes
*/
public static boolean isEmailFormat(String string) {
if (StringUtils.isEmpty(string)) {
return false;
}
String emailFormat = "^([a-zA-Z0-9_\\.-]+)@([\\da-zA-Z\\.-]+)\\.([a-zA-Z\\.]{1,16})$";
return Pattern.matches(emailFormat, string);
}
/**
* 测试是否为有效的登录电子邮件格式
*
* @param string 内容
* @return true if yes
*/
public static boolean isLoginEmailFormat(String string) {
if (StringUtils.isEmpty(string)) {
return false;
}
String emailFormat = "^\\s*\\w+(?:\\.?[\\w-]+\\.?)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
return Pattern.matches(emailFormat, string);
}
/**
* 是否在长度范围之类
*
* @param string 内容
* @param begin 最小长度(inclusive)
* @param end 最大长度(inclusive)
* @return 字符串长度在begin和end之内返回true,否则返回false。<p><b>输入字符串为null时,返回false</b></p>
*/
public static boolean lengthInRange(String string, int begin, int end) {
return string != null && string.length() >= begin && string.length() <= end;
}
/**
* 去除文件名中的无效字符
*
* @param srcStr srcStr
* @return 去除文件名后的字符
*/
public static String validateFilePath(String srcStr) {
return StringUtils.isEmpty(srcStr) ? srcStr : srcStr.replaceAll("[\\\\/:\"*?<>|]+", "_");
}
/**
* 获取字串字符长度,规则如下:
* 中文一个字长度为2,英文、字符长度为1
* 如:"我c"长度为3
*
* @param str str
* @return 字符串长度
*/
public static int getCharsLength(String str) {
int length = 0;
try {
if (str == null) {
return 0;
}
str = str.replaceAll("[^\\x00-\\xff]", "**");
length += str.length();
} catch (Exception e) {
e.printStackTrace();
}
return length;
}
/**
* 获取字串的文字个数,规则如下:
* 汉字为1,英文、字符算0.5个字
* 如:"我"字数为1,"我k"字数为2,"我ko"字数也为2
*
* @param str str
* @return 字符串长度
*/
public static int getWordCount(String str) {
int length = getCharsLength(str);
return length % 2 + length / 2;
}
/**
* 得到毫秒数对应的时间串, 格式 "2013-07-04 12:44:53.098" <br>
* <br>
* 这个方法使用Android的Time类实现,用以替代java.util.Calender<br>
* 使用同余计算毫秒数,在某些ROM上,JDK被替换的算法不能计算毫秒数 (e.g. 华为荣耀)
*
* @param time 毫秒数
* @return 时间字符串
*/
public static String getTimeStr(long time) {
long ms = time % 1000;
Time timeObj = new Time();
timeObj.set(time);
StringBuilder builder = new StringBuilder();
builder.append(timeObj.format("%Y-%m-%d %H:%M:%S")).append('.');
if (ms < 10) {
builder.append("00");
} else if (ms < 100) {
builder.append('0');
}
builder.append(ms);
return builder.toString();
}
/**
* 比较两个字符串,是否prefix字符串是source字符串的前缀,忽略大小写差别
*
* @param source 查找的字符串..
* @param prefix 前缀.
* @return {@code true} 如果指定字符串是这个字符串的前缀, 否则{@code false}
*/
public static boolean startsWithIgnoreCase(String source, String prefix) {
if (source == prefix) {
return true;
}
if (source == null || prefix == null) {
return false;
}
return source.regionMatches(true, 0, prefix, 0, prefix.length());
}
/**
* 比较两个字符串,是否prefix字符串是source字符串的后缀,忽略大小写差别
*
* @param source 查找的字符串..
* @param suffix 后缀.
* @return {@code true} 如果指定字符串是这个字符串的后缀, 否则{@code false}
*/
public static boolean endsWithIgnoreCase(String source, String suffix) {
if (source == suffix) {
return true;
}
if (source == null || suffix == null) {
return false;
}
int startIndex = source.length() - suffix.length();
if (startIndex < 0) {
return false;
}
return source.regionMatches(true, startIndex, suffix, 0, suffix.length());
}
/**
* 使用数组中的键值对替换字符串. 算法将每个在字符串中找的的key替换成对应value.
* 数组的构造类似 {key1, value1, key2, value2...}.
*
* @param source source字符串.
* @param keyValueArray 包含键值对的数组.
* @return 被替换了的字符串,如果没有找到任意key则返回source.
*/
public static String replaceWith(String source, Object... keyValueArray) {
if (TextUtils.isEmpty(source)) {
return source;
}
if (keyValueArray.length % 2 != 0) {
throw new IllegalArgumentException("key value array not valid");
}
StringBuilder sb = null;
for (int i = 0; i < keyValueArray.length; i += 2) {
String key = String.valueOf(keyValueArray[i]);
String value = String.valueOf(keyValueArray[i + 1]);
int index = sb != null ? sb.indexOf(key) : source.indexOf(key);
while (index >= 0) {
if (sb == null) {
sb = new StringBuilder(source);
}
sb.replace(index, index + key.length(), value);
index = sb.indexOf(key, index + value.length());
}
}
return sb != null ? sb.toString() : source;
}
/**
* 使用数组中的键值对替换StringBuilder. 算法将每个在字符串中找的的key替换成对应value.
* 数组的构造类似 {key1, value1, key2, value2...}.
*
* @param source source StringBuilder.
* @param keyValueArray 包含键值对的数组.
* @return 被处理过的StringBuilder.
*/
public static StringBuilder replaceWith(StringBuilder source, Object... keyValueArray) {
if (TextUtils.isEmpty(source)) {
return source;
}
if (keyValueArray.length % 2 != 0) {
throw new IllegalArgumentException("key value array not valid");
}
for (int i = 0; i < keyValueArray.length; i += 2) {
String key = String.valueOf(keyValueArray[i]);
String value = String.valueOf(keyValueArray[i + 1]);
int index = source.indexOf(key);
while (index >= 0) {
source.replace(index, index + key.length(), value);
index = source.indexOf(key, index + value.length());
}
}
return source;
}
}
| [
"wlwangjc@foxmail.com"
] | wlwangjc@foxmail.com |
b29ab5698245fcfce0618f0146ded1cbbc7c4cf1 | f27cb821dd601554bc8f9c112d9a55f32421b71b | /integration/spring-data/base-3.1/src/main/java/com/blazebit/persistence/spring/data/repository/config/BlazeRepositoriesRegistrar.java | 4e565168370ddc9ecee4c6963f57acbbfdc53956 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Blazebit/blaze-persistence | 94f7e75154e80ce777a61eb3d436135ad6d7a497 | a9b1b6efdd7ae388e7624adc601a47d97609fdaa | refs/heads/main | 2023-08-31T22:41:17.134370 | 2023-07-14T15:31:39 | 2023-07-17T14:52:26 | 21,765,334 | 1,475 | 92 | Apache-2.0 | 2023-08-07T18:10:38 | 2014-07-12T11:08:47 | Java | UTF-8 | Java | false | false | 1,318 | java | /*
* Copyright 2014 - 2023 Blazebit.
*
* 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.blazebit.persistence.spring.data.repository.config;
import org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport;
import org.springframework.data.repository.config.RepositoryConfigurationExtension;
import java.lang.annotation.Annotation;
/**
* @author Christian Beikov
* @author Eugen Mayer
* @since 1.6.9
*/
public class BlazeRepositoriesRegistrar extends RepositoryBeanDefinitionRegistrarSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {
return EnableBlazeRepositories.class;
}
@Override
protected RepositoryConfigurationExtension getExtension() {
return new BlazeRepositoryConfigExtension();
}
}
| [
"christian.beikov@gmail.com"
] | christian.beikov@gmail.com |
1595f692018c5921f06fefeeb9be6861ebce0890 | 042da4516ee0c039f1345300acb3b94f1c3dbd68 | /src/ui/editarDados/EditarDadosCarregador.java | bf4f2818306ba1c0a939c7ff556b13eb17d3370d | [] | no_license | ERBFilho/ImovelFacilBD | 71e8769ec480d52d1201dd3ff93c839f11e2417e | 0e46e624a35b902db9f9c3e60bdd92d6d84220fd | refs/heads/master | 2021-09-15T05:40:09.432477 | 2018-05-27T03:13:33 | 2018-05-27T03:13:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 853 | 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 ui.editarDados;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* @author khadgar
*/
public class EditarDadosCarregador extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("editarDados.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| [
"khadgar@Khadgar"
] | khadgar@Khadgar |
f689cf61b83cd2dee7270485ef812ddd5e2eed01 | d7da1a7e3fe09711682d72be60b5607bde3d2f33 | /src/main/java/com/basilio/hiit/repository/ProgramRepository.java | 3ee068a7bfdc6a22fb4f6df39779e2f636304f86 | [
"MIT"
] | permissive | jimbasilio/hiit | 22bf5c914961c3c61f0b4a5099ce7b76b4c69338 | 1d648ce45fdd86f89c1c0fedef40b9fc8832a0fa | refs/heads/master | 2021-01-17T12:29:09.723955 | 2015-12-30T00:24:18 | 2015-12-30T01:43:37 | 21,879,833 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 533 | java | package com.basilio.hiit.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.basilio.hiit.entity.ProgramEntity;
public interface ProgramRepository extends JpaRepository<ProgramEntity, Long> {
// @Query("select p from #{#entityName} p where p.createdBy = ?1")
// List<ProgramEntity> findByUserName(String user);
@Query("select p from #{#entityName} p")
List<ProgramEntity> findByUserName(String user);
}
| [
"jim.basilio@gmail.com"
] | jim.basilio@gmail.com |
a8705b676315203a09a8c5d11bf7050d292abfc0 | f22534e22d639e6482233ae6fcf2c84dc970aeb7 | /src/main/java/com/johndoeo/proxy/staticProxy/ISinger.java | 36e2896c18beb3dd2951cf1730f5cb3af7ffc63a | [] | no_license | JohnDoeo/interview | fcfef8f05236b6e531f1e0264926723e9b900cd7 | 3146f0a4d930c0c0b35b26193a7f3e3f0735b3ba | refs/heads/master | 2020-05-19T05:24:59.331374 | 2019-05-06T08:19:00 | 2019-05-06T08:19:00 | 184,848,697 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 87 | java | package com.johndoeo.proxy.staticProxy;
public interface ISinger {
void sing();
}
| [
"18829348962@163.com"
] | 18829348962@163.com |
e99555957113d2c670bcecf4c78a45a619c69378 | 9afd76a7d2458e4186a73df83029a76002b521f8 | /src/main/java/com/swf/playground/model/Pojo.java | 1c9b818f72ef7420b4f7dc5746f773c03f948c32 | [
"MIT"
] | permissive | benhunterlearn/spring-playground | 2485e82e9b9e7ee16120d36776a44a34d2f7c8a7 | 507f2d6059ec960dd8f68df8f27e8ed37e162cc2 | refs/heads/main | 2023-08-16T06:01:00.665032 | 2021-09-29T21:32:04 | 2021-09-29T21:32:04 | 406,036,426 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 417 | java | package com.swf.playground.model;
public class Pojo {
private String one;
private String two;
@Override
public String toString() {
return "Pojo{" + "one='" + one + '\'' + ", two='" + two + '\'' + '}';
}
public String getOne() {
return one;
}
public void setOne(String one) {
this.one = one;
}
public String getTwo() {
return two;
}
public void setTwo(String two) {
this.two = two;
}
}
| [
"learntocode@benhunter.me"
] | learntocode@benhunter.me |
545f1eee49d25125459f5f20ec6856299cc70ebb | a4e6f7abe6912361e0c8eb50cbfd35602aa1064e | /app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/android/support/compat/R.java | 29bc76b4067893522b91b4248f39cdfe1adfc6b4 | [] | no_license | xinyanglib/xinyang4-FeelsBook | 25963c3792719bb3f85f1d5031a1f7842ec4692f | 180d799175b3e9356db509539a06affcc5924b31 | refs/heads/master | 2020-03-30T17:33:50.893279 | 2018-10-05T20:09:58 | 2018-10-05T20:09:58 | 151,460,668 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 7,944 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.compat;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int font = 0x7f0300a0;
public static final int fontProviderAuthority = 0x7f0300a2;
public static final int fontProviderCerts = 0x7f0300a3;
public static final int fontProviderFetchStrategy = 0x7f0300a4;
public static final int fontProviderFetchTimeout = 0x7f0300a5;
public static final int fontProviderPackage = 0x7f0300a6;
public static final int fontProviderQuery = 0x7f0300a7;
public static final int fontStyle = 0x7f0300a8;
public static final int fontWeight = 0x7f0300a9;
}
public static final class bool {
private bool() {}
public static final int abc_action_bar_embed_tabs = 0x7f040000;
}
public static final class color {
private color() {}
public static final int notification_action_color_filter = 0x7f05004d;
public static final int notification_icon_bg_color = 0x7f05004e;
public static final int ripple_material_light = 0x7f050059;
public static final int secondary_text_default_material_light = 0x7f05005b;
}
public static final class dimen {
private dimen() {}
public static final int compat_button_inset_horizontal_material = 0x7f06004d;
public static final int compat_button_inset_vertical_material = 0x7f06004e;
public static final int compat_button_padding_horizontal_material = 0x7f06004f;
public static final int compat_button_padding_vertical_material = 0x7f060050;
public static final int compat_control_corner_material = 0x7f060051;
public static final int notification_action_icon_size = 0x7f060087;
public static final int notification_action_text_size = 0x7f060088;
public static final int notification_big_circle_margin = 0x7f060089;
public static final int notification_content_margin_start = 0x7f06008a;
public static final int notification_large_icon_height = 0x7f06008b;
public static final int notification_large_icon_width = 0x7f06008c;
public static final int notification_main_column_padding_top = 0x7f06008d;
public static final int notification_media_narrow_margin = 0x7f06008e;
public static final int notification_right_icon_size = 0x7f06008f;
public static final int notification_right_side_padding_top = 0x7f060090;
public static final int notification_small_icon_background_padding = 0x7f060091;
public static final int notification_small_icon_size_as_large = 0x7f060092;
public static final int notification_subtext_size = 0x7f060093;
public static final int notification_top_pad = 0x7f060094;
public static final int notification_top_pad_large_text = 0x7f060095;
}
public static final class drawable {
private drawable() {}
public static final int notification_action_background = 0x7f070066;
public static final int notification_bg = 0x7f070067;
public static final int notification_bg_low = 0x7f070068;
public static final int notification_bg_low_normal = 0x7f070069;
public static final int notification_bg_low_pressed = 0x7f07006a;
public static final int notification_bg_normal = 0x7f07006b;
public static final int notification_bg_normal_pressed = 0x7f07006c;
public static final int notification_icon_background = 0x7f07006d;
public static final int notification_template_icon_bg = 0x7f07006e;
public static final int notification_template_icon_low_bg = 0x7f07006f;
public static final int notification_tile_bg = 0x7f070070;
public static final int notify_panel_notification_icon_bg = 0x7f070071;
}
public static final class id {
private id() {}
public static final int action_container = 0x7f08000e;
public static final int action_divider = 0x7f080010;
public static final int action_image = 0x7f080011;
public static final int action_text = 0x7f080017;
public static final int actions = 0x7f080018;
public static final int async = 0x7f08001e;
public static final int blocking = 0x7f080022;
public static final int chronometer = 0x7f08002c;
public static final int forever = 0x7f08005a;
public static final int icon = 0x7f080060;
public static final int icon_group = 0x7f080061;
public static final int info = 0x7f080064;
public static final int italic = 0x7f080066;
public static final int line1 = 0x7f08006a;
public static final int line3 = 0x7f08006b;
public static final int normal = 0x7f080078;
public static final int notification_background = 0x7f080079;
public static final int notification_main_column = 0x7f08007a;
public static final int notification_main_column_container = 0x7f08007b;
public static final int right_icon = 0x7f080087;
public static final int right_side = 0x7f080088;
public static final int text = 0x7f0800b2;
public static final int text2 = 0x7f0800b3;
public static final int time = 0x7f0800ba;
public static final int title = 0x7f0800bc;
}
public static final class integer {
private integer() {}
public static final int status_bar_notification_info_maxnum = 0x7f090009;
}
public static final class layout {
private layout() {}
public static final int notification_action = 0x7f0a002c;
public static final int notification_action_tombstone = 0x7f0a002d;
public static final int notification_template_custom_big = 0x7f0a0034;
public static final int notification_template_icon_group = 0x7f0a0035;
public static final int notification_template_part_chronometer = 0x7f0a0039;
public static final int notification_template_part_time = 0x7f0a003a;
}
public static final class string {
private string() {}
public static final int status_bar_notification_info_overflow = 0x7f0d0029;
}
public static final class style {
private style() {}
public static final int TextAppearance_Compat_Notification = 0x7f0e0104;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0e0105;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0e0107;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0e010a;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0e010c;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0e0182;
public static final int Widget_Compat_NotificationActionText = 0x7f0e0183;
}
public static final class styleable {
private styleable() {}
public static final int[] FontFamily = { 0x7f0300a2, 0x7f0300a3, 0x7f0300a4, 0x7f0300a5, 0x7f0300a6, 0x7f0300a7 };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x7f0300a0, 0x7f0300a8, 0x7f0300a9 };
public static final int FontFamilyFont_font = 0;
public static final int FontFamilyFont_fontStyle = 1;
public static final int FontFamilyFont_fontWeight = 2;
}
}
| [
"xinyang4@ualberta.ca"
] | xinyang4@ualberta.ca |
3044dcc69a6a0e1ba75aa57172b191884879558f | f76bdd8c72fc90ea95b4bd6d0a331029ed07f98a | /gmall-manage-service/src/main/java/com/atguigu/gmall0228/manage/mapper/SpuInfoMapper.java | 4c2de6eec807091b741a0fb0017560963e50e339 | [] | no_license | signngis/gmall | 6842e7fb5d6b084c28647a29cc0aee76a74a7da2 | 6765c56f3820ff2b8591b08ff04f60b07d20032a | refs/heads/master | 2020-04-27T04:15:11.826989 | 2019-04-11T03:46:57 | 2019-04-11T03:46:57 | 174,048,823 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 189 | java | package com.atguigu.gmall0228.manage.mapper;
import com.atguigu.gmall0228.bean.SpuInfo;
import tk.mybatis.mapper.common.Mapper;
public interface SpuInfoMapper extends Mapper<SpuInfo> {
}
| [
"wangliang@skybility.com"
] | wangliang@skybility.com |
2d8a8a5c223d9f0fc48dab13912a992df2a054c5 | 2b2c19a8885667c87ab20a971e8bad270326a1a6 | /src/designpatterns/creational/abstractfactory/ShapeFactory.java | 43c63d45bbbf4c7085118ffabf2e71ece52eb400 | [] | no_license | nsimonyan/DesignPatterns | e38cadfe967104c2018a5173056dfa74429f4633 | 8644cbb6ee50e5decbcc28897becb1afc94ee82e | refs/heads/master | 2021-04-30T15:11:43.790791 | 2018-12-13T13:58:51 | 2018-12-13T13:58:51 | 121,234,341 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 712 | java | package designpatterns.creational.abstractfactory;
/**
* Create Factory classes extending AbstractFactory to generate object of concrete class
* based on given information.
* @author Admin
*
*/
public class ShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
@Override
Color getColor(String color) {
return null;
}
} | [
"noreply@github.com"
] | nsimonyan.noreply@github.com |
af503847df9270ae52e661ecb3402a54856cdc0e | b74f2c19ea8e730b93e3da8842fc0ca3db9639dd | /aws-java-sdk-appstream/src/main/java/com/amazonaws/services/appstream/model/AssociateFleetResult.java | 1840a7abd9810120a6a66b39c2d05c021e1895e8 | [
"Apache-2.0"
] | permissive | mgivney/aws-sdk-java | 2de4a597beeda68735ba5bb822f45e924de29d14 | 005db50a80c825dc305306a0633cac057b95b054 | refs/heads/master | 2021-05-02T04:51:13.281576 | 2016-12-16T01:48:44 | 2016-12-16T01:48:44 | 76,672,974 | 1 | 0 | null | 2016-12-16T17:36:09 | 2016-12-16T17:36:09 | null | UTF-8 | Java | false | false | 2,009 | java | /*
* Copyright 2011-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.appstream.model;
import java.io.Serializable;
/**
*
*/
public class AssociateFleetResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof AssociateFleetResult == false)
return false;
AssociateFleetResult other = (AssociateFleetResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public AssociateFleetResult clone() {
try {
return (AssociateFleetResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| [
""
] | |
0d6c07d540b69f76b3707cc71b2aeb17c1c1cf50 | 1c6e520815520f2bb78ba736cd8ba4d4d1444d41 | /app/src/main/java/com/example/enes/cinemaapp/movie/MvpView.java | 463d50fa25a3c5d2fb17ae4da38cf79017e7bf9a | [] | no_license | enofeb/CinemaApp | 80b998541929014d15d3d07c3acb0cfa06901d9c | f94e3c4adec7543dfd6013e1b5b00d76edbb763e | refs/heads/master | 2021-10-19T12:25:04.888663 | 2018-12-21T23:04:38 | 2018-12-21T23:04:38 | 158,454,525 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 72 | java | package com.example.enes.cinemaapp.movie;
public interface MvpView {
}
| [
"eneszor95@gmail.com"
] | eneszor95@gmail.com |
6f5d2aa46a9fa59d3d87d005e7d14bf5a4f5d998 | 81f8cc83339bd04fde31f6195183596a6fea6c73 | /db-mapper/java/entity/PassengerAddress.java | 682ad23d8b9db6947e0e20605341dc3ac19fc136 | [] | no_license | thoughtbit/yesina | ac7c588241edc46e29b4314daef122cb8323290b | e4b5437ef2a901e089f8b0fe8be59779fbca5c5c | refs/heads/master | 2020-03-28T03:40:23.430848 | 2018-09-03T12:24:24 | 2018-09-03T12:24:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,417 | java | package com.lkmotion.yesincar.file.entity;
public class PassengerAddress {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tbl_passenger_address.id
*
* @mbggenerated
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tbl_passenger_address.passenger_info_id
*
* @mbggenerated
*/
private Integer passengerInfoId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tbl_passenger_address.latitude
*
* @mbggenerated
*/
private Double latitude;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tbl_passenger_address.longitude
*
* @mbggenerated
*/
private Double longitude;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tbl_passenger_address.address_name
*
* @mbggenerated
*/
private String addressName;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tbl_passenger_address.type
*
* @mbggenerated
*/
private Integer type;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column tbl_passenger_address.address_desc
*
* @mbggenerated
*/
private String addressDesc;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tbl_passenger_address.id
*
* @return the value of tbl_passenger_address.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tbl_passenger_address.id
*
* @param id the value for tbl_passenger_address.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tbl_passenger_address.passenger_info_id
*
* @return the value of tbl_passenger_address.passenger_info_id
*
* @mbggenerated
*/
public Integer getPassengerInfoId() {
return passengerInfoId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tbl_passenger_address.passenger_info_id
*
* @param passengerInfoId the value for tbl_passenger_address.passenger_info_id
*
* @mbggenerated
*/
public void setPassengerInfoId(Integer passengerInfoId) {
this.passengerInfoId = passengerInfoId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tbl_passenger_address.latitude
*
* @return the value of tbl_passenger_address.latitude
*
* @mbggenerated
*/
public Double getLatitude() {
return latitude;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tbl_passenger_address.latitude
*
* @param latitude the value for tbl_passenger_address.latitude
*
* @mbggenerated
*/
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tbl_passenger_address.longitude
*
* @return the value of tbl_passenger_address.longitude
*
* @mbggenerated
*/
public Double getLongitude() {
return longitude;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tbl_passenger_address.longitude
*
* @param longitude the value for tbl_passenger_address.longitude
*
* @mbggenerated
*/
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tbl_passenger_address.address_name
*
* @return the value of tbl_passenger_address.address_name
*
* @mbggenerated
*/
public String getAddressName() {
return addressName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tbl_passenger_address.address_name
*
* @param addressName the value for tbl_passenger_address.address_name
*
* @mbggenerated
*/
public void setAddressName(String addressName) {
this.addressName = addressName == null ? null : addressName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tbl_passenger_address.type
*
* @return the value of tbl_passenger_address.type
*
* @mbggenerated
*/
public Integer getType() {
return type;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tbl_passenger_address.type
*
* @param type the value for tbl_passenger_address.type
*
* @mbggenerated
*/
public void setType(Integer type) {
this.type = type;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column tbl_passenger_address.address_desc
*
* @return the value of tbl_passenger_address.address_desc
*
* @mbggenerated
*/
public String getAddressDesc() {
return addressDesc;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column tbl_passenger_address.address_desc
*
* @param addressDesc the value for tbl_passenger_address.address_desc
*
* @mbggenerated
*/
public void setAddressDesc(String addressDesc) {
this.addressDesc = addressDesc == null ? null : addressDesc.trim();
}
} | [
"7800017@163.com"
] | 7800017@163.com |
f02ededd800497171d8a7968ae18c08dc0014d17 | 32d39555b329b36b210f5b4df28145fe3fc7c17e | /src/cn/esup/web/datadictionary/DatadictionarytypeAction.java | 8888e57b926e3705b96b376cd580f5e2d65ba59e | [] | no_license | cnyangqi/esup | e3524d8056455873944decb96590cda02cd5e10f | 4a5ffe7a2a2568dfe3a05341d3755b5091ea7e6c | refs/heads/master | 2020-04-06T03:43:23.319739 | 2012-02-06T07:57:44 | 2012-02-06T07:57:44 | 3,143,832 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,884 | java | /**
* Copyright 2011 iThinkGo, Inc. All rights reserved.
*/
package cn.esup.web.datadictionary;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import cn.esup.common.AjaxResponse;
import cn.esup.common.Cn2Spell;
import cn.esup.entity.datadictionary.DataDictionaryType;
import cn.esup.service.datadictionary.DataDictionaryTypeManager;
import cn.esup.web.CrudActionSupport;
/**
* @author <a href= "mailto:qi.yang.cn@gmail.com"> qi.yang.cn@gmail.com </a>
* @version 1.0
* @since 1.0
*/
@Namespace("/datadictionary")
@Results({ @Result(name = "reload", location = "DataDictionaryType.action", type = "redirect") })
public class DatadictionarytypeAction extends CrudActionSupport<DataDictionaryType> {
private static final long serialVersionUID = 1L;
private DataDictionaryTypeManager dataDictionaryTypeManager;
// - 页面属性 -//
private Long id;
private String ids;
private DataDictionaryType dataDictionaryType;
// - ModelDriven 与 Preparable函数 -//
public void setId(Long id) {
this.id = id;
}
@Override
public DataDictionaryType getModel() {
return dataDictionaryType;
}
@Override
protected void prepareModel() throws Exception {
if (id != null) {
dataDictionaryType = dataDictionaryTypeManager.queryDataDictionaryTypeById(id);
} else {
dataDictionaryType = new DataDictionaryType();
}
}
// - CRUD Action 函数 -//
@Override
public String list() throws Exception {
// 将父节点的主键作为子节点的查询条件(Long parentId)
AjaxResponse.ajaxResp(dataDictionaryTypeManager.queryDataDictionaryTypeTreeView(id));
return null;
}
@Override
public String delete() throws Exception {
dataDictionaryTypeManager.deleteDataDictionaryType(id);
AjaxResponse.ajaxResp(true);
return null;
}
public String batchDelete() throws Exception {
dataDictionaryTypeManager.batchDeleteDataDictionaryType(ids);
AjaxResponse.ajaxResp(true);
return null;
}
@Override
public String save() throws Exception {
dataDictionaryType.setCode(Cn2Spell.converterToFirstSpell(dataDictionaryType.getName()));// 自动生成类型代码
dataDictionaryTypeManager.saveDataDictionaryType(dataDictionaryType);
AjaxResponse.ajaxResp(true);
return null;
}
@Override
public String input() throws Exception {
AjaxResponse.ajaxResp(dataDictionaryTypeManager.queryDataDictionaryTypeById(id));
return null;
}
@Autowired
public void setDataDictionaryTypeManager(DataDictionaryTypeManager dataDictionaryTypeManager) {
this.dataDictionaryTypeManager = dataDictionaryTypeManager;
}
public Long getId() {
return id;
}
public String getIds() {
return ids;
}
public void setIds(String ids) {
this.ids = ids;
}
} | [
"qi.yang.cn@gmail.com"
] | qi.yang.cn@gmail.com |
416b3c8b9cd298b271e17d7dad3e6c39518a057e | dac3178729a4579486497c8c1c063eeb6844a48f | /commonframework/src/main/java/com/base/commonframework/baselibrary/network/httpcache/HttpCacheInterceptorUtil.java | 1068e308aa6495d4abea15d2e8650514fe59cef6 | [] | no_license | r0shanbhagat/SelfieCelebriti | 7d222061d28fcbac7fb1721cf0463442b19ea5e0 | 879a216fdcdbd74b59130b74fb94108235f81024 | refs/heads/master | 2023-04-13T15:33:14.822044 | 2021-04-25T08:02:42 | 2021-04-25T08:02:42 | 361,368,334 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,875 | java | package com.base.commonframework.baselibrary.network.httpcache;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import com.base.commonframework.R;
import com.base.commonframework.baselibrary.network.httpcache.internal.data.HttpCacheContentProvider;
import com.base.commonframework.baselibrary.network.httpcache.internal.data.HttpHeader;
import com.base.commonframework.baselibrary.network.httpcache.internal.data.HttpTransaction;
import com.base.commonframework.baselibrary.network.httpcache.statusmodel.Status;
import com.base.commonframework.baselibrary.utility.NetworkUtility;
import com.base.commonframework.baselibrary.utility.ParseUtility;
import com.base.commonframework.utility.CommonFrameworkUtil;
import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okio.Buffer;
import okio.BufferedSource;
import okio.GzipSource;
import okio.Okio;
/**
* Created by roshan on 18/4/17.
*/
public class HttpCacheInterceptorUtil {
/**
* The constant UTF8.
*/
public static final Charset UTF8 = Charset.forName("UTF-8");
/**
* The constant COL_ID.
*/
public static final String COL_ID = "_id";
/**
* The constant COL_REQUEST_HEADER.
*/
public static final String COL_REQUEST_HEADER = "requestHeaders";
/**
* The constant COL_REQUEST_BODY.
*/
public static final String COL_REQUEST_BODY = "requestBody";
/**
* The constant COL_METHOD.
*/
public static final String COL_METHOD = "method";
/**
* The constant COL_URL.
*/
public static final String COL_URL = "url";
/**
* The constant COL_RESPONSE_CODE.
*/
public static final String COL_RESPONSE_CODE = "responseCode";
/**
* The constant COL_RESPONSE_BODY.
*/
public static final String COL_RESPONSE_BODY = "responseBody";
/**
* The constant COL_RESPONSE_CONTENT_TYPE.
*/
public static final String COL_RESPONSE_CONTENT_TYPE = "responseContentType";
/**
* The constant COL_RESPONSE_MESSAGE.
*/
public static final String COL_RESPONSE_MESSAGE = "responseMessage";
/**
* The constant COL_RESPONSE_DATE.
*/
public static final String COL_RESPONSE_DATE = "responseDate";
/**
* The constant COL_RESPONSE_HEADER.
*/
public static final String COL_RESPONSE_HEADER = "responseHeaders";
/**
* The constant COL_PROTOCOL.
*/
public static final String COL_PROTOCOL = "protocol";
/**
* The constant TAG.
*/
public static String TAG = HttpCacheInterceptorUtil.class.getSimpleName();
/**
* The constant SUCCESS_STATUS_CODE.
*/
public static int SUCCESS_STATUS_CODE = 200;
public static int SUCCESS_STATUS_CODE_ = 201;
/**
* The constant maxContentLength.
*/
public static long maxContentLength = 2500000L;
/**
* Gets available response.
*
* @param mContext the m context
* @param cacheMaxAge the cache max age
* @param transaction the transaction
* @return the available response
*/
public static CustomHttpCacheModel getAvailableResponse(Context mContext, long cacheMaxAge, HttpTransaction transaction) {
CustomHttpCacheModel customModel = null;
try {
validateTransActionValue(transaction);
String selection = /*COL_REQUEST_HEADER + "=? and " +*/ COL_URL + "=? and "
+ COL_REQUEST_BODY + "=? and " + COL_METHOD + "=? and " + COL_RESPONSE_CODE + "=? ";
String selectionArgs[] = {/*transaction.requestHeaders,*/ transaction.getUrl(),
transaction.getRequestBody(), transaction.getMethod(), String.valueOf(SUCCESS_STATUS_CODE)};
Cursor cursor = mContext.getContentResolver().query(HttpCacheContentProvider.TRANSACTION_URI,
null, selection, selectionArgs, "");
if (null != cursor) {
if (cursor.moveToFirst()) {
customModel = new CustomHttpCacheModel();
long responseDate = cursor.getLong(cursor.getColumnIndex(COL_RESPONSE_DATE));
long diff = System.currentTimeMillis() - responseDate;
if (diff < cacheMaxAge || !NetworkUtility.isNetworkAvailable(mContext)) {
customModel.setStatus(true);
customModel.setHttpTransaction(getUpdatedTransaction(cursor, transaction));
} else {
//Option:Network check
long rowId = cursor.getLong(cursor.getColumnIndex(COL_ID));
deleteRowIfExist(mContext, String.valueOf(rowId));
}
}
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return customModel;
}
/**
* @param transaction Setting value for Null Column Data
*/
private static void validateTransActionValue(HttpTransaction transaction) {
if (TextUtils.isEmpty(transaction.getRequestBody())) {
transaction.setRequestBody("");
}
if (TextUtils.isEmpty(transaction.getMethod())) {
transaction.setMethod("");
}
if (TextUtils.isEmpty(transaction.getUrl())) {
transaction.setUrl("");
}
if (TextUtils.isEmpty(transaction.getRequestHeadersString(true))) {
// transaction.setRequestHeaders(new Headers(null));
}
}
/**
* @param mContext
* @param rowId
*/
private static void deleteRowIfExist(Context mContext, String rowId) {
try {
String selection = COL_ID + " = ?";
String[] selectionArgs = {rowId};
mContext.getContentResolver().delete(HttpCacheContentProvider.TRANSACTION_URI, selection, selectionArgs);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param cursor
* @param transaction
* @return
*/
private static HttpTransaction getUpdatedTransaction(Cursor cursor, HttpTransaction transaction) {
transaction.setResponseCode(cursor.getInt(cursor.getColumnIndex(COL_RESPONSE_CODE)));
transaction.setResponseBody(cursor.getString(cursor.getColumnIndex(COL_RESPONSE_BODY)));
transaction.setResponseContentType(cursor.getString(cursor.getColumnIndex(COL_RESPONSE_CONTENT_TYPE)));
transaction.setResponseMessage(cursor.getString(cursor.getColumnIndex(COL_RESPONSE_MESSAGE)));
transaction.setProtocol(cursor.getString(cursor.getColumnIndex(COL_PROTOCOL)));
transaction.setResponseHeaders(cursor.getString(cursor.getColumnIndex(COL_RESPONSE_HEADER)));
return transaction;
}
/**
* Returns true if the body in question probably contains human readable text. Uses a small sample
* of code points to detect unicode control characters commonly used in binary file signatures.
*/
private static boolean isPlaintext(Buffer buffer) {
try {
Buffer prefix = new Buffer();
long byteCount = buffer.size() < 64 ? buffer.size() : 64;
buffer.copyTo(prefix, 0, byteCount);
for (int i = 0; i < 16; i++) {
if (prefix.exhausted()) {
break;
}
int codePoint = prefix.readUtf8CodePoint();
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false;
}
}
return true;
} catch (EOFException e) {
return false; // Truncated UTF-8 sequence.
}
}
/**
* @param headers
* @return
*/
private static boolean bodyHasUnsupportedEncoding(Headers headers) {
String contentEncoding = headers.get("Content-Encoding");
return contentEncoding != null &&
!contentEncoding.equalsIgnoreCase("identity") &&
!contentEncoding.equalsIgnoreCase("gzip");
}
/**
* @param headers
* @return
*/
private static boolean bodyGzipped(Headers headers) {
String contentEncoding = headers.get("Content-Encoding");
return "gzip".equalsIgnoreCase(contentEncoding);
}
/**
* @param mContext
* @param buffer
* @param charset
* @return
*/
private static String readFromBuffer(Context mContext, Buffer buffer, Charset charset) {
long bufferSize = buffer.size();
long maxBytes = Math.min(bufferSize, maxContentLength);
String body = "";
try {
body = buffer.readString(maxBytes, charset);
} catch (EOFException e) {
body += mContext.getString(R.string.httpCacheBodyUnexpectedEof);
}
if (bufferSize > maxContentLength) {
body += mContext.getString(R.string.httpCacheBodyContentTruncated);
}
return body;
}
/**
* @param input
* @param isGzipped
* @return
*/
private static BufferedSource getNativeSource(BufferedSource input, boolean isGzipped) {
if (isGzipped) {
GzipSource source = new GzipSource(input);
return Okio.buffer(source);
} else {
return input;
}
}
/**
* Gets request transaction.
*
* @param mContext the m context
* @param request the request
* @return the request transaction
*/
public static HttpTransaction getRequestTransaction(Context mContext, Request request) {
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
HttpTransaction transaction = new HttpTransaction();
transaction.setRequestDate(new Date());
transaction.setNetworkTime(System.nanoTime());
transaction.setMethod(request.method());
transaction.setUrl(request.url().toString());
transaction.setRequestHeaders(request.headers());
if (hasRequestBody) {
if (requestBody.contentType() != null) {
transaction.setRequestContentType(requestBody.contentType().toString());
}
try {
if (requestBody.contentLength() != -1) {
transaction.setRequestContentLength(requestBody.contentLength());
}
} catch (IOException e) {
e.printStackTrace();
}
}
transaction.setRequestBodyIsPlainText(!bodyHasUnsupportedEncoding(request.headers()));
if (hasRequestBody && transaction.requestBodyIsPlainText()) {
BufferedSource source = getNativeSource(new Buffer(), bodyGzipped(request.headers()));
Buffer buffer = source.buffer();
try {
requestBody.writeTo(buffer);
} catch (IOException e) {
e.printStackTrace();
}
Charset charset = HttpCacheInterceptorUtil.UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(HttpCacheInterceptorUtil.UTF8);
}
if (isPlaintext(buffer)) {
transaction.setRequestBody(readFromBuffer(mContext, buffer, charset));
} else {
transaction.setResponseBodyIsPlainText(false);
}
}
return transaction;
}
/**
* Gets response transaction.
*
* @param mContext the m context
* @param transaction the transaction
* @param response the response
* @throws IOException the io exception
*/
public static void getResponseTransaction(Context mContext, HttpTransaction transaction, Response response) throws IOException {
long tookMs = response.receivedResponseAtMillis() - response.sentRequestAtMillis();
ResponseBody responseBody = response.body();
transaction.setRequestHeaders(response.request().headers()); // includes headers added later in the chain
transaction.setResponseDate(new Date());
transaction.setTookMs(tookMs);
transaction.setProtocol(response.protocol().toString());
transaction.setResponseMessage(response.message());
transaction.setResponseContentLength(responseBody.contentLength());
if (responseBody.contentType() != null) {
transaction.setResponseContentType(responseBody.contentType().toString());
}
transaction.setResponseHeaders(response.headers());
transaction.setResponseBodyIsPlainText(!bodyHasUnsupportedEncoding(response.headers()));
if (HttpHeaders.hasBody(response) && transaction.responseBodyIsPlainText()) {
BufferedSource source = getNativeSource(maxContentLength, response);
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();
Charset charset = HttpCacheInterceptorUtil.UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
try {
charset = contentType.charset(HttpCacheInterceptorUtil.UTF8);
} catch (UnsupportedCharsetException e) {
//update(transaction, transactionUri);
}
}
if (isPlaintext(buffer)) {
transaction.setResponseBody(readFromBuffer(mContext, buffer.clone(), charset));
} else {
transaction.setResponseBodyIsPlainText(false);
}
transaction.setResponseCode(getResponseBody(transaction.getResponseBody()));
transaction.setResponseContentLength(buffer.size());
}
}
private static int getResponseBody(String responseBody) {
int responseCode = 0;
try {
if (!TextUtils.isEmpty(responseBody)) {
responseCode=200;
/*Status status = ParseUtility.getObject(responseBody, Status.class);
if (null != status) {
responseCode = status.getStatus().getStatusCode();
}*/
}
} finally {
return responseCode;
}
}
public static void showRequestLog(HttpTransaction transaction, HttpCacheInterceptor.Logger logger) {
String requestStartMessage =
"--> REQUEST START " + String
.valueOf(transaction.getUrl()) + ' ' + transaction.getMethod() + ' ' + HttpCacheInterceptor.protocol(transaction.getProtocol());
requestStartMessage += "\n Request Body: " + transaction.getRequestBody() + "\n (" + transaction.getRequestContentLength() + "-byte body)";
logger.log(requestStartMessage);
List<HttpHeader> headers = transaction.getRequestHeaders();
boolean isEncrypted = false;
if (null != headers && !headers.isEmpty()) {
logger.log("Headers START -->");
for (int i = 0, count = headers.size(); i < count; i++) {
logger.log(headers.get(i).getName() + ": " + headers.get(i).getValue());
if (headers.get(i).getValue().equalsIgnoreCase("y")) {
isEncrypted = true;
}
}
logger.log("<-- Headers END");
}
if (isEncrypted) {
try {
//logger.log("Decrypted Request START -->" + AESSecurity.decrypt(transaction.getRequestBody()));
//logger.log();
logger.log("<-- Decrypted Request END");
} catch (Exception e) {
logger.log(Log.getStackTraceString(e));
}
}
long tookMsRequest = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - transaction.getNetworkTime());
String endMessage = "\nRequestTime:" + tookMsRequest + "ms";
logger.log(endMessage);
logger.log("--> REQUEST END ");
}
/**
* @param maxContentLength
* @param response
* @return
* @throws IOException
*/
private static BufferedSource getNativeSource(long maxContentLength, Response response) throws IOException {
if (bodyGzipped(response.headers())) {
BufferedSource source = response.peekBody(maxContentLength).source();
if (source.buffer().size() < maxContentLength) {
return getNativeSource(source, true);
} else {
Log.w(TAG, "gzip encoded response was too long");
}
}
return response.body().source();
}
public static void clearHttpCacheDb(Context mContext) {
try {
mContext.getContentResolver().delete(HttpCacheContentProvider.TRANSACTION_URI, null, null);
} catch (Exception e) {
CommonFrameworkUtil.showException(e);
}
}
public static void showResponseLog(HttpTransaction response, boolean isFromCache, HttpCacheInterceptor.Logger logger, long startNwResponse) {
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNwResponse);
final Charset UTF8 = Charset.forName("UTF-8");
logger.log("<--" + (isFromCache ? "CACHE" : "") + " RESPONSE START " + response.getProtocol() + ' ' + response.getResponseCode() + ' '
+ response.getResponseBody() + "\n (" + response.getRequestContentLength() + "-byte body) ");
List<HttpHeader> headers = response.getResponseHeaders();
if (null != headers && !headers.isEmpty()) {
logger.log("Headers START -->");
for (int i = 0, count = headers.size(); i < count; i++) {
logger.log(headers.get(i).getName() + ": " + headers.get(i).getValue());
}
logger.log("<-- Headers END");
}
logger.log("ResponseTime:" + tookMs + "ms");
logger.log("response Code >> " + response.getResponseCode());
logger.log("response SuccessFul >> " + response.getResponseMessage());
logger.log("<-- RESPONSE END ");
}
/**
* The enum Period.
*/
public enum Period {
/**
* Retain data for the last hour.
*/
ONE_HOUR,
/**
* Retain data for the last day.
*/
ONE_DAY,
/**
* Retain data for the last week.
*/
ONE_WEEK,
/**
* Retain data forever.
*/
FOREVER
}
}
| [
"roshan.bhagat@girnarsoft.com"
] | roshan.bhagat@girnarsoft.com |
a771d381596176d10ca7b0cc56003654b1583f56 | 93cb0748bd5b8724c45e8ea3095a613e536bdb77 | /src/test/java/AgendaCheckWeb/Data/DepartmentNameCheckerTest.java | f44de01c5e18f71e831c4595331901e513f526a9 | [
"MIT"
] | permissive | StanislawNagorski/AgendaCheckWeb | ba57b293a46a5de72e93a0c1bcf372b29a05c265 | b5fe28a371703a1c9a734d07b90046caed3c6803 | refs/heads/master | 2023-01-24T18:52:30.000738 | 2020-11-17T14:18:37 | 2020-11-17T14:18:37 | 299,578,753 | 0 | 0 | MIT | 2020-11-17T13:59:28 | 2020-09-29T10:11:56 | Java | UTF-8 | Java | false | false | 3,642 | java | package AgendaCheckWeb.Data;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
public class DepartmentNameCheckerTest {
@Test
public void shouldReturnTrueForSameNames(){
//Given
String givenNameForecast = "X";
String givenNameSchedule = "X";
//When
boolean result = DepartmentNameChecker.namesCheck(givenNameForecast,givenNameSchedule);
//Then
Assertions.assertTrue(result);
}
@Test
public void shouldReturnFalseForDiffrentNames(){
//Given
String givenNameForecast = "OdjechanaNazwa";
String givenNameSchedule = "X";
//When
boolean result = DepartmentNameChecker.namesCheck(givenNameForecast,givenNameSchedule);
//Then
Assertions.assertFalse(result);
}
@Test
public void shouldReturnTrueIfNamesAreSimilar(){
//Given
String givenNameForecast = "Rowery";
String givenNameSchedule = "(643.1) Rowery";
//When
boolean result = DepartmentNameChecker.namesCheck(givenNameForecast,givenNameSchedule);
//Then
Assertions.assertTrue(result);
}
@Test
public void shouldReturnFalseIfNamesAreDiffrent(){
//Given
String givenNameForecast = "BieganieOXELO";
String givenNameSchedule = "(643.1) Rowery";
//When
boolean result = DepartmentNameChecker.namesCheck(givenNameForecast,givenNameSchedule);
//Then
Assertions.assertFalse(result);
}
@Test
public void shouldReturnTrueIfNamesHaveSameElement(){
//Given
String givenNameForecast = "BieganieOXELO";
String givenNameSchedule = "(643.8) Bieganie";
//When
boolean result = DepartmentNameChecker.namesCheck(givenNameForecast,givenNameSchedule);
//Then
Assertions.assertTrue(result);
}
@Test
public void shouldReturnTrueIfNamesHaveSameElementCompicated(){
//Given
String givenNameForecast = "Tetris - Gry/Rakiety";
String givenNameSchedule = "(643.20) Gry/Tenis";
//When
boolean result = DepartmentNameChecker.namesCheck(givenNameForecast,givenNameSchedule);
//Then
Assertions.assertTrue(result);
}
//
// @Test
// public void hoursSetShouldContainAllSheetsFromForecastFor729() throws Exception {
// //Given
// OPCPackage scheduleInput = OPCPackage.open(new File("SampleInput/godzinyCzerwiec729.xlsx"));
// XSSFWorkbook schedule = new XSSFWorkbook(scheduleInput);
// scheduleInput.close();
//
// OPCPackage forecastInput = OPCPackage.open(new File("SampleInput/729 Gessef 2020.xlsx"));
// XSSFWorkbook forecast = new XSSFWorkbook(forecastInput);
// forecastInput.close();
// ScheduleReader scheduleReader = new ScheduleReader(schedule);
// ForecastReader forecastReader = new ForecastReader(forecast);
// double productivityTargetUserInput = 800;
// DataBank dataBank = new DataBank(scheduleReader, forecastReader, productivityTargetUserInput);
//
// Map<String, Double> turnover = dataBank.getMonthlyDepartmentTurnOver();
// Map<String, List<Double>> hours = dataBank.getDailyDepartmentHoursByName();
//
// //When
// System.out.println(hours.keySet());
// DepartmentNameChecker.changeDepartmentNamesInScheduleToThoseFromForecast(turnover, hours);
//
// //Then
// System.out.println(turnover.keySet());
// System.out.println(hours.keySet());
//
// Assertions.assertTrue(hours.keySet().containsAll(turnover.keySet()));
// }
} | [
"stanislaw.nagorski@gmail.com"
] | stanislaw.nagorski@gmail.com |
6a7abf898e9a51c69a26ce9cca767081b5b59457 | b065d3f9e74c1b49ba4a695f9261f77c8f580bb7 | /java-core/SILO/src/main/java/silo/data/utils/DataUtils.java | 8e5b3e8aaf0374568660c57bb543db6f8afc8f0b | [
"Apache-2.0"
] | permissive | NoahGibson/silo | 2d4e010f1e0eccfbbe3f9ec4c43608217e13cff9 | 0df43f4a144e932f69f7e27d683d7f57129961c0 | refs/heads/master | 2020-03-23T23:10:04.558158 | 2018-08-21T18:30:59 | 2018-08-21T18:30:59 | 142,219,586 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,896 | java | package silo.data.utils;
import silo.data.ArrayListDataFrame;
import silo.data.DataFrame;
import silo.data.HashMapDataRow;
import java.util.*;
/**
* Class containing utility methods for manipulating data sets.
*
* @author Noah Gibson
* @version 1.0
* @since 20180811
*/
public class DataUtils {
/**
* Randomly splits the given data frame into two new data frames, a test set and a train set. Each row in the given
* data frame will have a probability of {@code testRatio} percent of being in the test set. If it is not chosen
* to be in the test set, then it will be placed in the train set.
*
* @param data
* the data to split into a train and test set
* @param testRatio
* the ratio of data rows which should be put in the test set
*
* @return a {@link TrainTestSplit} containing the new train and test sets
*
* @throws IllegalArgumentException if the given data is {@code null}
*/
public static <T> TrainTestSplit<T> trainTestSplit(DataFrame<T> data, double testRatio) throws IllegalArgumentException {
if (data == null) {
throw new IllegalArgumentException("data must not be null");
}
DataFrame<T> testSet = new ArrayListDataFrame<>(new HashSet<>(data.columns()));
DataFrame<T> trainSet = new ArrayListDataFrame<>(new HashSet<>(data.columns()));
Random rand = new Random();
for (int i = 0; i < data.size(); i++ ) {
if (rand.nextDouble() < testRatio) {
testSet.addRow(new HashMapDataRow<>(data.getRow(i)), testSet.size());
} else {
trainSet.addRow(new HashMapDataRow<>(data.getRow(i)), trainSet.size());
}
}
Collections.shuffle(testSet.rows());
Collections.shuffle(trainSet.rows());
return new TrainTestSplit<>(trainSet, testSet);
}
}
| [
"135noahg@gmail.com"
] | 135noahg@gmail.com |
3313b5bfd736b51590e4ccd38dd7dbc004cbea3a | 3296845f9703f3379885ee52c9c53eada3cd3382 | /src/StartCalcScreen.java | bb9661d596e6b723c36fd96bac00fe7a72e69eab | [] | no_license | Noodle-Sling/MicroProject | 2a0f7a29fe6cb5ced27b18b3d26f3c3c27cf102d | 23878f256bf43059c3d356f94285772bba8b9b16 | refs/heads/master | 2021-08-24T07:18:47.808715 | 2017-12-08T05:38:18 | 2017-12-08T05:38:18 | 112,780,610 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,666 | java | import javax.swing.JPanel;
import javax.swing.JTextArea;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.Font;
import java.awt.Color;
import java.awt.Component;
import javax.swing.UIManager;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.JTextPane;
import java.awt.ComponentOrientation;
import java.awt.Rectangle;
import java.awt.Dimension;
import javax.swing.border.LineBorder;
public class StartCalcScreen extends JPanel {
public JTextField textField;
public JTextField textField_1;
public JTextField textField_2;
/**
* Create the panel.
*/
public StartCalcScreen(ActionListener moveOn, ActionListener home) {
setBackground(new Color(147, 112, 219));
setSize(700, 700);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{150, 30, 100, 240, 180};
gridBagLayout.rowHeights = new int[]{90, 90, 30, 35, 35, 35, 30, 50, 212, 50};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
setLayout(gridBagLayout);
JTextPane txtpnMakeSureThat = new JTextPane();
StyledDocument doc = txtpnMakeSureThat.getStyledDocument();
SimpleAttributeSet attribs = new SimpleAttributeSet();
StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_CENTER);
StyleConstants.setFontFamily(attribs, "Lucida Grande");
StyleConstants.setFontSize(attribs, 20);
doc.setParagraphAttributes(0, doc.getLength(), attribs,true);
txtpnMakeSureThat.setEditable(false);
txtpnMakeSureThat.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
txtpnMakeSureThat.setBackground(new Color(147, 112, 219));
txtpnMakeSureThat.setText("Make sure that all \nentered values are \nnumbers");
GridBagConstraints gbc_txtpnMakeSureThat = new GridBagConstraints();
gbc_txtpnMakeSureThat.fill = GridBagConstraints.VERTICAL;
gbc_txtpnMakeSureThat.insets = new Insets(0, 0, 5, 5);
gbc_txtpnMakeSureThat.gridx = 3;
gbc_txtpnMakeSureThat.gridy = 1;
add(txtpnMakeSureThat, gbc_txtpnMakeSureThat);
JLabel lblQuestion = new JLabel("Units of labor:");
GridBagConstraints gbc_lblQuestion = new GridBagConstraints();
gbc_lblQuestion.anchor = GridBagConstraints.EAST;
gbc_lblQuestion.insets = new Insets(0, 0, 5, 5);
gbc_lblQuestion.gridx = 2;
gbc_lblQuestion.gridy = 3;
add(lblQuestion, gbc_lblQuestion);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 5);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 3;
gbc_textField.gridy = 3;
add(textField, gbc_textField);
textField.setColumns(10);
JLabel lblQuestion_1 = new JLabel("Price of labor:");
GridBagConstraints gbc_lblQuestion_1 = new GridBagConstraints();
gbc_lblQuestion_1.anchor = GridBagConstraints.EAST;
gbc_lblQuestion_1.insets = new Insets(0, 0, 5, 5);
gbc_lblQuestion_1.gridx = 2;
gbc_lblQuestion_1.gridy = 4;
add(lblQuestion_1, gbc_lblQuestion_1);
textField_1 = new JTextField();
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.insets = new Insets(0, 0, 5, 5);
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.gridx = 3;
gbc_textField_1.gridy = 4;
add(textField_1, gbc_textField_1);
textField_1.setColumns(10);
JLabel lblQuestion_2 = new JLabel("Wages:");
GridBagConstraints gbc_lblQuestion_2 = new GridBagConstraints();
gbc_lblQuestion_2.anchor = GridBagConstraints.EAST;
gbc_lblQuestion_2.insets = new Insets(0, 0, 5, 5);
gbc_lblQuestion_2.gridx = 2;
gbc_lblQuestion_2.gridy = 5;
add(lblQuestion_2, gbc_lblQuestion_2);
textField_2 = new JTextField();
GridBagConstraints gbc_textField_2 = new GridBagConstraints();
gbc_textField_2.insets = new Insets(0, 0, 5, 5);
gbc_textField_2.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_2.gridx = 3;
gbc_textField_2.gridy = 5;
add(textField_2, gbc_textField_2);
textField_2.setColumns(10);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel_1.setBackground(Color.LIGHT_GRAY);
panel_1.setLayout(null);
GridBagConstraints gbc_panel_1 = new GridBagConstraints();
gbc_panel_1.insets = new Insets(0, 0, 5, 5);
gbc_panel_1.fill = GridBagConstraints.BOTH;
gbc_panel_1.gridx = 3;
gbc_panel_1.gridy = 7;
add(panel_1, gbc_panel_1);
JButton btnCalculate = new JButton("Calculate");
btnCalculate.setBorderPainted(false);
btnCalculate.setBounds(0, 0, 235, 45);
panel_1.add(btnCalculate);
btnCalculate.addActionListener(moveOn);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 2));
panel.setBackground(Color.LIGHT_GRAY);
panel.setBounds(0, 0, 150, 50);
panel.setLayout(null);
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.insets = new Insets(0, 0, 0, 5);
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 0;
gbc_panel.gridy = 9;
add(panel, gbc_panel);
JButton btnHome = new JButton("Home");
btnHome.setBounds(0, 0, 145, 50);
btnHome.setAlignmentY(Component.TOP_ALIGNMENT);
btnHome.setPreferredSize(new Dimension(146, 56));
btnHome.setContentAreaFilled(false);
btnHome.setBorderPainted(false);
panel.add(btnHome);
btnHome.addActionListener(home);
}
} | [
"mwolfman18@spxstudent.org"
] | mwolfman18@spxstudent.org |
66cd088a42879170ae0aba98aa8b0904b4dab455 | 77b7f3b87ef44182c5d0efd42ae1539a9b8ca14c | /src/generated/java/com/turnengine/client/api/global/game/GetGameInstancesByGameNameReturnTypeXmlSerializer.java | 34fae264c2c53f72b30ea3b8b36a9c1eb7abb259 | [] | no_license | robindrew/turnengine-client-api | b4d9e767e9cc8401859758d83b43b0104bce7cd1 | 5bac91a449ad7f55201ecd64e034706b16578c36 | refs/heads/master | 2023-03-16T05:59:14.189396 | 2023-03-08T14:09:24 | 2023-03-08T14:09:24 | 232,931,212 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,240 | java | package com.turnengine.client.api.global.game;
import com.robindrew.codegenerator.api.serializer.xml.IXmlReader;
import com.robindrew.codegenerator.api.serializer.xml.IXmlSerializer;
import com.robindrew.codegenerator.api.serializer.xml.IXmlWriter;
import com.robindrew.codegenerator.api.serializer.xml.serializer.collection.ListSerializer;
import java.util.List;
public class GetGameInstancesByGameNameReturnTypeXmlSerializer implements IXmlSerializer<List<IGameInstance>> {
private String name;
public GetGameInstancesByGameNameReturnTypeXmlSerializer() {
this("GetGameInstancesByGameNameReturnType");
}
public GetGameInstancesByGameNameReturnTypeXmlSerializer(String name) {
this.name = name;
}
/**
* Getter for the name field.
* @return the value of the name field.
*/
public String getName() {
return name;
}
@Override
public List<IGameInstance> readObject(IXmlReader reader) {
return new ListSerializer<IGameInstance>(getName(), new GameInstanceXmlSerializer("element")).readObject(reader);
}
@Override
public void writeObject(IXmlWriter writer, List<IGameInstance> object) {
new ListSerializer<IGameInstance>(getName(), new GameInstanceXmlSerializer("element")).writeObject(writer, object);
}
}
| [
"robin.drew@gmail.com"
] | robin.drew@gmail.com |
1b191e9461ea68c8f62b295a088a3211d046cecd | f385cfaa11515a28f0de2c4a0f4818612914a722 | /concerttours/gensrc/concerttours/constants/GeneratedConcerttoursConstants.java | c9e14c169a61ae61bd658d4343d7dcdd2f641432 | [] | no_license | PoojaSapreRC/HybrisRepository | 09dae3d50954acca7a0a6ecb078c21da3ae307fa | b30f6ed6538fcb2a3b11774ba747a4a2137b91e9 | refs/heads/main | 2023-05-29T23:18:26.998234 | 2021-06-04T11:49:34 | 2021-06-04T11:49:34 | 373,798,134 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,814 | java | /*
* ----------------------------------------------------------------
* --- WARNING: THIS FILE IS GENERATED AND WILL BE OVERWRITTEN! ---
* --- Generated at 02-Jun-2021, 4:14:19 PM ---
* ----------------------------------------------------------------
*/
package concerttours.constants;
/**
* @deprecated since ages - use constants in Model classes instead
*/
@Deprecated(since = "ages", forRemoval = false)
@SuppressWarnings({"unused","cast"})
public class GeneratedConcerttoursConstants
{
public static final String EXTENSIONNAME = "concerttours";
public static class TC
{
public static final String BAND = "Band".intern();
public static final String CONCERT = "Concert".intern();
public static final String CONCERTTYPE = "ConcertType".intern();
public static final String MUSICTYPE = "MusicType".intern();
public static final String NEWS = "News".intern();
public static final String NOTLOREMIPSUMCONSTRAINT = "NotLoremIpsumConstraint".intern();
}
public static class Attributes
{
public static class MusicType
{
public static final String BANDS = "bands".intern();
}
public static class Product
{
public static final String BAND = "band".intern();
public static final String HASHTAG = "hashtag".intern();
}
}
public static class Enumerations
{
public static class ConcertType
{
public static final String OPENAIR = "openair".intern();
public static final String INDOOR = "indoor".intern();
}
public static class MusicType
{
// no values defined
}
}
public static class Relations
{
public static final String BAND2MUSICTYPE = "Band2MusicType".intern();
public static final String PRODUCT2ROCKBAND = "Product2RockBand".intern();
}
protected GeneratedConcerttoursConstants()
{
// private constructor
}
}
| [
"poojasaprerc@gmail.com"
] | poojasaprerc@gmail.com |
b24b0db9bd61b24aa489ba60ee71cfc5ea3f4067 | 24c567c1d42a3f57a40dd43a164df3b38e8c81ad | /java/src/rocks/ditto/leetcode/medium/FindUnsortedSubarray.java | b17812da2b7164c892ca5e5b193e28f8ed86a557 | [] | no_license | MurphyWhite/Leetcode | 7d5f3c1ecb3e8789fb63d1ed42a21d1633fa0ae7 | d25362dbf926510d2ce8200a7ca83c649752327b | refs/heads/master | 2023-08-08T22:18:32.045827 | 2023-07-29T14:48:24 | 2023-07-29T14:48:24 | 72,352,157 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,565 | java | package src.rocks.ditto.leetcode.medium;
/**
* 581. 最短无序连续子数组
* https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/
*/
public class FindUnsortedSubarray {
int MIN = -100005, MAX = 100005;
public int findUnsortedSubarray(int[] nums) {
int i = 0, j = nums.length - 1;
// 找单调递增的右端点
while (i < j && nums[i] <= nums[i+1]) {
i++;
}
// 找单调递增的左端点
while (i < j && nums[j] >= nums[j - 1]) {
j--;
}
int l = i, r = j;
int min = nums[i], max = nums[j];
// 遍历非单调的数组段,查找该段中的最大值和最小值
for (int k = l; k <= r; k++){
if (nums[k] < min) {
while ( i >= 0 && nums[i] > nums[k]) {
i--;
}
// 如果i已经到了数组左边界(-1)了,那就不需要考虑
min = i >= 0 ? nums[i] : MIN;
}
if (nums[k] > max) {
while ( j <= nums.length - 1 && nums[j] < nums[k]) {
j++;
}
// 如果j已经到了数组右边界(n)了,那就不需要考虑
max = j <= nums.length - 1 ? nums[j] : MAX;
}
}
return j == i ? 0 : (j - 1) - (i + 1) + 1;
}
public static void main(String[] args) {
FindUnsortedSubarray f = new FindUnsortedSubarray();
f.findUnsortedSubarray(new int[] {2,6,4,8,10,9,15});
}
}
| [
"mzh306291465@gmail.com"
] | mzh306291465@gmail.com |
68ca15471a73519b8cf8a281d8e208e718e117aa | 1d3fbc0bfb3620cad82726a1ad91b230f5c3f741 | /src/main/java/com/wondertek/baiying/marketing/domain/package-info.java | e40912d5f3fea5527c792351a940a881b65008c9 | [] | no_license | denney/marketing-service | ff977bbcdd48dbf9c5de2c42de0c9883fe82f52b | f81e728e3dd115918b19251bd760f5627890ecd6 | refs/heads/master | 2020-01-19T21:13:53.501584 | 2017-06-17T07:29:53 | 2017-06-17T07:29:53 | 94,213,612 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 79 | java | /**
* JPA domain objects.
*/
package com.wondertek.baiying.marketing.domain;
| [
"695493589@qq.com"
] | 695493589@qq.com |
a4facd1cda37042816aeae83691fd373d20622cc | 05d699d3db0264eb0018c351aed8b482b5647110 | /src/main/java/com/assignup/ie/entity/AppUser.java | e8d091ba031847de48b97e2636039d2905d10550 | [] | no_license | beingstoic/spring-security-jwt---setup | c1a08c5ff22d10bb3528bd9ba719cb47d29bc67d | 3899fdbc95afcd95ef43bf052b42b4816d2de04c | refs/heads/master | 2023-04-18T14:02:05.537396 | 2021-05-07T02:10:01 | 2021-05-07T02:10:01 | 365,088,265 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,060 | java | package com.assignup.ie.entity;
import java.util.Collection;
import java.util.Collections;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.assignup.ie.constants.UserRole;
@Entity
public class AppUser implements UserDetails {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long userId;
@Column(name="password")
private String password;
@Column(name="email")
private String email;
private String firstname;
private String lastname;
@Enumerated(EnumType.STRING)
@Column(name="role")
public UserRole role;
private boolean locked = false;
private boolean enabled = false;
public AppUser() {
super();
}
public AppUser(String email, String password, String firstname, String lastname, UserRole role) {
super();
this.email = email;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
this.role = role;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public UserRole getRole() {
return role;
}
public void setRole(UserRole role) {
this.role = role;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority authority =
new SimpleGrantedAuthority(role.name());
return Collections.singletonList(authority);
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return email;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return !locked;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return enabled;
}
}
| [
"59771568+beingstoic@users.noreply.github.com"
] | 59771568+beingstoic@users.noreply.github.com |
a327347aae60186a74b5daf443585980b90cff88 | 9e03ea506cdb0fd49242ae5d834dc1c0f5736637 | /backend/coreMicroservice/core-microservice/poruke-korisnik-service/src/main/java/com/megatravel/porukeservice/jwt/JwtTokenUtils.java | 986306bea1c465967cd3b292c867cb9b3360f370 | [] | no_license | MarkoKatic96/megaTravel | 523ead112eba57bdb9045cebc15701806b98b7f1 | e2094bfb595a8f6a153f6e7894e8814572cbfda6 | refs/heads/master | 2023-01-11T18:32:23.003586 | 2019-06-30T05:51:59 | 2019-06-30T05:51:59 | 174,172,768 | 1 | 3 | null | 2023-01-04T17:30:53 | 2019-03-06T15:40:55 | Java | UTF-8 | Java | false | false | 3,433 | java | package com.megatravel.porukeservice.jwt;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.megatravel.porukeservice.model.Korisnik;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Component
public class JwtTokenUtils {
@Value("${security.jwt.token.secret-key:secret-key}")
private String secretKey;
@Value("${security.jwt.token.expire-length:86400000}")
private long validityInMilliseconds = 86400000; // 1 dan
@Autowired
private com.megatravel.porukeservice.security.UserDetails mineUserDetails;
@Autowired
private RestTemplate restTemplate;
@PostConstruct
protected void init() {
secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());
}
public String createToken(String email) {
List<SimpleGrantedAuthority> tipoviKorisnika = new ArrayList<>();
//treba proslediti sve role koje korisnik ima
//UserDetails userDetails = mineUserDetails.loadUserByUsername(email);
ResponseEntity<Korisnik> korisnikEntity = restTemplate.getForEntity("http://korisnik-service/korisnik/"+email, Korisnik.class);
if (korisnikEntity.getStatusCode() != HttpStatus.OK) {
return null;
}
Korisnik korisnik = korisnikEntity.getBody();
if (korisnik == null) {
return null;
}
tipoviKorisnika.add(new SimpleGrantedAuthority(korisnik.getRola()));
Claims claims = Jwts.claims().setSubject(email);
claims.put("auth", tipoviKorisnika);
Date now = new Date();
Date validity = new Date(now.getTime() + validityInMilliseconds);
return Jwts.builder()//
.setClaims(claims)//
.setIssuedAt(now)//
.setExpiration(validity)//
.signWith(SignatureAlgorithm.HS256, secretKey)//
.compact();
}
public Authentication getAuthentication(String token) {
UserDetails userDetails = mineUserDetails.loadUserByUsername(getUsername(token));
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
}
public String getUsername(String token) {
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
}
public String resolveToken(HttpServletRequest req) {
String bearerToken = req.getHeader("Authorization");
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7, bearerToken.length());
}
return null;
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
return true;
} catch (JwtException | IllegalArgumentException e) {
throw new CustomException("Expired or invalid JWT token", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| [
"borisbibic1996@gmail.com"
] | borisbibic1996@gmail.com |
9061b159a8f08ba1d05f6bf29ef60775ac7ead55 | 0dbb5038d2ab2361263d4fed9369f7cc4109d7e9 | /src/array/easy/MergeSortedArray.java | f5aadc9808571b51a2f9f9670d98ccbea63e842e | [] | no_license | b94901099/ProJavaTutorial | 435748d0c78ed95a0c61a4932ce7893517be6c04 | 14281b31cbc0f4bb7625adcd4c67bf17c64e7f0e | refs/heads/master | 2021-01-01T04:57:47.727461 | 2016-05-10T06:17:00 | 2016-05-10T06:17:00 | 55,988,855 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 606 | java | package array.easy;
public class MergeSortedArray {
public void merge(int nums1[], int m, int nums2[], int n) {
if (nums1 == null || nums2 == null || nums1.length < 1 || nums2.length < 1) {
return;
}
int indexPos = m + n - 1;
int index1 = m - 1;
int index2 = n - 1;
while (index1 >= 0 && index2 >= 0) {
if (nums1[index1] >= nums2[index2]) {
nums1[indexPos--] = nums1[index1--];
} else {
nums1[indexPos--] = nums2[index2--];
}
}
while (index1 >= 0) {
nums1[indexPos--] = nums1[index1--];
}
while (index2 >= 0) {
nums1[indexPos--] = nums2[index2--];
}
}
}
| [
"chen@Yunlus-MacBook-Pro.local"
] | chen@Yunlus-MacBook-Pro.local |
6fd8915762fdd86b5447558e98d4baab98bc1d1b | 6756acd44bff38775cf9e67066d206e488dcd2ff | /src/main/java/com/rajtech/stockwebservice/controllers/SalesController.java | 29735c3a21201709ca5734798a68932f61ebcc4d | [
"Apache-2.0"
] | permissive | rajkumarfarshore84/stock-management | 3507ef4db4e934d8a875bae7a9b931a29944166d | da71a44e0eb430aae202a223df17b3b5254baaaa | refs/heads/develop | 2021-01-13T11:33:21.515469 | 2017-03-31T11:08:04 | 2017-03-31T11:08:04 | 81,200,868 | 0 | 0 | null | 2017-02-07T13:09:37 | 2017-02-07T11:27:45 | CSS | UTF-8 | Java | false | false | 1,331 | 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 com.rajtech.stockwebservice.controllers;
import com.rajtech.stockwebservice.utilities.Utility;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
*
* @author node
*/
@Controller
public class SalesController extends AppController implements Serializable{
@Autowired
private Utility utilHashSecure;
@RequestMapping(value = {"/admin/sales/invoice/{page}","/supervisor/sales/invoice/{page}"
,"/user/sales/invoice/{page}"},method = RequestMethod.GET)
public String listSales(@PathVariable("page") String page,ModelMap model){
try {
utilHashSecure = new Utility();
int _page = Integer.parseInt(utilHashSecure.decrypt(page));
} catch (Exception e) {
System.err.println(e);
}
return "sales/list";
}
}
| [
"rajkumarramasamy86@yahoo.in"
] | rajkumarramasamy86@yahoo.in |
8fa7073f3ff46aa755435ce1c7c9bc968858ae08 | f4004c585b169baa803a5955c0ebd1c755b53bb0 | /Dice_3.java | fb8591c9a120358dbee84f2a9abbec896dc89328 | [] | no_license | suck-at-programming/HumanRobotics_HW | e6d1876654a9a762f4c5de72db97086e2bff48a0 | c2c7ba5a81d6101868529f26875861e625bc0a69 | refs/heads/master | 2020-08-03T13:47:33.086957 | 2019-09-30T04:30:20 | 2019-09-30T04:30:20 | 211,772,712 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,165 | java | import java.util.Scanner;
class Dice_3{
public static void main(String[] args){
java.util.Scanner sc = new java.util.Scanner(System.in);
int[] numbers = new int[6];
for(int i = 0; i < 6; i++){
numbers[i] = sc.nextInt();
if(numbers[i] > 100){
System.out.println("the element is too big.");
System.exit(0);
}else{
}
}
int[] numbers2 = new int[6];
for(int i = 0; i < 6; i++){
numbers2[i] = sc.nextInt();
if(numbers2[i] > 100){
System.out.println("the element is too big.");
System.exit(0);
}else{
}
}
for(int j = 0; j < 6; j++){
for(int k = 0; k < 6; k++){
if(j == k){
}else{
if(numbers[j] == numbers[k]){
System.out.println("you can't enter same number in a Dice.");
System.exit(0);
}else{
}
}
}
}
for(int j = 0; j < 6; j++){
for(int k = 0; k < 6; k++){
if(j == k){
}else{
if(numbers2[j] == numbers2[k]){
System.out.println("you can't enter same number in a Dice.");
System.exit(0);
}else{
}
}
}
}
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 4; k++){
for(int l = 0; l < 4; l++){
if((numbers[0] == numbers2[0])&&(numbers[1] == numbers2[1])&&(numbers[2] == numbers2[2])&&
(numbers[3] == numbers2[3])&&(numbers[4] == numbers2[4])&&(numbers[5] == numbers2[5])){
System.out.println("YES");
System.exit(0);
}else{
numbers = round(numbers, 'N');
}
}
numbers = round(numbers, 'W');
}
numbers = round(numbers, 'S');
}
numbers = round(numbers, 'E');
}
System.out.println("NO");
}
public static int[] round(int[] a, char x){
if(x == 'N'){
int temp = a[0];
a[0] = a[1];
a[1] = a[5];
a[5] = a[4];
a[4] = temp;
}else if(x == 'S'){
int temp = a[0];
a[0] = a[4];
a[4] = a[5];
a[5] = a[1];
a[1] = temp;
}else if(x == 'E'){
int temp = a[0];
a[0] = a[3];
a[3] = a[5];
a[5] = a[2];
a[2] = temp;
}else if(x == 'W'){
int temp = a[0];
a[0] = a[2];
a[2] = a[5];
a[5] = a[3];
a[3] = temp;
}else{
System.out.println("move failure.");
System.exit(0);
}
return a;
}
}
| [
"noreply@github.com"
] | suck-at-programming.noreply@github.com |
34cc3cf06f94da9309ccea4955b217305e44fbdf | 1f9cb7db96f2c18d91f69b6c476b18d19a5640b3 | /src/test/java/com/redhat/empowered/TestSending.java | d10aeddbdc4d13b853be773eeea18cc999ca66b5 | [] | no_license | alainpham/amq-broker-network | f94af590cb12f3426c8a0eadee7d7d055cd39852 | 5ce966963be2de42eca4e610762047431b959088 | refs/heads/master | 2020-06-11T00:41:39.171447 | 2017-02-02T17:11:19 | 2017-02-02T17:11:19 | 75,830,874 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,033 | java | //package com.redhat.empowered;
//
//
//import java.net.URI;
//
//import org.apache.activemq.command.ActiveMQQueue;
//import org.apache.camel.EndpointInject;
//import org.apache.camel.Produce;
//import org.apache.camel.ProducerTemplate;
//import org.apache.camel.builder.RouteBuilder;
//import org.apache.camel.component.mock.MockEndpoint;
//import org.apache.camel.test.spring.CamelSpringTestSupport;
//import org.junit.After;
//import org.junit.Before;
//import org.junit.Test;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.context.support.ClassPathXmlApplicationContext;
//
//public class TestSending extends CamelSpringTestSupport {
//
// final static Logger logger = LoggerFactory.getLogger(TestSending.class);
//
//
// @Produce(uri = "s01-activemq:queue:sensor.events")
// protected ProducerTemplate inputEndpoint;
//
// @EndpointInject(uri = "mock:collector01")
// protected MockEndpoint collector01;
// @EndpointInject(uri = "mock:collector02")
// protected MockEndpoint collector02;
// @EndpointInject(uri = "mock:totalCollector")
// protected MockEndpoint totalCollector;
//
// protected ActiveMQQueue queue = new ActiveMQQueue("sensor.events");
//
// @Before
// public void setUp() throws Exception {
// super.setUp();
//
// }
//
// @After
// public void tearDown() throws Exception {
// super.tearDown();
// }
//
// @Test
// public void scaleUp() throws Exception {
//
// context.addRoutes(new RouteBuilder() {
// @Override
// public void configure() throws Exception {
// //create 2 consumers
//// from("c01-activemq:queue:sensor.events").to(collector01).to(totalCollector);
//// from("c02-activemq:queue:sensor.events").to(collector02).to(totalCollector);
// }
// });
//
// // Define some expectations
//// collector01.setMinimumExpectedMessageCount(1);
//// collector02.setMinimumExpectedMessageCount(1);
//// totalCollector.setExpectedMessageCount(1000);
// // For now, let's just wait for some messages// TODO Add some expectations here
// logger.info("Start Sending 1000 messages");
// String message = "Hello World Message!";
// //send first 500 messages
// for (int i = 0; i < 500; i++) {
// inputEndpoint.sendBody(message);
// }
// //start the broker and see that messages are redistributed
// logger.info("############### Start instance now!!! #########################");
// Thread.sleep(30000); //wait a bit for broker to connect and redistribute connections
// logger.info("############### sending further messages #########################");
//
// for (int i = 0; i < 500; i++) {
// inputEndpoint.sendBody(message);
// }
//
// Thread.sleep(5000); //wait a bit for messages to drain
// logger.info("############### scaleUp #########################");
//
// // Validate our expectations
// assertMockEndpointsSatisfied();
// }
//
//
//
// @Override
// protected ClassPathXmlApplicationContext createApplicationContext() {
// return new ClassPathXmlApplicationContext("META-INF/spring/camel-context.xml");
// }
//
//}
| [
"apham@redhat.com"
] | apham@redhat.com |
0e83d65f27c0d421d6ebd970f5d5701e4646b1a6 | 5068a3613929ed17d8cb5900e13acd797f0a2a30 | /src/com/clinicmanagement/Action/PatientAppointmentAction.java | ca4bd8b5d426bba4b9a85e816bc538b4e2f69324 | [] | no_license | PragyaDeep12/Online-Clinic-Management-System | e942881520f002ff7fe39c7764220d3c2598c2e0 | d7d136d1c278d15d3fb80a5cd9667de8b12140f0 | refs/heads/master | 2020-03-23T06:52:22.402693 | 2018-07-17T05:27:58 | 2018-07-17T05:27:58 | 141,234,094 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,438 | java | package com.clinicmanagement.Action;
import java.util.ArrayList;
import com.clinicmanagement.Dao.DatabaseHandler;
import com.clinicmanagement.Dao.DoctorDao;
import com.clinicmanagement.Dao.SlotsDao;
import com.clinicmanagement.Model.Doctor;
import com.opensymphony.xwork2.ActionSupport;
public class PatientAppointmentAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private ArrayList<Doctor> list_docs=new ArrayList<Doctor>();
private ArrayList<String> list_types=new ArrayList<String>();
private ArrayList<String> list_slot=new ArrayList<String>();
private String dept_type;
private String doctorid;
private String dtaval;
public String getDtaval() {
return dtaval;
}
public void setDtaval(String dtaval) {
this.dtaval = dtaval;
}
public ArrayList<Doctor> getList_docs() {
return list_docs;
}
public String setList_docs() {
DoctorDao dao=new DoctorDao();
ArrayList<Doctor> doctors=dao.getDoctors("Orthopedic");
ArrayList<String> doctypes=dao.gettypes();
this.list_docs = doctors;
this.list_types=doctypes;
return "DONE";
}
public ArrayList<String> getList_types() {
return list_types;
}
public void setList_types(ArrayList<String> list_types) {
this.list_types = list_types;
}
public String setList_docsnew(){
System.out.println("reached");
DoctorDao dao=new DoctorDao();
System.out.println(dept_type);
ArrayList<Doctor> doctors=dao.getDoctors(dept_type);
ArrayList<String> doctypes=dao.gettypes();
this.list_types=doctypes;
this.list_docs=doctors;
return "DONE";
}
public String checkslots(){
SlotsDao dao=new SlotsDao();
System.out.println("Doctor Id:"+doctorid);
System.out.println("Date:"+dtaval);
list_slot= dao.getslot(getDtaval(), doctorid);
System.out.println(list_slot.size());
return "DONE";
}
public String getDept_type() {
return dept_type;
}
public void setDept_type(String dept_type) {
this.dept_type = dept_type;
}
public String getDoctorid() {
return doctorid;
}
public void setDoctorid(String doctorid) {
this.doctorid = doctorid;
}
public String bookappointment(){
return "DONE";
}
public ArrayList<String> getList_slot() {
return list_slot;
}
public void setList_slot(ArrayList<String> list_slot) {
this.list_slot = list_slot;
}
}
| [
"Sourav@DESKTOP-L4F7O9H"
] | Sourav@DESKTOP-L4F7O9H |
d6ca21db61e189a09f83f978534841f0d95e3565 | a914d0eaf9fcfff1ca6beda4e36c9c6f970bdd30 | /ocp-fis/src/main/java/gov/samhsa/ocp/ocpfis/service/validation/ParticipantRoleCodeValidator.java | 84f9ef97a98702f835207b862b356b1793c92e35 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | petercyli/ocp-fis | ca67721fbf115f98454eb20d15bec8e0d5316643 | f4f607fa8c93afc5e4d5062fd037f16ec8540000 | refs/heads/master | 2022-01-09T23:54:39.691797 | 2018-09-07T19:10:48 | 2018-09-07T19:10:48 | 185,267,115 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,161 | java | package gov.samhsa.ocp.ocpfis.service.validation;
import gov.samhsa.ocp.ocpfis.service.LookUpService;
import gov.samhsa.ocp.ocpfis.service.dto.ValueSetDto;
import gov.samhsa.ocp.ocpfis.service.exception.InvalidValueException;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;
public class ParticipantRoleCodeValidator implements ConstraintValidator<ParticipantRoleCodeConstraint, String> {
@Autowired
LookUpService lookUpService;
@Override
public void initialize(ParticipantRoleCodeConstraint constraint) {
}
public boolean isValid(String roleCodeToCheck, ConstraintValidatorContext context) {
if(roleCodeToCheck == null) {
//this value is optional
return true;
}
List<ValueSetDto> list = lookUpService.getParticipantRoles();
boolean isValid = list.stream().anyMatch(t -> t.getCode().equals(roleCodeToCheck));
if(!isValid) {
throw new InvalidValueException("Received invalid Role Code for a Participant");
}
return isValid;
}
}
| [
"utish.rajkarnikar@feisystems.com"
] | utish.rajkarnikar@feisystems.com |
2fc3d988a19a6e480389d87574b69d3d38933fa0 | 1df2704575b1e896c3d53b63a0e50eee3cd3a4db | /app/src/main/java/id/example/bagasekaa/cekgadgetmu_2/user_account_edit.java | 072ca71d6846416ba160eec0c6a5ae6b7b2921d3 | [] | no_license | SameItuHiu/CekGadgetMu | f63a554492d9adf79db12b734fe6922b69d96b32 | c5196a843c24c9912457486105e8ffd7da431537 | refs/heads/master | 2020-09-02T22:49:06.281878 | 2019-11-06T19:48:57 | 2019-11-06T19:48:57 | 219,324,112 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,603 | java | package id.example.bagasekaa.cekgadgetmu_2;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class user_account_edit extends AppCompatActivity {
String userID, status;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
LinearLayout layout_mitra;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_account_edit);
layout_mitra = findViewById(R.id.layout_mitra);
//user auth
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference().child("account").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
status = dataSnapshot.child("status").getValue().toString();
if (status.equals("mitra")){
layout_mitra.setVisibility(View.VISIBLE);
}else {
layout_mitra.setVisibility(View.GONE);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public void back(View view) {
Intent intent = new Intent(user_account_edit.this, user_account.class);
startActivity(intent);
finish();
}
public void edit_telepon(View view) {
Intent intent = new Intent(user_account_edit.this, edit_telepon.class);
startActivity(intent);
finish();
}
public void edit_email(View view) {
Intent intent = new Intent(user_account_edit.this, edit_email.class);
startActivity(intent);
finish();
}
public void edit_password(View view) {
Intent intent = new Intent(user_account_edit.this, edit_password.class);
startActivity(intent);
finish();
}
public void edit_nama_toko(View view) {
Intent intent = new Intent(user_account_edit.this, edit_toko_nama.class);
startActivity(intent);
finish();
}
public void edit_alamat_toko(View view) {
Intent intent = new Intent(user_account_edit.this, edit_toko_alamat.class);
startActivity(intent);
finish();
}
public void edit_lokasi_toko(View view) {
Intent intent = new Intent(user_account_edit.this, edit_toko_lokasi.class);
startActivity(intent);
finish();
}
public void jadwal_buka(View view) {
Intent intent = new Intent(user_account_edit.this, edit_jadwal_buka_toko.class);
startActivity(intent);
finish();
}
@Override
public void onBackPressed() {
Intent intent = new Intent(this, user_account.class);
startActivity(intent);
finish();
super.onBackPressed();
}
}
| [
"sameituhiu@gmail.com"
] | sameituhiu@gmail.com |
808ecb13f63f927e2fdc2647a6a2310f732ef0f2 | ea2d58dc9a5f00868a39d72b34805188d354d76b | /app/src/main/java/cn/cbdi/savecap/Tools/ActivityCollector.java | 665e8d1e6aeadc52dfd64829cb096fb8a9aebea8 | [] | no_license | goalgate/SaveCap | 0202507b9241fb8ee2b66d35513918fca1070e1c | d499d89ce61f90f7a138c93bdf4156525ef3f062 | refs/heads/master | 2020-05-30T06:29:39.991509 | 2019-06-19T12:28:29 | 2019-06-19T12:28:49 | 189,579,807 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 695 | java | package cn.cbdi.savecap.Tools;
import android.app.Activity;
import com.baidu.aip.manager.FaceSDKManager;
import java.util.ArrayList;
import java.util.List;
public class ActivityCollector {
public static List<Activity> activities = new ArrayList<>();
public static void addActivity(Activity activity){
activities.add(activity);
}
public static void removeActivity(Activity activity){
activities.remove(activity);
}
public static void finishAll(){
FaceSDKManager.getInstance().release();
for (Activity activity:activities){
if (!activity.isFinishing()){
activity.finish();
}
}
}
}
| [
"522508134@qq.com"
] | 522508134@qq.com |
9964a9aab373dd6b9241095b309b4287b258bac1 | 2a59a3cbfcf639b7158bf46aa7dd6da89478fbaa | /Cassandra-Neo4j-Confronto/NetBeans Query & Import Cassandra/Cassandra/src/main/java/com/dario/cassandra/UploadContractAward.java | 56dab4433c35adbe4b9a9c3a67eb1fd702d6d386 | [] | no_license | dariofama96/Benchmark-Cassandra-Neo4j | 597eb5ede81773f86ed1894fff86d4ee36cf07e3 | 1e9306c9cf12ab973cf72f13c864df33bb8048ed | refs/heads/master | 2022-07-30T15:24:00.534602 | 2019-11-12T13:00:31 | 2019-11-12T13:00:31 | 221,227,696 | 0 | 0 | null | 2022-06-27T16:15:09 | 2019-11-12T13:44:04 | Java | UTF-8 | Java | false | false | 4,611 | java |
package com.dario.cassandra;
import com.datastax.spark.connector.japi.CassandraJavaUtil;
import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapToRow;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
public class UploadContractAward {
private static final String CSV_FILE_PATH = "C://Users//Dario//Desktop//50000.csv";
public static void main(String[] args) throws IOException {
SparkConf conf = new SparkConf();
conf.setAppName("Ciao");
conf.set("spark.master", "local");
conf.set("spark.cassandra.connection.host", "localhost");
JavaSparkContext sc = new JavaSparkContext(conf);
Map<String, ContractAward> mappa = new HashMap<String, ContractAward>();
ContractAward contr;
Reader reader;
CSVParser csvParser = null;
try {
reader = Files.newBufferedReader(Paths.get(CSV_FILE_PATH), StandardCharsets.UTF_8);
csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().withDelimiter(';').parse(reader);
for (CSVRecord csvRecord : csvParser) {
// Accessing values by the names assigned to each column
String id_award = csvRecord.get("ID_AWARD");
if(!id_award.equals("")){
contr = mappa.get(id_award);
if (contr == null) {
contr = new ContractAward();
contr.setIdAward(csvRecord.get("ID_AWARD"));
contr.setWinTown(csvRecord.get("WIN_TOWN"));
contr.setWinName(csvRecord.get("WIN_NAME"));
contr.setWinCountryCode(csvRecord.get("WIN_COUNTRY_CODE"));
if(!csvRecord.get("AWARD_VALUE_EURO_FIN_1").equals("")){
contr.setContractPrice(Float.parseFloat(
csvRecord.get("AWARD_VALUE_EURO_FIN_1")));
}
mappa.put(id_award, contr);
List<ContractAward> listainserimento = new ArrayList<ContractAward>(mappa.values());
JavaRDD<ContractAward> parallelize = sc.parallelize(listainserimento);
CassandraJavaUtil.javaFunctions(parallelize)
.writerBuilder("database2", "contract_award", mapToRow(ContractAward.class)).saveToCassandra();
}
/*int id_notice_can = Integer.parseInt(csvRecord.get("ID"));
String cae_name = csvRecord.get("CAE_NAME");
String cae_town = csvRecord.get("CAE_TOWN");
String cae_type = csvRecord.get("CAE_TYPE");
String main_activity = csvRecord.get("MAIN_ACTIVITY");
String type_of_contract = csvRecord.get("TYPE_OF_CONTRACT");
String id_award = csvRecord.get("ID_AWARD");
String id_lot_awarded = csvRecord.get("ID_LOT_AWARDED");
String win_name = csvRecord.get("WIN_NAME");
String win_town = csvRecord.get("WIN_TOWN");
String win_country_code = csvRecord.get("WIN_COUNTRY_CODE");
String title = csvRecord.get("TITLE");
String number_offers = csvRecord.get("NUMBER_OFFERS");
String award_value_euro = csvRecord.get("AWARD_VALUE_EURO_FIN_1");
String dt_award = csvRecord.get("DT_AWARD");
/*System.out.println("Record No - " + csvRecord.getRecordNumber());
System.out.println("---------------");
//System.out.println(id_notice_can);
System.out.println(contract_number);
System.out.println(title);
System.out.println(number_offers);
System.out.println("---------------\n\n");*/
}
}
}catch (IOException ex) {
Logger.getLogger(UploadAuthority.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| [
"57667453+dariofama96@users.noreply.github.com"
] | 57667453+dariofama96@users.noreply.github.com |
cadff4fcc85e09259435734564bd07b3878a27c1 | dff07fc0e2542c367ff3cc34c149aed582121d90 | /src/com/company/lesson8/СircleComtuting/SecondCicrle.java | be0f3fae2a503593d13f4dca23a242351f012c84 | [] | no_license | vladddooonnn96/vladddooonnn | e6e833a0d102882634783e4515b5730ca5da712d | e8f95f023fa27e18df2d44ae16e6727572a1cb14 | refs/heads/master | 2021-04-29T17:33:12.308962 | 2018-03-19T15:02:58 | 2018-03-19T15:02:58 | 121,659,888 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 566 | java | package com.company.lesson8.СircleComtuting;
public class SecondCicrle {
private double radius;
private final double pi=3.14;
public SecondCicrle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getPi() {
return pi;
}
public double area(){
return (getRadius()*getRadius())*pi;
}
public double lengthCircle(){
return 2 * pi * getRadius();
}
}
| [
"madara110@mail.ru"
] | madara110@mail.ru |
4110d7824508b28aa9439155c382e8f7ba555dd1 | d82a72c5c1f6774663b25c6a0797ce9b2d306f28 | /src/main/java/com/company/constant/ActionKeys.java | 974f7217f45517b976e1bd234cd5244ba0311c72 | [] | no_license | linux-root/ATM | df52a97101c54c648c64b51b542ca98599325287 | 437dc1fcb7453de31716d3cc9af30e0c1240b171 | refs/heads/master | 2022-12-31T11:23:47.880244 | 2020-10-18T11:48:31 | 2020-10-18T11:48:31 | 305,082,741 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 190 | java | package com.company.constant;
public class ActionKeys {
public static String BALANCE = "B";
public static String WITHDRAW = "W";
public static String TERMINATE_SESSION = "";
}
| [
"khanhdb@MacBook-Air-cua-MVFH2.local"
] | khanhdb@MacBook-Air-cua-MVFH2.local |
cadbf7616ac8f2fe216282dee9e72369eb015e31 | ebbd16e3651d0ce6b83eb048cb6b5e7da01e041e | /server/java/MonsysServer/src/com/letsmidi/monsys/login/LoginServerApp.java | 3d63d0b02fec50c37e33b35b5f68ea91b9aafdf8 | [] | no_license | zaopuppy/monsys | bbd71dda7517cd87ef6e9f0712d03d342f3ee7a2 | ee965530cb82193bd0bd885f2f691a55bfa6f41e | refs/heads/master | 2020-05-17T12:23:07.426719 | 2015-06-28T16:10:33 | 2015-06-28T16:10:33 | 8,972,992 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,836 | java | package com.letsmidi.monsys.login;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.letsmidi.monsys.database.AccountInfo;
import com.letsmidi.monsys.log.LogFormatter;
import com.letsmidi.monsys.protocol.client.Client.ClientMsg;
import com.letsmidi.monsys.protocol.commserver.CommServer;
import com.letsmidi.monsys.util.HibernateUtil;
import com.letsmidi.monsys.util.MonsysException;
import com.letsmidi.monsys.util.NettyUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.HashedWheelTimer;
/**
* 开发的时候,阅读参考了某公司的开源服务端代码,有如下问题:
* <p>
* 1. 服务端和客户端共用一个监听,根据上报的类型区分服务端和客户端,很容易欺骗伪装为服务端,从而得到客户端的隐私(用户名,密码,聊天记录)
* -- 分开监听
* <p>
* 2. 流程上是先申请服务端再进行登录,也就是说可以在没有用户名和密码的情况下就能枚举所有服务端
* -- 也许做两次验证(login & msg server各一次)可以解决这个问题?
*/
public class LoginServerApp {
private final Logger mLogger = Logger.getLogger(LoginConfig.LoggerName);
public static void main(String[] args) throws IOException, MonsysException {
//Config.load();
initLogger();
Class[] mapping_classes = new Class[]{
AccountInfo.class,
};
// initialize hibernate
if (!HibernateUtil.init(mapping_classes)) {
System.out.println("Failed to initialize hibernate, failed");
return;
}
LoginServerApp push_server = new LoginServerApp();
push_server.start();
}
private static void initLogger() throws IOException {
Handler log_handler = new FileHandler(LoginConfig.LoggerFileName, 1 << 20, 10000, true);
final Logger logger = Logger.getLogger(LoginConfig.LoggerName);
logger.setLevel(Level.ALL);
logger.addHandler(log_handler);
for (Handler h : logger.getHandlers()) {
System.out.println("handler: " + h.getClass().getCanonicalName());
h.setFormatter(new LogFormatter());
}
}
public void start() {
mLogger.info("-----------------------------------");
mLogger.info("login server start");
// global timer
final HashedWheelTimer timer = new HashedWheelTimer(1, TimeUnit.SECONDS);
timer.start();
ArrayList<EventLoopGroup> group_list = new ArrayList<>();
ArrayList<ChannelFuture> future_list = new ArrayList<>();
// share worker
NioEventLoopGroup shared_worker = new NioEventLoopGroup();
group_list.add(shared_worker);
// listen clients
NioEventLoopGroup client_boss = new NioEventLoopGroup(1);
ChannelFuture client_future = NettyUtil.startServer(
LoginConfig.ClientListenPort, client_boss, shared_worker,
new LoggingHandler(LoginConfig.LoggerName, LogLevel.INFO),
new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(
new ProtobufVarint32LengthFieldPrepender(),
new ProtobufVarint32FrameDecoder(),
new ProtobufEncoder(),
new ProtobufDecoder(ClientMsg.getDefaultInstance()),
new ClientHandler(timer));
}
}
);
group_list.add(client_boss);
future_list.add(client_future);
// listen servers
NioEventLoopGroup msg_server_boss = new NioEventLoopGroup(1);
ChannelFuture msg_server_future = NettyUtil.startServer(
LoginConfig.CommServerListenPort, msg_server_boss, shared_worker,
new LoggingHandler(LoginConfig.LoggerName, LogLevel.INFO),
new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(
new ProtobufVarint32LengthFieldPrepender(),
new ProtobufVarint32FrameDecoder(),
new ProtobufEncoder(),
new ProtobufDecoder(CommServer.CommServerMsg.getDefaultInstance()),
new CommServerHandler(timer));
}
}
);
group_list.add(msg_server_boss);
future_list.add(msg_server_future);
group_list.add(shared_worker);
// wait
future_list.forEach(f -> {
try {
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// clean up
group_list.forEach(io.netty.channel.EventLoopGroup::shutdownGracefully);
}
}
| [
"zhaoyi.zero@gmail.com"
] | zhaoyi.zero@gmail.com |
a639c07a50c40595e562d6a02acc8ee1bd932435 | 47fd76c6d791ea6508e3a89388cb4683469f226b | /leetcode/problems/arrays/ThreeSum.java | 9ced8fc9ee5a8b890803f08138fec599192ce505 | [] | no_license | AmrutaKajrekar/ProgrammingConcepts | 6e88100cdb27832aae7664db645c799a79537c9a | 300f2d808e81801adddea1be0a86c98e6a4b92bb | refs/heads/develop | 2023-04-29T12:25:31.652130 | 2019-09-26T01:40:09 | 2019-09-26T01:40:09 | 60,045,119 | 0 | 0 | null | 2018-08-12T23:02:05 | 2016-05-30T23:47:36 | Java | UTF-8 | Java | false | false | 6,235 | java | package problems.arrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author amruta.kajrekar on 5/4/18.
* leetcode problem #15
* Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
*/
public class ThreeSum {
public static void main(String[] args){
ThreeSum sum = new ThreeSum();
// System.out.println(sum.uniqueMorseRepresentations(new String[]{"vtpke","vngc","vnqr","gbzx","qvdx"}));
// System.out.println(sum.superPow(2, new int[]{3,5,6}));
// System.out.println(sum.validPalindrome(
//"aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga"));
System.out.print(sum.threeSum(new int[]{-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6}));
//[[-4,-2,6],[-4,0,4],[-4,1,3],[-4,2,2],[-2,-2,4],[-2,0,2]]
}
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> list = new ArrayList<List<Integer>>();
Set<String> set = new HashSet<>();
int l=0;
int r=nums.length-1;
int temp=-999; int count=1;
while(l<r && l>=0 && r>=0){
for(int i=l+1;i<nums.length-1;i++){
System.out.println("l,i,r:"+ l+","+i+","+ r+"=="+nums[l]+","+nums[i]+","+nums[r]);
temp = nums[l]+nums[r]+nums[i];
if(temp==0 && l!=r && r!=i && l!=i){
List<Integer> nl = new ArrayList<>();
nl.add(nums[l]);
nl.add(nums[i]);
nl.add(nums[r]);
Collections.sort(nl);
if(set.add(nl.get(0)+","+nl.get(1)+","+nl.get(2))) {
list.add(nl);
}
}
}
if(count%2==0) r--;
else l++;
count++;
}
return list;
}
// private boolean doesExist(List<List<Integer>> list, List<Integer> nl) {
// for(List<Integer> l:list){
// HashMap map = new HashMap();
// for (Integer sub:l) {
// map.put(sub,);
// }
// }
// }
private void printArray(int[] nums) {
for(int i=0;i<nums.length;i++){
System.out.print(nums[i]+",");
}
}
// public List<List<Integer>> threeSum(int[] nums) {
//
// }
public double myPow(double x, int n) {
return Math.pow(x,new Double(n));
}
public int superPow(int a, int[] b) {
System.out.println(Arrays.toString(b).replaceAll("[^0-9]+", ""));
int power = (int) Math
.pow(new Double(a), new Double(Integer.parseInt(Arrays.toString(b).replaceAll("[^0-9]+", ""))));
return power % 1337;
}
public int sqrt(int x){
return (int)Math.sqrt(x);
}
public int uniqueMorseRepresentations(String[] words) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("a",".-"); map.put("b","-..."); map.put("c","-.-."); map.put("d","-.-."); map.put("e","."); map.put("f","..-.");
map.put("g","--."); map.put("h","...."); map.put("i",".."); map.put("j",".---"); map.put("k","-.-"); map.put("l",".-..");
map.put("m","--"); map.put("n","-."); map.put("o","---"); map.put("p",".--."); map.put("q","--.-"); map.put("r",".-.");
map.put("s","..."); map.put("t","-"); map.put("u","..-"); map.put("v","...-"); map.put("w",".--"); map.put("x","-..-");
map.put("y","-.--"); map.put("z","--..");
Set<String> returnSet = new HashSet<String>();
for(int i=0;i<words.length;i++){
StringBuilder str = new StringBuilder();
for(int j=0;j<words[i].length();j++){
System.out.println(words[i].charAt(j) + " >>> " + map.get(Character.toString(words[i].charAt(j))));
str.append(map.get(Character.toString(words[i].charAt(j))));
}
System.out.println(str.toString());
returnSet.add(str.toString());
}
return returnSet.size();
}
public boolean validPalindrome(String s) {
int front =0, end = s.length()-1;
while(front<=end){
if(s.charAt(front)!=s.charAt(end)){
return (isPal(s,front+1,end) || isPal(s,front,end-1));
}
front++;
end--;
}
return true;
}
private boolean isPal(String s, int front, int end) {
while(front<end){
if(s.charAt(front)!=s.charAt(end)) return false;
front++;end--;
}
return true;
}
public boolean validPalindrome2(String s) {
int front =0, end = s.length()-1;
int count =0;
while(front<=end){
if(front==end && count==1) return false;
if(s.charAt(front)!=s.charAt(end)){
System.out.println(s.charAt(front) + " >>> " + s.charAt(end));
count++;
if(s.charAt(front+1) == s.charAt(end)){
if(count>1) {
System.out.println("s.charAt(front+1) == s.charAt(end)");
return false;
}
front++;
}else if(s.charAt(front) == s.charAt(end-1)){
if(count>1) {
System.out.println("s.charAt(front) == s.charAt(end-1)");
return false;
}
end--;
}else{
System.out.println("front = " + front + "end = "+end);
System.out.println(s.charAt(front) + " >>> " + s.charAt(end));
if(count>1) return false;
}
}
front++;
end--;
}
if(count>1) return false;
else return true;
}
}
| [
"amruta.kajrekar@ge.com"
] | amruta.kajrekar@ge.com |
d20338311c9d9d17843029d04ae4dfe38229dc19 | 4270762871a0513996763aec4841a68394309805 | /servlet-gui-client/ComputerShopRediscount/src/main/java/com/cherkashyn/vitalii/computer_shop/rediscount/domain/PatternOfMoneyNote.java | 121981310554c6b0aab07b400861597afd18e512 | [] | no_license | cherkavi/java-web | 0e80c901c5f6b60e8a575a08f4047ee427b71bf8 | 6ae2a5fefef99c19792cffbff7689b737f070251 | refs/heads/master | 2022-12-22T06:04:08.688298 | 2020-11-22T21:23:24 | 2020-11-22T21:23:24 | 65,675,689 | 1 | 0 | null | 2022-12-16T04:26:03 | 2016-08-14T16:27:39 | Java | UTF-8 | Java | false | false | 961 | java | package com.cherkashyn.vitalii.computer_shop.rediscount.domain;
// Generated 14.09.2013 14:22:22 by Hibernate Tools 3.4.0.CR1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* PatternOfMoneyNote generated by hbm2java
*/
@Entity
@Table(name = "PATTERN_OF_MONEY_NOTE")
public class PatternOfMoneyNote implements java.io.Serializable {
private int kod;
private String name;
public PatternOfMoneyNote() {
}
public PatternOfMoneyNote(int kod) {
this.kod = kod;
}
public PatternOfMoneyNote(int kod, String name) {
this.kod = kod;
this.name = name;
}
@Id
@Column(name = "KOD", unique = true, nullable = false)
public int getKod() {
return this.kod;
}
public void setKod(int kod) {
this.kod = kod;
}
@Column(name = "NAME", length = 50)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
| [
"technik7job@gmail.com"
] | technik7job@gmail.com |
30ab1bd97940bd7142eaac24065f783030a81912 | 082e26b011e30dc62a62fae95f375e4f87d9e99c | /docs/weixin_7.0.4_source/反编译源码/未反混淆/src/main/java/com/tencent/mm/plugin/m/b.java | 933f406fc931fda58d3117ee99ec8804bc3c7208 | [] | no_license | xsren/AndroidReverseNotes | 9631a5aabc031006e795a112b7ac756a8edd4385 | 9202c276fe9f04a978e4e08b08e42645d97ca94b | refs/heads/master | 2021-04-07T22:50:51.072197 | 2019-07-16T02:24:43 | 2019-07-16T02:24:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 510 | java | package com.tencent.mm.plugin.m;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.kernel.b.c;
public final class b implements c {
private static b ops;
private b() {
}
public static synchronized b bOh() {
b bVar;
synchronized (b.class) {
AppMethodBeat.i(79105);
if (ops == null) {
ops = new b();
}
bVar = ops;
AppMethodBeat.o(79105);
}
return bVar;
}
}
| [
"alwangsisi@163.com"
] | alwangsisi@163.com |
2673ce08067db2c7a24aeb8a9e67d45f9c0f7bc3 | 7547af61f0ba9008c40448e29562c5bcd93b9288 | /src/matrix/BigDecimalMatrix.java | 4e6a39d8b16ae42fbcb797bff290702bb331c2e2 | [] | no_license | parkerahall/matrix | 69e0b3b9211a0cbead8d3ffd12692b4c47533201 | 9ba46fa952487afb1d3b8e5e89f88781da651797 | refs/heads/master | 2021-01-23T06:05:40.568122 | 2017-08-28T21:53:19 | 2017-08-28T21:53:19 | 93,010,633 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 26,351 | java | package matrix;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/*
* Implementation of Matrix with nonzero dimensions.
*/
public class BigDecimalMatrix implements Matrix<BigDecimal> {
private final static Complex ONE = new Complex(1, 0);
private final static Complex ZERO = new Complex(0, 0);
private final static BigDecimal ERROR = new BigDecimal(Math.pow(10, -5));
private final static int RREF_INDEX = 0;
private final static int INV_INDEX = 1;
private final BigDecimal[][] matrix;
private final int numRows;
private final int numCols;
public BigDecimalMatrix(double[][] entries) {
matrix = new BigDecimal[entries.length][entries[0].length];
for (int row = 0; row < entries.length; row++) {
double[] currentRow = entries[row];
for (int column = 0; column < currentRow.length; column++) {
matrix[row][column] = new BigDecimal(currentRow[column]);
}
}
numRows = entries.length;
numCols = entries[0].length;
}
public BigDecimalMatrix(int[][] entries) {
matrix = new BigDecimal[entries.length][entries[0].length];
for (int row = 0; row < entries.length; row++) {
int[] currentRow = entries[row];
for (int column = 0; column < currentRow.length; column++) {
matrix[row][column] = new BigDecimal(currentRow[column]);
}
}
numRows = entries.length;
numCols = entries.length;
}
public BigDecimalMatrix(BigDecimal[][] entries) {
matrix = new BigDecimal[entries.length][entries[0].length];
for (int row = 0; row < entries.length; row++) {
BigDecimal[] currentRow = entries[row];
for (int column = 0; column < currentRow.length; column++) {
matrix[row][column] = currentRow[column];
}
}
numRows = entries.length;
numCols = entries[0].length;
}
public BigDecimalMatrix(List<List<Double>> entries) {
matrix = new BigDecimal[entries.size()][entries.get(0).size()];
for (int row = 0; row < entries.size(); row++) {
List<Double> currentRow = entries.get(row);
for (int column = 0; column < currentRow.size(); column++) {
matrix[row][column] = new BigDecimal(currentRow.get(column));
}
}
numRows = entries.size();
numCols = entries.get(0).size();
}
public static Matrix<BigDecimal> identity(int size) {
double[][] newMatrix = new double[size][size];
for (int i = 0; i < size; i++) {
newMatrix[i][i] = 1;
}
return new BigDecimalMatrix(newMatrix);
}
@Override
public BigDecimal getElement(int row, int column) throws IndexOutOfBoundsException {
if (row < 0 || row >= numRows || column < 0 || column >= numCols) {
throw new IndexOutOfBoundsException("Location out of bounds");
}
return matrix[row][column];
}
@Override
public int[] size() {
int[] dimensions = {numRows, numCols};
return dimensions;
}
@Override
public BigDecimal[] getRow(int row) throws IndexOutOfBoundsException {
if (row < 0 || row >= numRows) {
throw new IndexOutOfBoundsException("Row index out of bounds");
}
BigDecimal[] currentRow = matrix[row];
BigDecimal[] copyRow = new BigDecimal[numCols];
for (int i = 0; i < numCols; i++) {
copyRow[i] = currentRow[i];
}
return copyRow;
}
@Override
public BigDecimal[] getColumn(int column) throws IndexOutOfBoundsException {
if (column < 0 || column >= numCols) {
throw new IndexOutOfBoundsException("Column index out of bounds");
}
BigDecimal[] copyColumn = new BigDecimal[numRows];
for (int i = 0; i < numRows; i++) {
copyColumn[i] = matrix[i][column];
}
return copyColumn;
}
@Override
public Matrix<BigDecimal> add(Matrix<BigDecimal> matr) throws IncompatibleDimensionsException {
int[] thisSize = size();
int[] thatSize = matr.size();
if (thisSize[0] != thatSize[0] || thisSize[1] != thatSize[1]) {
throw new IncompatibleDimensionsException("Invalid dimensions for addition");
}
BigDecimal[][] newMatrix = new BigDecimal[thisSize[0]][thisSize[1]];
for (int row = 0; row < thisSize[0]; row++) {
for (int column = 0; column < thisSize[1]; column++) {
newMatrix[row][column] = getElement(row, column).add(matr.getElement(row, column));
}
}
return new BigDecimalMatrix(newMatrix);
}
@Override
public Matrix<BigDecimal> subtract(Matrix<BigDecimal> matr) throws IncompatibleDimensionsException {
int[] thisSize = size();
int[] thatSize = matr.size();
if (thisSize[0] != thatSize[0] || thisSize[1] != thatSize[1]) {
throw new IncompatibleDimensionsException("Invalid dimensions for addition");
}
BigDecimal[][] newMatrix = new BigDecimal[thisSize[0]][thisSize[1]];
for (int row = 0; row < thisSize[0]; row++) {
for (int column = 0; column < thisSize[1]; column++) {
newMatrix[row][column] = getElement(row, column).subtract(matr.getElement(row, column));
}
}
return new BigDecimalMatrix(newMatrix);
}
@Override
public Matrix<BigDecimal> multiply(Matrix<BigDecimal> matr) throws IncompatibleDimensionsException {
int[] thisSize = size();
int[] thatSize = matr.size();
if (thisSize[1] != thatSize[0]) {
throw new IncompatibleDimensionsException("Invalid dimensions for multiplication");
}
BigDecimal[][] newMatrix = new BigDecimal[thisSize[0]][thatSize[1]];
for (int row = 0; row < thisSize[0]; row++) {
BigDecimal[] currentRow = matrix[row];
for (int column = 0; column < thatSize[1]; column++) {
BigDecimal[] currentColumn = matr.getColumn(column);
BigDecimal dotProduct = BigDecimal.ZERO;
for (int i = 0; i < thisSize[1]; i++) {
BigDecimal partial = currentRow[i].multiply(currentColumn[i]);
dotProduct = dotProduct.add(partial);
}
newMatrix[row][column] = dotProduct;
}
}
return new BigDecimalMatrix(newMatrix);
}
@Override
public Matrix<BigDecimal> multiply(double element) {
BigDecimal[][] newMatrix = new BigDecimal[matrix.length][matrix[0].length];
for (int row = 0; row < numRows; row++) {
BigDecimal[] currentRow = matrix[row];
for (int column = 0; column < numCols; column++) {
BigDecimal currentElement = currentRow[column];
newMatrix[row][column] = currentElement.multiply(new BigDecimal(element));
}
}
return new BigDecimalMatrix(newMatrix);
}
@Override
public Matrix<BigDecimal> rref() {
return rrefAndPseudoInverse().get(RREF_INDEX);
}
@Override
public int rank() {
int numNonzeroRows = 0;
Matrix<BigDecimal> ref = rref();
for (int row = 0; row < ref.size()[0]; row++) {
if (ref.rowNotZero(row)) {
numNonzeroRows += 1;
} else {
return numNonzeroRows;
}
}
return numNonzeroRows;
}
@Override
public int nullity() {
int rank = rank();
return numCols - rank;
}
@Override
/**
* @return a String representation of the matrix in the following form:
* 1 0 0
* 0 1 0
* 0 0 1
*/
public String toString() {
String grid = "";
for (int row = 0; row < numRows; row++) {
BigDecimal[] currentRow = matrix[row];
for (int column = 0; column < numCols; column++) {
String currentElt = currentRow[column].toString();
if (column == numCols - 1) {
grid += currentElt + "\n";
} else {
grid += currentElt + "\t";
}
}
}
return grid;
}
/**
* two matrices are considered equivalent if their dimensions are the same, and each element
* is equal up to an error of 10^(-15)
* this and that must have both have BigDecimal elements
*/
@Override
public boolean equals(Object that) {
if (!(that instanceof Matrix)) return false;
// warnings suppressed as javadoc requires that to be Matrix<BigDecimal>
@SuppressWarnings("unchecked")
Matrix<BigDecimal> thatMat = (Matrix<BigDecimal>)that;
int[] thisDim = size();
int[] thatDim = thatMat.size();
if (thisDim[0] != thatDim[0] || thisDim[1] != thatDim[1]) {
return false;
}
for (int i = 0; i < thisDim[0]; i++) {
for (int j = 0; j < thisDim[1]; j++) {
BigDecimal thisElt = getElement(i, j);
BigDecimal thatElt = thatMat.getElement(i, j);
if (thisElt.subtract(thatElt).abs().compareTo(ERROR) == 1) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
double sum = 0;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
sum += getElement(i, j).doubleValue();
}
}
return (int)sum % 10000;
}
@Override
public BigDecimal determinant() throws IncompatibleDimensionsException {
if (numRows != numCols) {
throw new IncompatibleDimensionsException("Determinant not defined for non-square matrix");
}
if (numCols == 1) {
return getElement(0,0);
}
BigDecimal[] firstRow = getRow(0);
BigDecimal determinant = BigDecimal.ZERO;
for (int i = 0; i < numRows; i++) {
BigDecimal cofactor = firstRow[i];
BigDecimal sign = new BigDecimal(Math.pow(-1, i));
Matrix<BigDecimal> minor = minor(0, i);
BigDecimal minorDet = minor.determinant();
determinant = determinant.add(sign.multiply(cofactor.multiply(minorDet)));
}
return determinant;
}
@Override
public Matrix<BigDecimal> minor(int row, int column) throws IndexOutOfBoundsException, IncompatibleDimensionsException {
if (numRows != numCols) {
throw new IncompatibleDimensionsException("Matrix needs to be square");
}
if (row >= numRows || column >= numCols || row < 0 || column < 0) {
throw new IndexOutOfBoundsException("Indices out of range");
}
BigDecimal[][] minorMatrix = new BigDecimal[numRows - 1][numCols - 1];
int currentRow = 0;
for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {
if (rowIndex != row) {
int currentCol = 0;
for (int colIndex = 0; colIndex < numCols; colIndex++) {
if (colIndex != column) {
minorMatrix[currentRow][currentCol] = matrix[rowIndex][colIndex];
currentCol++;
}
}
currentRow++;
}
}
return new BigDecimalMatrix(minorMatrix);
}
@Override
public Matrix<BigDecimal> inverse() throws IncompatibleDimensionsException {
if (numRows != numCols) {
throw new IncompatibleDimensionsException("Inverse not defined for non-square matrix");
}
BigDecimal determinant = determinant();
if (determinant.compareTo(BigDecimal.ZERO) == 0) {
throw new IncompatibleDimensionsException("Inverse not defined for matrices with determinant of zero");
}
return rrefAndPseudoInverse().get(INV_INDEX);
}
@Override
public Set<Matrix<BigDecimal>> nullspace() {
//perform same column operations on matrix and identity simultaneously, similarly to inverse
//any zero columns in augmented matrix correspond to columns in augmented id that are in nullspace of matrix
//construct transpose of matrix
BigDecimalMatrix transpose = (BigDecimalMatrix)transpose();
//find ref and inverse of transpose
List<Matrix<BigDecimal>> matrices = transpose.rrefAndPseudoInverse();
Matrix<BigDecimal> rref = matrices.get(RREF_INDEX);
Matrix<BigDecimal> inverse = matrices.get(INV_INDEX);
int[] dimensions = rref.size();
//any zero rows in ref correspond to the transpose of nullspace vectors in inverse
Set<Matrix<BigDecimal>> nullspace = new HashSet<>();
for (int row = 0; row < dimensions[1]; row++) {
if (!rref.rowNotZero(row)) {
BigDecimal[] nullArr = inverse.getRow(row);
BigDecimal[][] colArr = new BigDecimal[dimensions[1]][1];
for (int columnIndex = 0; columnIndex < dimensions[1]; columnIndex++) {
colArr[columnIndex][0] = nullArr[columnIndex];
}
Matrix<BigDecimal> columnVec = new BigDecimalMatrix(colArr);
nullspace.add(columnVec);
}
}
return nullspace;
}
@Override
public Matrix<BigDecimal> transpose() {
BigDecimal[][] transposeArr = new BigDecimal[numCols][numRows];
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
transposeArr[j][i] = matrix[i][j];
}
}
return new BigDecimalMatrix(transposeArr);
}
@Override
public boolean rowNotZero(int row) {
BigDecimal[] currentRow = matrix[row];
for (BigDecimal elt: currentRow) {
if (elt.compareTo(BigDecimal.ZERO) != 0) {
return true;
}
}
return false;
}
@Override
public Matrix<BigDecimal> stack(Matrix<BigDecimal> bottom) throws IncompatibleDimensionsException {
int[] thisDims = this.size();
int[] thatDims = bottom.size();
if (thisDims[1] != thatDims[1]) {
throw new IncompatibleDimensionsException("Unable to stack due to different number of columns");
}
BigDecimal[][] newMatrix = new BigDecimal[thisDims[0] + thatDims[1]][numCols];
for (int i = 0; i < numRows; i++) {
BigDecimal[] currentRow = this.getRow(i);
newMatrix[i] = currentRow;
}
for (int j = 0; j < thatDims[0]; j++) {
BigDecimal[] currentRow = bottom.getRow(j);
newMatrix[numRows + j] = currentRow;
}
return new BigDecimalMatrix(newMatrix);
}
@Override
public Complex[] eigenvalues() throws IncompatibleDimensionsException {
if (numRows != numCols) {
throw new IncompatibleDimensionsException("Eigenvalues not defined for non-square matrix");
}
if (numCols == 1) {
Complex[] output = new Complex[1];
output[0] = new Complex(this.getElement(0, 0).doubleValue(), 0);
return output;
}
Polynomial<Complex>[][] polyGrid = new ComplexPoly[numRows][numCols];
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
Polynomial<Complex> newElt;
BigDecimal matrixElt = this.getElement(i, j).negate();
Complex complexElt = new Complex(matrixElt.doubleValue(), 0);
if (i == j) {
Complex[] diagonalPolyArray = new Complex[2];
diagonalPolyArray[0] = complexElt;
diagonalPolyArray[1] = ONE;
newElt = new ComplexPoly(diagonalPolyArray);
} else {
newElt = new ComplexPoly(complexElt);
}
polyGrid[i][j] = newElt;
}
}
Polynomial<Complex> determinant = BigDecimalMatrix.determinantFromArray(polyGrid);
return determinant.zeroes((int)-Math.log(ERROR.doubleValue()));
}
@Override
public Map<Complex, Set<Matrix<Complex>>> eigenMap() throws IncompatibleDimensionsException {
Map<Complex, Set<Matrix<Complex>>> mapping = new HashMap<>();
Complex[] eigenvalues = this.eigenvalues();
for (Complex ev: eigenvalues) {
Set<Matrix<Complex>> eigenvectors = this.eigenvectors(ev);
mapping.put(ev, eigenvectors);
}
return mapping;
}
@Override
public Set<Matrix<Complex>> eigenvectors(Complex eigenvalue) throws IncompatibleDimensionsException {
if (numRows != numCols) {
throw new IncompatibleDimensionsException("Matrix must be square");
}
Complex[][] lambdaIArr = new Complex[numRows][numCols];
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (i == j) {
lambdaIArr[i][j] = eigenvalue;
} else {
lambdaIArr[i][j] = ZERO;
}
}
}
Matrix<Complex> thisComplex = this.convertToComplex();
Matrix<Complex> lambdaI = new ComplexMatrix(lambdaIArr);
Matrix<Complex> adjusted = thisComplex.subtract(lambdaI);
return adjusted.nullspace();
}
/**
* checks whether row contains nonzero values
* @param row array of BigDecimals
* @return false if row only contains 0, true otherwise
*/
private static boolean rowNotZero(BigDecimal[] row) {
for (BigDecimal elt: row) {
if (elt.compareTo(BigDecimal.ZERO) != 0) {
return true;
}
}
return false;
}
/**
* Returns minor two-dimensional array (must be square)
* @param grid two-dimensional array of complex polynomials
* @param row row index
* @param column column index
* @return two-dimensional grid representing minor matrix
* @throws ArrayIndexOutOfBoundsException if indices not in range
*/
private static Polynomial<Complex>[][] minorFromArray(Polynomial<Complex>[][] grid, int row, int column)
throws ArrayIndexOutOfBoundsException {
List<List<Polynomial<Complex>>> newGrid = new ArrayList<>();
for (int rowIndex = 0; rowIndex < grid.length; rowIndex++) {
if (rowIndex != row) {
List<Polynomial<Complex>> newRow = new ArrayList<>();
for (int colIndex = 0; colIndex < grid.length; colIndex++) {
if (colIndex != column) {
newRow.add(grid[rowIndex][colIndex]);
}
}
newGrid.add(newRow);
}
}
Polynomial<Complex>[][] minorArray = new ComplexPoly[grid.length - 1][grid.length - 1];
for (int i = 0; i < newGrid.size(); i++) {
List<Polynomial<Complex>> currentRow = newGrid.get(i);
for (int j = 0; j < newGrid.size(); j++) {
minorArray[i][j] = currentRow.get(j);
}
}
return minorArray;
}
/**
* Calculate the determinant of a two-dimensional array
* @param grid two-dimensional array representation of a matrix (must be square)
* @return determinant of two-dimensional grid
*/
private static Polynomial<Complex> determinantFromArray(Polynomial<Complex>[][] grid) {
if (grid.length == 1) {
return grid[0][0];
}
Polynomial<Complex>[] firstRow = grid[0];
Polynomial<Complex> determinant = new ComplexPoly(ZERO);
for (int i = 0; i < grid.length; i++) {
Polynomial<Complex> cofactor = firstRow[i];
double sign = Math.pow(-1, i);
Polynomial<Complex>[][] minor = BigDecimalMatrix.minorFromArray(grid, 0, i);
Polynomial<Complex> minorDet = BigDecimalMatrix.determinantFromArray(minor);
determinant = determinant.add(cofactor.mult(minorDet).mult(sign));
}
return determinant;
}
private Matrix<Complex> convertToComplex() {
List<List<Complex>> newGrid = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
List<Complex> newRow = new ArrayList<>();
for (int j = 0; j < numCols; j++) {
Complex newElt = new Complex(this.getElement(i, j).doubleValue(), 0);
newRow.add(newElt);
}
newGrid.add(newRow);
}
return new ComplexMatrix(newGrid);
}
/**
* while reducing matrix A to rref, perform all necessary row operations on identity matrix I
* @return an two-element list of Matrix objects
* the first element is A in rref, while the second element is the result of performing
* the same row operations on I
*/
private List<Matrix<BigDecimal>> rrefAndPseudoInverse() {
//perform same operations as ref, while copying row operations to identity matrix of same size
BigDecimal[][] id = new BigDecimal[numRows][numCols];
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (i == j) {
id[i][j] = BigDecimal.ONE;
} else {
id[i][j] = BigDecimal.ZERO;
}
}
}
BigDecimal[][] newMatrix = new BigDecimal[numRows][numCols];
for (int row = 0; row < numRows; row++) {
for (int column = 0; column < numCols; column++) {
newMatrix[row][column] = getElement(row, column);
}
}
//perform row swaps for each column
for (int columnCheck = 0; columnCheck < numCols; columnCheck++) {
//find any row with a nonzero value in this column
BigDecimal valueCheck = BigDecimal.ZERO;
BigDecimal[] lowestRow = new BigDecimal[numCols];
int index = columnCheck - 1;
while (valueCheck.compareTo(BigDecimal.ZERO) == 0 && index < numRows - 1) {
index++;
lowestRow = newMatrix[index];
valueCheck = lowestRow[columnCheck];
}
if (valueCheck.compareTo(BigDecimal.ZERO) == 0) {
continue;
}
//retrieve same information from id matrix
BigDecimal[] idRow = id[index];
//simplify row so that first element is 1
BigDecimal criticalElt = valueCheck;
for (int j = 0; j < lowestRow.length; j++) {
lowestRow[j] = new BigDecimal(lowestRow[j].doubleValue() / criticalElt.doubleValue());
idRow[j] = new BigDecimal(idRow[j].doubleValue() / criticalElt.doubleValue());
}
//use simplified row to reduce rest of matrix
for (int row = 0; row < numRows; row++) {
if (row != index) {
BigDecimal[] rowToBeReduced = newMatrix[row];
BigDecimal entryFactor = rowToBeReduced[columnCheck];
BigDecimal[] idTBR = new BigDecimal[numCols];
for (int zero = 0; zero < numCols; zero++) {
idTBR[zero] = BigDecimal.ZERO;
}
if (row < numCols) {
idTBR = id[row];
}
for (int j = 0; j < numCols; j++) {
rowToBeReduced[j] = rowToBeReduced[j].subtract(entryFactor.multiply(lowestRow[j]));
idTBR[j] = idTBR[j].subtract(entryFactor.multiply(idRow[j]));
}
}
}
//swap rows
BigDecimal[] tmp = newMatrix[columnCheck];
newMatrix[columnCheck] = lowestRow;
newMatrix[index] = tmp;
BigDecimal[] idTmp = id[columnCheck];
id[columnCheck] = idRow;
id[index] = idTmp;
}
//move all zero rows to the bottom of the matrix
for (int i = 0; i < numRows; i++) {
BigDecimal[] currentRow = newMatrix[i];
if (!BigDecimalMatrix.rowNotZero(currentRow)) {
for (int j = i; j < numRows - 1; j++) {
BigDecimal[] tmp = newMatrix[j + 1];
newMatrix[j + 1] = newMatrix[j];
newMatrix[j] = tmp;
if (j < numCols) {
BigDecimal[] idTmp = id[j + 1];
id[j + 1] = id[j];
id[j] = idTmp;
}
}
}
}
Matrix<BigDecimal> rref = new BigDecimalMatrix(newMatrix);
Matrix<BigDecimal> pseudoId = new BigDecimalMatrix(id);
List<Matrix<BigDecimal>> output = new ArrayList<>(Arrays.asList(rref, pseudoId));
return output;
}
public static void main(String[] args) {
int[] firstRow = {7, 2};
int[] secondRow = {1, 1};
int[][] grid = {firstRow, secondRow};
Matrix<BigDecimal> matrix = new BigDecimalMatrix(grid);
System.out.println(matrix.eigenMap());
}
}
| [
"parkerh@mit.edu"
] | parkerh@mit.edu |
6b24b9076cf76b9170b931ba9c3b73a205669962 | 38b7060d509bf007d15a53c1a5ea9b5a17277c7e | /src/com/ubboeicke/application/Model/DB/Save_Load/SaveAndLoadHandler.java | 519b969608b62b84b0f6b01f5968c0e06d5b15b0 | [] | no_license | ucestorage/GCC | dbf2552c03449f99020b36fd01310fdde70ac9a8 | d554a96564098bf27e43b1982283e99af5814fa3 | refs/heads/master | 2021-01-19T15:13:57.375221 | 2018-01-18T13:59:20 | 2018-01-18T13:59:20 | 100,953,034 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,439 | java | package com.ubboeicke.application.Model.DB.Save_Load;
import com.ubboeicke.application.Controller.Center.CenterSubController.Tabs.OverviewController;
import com.ubboeicke.application.Controller.Center.CenterViewController;
import com.ubboeicke.application.Controller.Main.MainController;
import com.ubboeicke.application.Controller.Top.TopViewController;
import com.ubboeicke.application.Model.Gamedata.CastleComponents.CastleComponent;
import com.ubboeicke.application.Model.Gamedata.CastleComponents.CastleComponentParser;
import com.ubboeicke.application.Model.Gamedata.Decks.Deck;
import com.ubboeicke.application.Model.Gamedata.Decks.DeckParser;
import com.ubboeicke.application.Model.Gamedata.Heroes.Hero;
import com.ubboeicke.application.Model.Gamedata.Heroes.HeroParser;
import com.ubboeicke.application.Model.Gamedata.Items.Item;
import com.ubboeicke.application.Model.Gamedata.Items.ItemParser;
import com.ubboeicke.application.Model.Gamedata.Leaders.Leader;
import com.ubboeicke.application.Model.Gamedata.Leaders.LeaderParser;
import com.ubboeicke.application.Model.Gamedata.Towers.Tower;
import com.ubboeicke.application.Model.Gamedata.Towers.TowerParser;
import com.ubboeicke.application.Model.MainModel;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TableView;
/**
* Created by Ubbo Eicke on 12.06.2017.
*/
public class SaveAndLoadHandler {
private MainController mMainController;
private MainModel mMainModel;
private TopViewController mTopViewController;
private CenterViewController mCenterViewController;
private ItemParser mItemParser;
private CastleComponentParser mCastleComponentParser;
private TowerParser mTowerParser;
private SaveAndLoadController mSaveAndLoadController;
private LeaderParser mLeaderParser;
private HeroParser mHeroParser;
private DeckParser mDeckParser;
private ObservableList<Leader> LDRList = FXCollections.observableArrayList();
private ObservableList<Tower> TWRList = FXCollections.observableArrayList();
private ObservableList<CastleComponent> CCList = FXCollections.observableArrayList();
private ObservableList<Hero> HeroList = FXCollections.observableArrayList();
private ObservableList<Deck> DeckList = FXCollections.observableArrayList();
private OverviewController mOverviewController;
public SaveAndLoadHandler(MainModel mainModel, MainController mainController) {
this.mMainController = mainController;
this.mMainModel = mainModel;
this.mCenterViewController = mMainController.getCenterViewController();
this.mTopViewController = mMainController.getTopViewController();
this.mSaveAndLoadController = mMainModel.getSaveAndLoadController();
mItemParser = new ItemParser(mCenterViewController);
mTowerParser = new TowerParser(mCenterViewController);
mCastleComponentParser = new CastleComponentParser(mCenterViewController);
mLeaderParser = new LeaderParser(mCenterViewController);
mHeroParser = new HeroParser(mCenterViewController);
mDeckParser = new DeckParser(mCenterViewController);
mOverviewController = new OverviewController(mMainController);
}
public void saveAll() {
saveGeneralInformation();
saveCastleComponents();
saveItemsWeapons();
saveItemsAccessories();
saveTowers();
saveLeaders();
saveHeroes_OH();
saveHeroes_UH();
saveDecks();
}
public void loadAll() {
loadGeneralInformation();
loadItemsWeapons();
loadItemsAccessories();
loadCastleComponents();
loadTowers();
loadLeaders();
loadHeroes_OH();
loadHeroes_UH();
loadDecks();
mOverviewController.populateDeckCB();
}
public void loadGeneralInformation() {
mTopViewController.setPlayerNameLabel(mSaveAndLoadController.load().get(0));
mTopViewController.setPlayerLevelLabel(mSaveAndLoadController.load().get(1));
mTopViewController.setGuildLabel(mSaveAndLoadController.load().get(2));
mTopViewController.setstartDateLabel(mSaveAndLoadController.load().get(3));
mTopViewController.setWaveCountTextField(mSaveAndLoadController.load().get(4));
mTopViewController.seteColoLabel(mSaveAndLoadController.load().get(5));
mTopViewController.sethColoLabel(mSaveAndLoadController.load().get(6));
mTopViewController.setoColoLabel(mSaveAndLoadController.load().get(7));
mTopViewController.setTwLabel(mSaveAndLoadController.load().get(8));
mTopViewController.setOwLabel(mSaveAndLoadController.load().get(9));
mTopViewController.setCastleLvlVTF(mSaveAndLoadController.load().get(10));
mTopViewController.setTALvlVTF(mSaveAndLoadController.load().get(11));
}
public void loadItemsWeapons() {
ObservableList<Item> mItemObservableList = mCenterViewController.getItemWeaponTableView().getItems();
TableView<Item> mItemTableView = mCenterViewController.getItemWeaponTableView();
for (String s : mSaveAndLoadController.loadItemsWeapons()) {
mItemObservableList.add(mItemParser.splitItem(s));
}
mItemTableView.setItems(mItemObservableList);
}
public void loadItemsAccessories() {
ObservableList<Item> mItemObservableList = mCenterViewController.getItemAccessoryTableView().getItems();
TableView<Item> mItemTableView = mCenterViewController.getItemAccessoryTableView();
for (String s : mSaveAndLoadController.loadItemsAccessories()) {
mItemObservableList.add(mItemParser.splitItem(s));
}
mItemTableView.setItems(mItemObservableList);
}
public void loadCastleComponents() {
TableView<CastleComponent> tvcc = mCenterViewController.getCcTableView();
for (String s : mSaveAndLoadController.loadCC()) {
CCList.add(mCastleComponentParser.splitCC(s));
}
tvcc.setItems(CCList);
}
public void loadTowers() {
TableView<Tower> tvt = mCenterViewController.getTwrTableView();
for (String s : mSaveAndLoadController.loadTWR()) {
TWRList.add(mTowerParser.splitStrings(s));
}
tvt.setItems(TWRList);
}
public void loadLeaders() {
TableView<Leader> tv = mCenterViewController.getLeaderTableView();
for (String s : mSaveAndLoadController.loadLDR()) {
LDRList.add(mLeaderParser.splitStrings(s));
}
tv.setItems(LDRList);
}
public void loadHeroes_OH() {
TableView<Hero> tv = mCenterViewController.getHeroTableView1();
ObservableList<Hero> obsl = FXCollections.observableArrayList();
for (String s : mSaveAndLoadController.loadHeroesOh()) {
obsl.add(mHeroParser.splitStrings_OH(s));
HeroList.add(mHeroParser.splitStrings_OH(s));
}
tv.setItems(obsl);
}
public void loadHeroes_UH() {
TableView<Hero> tv1 = mCenterViewController.getHeroTableView2();
ObservableList<Hero> obsl = FXCollections.observableArrayList();
for (String s : mSaveAndLoadController.loadHeroesUh()) {
obsl.add(mHeroParser.splitStrings_UH(s));
HeroList.add(mHeroParser.splitStrings_UH(s));
}
tv1.setItems(obsl);
}
public void loadDecks() {
TableView<Deck> tv1 = mCenterViewController.getDeckTableView();
for (String s : mSaveAndLoadController.loadDecks()) {
DeckList.add(mDeckParser.splitStrings(s));
}
tv1.setItems(DeckList);
}
public void saveGeneralInformation() {
mSaveAndLoadController.save(mTopViewController.getPlayerNameLabel().getText());
mSaveAndLoadController.save(mTopViewController.getPlayerLevelLabel().getText());
mSaveAndLoadController.save(mTopViewController.getGuildLabel().getText());
mSaveAndLoadController.save(mTopViewController.getStartDateLabel().getText());
mSaveAndLoadController.save(mTopViewController.getWaveCountTextField().getText());
mSaveAndLoadController.save(mTopViewController.geteColoLabel().getText());
mSaveAndLoadController.save(mTopViewController.gethColoLabel().getText());
mSaveAndLoadController.save(mTopViewController.getoColoLabel().getText());
mSaveAndLoadController.save(mTopViewController.getTwLabel().getText());
mSaveAndLoadController.save(mTopViewController.getOwLabel().getText());
mSaveAndLoadController.save(mTopViewController.getCastleLvlVTF().getText());
mSaveAndLoadController.save(mTopViewController.getTALvlVTF().getText());
}
public void saveItemsWeapons() {
for (String s : mItemParser.getItemWeaponStringList()) {
mSaveAndLoadController.saveItemsWeapons(s);
}
}
public void saveItemsAccessories() {
for (String s : mItemParser.getItemAccessoryStringList()) {
mSaveAndLoadController.saveItemsAccessories(s);
}
}
public void saveCastleComponents() {
for (String s : mCastleComponentParser.getCCStrings()) {
mSaveAndLoadController.saveCC(s);
}
}
public void saveTowers() {
for (String s : mTowerParser.getStrings()) {
mSaveAndLoadController.saveTowers(s);
}
}
public void saveLeaders() {
for (String s : mLeaderParser.getStrings()) {
mSaveAndLoadController.saveLeaders(s);
}
}
public void saveHeroes_OH() {
for (String s : mHeroParser.getStrings_OH()) {
mSaveAndLoadController.saveHeroesOh(s);
}
}
public void saveHeroes_UH() {
for (String s : mHeroParser.getStrings_UH()) {
mSaveAndLoadController.saveHeroesUh(s);
}
}
public void saveDecks() {
for (String s : mDeckParser.getDeckStrings()) {
mSaveAndLoadController.saveDecks(s);
}
}
public ObservableList<Deck> getDeckList() {
return DeckList;
}
public ObservableList<Tower> getTWRList() {
return TWRList;
}
public ObservableList<Leader> getLDRList() {
return LDRList;
}
public ObservableList<CastleComponent> getCCList() {
return CCList;
}
public ObservableList<Hero> getHeroList() {
return HeroList;
}
}
| [
"ubboeicke@gmail.com"
] | ubboeicke@gmail.com |
8f57a0b43895ffb0ab877602e9703fafdbb7894d | be73270af6be0a811bca4f1710dc6a038e4a8fd2 | /crash-reproduction-moho/results/LANG-20b-2-16-FEMO-WeightedSum:TestLen:CallDiversity/org/apache/commons/lang3/StringUtils_ESTest.java | b1f14609890a85ad5469172cb1f4fbb4df85ecd0 | [] | no_license | STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application | cf118b23ecb87a8bf59643e42f7556b521d1f754 | 3bb39683f9c343b8ec94890a00b8f260d158dfe3 | refs/heads/master | 2022-07-29T14:44:00.774547 | 2020-08-10T15:14:49 | 2020-08-10T15:14:49 | 285,804,495 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 553 | java | /*
* This file was automatically generated by EvoSuite
* Sat Apr 04 07:16:03 UTC 2020
*/
package org.apache.commons.lang3;
import org.junit.Test;
import static org.junit.Assert.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true)
public class StringUtils_ESTest extends StringUtils_ESTest_scaffolding {
@Test
public void notGeneratedAnyTest() {
// EvoSuite did not generate any tests
}
}
| [
"pouria.derakhshanfar@gmail.com"
] | pouria.derakhshanfar@gmail.com |
0350b893ff9795072ced2ea7039c10a347d02782 | 5d533d0bc6b09093f18f20f5e07d6ebad6875aef | /library/src/main/java/jo/dis/library/x5web/WebViewJavaScriptFunction.java | c76617cb1e3df09b3afadd3854000be4e54c485c | [] | no_license | frank7023/X5WebView-1 | 7d3f5319256f692df32b972a9e4b501e8a52675c | 7eebf4eb70d3fcf09253f5f4cc304eec52d4c11a | refs/heads/master | 2021-05-31T06:57:53.395546 | 2016-04-18T14:59:40 | 2016-04-18T14:59:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 158 | java | package jo.dis.library.x5web;
/**
* Created by dis on 16/4/7.
*/
public interface WebViewJavaScriptFunction {
void onJsFunctionCalled(String tag);
}
| [
"dis@ios-server.local"
] | dis@ios-server.local |
dcffa33b92d7e3aea29398a6b6528b183ccfacc0 | d12f6b6f8adfdd285efc6398e8a1aa6808f80f68 | /src/main/java/no/amedia/appnexus/appnexusrest/model/appnexus/creative/ResponseCreative.java | a657c1c93bbddfa9aadd4dab92bcf7a4e0325856 | [] | no_license | fliropp/appnexus-rest | 26be9e011b173180a855f8f29cad32983f1a327d | 6c494f5d1c6ea66b97a8e95f9e882d0292d78b62 | refs/heads/master | 2020-04-07T18:03:00.007005 | 2018-11-21T20:20:37 | 2018-11-21T20:20:37 | 158,594,765 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 199 | java | package no.amedia.appnexus.appnexusrest.model.appnexus.creative;
import no.amedia.appnexus.appnexusrest.model.appnexus.Response;
public class ResponseCreative extends Response<CreativeRequest> {
}
| [
"grottum@gmail.com"
] | grottum@gmail.com |
84d08e2184589005a3cdd29688812cf61177d382 | 5762d68debef9b340e1b0bf568524f5c12f42b1f | /src/main/java/org/glite/security/voms/service/registration/VOMSRegistrationSoapBindingSkeleton.java | 4193c4738911ccdc4378def53e96ed247d282d49 | [] | no_license | italiangrid/CAOnlineBridge | 99e5d011ed4f1cd717dbb69ef435c984550bb736 | d05c28ddb8903a0f2345e1ae6dd10bef6deb32b9 | refs/heads/master | 2020-05-20T08:50:03.935947 | 2012-11-30T09:11:09 | 2012-11-30T09:11:09 | 5,273,273 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,765 | java | /**
* VOMSRegistrationSoapBindingSkeleton.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package org.glite.security.voms.service.registration;
@SuppressWarnings({ "serial", "unchecked", "rawtypes" })
public class VOMSRegistrationSoapBindingSkeleton implements org.glite.security.voms.service.registration.VOMSRegistration, org.apache.axis.wsdl.Skeleton {
private org.glite.security.voms.service.registration.VOMSRegistration impl;
private static java.util.Map _myOperations = new java.util.Hashtable();
private static java.util.Collection _myOperationsList = new java.util.ArrayList();
/**
* Returns List of OperationDesc objects with this name
*/
public static java.util.List getOperationDescByName(java.lang.String methodName) {
return (java.util.List)_myOperations.get(methodName);
}
/**
* Returns Collection of OperationDescs
*/
public static java.util.Collection getOperationDescs() {
return _myOperationsList;
}
static {
org.apache.axis.description.OperationDesc _oper;
org.apache.axis.description.FaultDesc _fault;
org.apache.axis.description.ParameterDesc [] _params;
_params = new org.apache.axis.description.ParameterDesc [] {
new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "in0"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://glite.org/wsdl/services/org.glite.security.voms.service.registration", "RegistrationRequest"), org.glite.security.voms.service.registration.RegistrationRequest.class, false, false),
};
_oper = new org.apache.axis.description.OperationDesc("submitRegistrationRequest", _params, null);
_oper.setElementQName(new javax.xml.namespace.QName("http://glite.org/wsdl/services/org.glite.security.voms.service.registration", "submitRegistrationRequest"));
_oper.setSoapAction("");
_myOperationsList.add(_oper);
if (_myOperations.get("submitRegistrationRequest") == null) {
_myOperations.put("submitRegistrationRequest", new java.util.ArrayList());
}
((java.util.List)_myOperations.get("submitRegistrationRequest")).add(_oper);
_fault = new org.apache.axis.description.FaultDesc();
_fault.setName("VOMSException");
_fault.setQName(new javax.xml.namespace.QName("http://glite.org/wsdl/services/org.glite.security.voms.service.registration", "fault"));
_fault.setClassName("org.glite.security.voms.VOMSException");
_fault.setXmlType(new javax.xml.namespace.QName("http://glite.org/wsdl/services/org.glite.security.voms", "VOMSException"));
_oper.addFault(_fault);
_params = new org.apache.axis.description.ParameterDesc [] {
new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "in0"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/encoding/", "string"), java.lang.String.class, false, false),
new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "in1"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/encoding/", "string"), java.lang.String.class, false, false),
new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "in2"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://glite.org/wsdl/services/org.glite.security.voms.service.registration", "RegistrationRequest"), org.glite.security.voms.service.registration.RegistrationRequest.class, false, false),
};
_oper = new org.apache.axis.description.OperationDesc("submitRegistrationRequestForUser", _params, null);
_oper.setElementQName(new javax.xml.namespace.QName("http://glite.org/wsdl/services/org.glite.security.voms.service.registration", "submitRegistrationRequestForUser"));
_oper.setSoapAction("");
_myOperationsList.add(_oper);
if (_myOperations.get("submitRegistrationRequestForUser") == null) {
_myOperations.put("submitRegistrationRequestForUser", new java.util.ArrayList());
}
((java.util.List)_myOperations.get("submitRegistrationRequestForUser")).add(_oper);
_fault = new org.apache.axis.description.FaultDesc();
_fault.setName("VOMSException");
_fault.setQName(new javax.xml.namespace.QName("http://glite.org/wsdl/services/org.glite.security.voms.service.registration", "fault"));
_fault.setClassName("org.glite.security.voms.VOMSException");
_fault.setXmlType(new javax.xml.namespace.QName("http://glite.org/wsdl/services/org.glite.security.voms", "VOMSException"));
_oper.addFault(_fault);
}
public VOMSRegistrationSoapBindingSkeleton() {
this.impl = new org.glite.security.voms.service.registration.VOMSRegistrationSoapBindingImpl();
}
public VOMSRegistrationSoapBindingSkeleton(org.glite.security.voms.service.registration.VOMSRegistration impl) {
this.impl = impl;
}
public void submitRegistrationRequest(org.glite.security.voms.service.registration.RegistrationRequest in0) throws java.rmi.RemoteException, org.glite.security.voms.VOMSException
{
impl.submitRegistrationRequest(in0);
}
public void submitRegistrationRequestForUser(java.lang.String in0, java.lang.String in1, org.glite.security.voms.service.registration.RegistrationRequest in2) throws java.rmi.RemoteException, org.glite.security.voms.VOMSException
{
impl.submitRegistrationRequestForUser(in0, in1, in2);
}
}
| [
"dmichelotto@fe.infn.it"
] | dmichelotto@fe.infn.it |
f1c5262a857d73e34a504a03ad1ddcba4822ae3c | e16cd9f20499f0fcb37baada06e593e282cff644 | /dex-lib/src/main/java/com/baidu/titan/dexlib/dx/dex/code/DalvCode.java | 8499d931487912a9f40509e99ce8680bd6ab8cf7 | [
"Apache-2.0"
] | permissive | baidu/titan-dex | 714c3c8ba13e3ab8a1434611fa7c80a26eaec658 | 76eab7dc3d5173580f763d3d06e0eb6e22d1a345 | refs/heads/master | 2023-09-05T14:26:23.890449 | 2022-05-13T11:26:14 | 2022-05-13T11:26:14 | 194,606,378 | 193 | 26 | Apache-2.0 | 2023-09-04T03:29:43 | 2019-07-01T05:37:03 | Java | UTF-8 | Java | false | false | 7,344 | java | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baidu.titan.dexlib.dx.dex.code;
import com.baidu.titan.dexlib.dx.rop.cst.Constant;
import com.baidu.titan.dexlib.dx.rop.type.Type;
import java.util.HashSet;
import java.util.List;
/**
* Container for all the pieces of a concrete method. Each instance
* corresponds to a {@code code} structure in a {@code .dex} file.
*/
public final class DalvCode {
/**
* how much position info to preserve; one of the static
* constants in {@link PositionList}
*/
private final int positionInfo;
/**
* {@code null-ok;} the instruction list, ready for final processing;
* nulled out in {@link #finishProcessingIfNecessary}
*/
private OutputFinisher unprocessedInsns;
/**
* {@code non-null;} unprocessed catch table;
* nulled out in {@link #finishProcessingIfNecessary}
*/
private CatchBuilder unprocessedCatches;
/**
* {@code null-ok;} catch table; set in
* {@link #finishProcessingIfNecessary}
*/
private CatchTable catches;
/**
* {@code null-ok;} source positions list; set in
* {@link #finishProcessingIfNecessary}
*/
private PositionList positions;
/**
* {@code null-ok;} local variable list; set in
* {@link #finishProcessingIfNecessary}
*/
private LocalList locals;
private List<LocalList.LocalEntry> mLocalEntrys;
public List<LocalList.LocalEntry> getLocalEnties() {
return mLocalEntrys;
}
private String[] mParameterNames;
/**
* {@code null-ok;} the processed instruction list; set in
* {@link #finishProcessingIfNecessary}
*/
private DalvInsnList insns;
/**
* Constructs an instance.
*
* @param positionInfo how much position info to preserve; one of the
* static constants in {@link PositionList}
* @param unprocessedInsns {@code non-null;} the instruction list, ready
* for final processing
* @param unprocessedCatches {@code non-null;} unprocessed catch
* (exception handler) table
*/
public DalvCode(int positionInfo, OutputFinisher unprocessedInsns,
CatchBuilder unprocessedCatches) {
if (unprocessedInsns == null) {
throw new NullPointerException("unprocessedInsns == null");
}
if (unprocessedCatches == null) {
throw new NullPointerException("unprocessedCatches == null");
}
this.positionInfo = positionInfo;
this.unprocessedInsns = unprocessedInsns;
this.unprocessedCatches = unprocessedCatches;
this.catches = null;
this.positions = null;
this.locals = null;
this.insns = null;
}
public void setLocalEntrys(List<LocalList.LocalEntry> locals) {
this.mLocalEntrys = locals;
}
public void setParameterNames(String[] names) {
this.mParameterNames = names;
}
public String[] getParameterNames() {
return mParameterNames;
}
/**
* Finish up processing of the method.
*/
private void finishProcessingIfNecessary() {
if (insns != null) {
return;
}
insns = unprocessedInsns.finishProcessingAndGetList();
positions = PositionList.make(insns, positionInfo);
locals = LocalList.make(mLocalEntrys);
catches = unprocessedCatches.build();
// Let them be gc'ed.
unprocessedInsns = null;
unprocessedCatches = null;
}
/**
* Assign indices in all instructions that need them, using the
* given callback to perform lookups. This must be called before
* {@link #getInsns}.
*
* @param callback {@code non-null;} callback object
*/
public void assignIndices(AssignIndicesCallback callback) {
unprocessedInsns.assignIndices(callback);
}
/**
* Gets whether this instance has any position data to represent.
*
* @return {@code true} iff this instance has any position
* data to represent
*/
public boolean hasPositions() {
return (positionInfo != PositionList.NONE)
&& unprocessedInsns.hasAnyPositionInfo();
}
/**
* Gets whether this instance has any local variable data to represent.
*
* @return {@code true} iff this instance has any local variable
* data to represent
*/
public boolean hasLocals() {
return mLocalEntrys != null && mLocalEntrys.size() > 0;
//return unprocessedInsns.hasAnyLocalInfo();
}
/**
* Gets whether this instance has any catches at all (either typed
* or catch-all).
*
* @return whether this instance has any catches at all
*/
public boolean hasAnyCatches() {
return unprocessedCatches.hasAnyCatches();
}
/**
* Gets the set of catch types handled anywhere in the code.
*
* @return {@code non-null;} the set of catch types
*/
public HashSet<Type> getCatchTypes() {
return unprocessedCatches.getCatchTypes();
}
/**
* Gets the set of all constants referred to by instructions in
* the code.
*
* @return {@code non-null;} the set of constants
*/
public HashSet<Constant> getInsnConstants() {
return unprocessedInsns.getAllConstants();
}
/**
* Gets the list of instructions.
*
* @return {@code non-null;} the instruction list
*/
public DalvInsnList getInsns() {
finishProcessingIfNecessary();
return insns;
}
/**
* Gets the catch (exception handler) table.
*
* @return {@code non-null;} the catch table
*/
public CatchTable getCatches() {
finishProcessingIfNecessary();
return catches;
}
/**
* Gets the source positions list.
*
* @return {@code non-null;} the source positions list
*/
public PositionList getPositions() {
finishProcessingIfNecessary();
return positions;
}
/**
* Gets the source positions list.
*
* @return {@code non-null;} the source positions list
*/
public LocalList getLocals() {
finishProcessingIfNecessary();
return locals;
}
/**
* Class used as a callback for {@link #assignIndices}.
*/
public static interface AssignIndicesCallback {
/**
* Gets the index for the given constant.
*
* @param cst {@code non-null;} the constant
* @return {@code >= -1;} the index or {@code -1} if the constant
* shouldn't actually be reified with an index
*/
public int getIndex(Constant cst);
public int getCurrentMethodId();
public int getCurrentClassId();
}
}
| [
"shanghuibo@baidu.com"
] | shanghuibo@baidu.com |
14d98229f2fc21f2152a79502919d948c7908a8f | c4f35cd867764202755f862c710907deb930e4ac | /shared_lib/src/main/java/com/vssnake/intervaltraining/shared/model/IntervalData.java | a7a40fd312bb55ec75efb5dd70c89b0d807d0bad | [] | no_license | vssnake/FithleticsInterval | 78c3c5b6e30aebf4a3fd30e78474f31da6928809 | d307c475b9f26a09056407434c3b900c719bd5a8 | refs/heads/master | 2016-09-09T21:12:17.519420 | 2014-10-24T11:21:45 | 2014-10-24T11:21:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,545 | java | package com.vssnake.intervaltraining.shared.model;
import com.vssnake.intervaltraining.shared.utils.Utils;
/**
* Created by unai on 04/07/2014.
*/
public class IntervalData {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public enum intervalDataKey{
INTERVAL_NAME,
INTERVAL_TIME,
TOTAL_INTERVAL_TIME,
NUMBER_INTERVAL,
TOTAL_INTERVALS,
INTERVAL_STATE,
}
public int getTotalIntervalTimeSeconds() {
return totalIntervalTimeSeconds;
}
public int getIntervalTimeSeconds() {
return intervalTimeSeconds;
}
public int getNumberInterval() {
return numberIntervals;
}
public int getTotalIntervals() {
return totalIntervals;
}
public eIntervalState getIntervalState() {
return intervalState;
}
public int getBpm() {
return bpm;
}
public long getTotalIntervalTimeMilliseconds() {
return totalIntervalTimeMilliseconds;
}
public long getIntervalTimeMilliseconds() {
return intervalTimeMilliseconds;
}
public boolean isIntervalDone() {
return intervalDone;
}
public enum eIntervalState{
RUNNING,
RESTING,
NOTHING
}
private int numberIntervals;
private int totalIntervals;
private eIntervalState intervalState;
private long totalIntervalTimeMilliseconds;
private long intervalTimeMilliseconds;
private int totalIntervalTimeSeconds;
private int intervalTimeSeconds;
//Beats per minute
private int bpm;
private String name;
private boolean intervalDone;
public IntervalData(){}
public void setIntervalData(int numberInterval, int totalIntervals,
eIntervalState intervalState,
long totalIntervalTime,
long intervalTime,
int bpm){
this.numberIntervals = numberInterval;
this.totalIntervals = totalIntervals;
this.intervalState = intervalState;
this.totalIntervalTimeMilliseconds = totalIntervalTime;
this.intervalTimeMilliseconds = intervalTime;
this.totalIntervalTimeSeconds = Utils.convertMillisecondsToSeconds(totalIntervalTime);
this.intervalTimeSeconds = Utils.convertMillisecondsToSeconds(intervalTime);
this.bpm = bpm;
}
public void intervalDone(){
intervalDone = true;
}
}
| [
"unaicorreacruz@gmail.com"
] | unaicorreacruz@gmail.com |
79380a9960cb90320163e918348cc75e57f9d154 | 39ddf470a2a8e2f659d85483a379d5541d95ac85 | /Тестовое1/src/com/company/Main.java | adeb6199cce07a1e57e1d7d7189ce3e58c917c61 | [] | no_license | ilyakibisov/airports | 60e8d456fcfcb4d37fbba792493ac1da8fe74957 | ce32d40abb01598c9162a324cfdab1f9f5359f44 | refs/heads/main | 2023-07-04T05:35:43.922164 | 2021-08-10T06:31:22 | 2021-08-10T06:31:22 | 394,549,067 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,452 | java | package com.company;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(
"airports.dat"));
String line = null;
Scanner scanner = null;
int index = 0;
List<Airports> airports = new ArrayList<>();
while ((line = reader.readLine()) != null) {
Airports air = new Airports();
scanner = new Scanner(line);
scanner.useDelimiter(",");
while (scanner.hasNext()) {
String data = scanner.next();
data = data.replaceAll("^\"|\"$", "");
if (index == 0) {
air.setId(Integer.parseInt(data));
}
else if (index == 1)
air.setName(data);
else if (index == 2)
air.setTown(data);
else if (index == 3)
air.setCountry(data);
else if (index == 4)
air.setCodeA(data);
else if (index == 5)
air.setCodeB(data);
else if (index == 6)
air.setCoordinateA(data);
else if (index == 7)
air.setCoordinateB(data);
else if (index == 8)
air.setCoordinateC(data);
else if (index == 9)
air.setCoordinateD(data);
else if (index == 10)
air.setSide(data);
else if (index == 11)
air.setLocation(data);
else if (index == 12)
air.setAirport(data);
else if (index == 13)
air.setOur(data);
index++;
}
index = 0;
airports.add(air);
}
reader.close();
Collections.sort(airports, new Comparator<Airports>() {
@Override
public int compare(Airports o1, Airports o2) {
String s1 = o1.getName();
String s2 = o2.getName();
return s1.compareToIgnoreCase(s2);
}
});
System.out.println("Введите строку");
Scanner in = new Scanner(System.in);
Scanner str = new Scanner(System.in);
index = in.nextInt();
String word = str.nextLine();
long start = System.currentTimeMillis();
int i = 0;
for (Airports air : airports){
String temp;
if (index == 1) {
temp = Integer.toString(air.getId());
if (temp.startsWith(word)) {
System.out.println(air.toString());
i++;
}
}
else if (index == 2) {
temp = air.getName();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 3) {
temp = air.getTown();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 4) {
temp = air.getCountry();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 5) {
temp = air.getCodeA();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 6) {
temp = air.getCodeB();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 7) {
temp = air.getCoordinateA();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 8) {
temp = air.getCoordinateB();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 9) {
temp = air.getCoordinateC();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 10) {
temp = air.getCoordinateD();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 11) {
temp = air.getSide();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 12) {
temp = air.getLocation();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 13) {
temp = air.getAirport();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
else if (index == 14) {
temp = air.getOur();
if (temp.startsWith(word)){
System.out.println(air.toString());
i++;
}
}
}
System.out.println("Количество найденных строк: " + i);
long timeWorkCode = System.currentTimeMillis() - start;
System.out.println("Время, затраченное на поиск: " + timeWorkCode + " мс.");
}
}
| [
"noreply@github.com"
] | ilyakibisov.noreply@github.com |
4d12e1805440fabc2c3d35e504afcccb3078ee5f | bea7cbcfda77de706ed46a2370e94ea9f9077bb7 | /test/com/thesis/classmgmtsystem/controller/student/TestStudentPanelController.java | dfee62bc2038472b0550b202ae2cb7ae58aba133 | [] | no_license | elkkhan/Thesis | edf1bc2d772241bd69a1e321b275c87fce1ccbd8 | 65d719e8d4a4ff109e59b4695659a3d2e4d60cac | refs/heads/master | 2023-01-22T12:56:37.903730 | 2020-12-02T10:35:56 | 2020-12-02T10:35:56 | 261,727,542 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,196 | java | package com.thesis.classmgmtsystem.controller.student;
import static org.junit.jupiter.api.Assertions.assertFalse;
import com.thesis.classmgmtsystem.main.DatabaseFiller;
import com.thesis.classmgmtsystem.main.TestMain;
import com.thesis.classmgmtsystem.model.Course;
import com.thesis.classmgmtsystem.model.Student;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.persistence.EntityManager;
import org.junit.jupiter.api.Test;
public class TestStudentPanelController {
private static DatabaseFiller db = TestMain.TEST_DATABASE_REF;
@Test
void dropCourse()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
StudentPanelController spc = new StudentPanelController();
Method dropCourse = StudentPanelController.class
.getDeclaredMethod("dropCourse", EntityManager.class, Student.class, Course.class);
dropCourse.setAccessible(true);
dropCourse.invoke(spc, TestMain.entityManager, db.S_CRIS_MOLTESANTI, db.C_ANALYSIS);
assertFalse(db.S_CRIS_MOLTESANTI.getCourses().contains(db.C_ANALYSIS));
assertFalse(db.C_ANALYSIS.getStudents().contains(db.S_CRIS_MOLTESANTI));
}
}
| [
"elxaneminov99@gmail.com"
] | elxaneminov99@gmail.com |
0f0263f4a47239ae3909ecc75b48dbd411bc5afc | 4cd029b3049ea06cda25549cb5ec0afca09c1c01 | /src/main/java/com/sisrni/pojo/rpt/RptProyectoPojo.java | ebfc2af17c125f4de02b7079e11e580f65eb7869 | [] | no_license | joaofunes/SISNRI | 94c6f6c8f95730c217a4d2395eec9f741c7f736a | f3f413cf973345f9980314109ef93a9a40028920 | refs/heads/master | 2020-04-12T05:35:46.893736 | 2017-07-06T19:51:09 | 2017-07-06T19:51:09 | 61,092,088 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,104 | 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 com.sisrni.pojo.rpt;
import java.math.BigDecimal;
/**
*
* @author Joao
*/
public class RptProyectoPojo{
private String nombre;
private String objetivo;
private Integer anioGestion;
private String orgamismo;
private String paisCooperante;
private String contraparteExterna;
private String beneficiadoUES;
private BigDecimal monto;
private String estado;
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getObjetivo() {
return objetivo;
}
public void setObjetivo(String objetivo) {
this.objetivo = objetivo;
}
public Integer getAnioGestion() {
return anioGestion;
}
public void setAnioGestion(Integer anioGestion) {
this.anioGestion = anioGestion;
}
public String getOrgamismo() {
return orgamismo;
}
public void setOrgamismo(String orgamismo) {
this.orgamismo = orgamismo;
}
public String getPaisCooperante() {
return paisCooperante;
}
public void setPaisCooperante(String paisCooperante) {
this.paisCooperante = paisCooperante;
}
public String getContraparteExterna() {
return contraparteExterna;
}
public void setContraparteExterna(String contraparteExterna) {
this.contraparteExterna = contraparteExterna;
}
public String getBeneficiadoUES() {
return beneficiadoUES;
}
public void setBeneficiadoUES(String beneficiadoUES) {
this.beneficiadoUES = beneficiadoUES;
}
public BigDecimal getMonto() {
return monto;
}
public void setMonto(BigDecimal monto) {
this.monto = monto;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
| [
"liliancisneros29@gmail.com"
] | liliancisneros29@gmail.com |
df729da1b4f5bb9a7f3990d00240720797058925 | 956d234f11944ab029f7ad8ccd2f5ea2b1f42028 | /src/main/java/com/yuhe/american/log_modules/PetEquipLog.java | 85da6ccb7631e5ca2d4dea5141c1de5804363091 | [] | no_license | chusen12/bm_storm | 8e087ae7990b35c18ff069e7729778e894746e19 | 5947947bcda11dd881971260e440a8a53d59a61a | refs/heads/master | 2021-06-20T10:25:53.120343 | 2017-07-19T07:26:26 | 2017-07-19T07:26:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,670 | java | package com.yuhe.american.log_modules;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.yuhe.american.db.log.CommonDB;
import com.yuhe.american.utils.RegUtils;
import net.sf.json.JSONObject;
public class PetEquipLog extends AbstractLogModule {
private static final String[] LOG_COLS = { "Uid", "Urs", "Name", "Position", "Consume", "OperationType",
"NewItemName" };
private static final String[] DB_COLS = { "HostID", "Uid", "Urs", "Name", "Position", "Consume", "OperationType",
"NewItemName", "Time" };
private static String TBL_NAME = "tblPetEquipLog";
@Override
public Map<String, List<Map<String, String>>> execute(List<String> logList, Map<String, String> hostMap) {
Map<String, List<Map<String, String>>> platformResults = new HashMap<String, List<Map<String, String>>>();
for (String logStr : logList) {
JSONObject json = JSONObject.fromObject(logStr);
if (json != null) {
String message = json.getString("message");
String hostID = json.getString("hostid");
if (StringUtils.isNotBlank(message) && hostMap.containsKey(hostID)) {
Map<String, String> map = new HashMap<String, String>();
map.put("HostID", hostID);
String time = RegUtils.getLogTime(message);
map.put("Time", time);
for (String col : LOG_COLS) {
String value = RegUtils.getLogValue(message, col, "");
map.put(col, value);
}
String platformID = hostMap.get(hostID);
List<Map<String, String>> platformResult = platformResults.get(platformID);
if (platformResult == null)
platformResult = new ArrayList<Map<String, String>>();
platformResult.add(map);
platformResults.put(platformID, platformResult);
}
}
}
// 插入数据库
Iterator<String> it = platformResults.keySet().iterator();
while (it.hasNext()) {
String platformID = it.next();
List<Map<String, String>> platformResult = platformResults.get(platformID);
CommonDB.batchInsertByDate(platformID, platformResult, DB_COLS, TBL_NAME);
}
return platformResults;
}
@Override
public String getStaticsIndex() {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<String, List<Map<String, String>>> execute4Kafka(JSONObject json, Map<String, String> staticsHosts) {
Map<String, List<Map<String, String>>> platformResults = new HashMap<String, List<Map<String, String>>>();
String message = json.getString("message");
String hostID = json.getString("hostid");
if (StringUtils.isNotBlank(message) && staticsHosts.containsKey(hostID)) {
Map<String, String> map = new HashMap<String, String>();
map.put("HostID", hostID);
String time = RegUtils.getLogTime(message);
map.put("Time", time);
for (String col : LOG_COLS) {
String value = RegUtils.getLogValue(message, col, "");
map.put(col, value);
}
String platformID = staticsHosts.get(hostID);
List<Map<String, String>> platformResult = platformResults.get(platformID);
if (platformResult == null)
platformResult = new ArrayList<Map<String, String>>();
if (StringUtils.isNotBlank(map.get("Uid"))) { // uid不为空的才添加
platformResult.add(map);
platformResults.put(platformID, platformResult);
}
}
// 插入数据库
Iterator<String> it = platformResults.keySet().iterator();
while (it.hasNext()) {
String platformID = it.next();
List<Map<String, String>> platformResult = platformResults.get(platformID);
CommonDB.batchInsertByDate(platformID, platformResult, DB_COLS, TBL_NAME);
}
return platformResults;
}
}
| [
"xiongyk1983@qq.com"
] | xiongyk1983@qq.com |
1722b15276ea14880ea42ab87e16dcd0f483b649 | d5fd0252f97d12d39907d7f4744f448023735cb1 | /src/main/java/by/aginskiy/application/model/dao/impl/GlobalArticleDaoImpl.java | aef7adb4f952af075ff40c8820f9edfb1e004d4e | [] | no_license | DmitriyAginskiy/AQuestions | 2b2cc29aaa20ca207b5f4aa1a6b0941ab4293d35 | b5ffd8e9941e7f578346ca5a905289a225926798 | refs/heads/main | 2023-04-13T06:26:45.741975 | 2021-04-28T12:23:36 | 2021-04-28T12:23:36 | 355,707,886 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,686 | java | package by.aginskiy.application.model.dao.impl;
import by.aginskiy.application.exception.ConnectionPoolException;
import by.aginskiy.application.exception.DaoException;
import by.aginskiy.application.model.dao.CloseableDao;
import by.aginskiy.application.model.dao.ColumnName;
import by.aginskiy.application.model.dao.GlobalArticleDao;
import by.aginskiy.application.model.dao.query.GlobalArticleQuery;
import by.aginskiy.application.model.entity.Article;
import by.aginskiy.application.model.pool.ConnectionPool;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* GlobalArticleDao implementation.
*
* @author Dzmitry Ahinski
*/
public enum GlobalArticleDaoImpl implements GlobalArticleDao, CloseableDao {
INSTANCE;
private static final Logger logger = LogManager.getLogger();
private static final String PERCENT_SYMBOL = "%";
@Override
public void add(int userId, Article article) throws DaoException {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.ADDING_ARTICLE_QUERY);
statement.setString(1, article.getTopic());
statement.setInt(2, userId);
statement.setString(3, article.getText());
statement.executeUpdate();
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
}
@Override
public int calculateActiveArticles() throws DaoException {
int articlesNumber = 0;
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.CALCULATE_ACTIVE_ARTICLES_QUERY);
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()) {
articlesNumber = resultSet.getInt(1);
}
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
return articlesNumber;
}
@Override
public int calculateArticles() throws DaoException {
int articlesNumber = 0;
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.CALCULATE_ALL_ARTICLES_QUERY);
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()) {
articlesNumber = resultSet.getInt(1);
}
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
return articlesNumber;
}
@Override
public int calculateByCriteria(String criteria) throws DaoException {
int articlesNumber = 0;
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.CALCULATE_ARTICLES_BY_CRITERIA_QUERY);
statement.setString(1, PERCENT_SYMBOL + criteria + PERCENT_SYMBOL);
statement.setString(2, PERCENT_SYMBOL + criteria + PERCENT_SYMBOL);
statement.setString(3, PERCENT_SYMBOL + criteria + PERCENT_SYMBOL);
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()) {
articlesNumber = resultSet.getInt(1);
}
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
return articlesNumber;
}
@Override
public boolean isBlockedArticle(int articleId) throws DaoException {
boolean isBlocked = false;
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.IS_BLOCKED_ARTICLE_QUERY);
statement.setInt(1, articleId);
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()) {
isBlocked = resultSet.getBoolean(ColumnName.IS_BLOCKED);
}
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
return isBlocked;
}
@Override
public void blockArticle(int articleId) throws DaoException {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.BLOCK_ARTICLE_QUERY);
statement.setInt(1, articleId);
statement.executeUpdate();
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
}
@Override
public void unblockArticle(int articleId) throws DaoException {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.UNBLOCK_ARTICLE_QUERY);
statement.setInt(1, articleId);
statement.executeUpdate();
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
}
@Override
public void hideArticle(int articleId) throws DaoException {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.HIDE_ARTICLE_QUERY);
statement.setInt(1, articleId);
statement.executeUpdate();
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
}
@Override
public void recoverArticle(int articleId) throws DaoException {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.RECOVER_ARTICLE_QUERY);
statement.setInt(1, articleId);
statement.executeUpdate();
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
}
@Override
public Optional<Article> findByCommentId(int commentId) throws DaoException {
Optional<Article> result = Optional.empty();
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.FIND_BY_COMMENT_ID_QUERY);
statement.setInt(1, commentId);
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()) {
int id = resultSet.getInt(ColumnName.ARTICLE_ID);
String topic = resultSet.getString(ColumnName.ARTICLE_TOPIC);
String author = resultSet.getString(ColumnName.USER_NAME);
String text = resultSet.getString(ColumnName.ARTICLE_TEXT);
String photoName = resultSet.getString(ColumnName.USER_PHOTO_NAME);
LocalDateTime date = resultSet.getTimestamp(ColumnName.ARTICLE_DATE).toLocalDateTime();
boolean active = resultSet.getBoolean(ColumnName.IS_ACTIVE);
boolean blocked = resultSet.getBoolean(ColumnName.IS_BLOCKED);
Article article = new Article(id, topic, author, text, photoName, date, active, blocked);
result = Optional.of(article);
}
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
return result;
}
@Override
public Optional<Article> findById(int articleId) throws DaoException {
Optional<Article> result = Optional.empty();
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.FIND_BY_ID_QUERY);
statement.setInt(1, articleId);
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()) {
int id = resultSet.getInt(ColumnName.ARTICLE_ID);
String topic = resultSet.getString(ColumnName.ARTICLE_TOPIC);
String author = resultSet.getString(ColumnName.USER_NAME);
String text = resultSet.getString(ColumnName.ARTICLE_TEXT);
String photoName = resultSet.getString(ColumnName.USER_PHOTO_NAME);
LocalDateTime date = resultSet.getTimestamp(ColumnName.ARTICLE_DATE).toLocalDateTime();
boolean active = resultSet.getBoolean(ColumnName.IS_ACTIVE);
boolean blocked = resultSet.getBoolean(ColumnName.IS_BLOCKED);
Article article = new Article(id, topic, author, text, photoName, date, active, blocked);
result = Optional.of(article);
}
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
return result;
}
@Override
public List<Article> findByCriteria(String criteria, int start, int limit) throws DaoException {
List<Article> articles = new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.FIND_BY_CRITERIA);
statement.setString(1, PERCENT_SYMBOL + criteria + PERCENT_SYMBOL);
statement.setString(2, PERCENT_SYMBOL + criteria + PERCENT_SYMBOL);
statement.setString(3, PERCENT_SYMBOL + criteria + PERCENT_SYMBOL);
statement.setInt(4, start);
statement.setInt(5, limit);
ResultSet resultSet = statement.executeQuery();
int id = 0;
String topic = null;
String author = null;
String text = null;
String photoName = null;
LocalDateTime date = null;
boolean active = true;
boolean blocked = false;
Article article = null;
while(resultSet.next()) {
id = resultSet.getInt(ColumnName.ARTICLE_ID);
topic = resultSet.getString(ColumnName.ARTICLE_TOPIC);
author = resultSet.getString(ColumnName.USER_NAME);
text = resultSet.getString(ColumnName.ARTICLE_TEXT);
photoName = resultSet.getString(ColumnName.USER_PHOTO_NAME);
date = resultSet.getTimestamp(ColumnName.ARTICLE_DATE).toLocalDateTime();
active = resultSet.getBoolean(ColumnName.IS_ACTIVE);
blocked = resultSet.getBoolean(ColumnName.IS_BLOCKED);
article = new Article(id, topic, author, text, photoName, date, active, blocked);
articles.add(article);
}
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
return articles;
}
@Override
public List<Article> findAll(int start, int limit) throws DaoException {
List<Article> articles = new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.FINDING_ARTICLES_QUERY);
statement.setInt(1, start);
statement.setInt(2, limit);
ResultSet resultSet = statement.executeQuery();
int id = 0;
String topic = null;
String author = null;
String text = null;
String photoName = null;
LocalDateTime date = null;
boolean active = true;
boolean blocked = false;
Article article = null;
while(resultSet.next()) {
id = resultSet.getInt(ColumnName.ARTICLE_ID);
topic = resultSet.getString(ColumnName.ARTICLE_TOPIC);
author = resultSet.getString(ColumnName.USER_NAME);
text = resultSet.getString(ColumnName.ARTICLE_TEXT);
photoName = resultSet.getString(ColumnName.USER_PHOTO_NAME);
date = resultSet.getTimestamp(ColumnName.ARTICLE_DATE).toLocalDateTime();
active = resultSet.getBoolean(ColumnName.IS_ACTIVE);
blocked = resultSet.getBoolean(ColumnName.IS_BLOCKED);
article = new Article(id, topic, author, text, photoName, date, active, blocked);
articles.add(article);
}
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
return articles;
}
@Override
public List<Article> findAllActive(int start, int limit) throws DaoException {
List<Article> articles = new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
try {
connection = ConnectionPool.INSTANCE.getConnection();
statement = connection.prepareStatement(GlobalArticleQuery.FINDING_ACTIVE_ARTICLES_QUERY);
statement.setInt(1, start);
statement.setInt(2, limit);
ResultSet resultSet = statement.executeQuery();
int id = 0;
String topic = null;
String author = null;
String text = null;
String photoName = null;
LocalDateTime date = null;
boolean active = true;
boolean blocked = false;
Article article = null;
while(resultSet.next()) {
id = resultSet.getInt(ColumnName.ARTICLE_ID);
topic = resultSet.getString(ColumnName.ARTICLE_TOPIC);
author = resultSet.getString(ColumnName.USER_NAME);
text = resultSet.getString(ColumnName.ARTICLE_TEXT);
photoName = resultSet.getString(ColumnName.USER_PHOTO_NAME);
date = resultSet.getTimestamp(ColumnName.ARTICLE_DATE).toLocalDateTime();
active = resultSet.getBoolean(ColumnName.IS_ACTIVE);
blocked = resultSet.getBoolean(ColumnName.IS_BLOCKED);
article = new Article(id, topic, author, text, photoName, date, active, blocked);
articles.add(article);
}
} catch (SQLException | ConnectionPoolException exception) {
logger.log(Level.ERROR, "Error while trying to get connection or execute query, ", exception);
throw new DaoException(exception);
} finally {
close(statement);
close(connection);
}
return articles;
}
}
| [
"noreply@github.com"
] | DmitriyAginskiy.noreply@github.com |
f08214e5be38339e86e4d4c4625830c6e5c9cd41 | 932f19f1a24edb5c17509b10f018080723cb45a2 | /First Line of Code/5.3 Send Standard-custom Broadcast.java | 73cc69bd6e1d25621caf92401f2b8f2ee8c312ff | [] | no_license | iGuure/AndroidCodeHub | 39f85ced116e5424795a2ca9d350fa206e43ef7a | a32459c1df7836065c92301680d479ad6aa4ecd0 | refs/heads/master | 2021-01-13T14:52:48.688974 | 2017-07-18T10:12:39 | 2017-07-18T10:12:39 | 76,474,564 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,292 | java | public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
// 如果接收有序广播,可以使用abortBroadcast()截断广播
// abortBroadcast();
}
}
/*
静态注册广播接收器
可以使用<intent-filter android:priority="100">规定广播接收器的优先级,默认为0(参考API文档)
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
自定义广播
<action android:name="com.example.broadcasttest.MY_BROADCAST" />
</intent-filter>
</receiver>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Broadcast"/>
*/
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 发送自定义广播
Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
sendBroadcast(intent);
// 发送有序广播
// sendOrderedBroadcast(intent, null);
}
}); | [
"543449492@qq.com"
] | 543449492@qq.com |
9e73f8775903f1e09662d3c90eb417cf2bc1941d | a0a72d488baf382aecd20d7546752957d6b88445 | /kotlin/collections/SlidingWindowKt.java | 763af931260681bc8b80c4b21dd5aa7eab4262ab | [
"MIT"
] | permissive | 3000IQPlay/epsilonloader | 3774fc02e0b69c326cbac3e96d2d5449ef04a547 | 78f536c3a020e56455a81e2f0833e5f8e8d5fe47 | refs/heads/main | 2023-05-24T09:05:32.557011 | 2021-06-15T15:03:43 | 2021-06-15T15:03:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,364 | java | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* org.jetbrains.annotations.NotNull
* org.jetbrains.annotations.Nullable
*/
package kotlin.collections;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import kotlin.Metadata;
import kotlin.ResultKt;
import kotlin.Unit;
import kotlin.collections.EmptyIterator;
import kotlin.collections.RingBuffer;
import kotlin.coroutines.Continuation;
import kotlin.coroutines.intrinsics.IntrinsicsKt;
import kotlin.jvm.functions.Function2;
import kotlin.jvm.internal.Intrinsics;
import kotlin.ranges.RangesKt;
import kotlin.sequences.Sequence;
import kotlin.sequences.SequenceScope;
import kotlin.sequences.SequencesKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Metadata(mv={1, 5, 1}, k=2, d1={"\u0000*\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0010\b\n\u0002\b\u0002\n\u0002\u0010(\n\u0002\u0010 \n\u0002\b\u0003\n\u0002\u0010\u000b\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0000\u001a\u0018\u0010\u0000\u001a\u00020\u00012\u0006\u0010\u0002\u001a\u00020\u00032\u0006\u0010\u0004\u001a\u00020\u0003H\u0000\u001aH\u0010\u0005\u001a\u000e\u0012\n\u0012\b\u0012\u0004\u0012\u0002H\b0\u00070\u0006\"\u0004\b\u0000\u0010\b2\f\u0010\t\u001a\b\u0012\u0004\u0012\u0002H\b0\u00062\u0006\u0010\u0002\u001a\u00020\u00032\u0006\u0010\u0004\u001a\u00020\u00032\u0006\u0010\n\u001a\u00020\u000b2\u0006\u0010\f\u001a\u00020\u000bH\u0000\u001aD\u0010\r\u001a\u000e\u0012\n\u0012\b\u0012\u0004\u0012\u0002H\b0\u00070\u000e\"\u0004\b\u0000\u0010\b*\b\u0012\u0004\u0012\u0002H\b0\u000e2\u0006\u0010\u0002\u001a\u00020\u00032\u0006\u0010\u0004\u001a\u00020\u00032\u0006\u0010\n\u001a\u00020\u000b2\u0006\u0010\f\u001a\u00020\u000bH\u0000\u00a8\u0006\u000f"}, d2={"checkWindowSizeStep", "", "size", "", "step", "windowedIterator", "", "", "T", "iterator", "partialWindows", "", "reuseBuffer", "windowedSequence", "Lkotlin/sequences/Sequence;", "kotlin-stdlib"})
public final class SlidingWindowKt {
public static final void checkWindowSizeStep(int n2, int n3) {
boolean bl = n2 > 0 && n3 > 0;
boolean bl2 = false;
boolean bl3 = false;
if (!bl) {
boolean bl4 = false;
String string = n2 != n3 ? "Both size " + n2 + " and step " + n3 + " must be greater than zero." : "size " + n2 + " must be greater than zero.";
throw (Throwable)new IllegalArgumentException(string.toString());
}
}
@NotNull
public static final <T> Sequence<List<T>> windowedSequence(@NotNull Sequence<? extends T> sequence, int n2, int n3, boolean bl, boolean bl2) {
Intrinsics.checkNotNullParameter(sequence, "$this$windowedSequence");
SlidingWindowKt.checkWindowSizeStep(n2, n3);
boolean bl3 = false;
return new Sequence<List<? extends T>>(sequence, n2, n3, bl, bl2){
final /* synthetic */ Sequence $this_windowedSequence$inlined;
final /* synthetic */ int $size$inlined;
final /* synthetic */ int $step$inlined;
final /* synthetic */ boolean $partialWindows$inlined;
final /* synthetic */ boolean $reuseBuffer$inlined;
{
this.$this_windowedSequence$inlined = sequence;
this.$size$inlined = n2;
this.$step$inlined = n3;
this.$partialWindows$inlined = bl;
this.$reuseBuffer$inlined = bl2;
}
@NotNull
public Iterator<List<? extends T>> iterator() {
boolean bl = false;
return SlidingWindowKt.windowedIterator(this.$this_windowedSequence$inlined.iterator(), this.$size$inlined, this.$step$inlined, this.$partialWindows$inlined, this.$reuseBuffer$inlined);
}
};
}
@NotNull
public static final <T> Iterator<List<T>> windowedIterator(@NotNull Iterator<? extends T> iterator2, int n2, int n3, boolean bl, boolean bl2) {
Intrinsics.checkNotNullParameter(iterator2, "iterator");
if (!iterator2.hasNext()) {
return EmptyIterator.INSTANCE;
}
return SequencesKt.iterator(new Function2<SequenceScope<? super List<? extends T>>, Continuation<? super Unit>, Object>(n2, n3, iterator2, bl2, bl, null){
private /* synthetic */ Object L$0;
Object L$1;
Object L$2;
int I$0;
int label;
final /* synthetic */ int $size;
final /* synthetic */ int $step;
final /* synthetic */ Iterator $iterator;
final /* synthetic */ boolean $reuseBuffer;
final /* synthetic */ boolean $partialWindows;
/*
* Unable to fully structure code
* Enabled force condition propagation
* Lifted jumps to return sites
*/
@Nullable
public final Object invokeSuspend(@NotNull Object var1_1) {
var11_2 = IntrinsicsKt.getCOROUTINE_SUSPENDED();
switch (this.label) {
case 0: {
ResultKt.throwOnFailure(var1_1);
var2_3 = (SequenceScope)this.L$0;
var3_4 = RangesKt.coerceAtMost(this.$size, 1024);
var4_5 = this.$step - this.$size;
if (var4_5 < 0) break;
var5_6 = new ArrayList<Object>(var3_4);
var6_8 = 0;
var9_10 = this.$iterator;
var10_12 = false;
var8_13 = var9_10;
lbl14:
// 4 sources
while (var8_13.hasNext()) {
var7_16 = var8_13.next();
if (var6_8 > 0) {
--var6_8;
continue;
}
var5_6.add(var7_16);
if (var5_6.size() != this.$size) continue;
this.L$0 = var2_3;
this.L$1 = var5_6;
this.L$2 = var8_13;
this.I$0 = var4_5;
this.label = 1;
v0 = var2_3.yield(var5_6, this);
if (v0 == var11_2) {
return var11_2;
}
** GOTO lbl39
}
break;
}
case 1: {
var4_5 = this.I$0;
var8_13 = (Iterator)this.L$2;
var5_6 = (ArrayList<Object>)this.L$1;
var2_3 = (SequenceScope)this.L$0;
ResultKt.throwOnFailure(var1_1);
v0 = var1_1;
lbl39:
// 2 sources
if (this.$reuseBuffer) {
var5_6.clear();
} else {
var5_6 = new ArrayList<E>(this.$size);
}
var6_8 = var4_5;
** GOTO lbl14
}
}
var7_16 = var5_6;
var8_14 = false;
if (!(var7_16.isEmpty() == false) || !this.$partialWindows && var5_6.size() != this.$size) return Unit.INSTANCE;
this.L$0 = null;
this.L$1 = null;
this.L$2 = null;
this.label = 2;
v1 = var2_3.yield(var5_6, this);
if (v1 != var11_2) return Unit.INSTANCE;
return var11_2;
{
case 2: {
ResultKt.throwOnFailure(var1_1);
v1 = var1_1;
return Unit.INSTANCE;
}
}
var5_7 = new RingBuffer<Collection<E>>(var3_4);
var8_15 = this.$iterator;
var9_11 = false;
var7_17 = var8_15;
lbl63:
// 4 sources
while (var7_17.hasNext()) {
var6_9 = var7_17.next();
var5_7.add(var6_9);
if (!var5_7.isFull()) continue;
if (var5_7.size() < this.$size) {
var5_7 = var5_7.expanded(this.$size);
continue;
}
this.L$0 = var2_3;
this.L$1 = var5_7;
this.L$2 = var7_17;
this.label = 3;
v2 = var2_3.yield(this.$reuseBuffer != false ? (List)var5_7 : (List)new ArrayList<E>((Collection)var5_7), this);
if (v2 == var11_2) {
return var11_2;
}
** GOTO lbl85
}
{
break;
case 3: {
var7_17 = (Iterator)this.L$2;
var5_7 = (RingBuffer)this.L$1;
var2_3 = (SequenceScope)this.L$0;
ResultKt.throwOnFailure(var1_1);
v2 = var1_1;
lbl85:
// 2 sources
var5_7.removeFirst(this.$step);
** GOTO lbl63
}
}
if (!this.$partialWindows) return Unit.INSTANCE;
lbl88:
// 2 sources
while (var5_7.size() > this.$step) {
this.L$0 = var2_3;
this.L$1 = var5_7;
this.L$2 = null;
this.label = 4;
v3 = var2_3.yield(this.$reuseBuffer != false ? (List)var5_7 : (List)new ArrayList<E>((Collection)var5_7), this);
if (v3 == var11_2) {
return var11_2;
}
** GOTO lbl103
}
{
break;
case 4: {
var5_7 = (RingBuffer<Collection<E>>)this.L$1;
var2_3 = (SequenceScope)this.L$0;
ResultKt.throwOnFailure(var1_1);
v3 = var1_1;
lbl103:
// 2 sources
var5_7.removeFirst(this.$step);
** GOTO lbl88
}
}
var6_9 = var5_7;
var7_18 = false;
if (!(var6_9.isEmpty() == false)) return Unit.INSTANCE;
this.L$0 = null;
this.L$1 = null;
this.L$2 = null;
this.label = 5;
v4 = var2_3.yield(var5_7, this);
if (v4 != var11_2) return Unit.INSTANCE;
return var11_2;
{
case 5: {
ResultKt.throwOnFailure(var1_1);
v4 = var1_1;
return Unit.INSTANCE;
}
}
throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
}
{
this.$size = n2;
this.$step = n3;
this.$iterator = iterator2;
this.$reuseBuffer = bl;
this.$partialWindows = bl2;
super(2, continuation);
}
@NotNull
public final Continuation<Unit> create(@Nullable Object object, @NotNull Continuation<?> continuation) {
Intrinsics.checkNotNullParameter(continuation, "completion");
Function2<SequenceScope<? super List<? extends T>>, Continuation<? super Unit>, Object> function2 = new /* invalid duplicate definition of identical inner class */;
Object object2 = function2.L$0 = object;
return function2;
}
public final Object invoke(Object object, Object object2) {
return (this.create(object, (Continuation)object2)).invokeSuspend(Unit.INSTANCE);
}
});
}
}
| [
"66845682+chrispycreme420@users.noreply.github.com"
] | 66845682+chrispycreme420@users.noreply.github.com |
333f8e13eebe843abb1f847549dc8a7abe8b21ff | fc06d3fa68b0077e49c8637db994813701038a32 | /business-center/device-data-kela/src/main/java/com/jecinfo/kelamqtt/opentsdb/builder/MetricBuilder.java | 8160eff9c9adb1642c0bed2c62c933fb9c99c895 | [
"Apache-2.0"
] | permissive | jecinfo2016/open-capacity-platform-backend | d194f237b98cd6f1198b704fab2b650e23544b9d | bfcb2cee2e8b47a40555a7ec7749b8e23a66a2ad | refs/heads/master | 2023-02-16T20:09:17.246856 | 2021-01-18T02:29:25 | 2021-01-18T02:29:25 | 330,533,472 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,248 | java | /*
* Copyright 2013 Proofpoint Inc.
*
* 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.jecinfo.kelamqtt.opentsdb.builder;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Preconditions.checkState;
/**
* Builder used to create the JSON to push metrics to KairosDB.
*/
public class MetricBuilder {
private List<Metric> metrics = new ArrayList<Metric>();
private transient Gson mapper;
private MetricBuilder() {
GsonBuilder builder = new GsonBuilder();
mapper = builder.create();
}
/**
* Returns a new metric builder.
*
* @return metric builder
*/
public static MetricBuilder getInstance() {
return new MetricBuilder();
}
/**
* Adds a metric to the builder.
*
* @param metricName
* metric name
* @return the new metric
*/
public Metric addMetric(String metricName) {
Metric metric = new Metric(metricName);
metrics.add(metric);
return metric;
}
/**
* Returns a list of metrics added to the builder.
*
* @return list of metrics
*/
public List<Metric> getMetrics() {
return metrics;
}
/**
* Returns the JSON string built by the builder. This is the JSON that can
* be used by the client add metrics.
*
* @return JSON
* @throws IOException
* if metrics cannot be converted to JSON
*/
public String build() throws IOException {
for (Metric metric : metrics) {
// verify that there is at least one tag for each metric
checkState(metric.getTags().size() > 0, metric.getName()
+ " must contain at least one tag.");
}
return mapper.toJson(metrics);
}
}
| [
"duj@jec.com.cn"
] | duj@jec.com.cn |
d1400bb14dc4bc115a46852203926aa0177c4ff9 | dea93674c8d4988297eaca6be1c222ab8beb264b | /src/main/java/com/gti619/services/AuthListener.java | d99554eeba06f7de57ac05809d83b194d126c602 | [] | no_license | JadMaa/rbac-app | 07b6a8f35c8fab25d0511ea1ad6f7fd928903600 | 7e9fac86ea0ec55fdeafd3afbc5de0d33dd65ff7 | refs/heads/master | 2021-08-23T22:51:07.926851 | 2017-12-06T23:49:09 | 2017-12-06T23:49:09 | 111,847,578 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,836 | java | package com.gti619.services;
import com.gti619.configurations.AuthParam;
import com.gti619.domain.User;
import com.gti619.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class AuthListener {
private UserRepository userRepository;
@Autowired
/**
* Contructeur par copie d'attribut
* @param userRepository la table des utilisateurs
*/
public AuthListener(UserRepository userRepository) {
this.userRepository = userRepository;
}
@EventListener
/**
* L'écouteur pour une authentication échouée.
* @param event l'événement d'authentification
* @throws Exception
*/
public void authenticationFailed(AuthenticationFailureBadCredentialsEvent event) throws Exception {
String username = (String) event.getAuthentication().getPrincipal();
User user= userRepository.findByUsername(username);
user.setConsecutiveAttemptsFail(user.getConsecutiveAttemptsFail()+1);
if(user.getConsecutiveAttemptsFail() > AuthParam.getMaxAttempt()){
if(user.getUnlockDate() == null){
Date lockUtil = new Date();
// Lock l'utilisateur pour x secondes . Ex : si Auth.getTime est = 30, l'utilisateur est locked pour 30 sec
lockUtil.setTime(lockUtil.getTime() + (1000 * AuthParam.getLockTime()));
user.setUnlockDate(lockUtil);
AuthLog.write("The user " +username+" has been locked for "+AuthParam.getLockTime()+" seconds.");
} else {
// Si l'utilisateur est encore locked, il doit contacter l'admin
AuthLog.write("The user " +username+" has been locked, contact the admin please.");
user.setAccountNonLocked(false);
}
user.setConsecutiveAttemptsFail(0);
}
this.userRepository.save(user);
}
@EventListener
/**
* L'écouteur pour une authentification réussie.
* @param event l'événement d'authentification
*/
public void authenticationSuccess(AuthenticationSuccessEvent event) {
User userEvent = (User) event.getAuthentication().getPrincipal();
// Quand l'utilisateur se connecte sans problèmes, remettre tout à 0 (tentatives, etc.).
User user= userRepository.findByUsername(userEvent.getUsername());
user.setConsecutiveAttemptsFail(0);
user.setUnlockDate(null);
this.userRepository.save(user);
}
} | [
"jad.maa1@gmail.com"
] | jad.maa1@gmail.com |
7f0008ab0d74f5d6121124cd864d4f2521c192ad | e7dadbfa057bba95de971976b868d929fbf7d5d7 | /AStar.java | c94a782c9e71d7b4e17cbf86ebaf4b786c7bf09a | [] | no_license | RossDuffy/Programs | 2d5cf4969de72c45f94c92f5adf287917f53df11 | b08bde37ba39bcac5d390d370ad92ff3685f2062 | refs/heads/master | 2022-03-08T13:49:33.676847 | 2022-02-14T18:39:32 | 2022-02-14T18:39:32 | 208,059,438 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 915 | java | public class AStar
{
public static void main(String args[])
{
int[][] startState = new int[3][3];
int[][] endState = new int[3][3];
int init = 1;
for(int i = 0; i < endState.length - 1; i++)
{
for (int j = 0; j < endState[i].length; j++)
{
endState[i][j] = init;
init++;
}
}
endState[3][3] = 0;
int heuristic = heuristic(startState, endState);
}
//best-first-search
//tiles-out-of-place heuristic
/*
* takes the current state and end state;
* compares both, counting how many tiles are out of place;
* returns that count as the heuristic value
* */
public static int heuristic(int [][] inState, int[][] endState)
{
int heuristic = 0;
for(int o = 0; o < inState.length; o++)
{
for(int p = 0; p < inState[o].length; p++)
{
if(inState[o][p] != endState[o][p])
heuristic++;
}
}
return heuristic;
}
}
| [
"noreply@github.com"
] | RossDuffy.noreply@github.com |
0464a71a0670f82a6a52daefb8368d5b50331b9e | a75998c2754dd2f992f4f0eba8bdea4cf00ea9a0 | /src/main/java/Main.java | aa0a2d52396b1cc6a7a032b68f545aedc11f52e2 | [] | no_license | SuranovAN/MultiThreadDialog | 680b25815435401360752dfd496b96f2656a1102 | 9d57e472f2dbd0e14df8e1e1d5fb22eddc5ea933 | refs/heads/master | 2022-12-17T13:58:00.317751 | 2020-09-26T12:01:31 | 2020-09-26T12:01:31 | 296,967,058 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 707 | java | public class Main {
public static void main(String[] args) throws InterruptedException {
int sleepTime = 12000;
System.out.println("Создаю потоки");
ThreadGroup mainGroup = new ThreadGroup("main group");
Thread thread1 = new MyThread(mainGroup, "1");
Thread thread2 = new MyThread(mainGroup, "2");
Thread thread3 = new MyThread(mainGroup, "3");
Thread thread4 = new MyThread(mainGroup, "4");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
Thread.sleep(sleepTime);
System.out.println("Завершаю все потоки");
mainGroup.interrupt();
}
}
| [
"syranov.a.n.1993@gmail.com"
] | syranov.a.n.1993@gmail.com |
24f4ad4288fb6815e96088fe931ec9a2acc3e2a2 | d279eb8e9773623adf71420609f61afd3a983827 | /Medium/Card_Number_Validation.java | d35e2a0bca205574469e74e4ac8c7a9581228b85 | [] | no_license | Aadeshp/Codeeval-Solutions | 56782d2499fac7904e3222b4b2d884dbb12b83d3 | 29af977f30e6c5e5823e1e34ecd6de3c77506682 | refs/heads/master | 2021-01-19T12:44:33.100778 | 2014-12-21T00:09:59 | 2014-12-21T00:09:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,272 | java | import java.io.*;
import java.util.*;
public class Main {
public static void main (String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File(args[0]));
while (input.hasNextLine()) {
String cn = input.nextLine();
boolean ifDouble = false;
int sum = 0;
for (int x = cn.length() - 1; x >= 0; x--) {
if (cn.charAt(x) == ' ')
continue;
int n = Character.getNumericValue(cn.charAt(x));
if (ifDouble) {
int d = n * 2;
if (String.valueOf(d).length() > 1) {
while (d > 0) {
sum += (d % 10);
d /= 10;
}
} else {
sum += d;
}
} else {
sum += n;
}
ifDouble = !ifDouble;
}
if (sum % 10 == 0)
System.out.println("1");
else
System.out.println("0");
}
}
}
| [
"aadeshpatel@Aadeshs-MacBook-Pro.local"
] | aadeshpatel@Aadeshs-MacBook-Pro.local |
751c156bc0850a1105a70d5b33fce40a70b89f96 | 8e7b2b88726b7dbce9b84aa27c6fc47ba7161376 | /Compiler_v4/src/Encoder.java | 31cc0fc749ea2d94cb370739d6b393afd64f6d61 | [] | no_license | gutodisse1/compilador_minipascal | 7a0ea4042615d8c93f9e149c498afa90f8b5fbbf | 49259729c87b9ec17d8c831620838cea67f70352 | refs/heads/master | 2022-08-03T11:16:25.970253 | 2020-05-29T19:04:07 | 2020-05-29T19:04:07 | 267,926,902 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,633 | java | /**
* Write a description of class Main here.
*
* @author Gustavo Marques ( @GUTODISSE )
* @version 23_03_2019
*/
import java.io.*;
import minipascal.ast.*;
import minipascal.syntatic_analyser.*;
import minipascal.runtime.*;
public class Encoder implements Visitor {
private byte phase;
private Instruction[] code = new Instruction[1024];
private short nextInstrAddr = 0;
private varTable varTable;
public void salve_code(String fileName) {
int i;
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
for(i=0;i<nextInstrAddr;i++)
{
bufferedWriter.write(codeLine(i)+"\n");
}
// Always close files.
bufferedWriter.close();
}
catch(IOException ex) {
System.out.println("[ERROR]");
System.out.println("\tPlease, verify object path. (-f param);");
System.out.println(
"\tError writing to file '"
+ fileName + "'");
System.exit(0);
// Or we could just do this:
// ex.printStackTrace();
}
}
public void print_code() {
int i;
for(i=0;i<nextInstrAddr;i++)
{
System.out.println(codeLine(i));
}
}
private String codeLine(int currentLine) {
String msg1;
byte op = code[currentLine].op;
byte n = code[currentLine].n;
byte r = code[currentLine].r;
String d = code[currentLine].d;
String msg = new String("\t"+currentLine+" : \t"+Instruction.spellings[op]+" ");
switch(code[currentLine].op) {
case Instruction.LOADop:
msg1 = new String("("+n+") "+d+"["+r+"]");
break;
case Instruction.LOADAop:
msg1 = new String(d+"["+r+"]");
break;
case Instruction.LOADLop:
msg1 = new String(d);
break;
case Instruction.STOREop:
msg1 = new String("("+n+") "+d+"["+r+"]");
break;
case Instruction.PUSHop:
msg1 = new String(d);
break;
case Instruction.CALLop:
msg1 = new String("("+n+") "+d+"["+r+"]");
break;
case Instruction.JUMPop:
msg1 = new String(d+"["+r+"]");
break;
case Instruction.JUMPIFop:
msg1 = new String("("+n+") "+d+"["+r+"]");
break;
case Instruction.POPop:
msg1 = new String("("+n+") "+d);
break;
case Instruction.STOREIop:
msg1 = new String("("+n+") ");
break;
case Instruction.HALTop:
msg1 = new String("");
break;
default:
msg1 = new String("\nCOMMAND NOT IMPLEMENTED");
//System.out.println(" ("+n+") "+d+"["+r+"]");
break;
}
return new String(msg+msg1);
}
private void emit(byte op, byte n, byte r, String d) {
code[nextInstrAddr++] = new Instruction(op, r, n, d);
}
private static short shortValueOf( Object obj) {
//return 0;
return ((Short) obj).shortValue();
}
private void patch( short addr, String d) {
code[addr].d = d;
}
// Program
public Object visitProgram (Program prog, Object arg)
{
Short LB;
phase = -1;
prog.I.visit(this, arg);
phase = 0;
LB = (Short) prog.Cr.visit(this, arg);
emit(Instruction.POPop,(byte) ((Short) LB).shortValue(), (byte) 0, "0");
emit(Instruction.HALTop,(byte) 0, (byte) 0, "0");
return null;
}
public Object visitSimpleId(Id_simples com, Object arg)
{
short s = 0;
short gs;
if(phase == 0)
{
gs = shortValueOf(arg);
s = (short) 1;
com.entity = new KnowAddress((short)1, gs);
varTable.enter(com.spelling,gs);
System.out.println("\t["+varTable.retrieve(com.spelling)+"]\t"+com.spelling);
}
return s;
}
public Object visitCompoundId(Id_seq com, Object arg)
{
short gs = shortValueOf(arg);
short s1 = (short) com.I1.visit(this, arg);
short s2 = (short) com.I2.visit(this, new Short((short)(gs+s1)));
return (short)(s1+s2) ;
}
// Body
public Object visitCorpo(Corpo com, Object arg)
{
short LB;
phase = 0;
System.out.println("MEMORY MAP");
System.out.println("- - - - - - - - - - - - - - - - - - - ");
System.out.println("\t[ADDR]\tIdentifier");
LB = new Short((short) com.D.visit(this, arg));
phase = 1;
System.out.println("\nMACHINE CODE");
System.out.println("- - - - - - - - - - - - - - - - - - - ");
if(com.C != null)
com.C.visit(this, arg);
return LB;
}
// Declaration
public Object visitSimpleDeclaration(Declaracao_simples com, Object arg)
{
short s = (short) com.I.visit(this, arg);
short t = shortValueOf( com.T.visit(this, arg) );
emit(Instruction.PUSHop, (byte) 0, (byte) 0, String.valueOf(s*t));
return new Short((short)(s*t));
}
public Object visitCompoundDeclaration(Declaracao_seq com, Object arg)
{
short gs = shortValueOf(arg);
short s1 = shortValueOf(com.D1.visit(this, arg));
short s2 = shortValueOf(com.D2.visit(this, new Short((short)(gs+s1))));
return new Short((short)(s1+s2));
}
// Term
public Object visitSimpleTerm(Termo_unico com, Object arg)
{
Type t = (Type) com.F.visit(this, null);
return t;
}
public Object visitCompoundTerm(Termo_composto com, Object arg)
{
Type t = null;
Type T1 = (Type) com.F1.visit(this, null);
Type T2 = (Type) com.F2.visit(this, null);
String Operador = com.OP_MUL;
if(Operador.equals("*")) {
Operador = "mult";
}
else if(Operador.equals("/")) {
Operador = "div";
}
emit(Instruction.CALLop, (byte) 0, (byte) 0, Operador);
return t;
}
// Fator
public Object visitFatorVar(Fator_VAR com, Object arg)
{
RuntimeEntity entity = (RuntimeEntity) com.V.visit(this, arg);
short d = ((KnowAddress) entity).address;
emit(Instruction.LOADAop, (byte) 0, Instruction.SBr, String.valueOf(d));
return null;
}
public Object visitFatorLit(Fator_LIT com, Object arg)
{
short d;
// DECORATION
emit(Instruction.LOADLop, (byte) 0, Instruction.SBr, com.Lit);
return com.type;
}
public Object visitFatorExp(Fator_EXP com, Object arg)
{
byte temp;
temp = phase;
phase = 3;
com.type = (Type) com.E.visit(this, arg);
phase = temp;
return com.type; // DECORATION
}
// Variable
public Object visitSimpleVar(Var_simples com, Object arg)
{
short E = (short) 0;
com.I.visit(this, arg);
short addr = varTable.retrieve(((Id_simples) com.I).spelling);
//System.out.println(((KnowAddress) com.entity).address);
// TODO:
// CONTEXTUAL ISN'T WORKING WITH [EXPRESSAO]
if(com.E != null)
{
com.E.visit(this, arg);
E = (short) 1;
}
com.entity = new KnowAddress(E, addr);
return com.entity;
}
// Expressions
public Object visitSimpleExpression(Expressao_s com, Object arg)
{
Short s = (Short) com.E.visit(this, null);
return s;
}
public Object visitCompoundExpression(Expressao_composta com, Object arg)
{
Type t = null;
Type T1 = (Type) com.E1.visit(this, null);
Type T2 = (Type) com.E2.visit(this, null);
String Operador = com.OP_REL;
if(Operador.equals("<=")) {
Operador = "le";
}
else if(Operador.equals("<")) {
Operador = "lt";
}
else if(Operador.equals(">=")) {
Operador = "ge";
}
else if(Operador.equals(">")) {
Operador = "gt";
}
emit(Instruction.CALLop, (byte) 0, (byte) 0, Operador);
return t;
}
// Expression Simple
public Object visitSimpleExpressionSimple(Expressao_simples_simples com, Object arg)
{
com.T.visit(this, null);
return null;
}
public Object visitCompoundExpressionSimple(Expressao_simples_composta com, Object arg)
{
Type t = null;
Type T1 = (Type) com.T1.visit(this, null);
Type T2 = (Type) com.T2.visit(this, null);
String Operador = com.OP_AD;
if(Operador.equals("+")) {
Operador = "add";
}
else if(Operador.equals("-")) {
Operador = "sub";
}
emit(Instruction.CALLop, (byte) 0, (byte) 0, Operador);
return t;
}
// Type
public Object visitSimpleType(Tipo_simples com, Object arg)
{
return new Short((short)1);
}
public Object visitArrayType(Tipo_array com, Object arg)
{
com.T1.visit(this, null);
Short s1 = Short.valueOf(com.L1);
Short s2 = Short.valueOf(com.L2);
return new Short((short)(s2-s1+1));
}
// Command
public Object visitIfCommand(Comando_IF com, Object arg)
{
short i;
Type T1 = (Type) com.E1.visit(this, arg);
i = nextInstrAddr;
emit(Instruction.JUMPIFop, (byte) 0, Instruction.CBr, "0");
com.C1.visit(this, arg);
emit(Instruction.JUMPop, (byte) 0, Instruction.CBr, "0");
patch(i,String.valueOf(nextInstrAddr));
return null;
}
public Object visitIfElseCommand(Comando_IF_composto com, Object arg)
{
short i, j, g;
Type T1 = (Type) com.E1.visit(this, null);
i = nextInstrAddr;
emit(Instruction.JUMPIFop, (byte) 0, Instruction.CBr, "0"); // jump g
com.C1.visit(this, arg);
j = nextInstrAddr;
emit(Instruction.JUMPop, (byte) 0, Instruction.CBr, "0"); // jump h
g = nextInstrAddr;
com.C2.visit(this, arg);
patch(i,String.valueOf(g));
patch(j,String.valueOf(nextInstrAddr));
return null;
}
public Object visitIfSequentialCommand(Comando_Seq com, Object arg)
{
com.C1.visit(this, arg);
if(com.C2 != null)
com.C2.visit(this, arg);
return null;
}
public Object visitVarCommand(Comando_VAR com, Object arg)
{
short gs = shortValueOf(arg);
short s = (short) 1;
RuntimeEntity entity = (RuntimeEntity) com.V1.visit(this, arg);
short d = ((KnowAddress) entity).address;
if( entity.size != 0)
{
emit(Instruction.LOADLop, (byte) 0, Instruction.SBr, String.valueOf(d));
emit(Instruction.CALLop, (byte) 0, (byte) 0, "add");
}
com.E1.visit(this, arg);
if( entity.size == 0)
{
emit(Instruction.STOREop, (byte) s, Instruction.SBr, String.valueOf(d));
}
else
{
emit(Instruction.STOREIop, (byte) s, Instruction.SBr, "0");
}
return null;
}
public Object visitWhileCommand(Comando_WHILE com, Object arg)
{
/* J: JUMP H
* G: EXECUTE C
* H: EVALUATE E
* JUMPIF(1) G
*/
short j,g,h;
// J: JUMP H
j = nextInstrAddr;
emit(Instruction.JUMPIFop, (byte) 0, Instruction.CBr, "0"); // jump g
g = nextInstrAddr;
com.C1.visit(this, arg);
h = nextInstrAddr;
com.E1.visit(this, arg);
emit(Instruction.JUMPIFop, (byte) 1, Instruction.CBr, String.valueOf(g)); // jump g
patch(j,String.valueOf(h));
return null;
}
public Encoder (Program prog) {
varTable = new varTable();
prog.visit(this, new Short((short)0));
}
}
| [
"gutodisse@gmail.com"
] | gutodisse@gmail.com |
5aad5633e53481b97da00b070be72d2d88e2d94c | 4496f8ed1465b8f093d8777401b0456b41df0c5a | /app/src/main/java/com/example/kathy/aialarm/AlarmSoundSetter.java | be4a16db04afc98d11af721cd338256b2095c49e | [
"Apache-2.0"
] | permissive | kguo901/AIAlarm | 4e544cbe2631ec56b1e005a518afb1524d69c677 | 1b0626f32ea60d7cedab70663ca5e230319d9c04 | refs/heads/master | 2021-05-05T06:33:37.423758 | 2018-02-05T14:47:31 | 2018-02-05T14:47:31 | 118,805,383 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,663 | java | package com.example.kathy.aialarm;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link AlarmSoundSetter.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link AlarmSoundSetter#newInstance} factory method to
* create an instance of this fragment.
*/
public class AlarmSoundSetter extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public AlarmSoundSetter() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment AlarmSoundSetter.
*/
// TODO: Rename and change types and number of parameters
public static AlarmSoundSetter newInstance(String param1, String param2) {
AlarmSoundSetter fragment = new AlarmSoundSetter();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_alarm_sound_setter, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| [
"guo.901@osu.edu"
] | guo.901@osu.edu |
94ec78e4aec4430f63a9848e410a5fc166faa46e | aeda82e3f222a1e0b8308c8c99ce85692e48970e | /OOP/Practice OOP10 Part 2/src/FileOperation.java | fef7dda3fea507f33c2dfe7198a7a8f8117547e5 | [] | no_license | ZiGiDi/JavaLearning | 7bd9b27f721a30ba15c0870a825bbba850d630b1 | 0e9e0e67e8545cfa884f159d88faf9176df7ed31 | refs/heads/master | 2020-03-08T02:24:43.923130 | 2018-04-03T06:16:31 | 2018-04-03T06:16:31 | 127,859,108 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,500 | java | /**
* Created by ZiGiDi on 14.01.2018.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOperation {
public static void fileCopy(File in, File out) throws IOException {
byte [] buffer =new byte[1024*1024];
int readByte = 0;
try(FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out)) {
for(;(readByte=fis.read(buffer))>0;){
fos.write(buffer,0,readByte);
}
}catch (IOException e){
throw e;
}
}
static long getDirSize(File dir){
long size =0;
if (dir.isFile()){
size = dir.length();
} else {
File [] subFiles = dir.listFiles();
for (File file: subFiles){
if(file.isFile()){
size += file.length();
} else{
size += getDirSize(file);
}
}
}
System.out.println("The size is " + size);
return size;
}
public static long calculateFolderSize(File folder){
if (folder.isFile()){
return folder.length();
}else{
long size = 0;
File[] fileArray = folder.listFiles();
for(File file: fileArray){
size +=calculateFolderSize(file);
}
return size;
}
}
}
| [
"zigidi1994@gmail.com"
] | zigidi1994@gmail.com |
5f9293341f564f8b2064456e3767c9b026e438ed | be73270af6be0a811bca4f1710dc6a038e4a8fd2 | /crash-reproduction-moho/results/XWIKI-14263-32-17-PESA_II-WeightedSum:TestLen:CallDiversity/com/xpn/xwiki/render/DefaultVelocityManager_ESTest_scaffolding.java | 1404d216a12b3346550b2810df343ed49bf0140a | [] | no_license | STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application | cf118b23ecb87a8bf59643e42f7556b521d1f754 | 3bb39683f9c343b8ec94890a00b8f260d158dfe3 | refs/heads/master | 2022-07-29T14:44:00.774547 | 2020-08-10T15:14:49 | 2020-08-10T15:14:49 | 285,804,495 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 447 | java | /**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Sat Apr 04 03:56:48 UTC 2020
*/
package com.xpn.xwiki.render;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
@EvoSuiteClassExclude
public class DefaultVelocityManager_ESTest_scaffolding {
// Empty scaffolding for empty test suite
}
| [
"pouria.derakhshanfar@gmail.com"
] | pouria.derakhshanfar@gmail.com |
4b8fcf94b320fb345c6c5a7409c3415b29fec949 | 93bbacae072b8a0ab5425a716151fe26c25a8276 | /src/main/java/com/bridgelabz/utility/ParkingLotSystemUtilities.java | 0d9f1e3a645e12e5bcf1587ed9dd5ac655520f89 | [] | no_license | Devki1/ParkingLotProblem | f820077a611e9a11f38e7f1fe5352e4052f05efe | 9dc12e2da1de920fb2f385b63a261cb6c7cc557b | refs/heads/master | 2022-06-30T10:06:28.108092 | 2020-04-27T16:04:59 | 2020-04-27T16:04:59 | 255,617,766 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 950 | java | package com.bridgelabz.utility;
public class ParkingLotSystemUtilities {
public int parkingLotCapacity = 0;
public static int parkingLotNumber = 0;
public static int numberOfParkingLots = 0;
public ParkingLotSystemUtilities(int parkingLotCapacity, int noOfParkingLots) {
this.numberOfParkingLots = noOfParkingLots;
this.parkingLotCapacity = parkingLotCapacity;
}
public int getNoOfSlotsPerLot() {
return parkingLotCapacity / numberOfParkingLots;
}
public static int assignLot(int slotID) {
switch (slotID % numberOfParkingLots) {
case 0:
parkingLotNumber = 4;
break;
case 1:
parkingLotNumber = 1;
break;
case 2:
parkingLotNumber = 2;
break;
case 3:
parkingLotNumber = 3;
}
return parkingLotNumber;
}
}
| [
"gdev3195@gmail.com"
] | gdev3195@gmail.com |
2626eb527effe953331fd19ac185e6195f33eddb | a1279acead0836912914cb9dc49c1bd78e41fc06 | /java/src/test/java/com/techelevator/dao/JDBCMealIntegrationTest.java | 837f3ffe45bdf69dfbd586326d5c948a334669eb | [] | no_license | levi-satterthwaite/final_capstone | 21366400f375fea78cd09c1b18d3e5d682a449a8 | ccc227a86fec6e586a053f1c0e55e628be818127 | refs/heads/main | 2023-07-21T18:32:15.327798 | 2021-08-12T19:02:27 | 2021-08-12T19:02:27 | 395,494,148 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,761 | java | package com.techelevator.dao;
import com.techelevator.mealPlanner.dao.JdbcMealDAO;
import com.techelevator.mealPlanner.dao.MealDAO;
import com.techelevator.mealPlanner.exceptions.InvalidMealException;
import com.techelevator.mealPlanner.exceptions.MealException;
import com.techelevator.mealPlanner.exceptions.MealNotFoundException;
import com.techelevator.mealPlanner.exceptions.MealPlanException;
import com.techelevator.mealPlanner.model.Meal;
import com.techelevator.mealPlanner.model.MealCategory;
import com.techelevator.mealPlanner.model.MealPlan;
import com.techelevator.recipes.dao.JdbcRecipeDAO;
import com.techelevator.recipes.dao.RecipeDAO;
import com.techelevator.recipes.exceptions.NegativeValueException;
import com.techelevator.recipes.exceptions.RecipeException;
import com.techelevator.recipes.exceptions.RecipeNotFoundException;
import com.techelevator.recipes.model.Recipe;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class JDBCMealIntegrationTest extends DAOIntegrationTest {
private JdbcTemplate jdbcTemplate;
private MealDAO mealDAO;
private RecipeDAO recipeDAO;
@Before
public void setup() {
this.jdbcTemplate = new JdbcTemplate(getDataSource());
this.recipeDAO = new JdbcRecipeDAO(jdbcTemplate);
this.mealDAO = new JdbcMealDAO(jdbcTemplate, recipeDAO);
}
@Test
public void retrieve_all_meals() throws MealException, RecipeNotFoundException {
List<Meal> originalList = mealDAO.getListOfMeal();
Meal testMeal = getById(-1L);
mealDAO.addMeal(testMeal);
List<Meal> mealFromDataBase = mealDAO.getListOfMeal();
Assert.assertEquals(originalList.size() + 1, mealFromDataBase.size());
}
@Test
public void retrieve_meals_by_name() throws MealException, RecipeNotFoundException {
List<Meal> originalList = mealDAO.getListOfMeal();
Meal mealOne = getByName("TestName1");
Meal mealTwo = getByName("TestName2");
mealDAO.addMeal(mealOne);
mealDAO.addMeal(mealTwo);
List<Meal> testMealList = mealDAO.getMealByName("TestName1", mealOne.getUserId());
Assert.assertTrue(testMealList.size() > 0);
}
@Test
public void retrieve_meal_by_id() throws MealException, RecipeNotFoundException {
Meal mealOne = getById(-1L);
mealDAO.addMeal(mealOne);
Meal testMeal = mealDAO.getMealById(mealOne.getMealId(), mealOne.getUserId());
Assert.assertEquals(mealOne, testMeal);
}
@Test
public void add_meal() throws MealException, RecipeNotFoundException {
Meal newMeal = getById(-1L);
mealDAO.addMeal(newMeal);
Assert.assertTrue(newMeal.getMealId() > 0);
Meal expectedMeal = mealDAO.getMealById(newMeal.getMealId(), newMeal.getUserId());
Assert.assertEquals(newMeal, expectedMeal);
}
@Test
public void add_recipes_to_meal() throws NegativeValueException, MealException, RecipeException {
Recipe newRecipe = getRecipe(-1L);
recipeDAO.addRecipe(newRecipe);
Meal newMeal = getById(-1L);
mealDAO.addMeal(newMeal);
List<Recipe> recipes = new ArrayList<>();
recipes.add(newRecipe);
Meal testMeal = mealDAO.addRecipesToMeal(newMeal, recipes);
Assert.assertTrue(testMeal.getRecipeList().size() > 0);
Assert.assertEquals(testMeal.getRecipeList().get(0), newRecipe);
}
@Test
public void update_meal() throws RecipeException, NegativeValueException, MealException {
Recipe newRecipe = getRecipe(-1L);
recipeDAO.addRecipe(newRecipe);
Meal newMeal = getById(-1L);
mealDAO.addMeal(newMeal);
newMeal.setName("updatedName");
newMeal.getRecipeList().add(newRecipe);
Meal expectedMeal = mealDAO.updateMeal(newMeal, newMeal.getUserId());
Assert.assertEquals(expectedMeal.getName(), "updatedName");
Assert.assertEquals(expectedMeal.getRecipeList().size(), 1);
}
@Test
public void delete_meal() throws MealException, RecipeException {
Meal newMeal = getById(-1L);
mealDAO.addMeal(newMeal);
mealDAO.deleteMeal(newMeal);
Assert.assertEquals(mealDAO.getMealByName(newMeal.getName(), newMeal.getUserId()).size(), 0);
}
private Meal getById(Long mealId) {
Meal meal = new Meal();
meal.setMealId(mealId);
meal.setUserId(1L);
meal.setName("testName");
meal.setCategory(MealCategory.LUNCH.toString());
meal.setImageFileName("testImage.jpg");
meal.setRecipeList(new ArrayList<>());
return meal;
}
private Meal getByName(String name) {
Meal meal = new Meal();
meal.setMealId(-1L);
meal.setUserId(1L);
meal.setName(name);
meal.setCategory(MealCategory.LUNCH.toString());
meal.setImageFileName("testImage.jpg");
meal.setRecipeList(new ArrayList<>());
return meal;
}
private Recipe getRecipe(Long recipeId) {
Recipe recipe = new Recipe();
recipe.setRecipeId(recipeId);
recipe.setUserId(1L);
recipe.setName("testName");
recipe.setCategory("Appetizer");
recipe.setDifficultyLevel("Easy");
recipe.setPrepTimeMin(5);
recipe.setCookTimeMin(20);
recipe.setServingSize(4);
recipe.setInstructions("testInstructions");
recipe.setDateCreated(LocalDate.of(2021, 8, 4));
recipe.setImageFileName("testImage.jpg");
recipe.setIngredientList(new ArrayList<>());
return recipe;
}
}
| [
"bhh920@gmail.com"
] | bhh920@gmail.com |
79fc7eaec4290911b5a00f9bbed51637fc014b3b | f4af559ed7c35b3b0a0b43eee8bebac9c5ef39a7 | /JavaWeb20180414/src/cn/edu/lingnan/servlet/FindAllCostomer.java | f743ea2449fe4d312b797f0f6d24d7b09be8e520 | [] | no_license | MrYTF/JavaWeb20180630 | cac91c29a5bfe001337d52afad7c3feff0ffca3e | 9ba411e7c3d53dfb191dd0376ef4012e39188d6b | refs/heads/master | 2020-03-25T02:05:55.988993 | 2018-08-02T09:52:14 | 2018-08-02T09:52:14 | 143,273,771 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,185 | java | package cn.edu.lingnan.servlet;
import java.io.IOException;
import java.util.Vector;
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 cn.edu.lingnan.dao.CostomerDao;
import cn.edu.lingnan.dto.CostomerDto;
public class FindAllCostomer extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String cid = req.getParameter("cid");
CostomerDao cd = new CostomerDao();
//System.out.println(cid);
Vector<CostomerDto> v= null;
if(cid == "") {
v = cd.findCostomer();
}else {
CostomerDto c = cd.findById(cid);
if(c!=null) {
v = new Vector<CostomerDto>();
v.add(c);
}
}
HttpSession s = req.getSession();
s.setAttribute("allcostomer", v);
resp.sendRedirect("costomer.jsp");
}
}
| [
"'1534171551@qq.com'"
] | '1534171551@qq.com' |
e97db2843183d7fea488b7ae4643ab05c587929a | 36bdf5adca926eb200373e7aaafbb36631a74eb8 | /src/test/java/poc/camel/eip/test/package-info.java | c39c135f2f3aa92054d123f0c9b1c8b5f2413874 | [] | no_license | spanderman/poc-camel-eip | 9eb32cc329d1d4864b68d2393986298f3a692621 | 97065395d30ba004ae0839b21ed5f7b0f406b85a | refs/heads/master | 2021-07-16T15:07:30.255308 | 2020-06-27T15:42:26 | 2020-06-27T15:42:26 | 168,891,595 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 77 | java | /**
* The main application test package.
*
*/
package poc.camel.eip.test;
| [
"spanderman@localhost"
] | spanderman@localhost |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.