blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
45cb1813ca408cda083ade396c8d1c641c2e793b
Java
firstABC/medical_sys
/src/main/java/com/controller/MedicalRecordController.java
UTF-8
5,493
2.140625
2
[]
no_license
package com.controller; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.dto.MsgDTO; import com.entity.MedicalRecord; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.service.MedicalRecordService; import com.util.Utils; @Controller @RequestMapping("/mere") public class MedicalRecordController { private static Logger logger = LoggerFactory .getLogger(MedicalRecordController.class); @Autowired private MedicalRecordService medicalRecordService; /** * 获取列表跳转 */ @RequestMapping(value="/list",method=RequestMethod.GET) public ModelAndView meReList(@RequestParam(value="icCardNum",defaultValue="")String icCardNum, @RequestParam(value="pageno",defaultValue="1")Integer pageno, @RequestParam(value="pagesize",defaultValue="9")Integer pagesize, ModelMap map ){ logger.info("Get MedicalRecord List Start: icCardNum="+icCardNum); MsgDTO msgDTO = new MsgDTO(); //指定查询的页码和每页的条数 PageHelper.startPage(pageno, pagesize); List<MedicalRecord> meList = new ArrayList<MedicalRecord>(); try{ if(Utils.stringNotEmpty(icCardNum)){ map.put("icCardNum", icCardNum); meList = medicalRecordService.getMeReListByCons(icCardNum); }else{ //参数为空,查询全部 meList = medicalRecordService.getMeReList(); } if(Utils.listNotNull(meList)){ msgDTO = MsgDTO.success(); msgDTO.setTotal(meList.size()); PageInfo<MedicalRecord> pageInfo = new PageInfo<MedicalRecord>(meList); Map<String,Object> mapP = new HashMap<String,Object>(); mapP.put("pageInfo", pageInfo); msgDTO.setData(mapP); //msgDTO.setData(meList); }else{ msgDTO = MsgDTO.zero(); } logger.info("Get MedicalRecord List End: Status:"+msgDTO.getStatus()+" Message:"+msgDTO.getMessage()+" Total:"+msgDTO.getTotal()); }catch(Exception e){ msgDTO.setStatus(MsgDTO.STATUS_ERR); msgDTO.setMessage(e.getMessage()); logger.error("Get MedicalRecord List Exception: Status:"+msgDTO.getStatus()+" Message:"+msgDTO.getMessage()); } map.put("msgDTO", msgDTO); return new ModelAndView("patientHis"); } /** * 获取病历详细信息 * @param id * @param map * @return */ @RequestMapping(value = "/getMeRe", method = RequestMethod.GET) public ModelAndView getMeRe(@RequestParam("id")String id,ModelMap map){ logger.info("Get MedicalRecord Start: id="+id); MsgDTO msgDTO = new MsgDTO(); try { if(Utils.stringNotEmpty(id)){ MedicalRecord meRe = medicalRecordService.getMeRe(id); if(meRe != null){ msgDTO = MsgDTO.success(); msgDTO.setTotal(1); msgDTO.setData(meRe); }else{ msgDTO = MsgDTO.zero(); } }else{ msgDTO = MsgDTO.fail(); } logger.info("Get MedicalRecord End: Status:"+msgDTO.getStatus()+" Message:"+msgDTO.getMessage()+" Total:"+msgDTO.getTotal()); } catch (Exception e) { msgDTO.setStatus(MsgDTO.STATUS_ERR); msgDTO.setMessage(e.getMessage()); logger.error("G MedicalRecord Exception: Status:"+msgDTO.getStatus()+" Message:"+msgDTO.getMessage()); } map.put("msgDTO", msgDTO); return new ModelAndView("patientHisLi"); } /** * 新增病历 * @param meRe * @return */ @RequestMapping(value = "/edit", method = { RequestMethod.POST }) public @ResponseBody MsgDTO addMedicalRecord(MedicalRecord meRe){ logger.info("Edit MedicalRecord Start: "+meRe.toString()); MsgDTO msgDTO = new MsgDTO(); MedicalRecord res = null; try { if(Utils.stringNotEmpty(meRe.getId())){ res = medicalRecordService.updateMeRe(meRe); if(res != null){ msgDTO.setStatus(MsgDTO.STATUS_OK); msgDTO.setMessage("修改成功!"); msgDTO.setTotal(1); msgDTO.setData(res); }else{ msgDTO = MsgDTO.zero(); } }else{ res = medicalRecordService.addMeRe(meRe); if(res != null){ msgDTO.setStatus(MsgDTO.STATUS_OK); msgDTO.setMessage("添加成功!"); msgDTO.setTotal(1); msgDTO.setData(res); }else{ msgDTO = MsgDTO.zero(); } } logger.info("Edit MedicalRecord End: Status:"+msgDTO.getStatus()+" Message:"+msgDTO.getMessage()+" Total:"+msgDTO.getTotal()); } catch (ParseException pe) { msgDTO.setStatus(MsgDTO.STATUS_ERR); msgDTO.setMessage(pe.getMessage()); logger.error("Edit MedicalRecord ParseException: Status:"+msgDTO.getStatus()+" Message:"+msgDTO.getMessage()); }catch (Exception e) { msgDTO.setStatus(MsgDTO.STATUS_ERR); msgDTO.setMessage(e.getMessage()); logger.error("Edit MedicalRecord Exception: Status:"+msgDTO.getStatus()+" Message:"+msgDTO.getMessage()); } return msgDTO; } }
true
4192d84cf3b905f77b390dc048b3d3a6f02199fd
Java
Caaarlowsz/NewPvP
/src/me/viitor/auth/Auth.java
UTF-8
1,851
2.484375
2
[]
no_license
package me.viitor.auth; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import me.viitor.API.HorarioAPI; import me.viitor.main.Main; public class Auth { public static ArrayList<Player> login = new ArrayList<>(); public static FileConfiguration kAuth; public static File Auth; public Auth() { Plugin plugin = Main.getPlugin(); if(!plugin.getDataFolder().exists()) { plugin.getDataFolder().mkdir(); } Auth = new File(plugin.getDataFolder(), "Auth.yml"); if(Auth.exists()) { try { Auth.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } kAuth = YamlConfiguration.loadConfiguration(Auth); } public static boolean checarRegistro(Player p) { return kAuth.get("Jogadores." + p.getName()) != null; } public static String pegarSenha(Player p) { return kAuth.getString("Jogadores." + p.getName() + ".Senha"); } public static void registrar(Player p, String senha) { double l = kAuth.getDouble("Jogadores registrados"); kAuth.set("Jogadores registrados", l + Double.valueOf(1.0D)); kAuth.set("Jogadores." + p.getName() + ".UUID", p.getUniqueId().toString()); kAuth.set("Jogadores." + p.getName() + ".Senha", senha); kAuth.set("Jogadores." + p.getName() + ".Data de registro", HorarioAPI.getHorario()); save(); } public static void unregistrar(Player p) { double l = kAuth.getDouble("Jogadores registrados"); kAuth.set("Jogadores registrados", l - Double.valueOf(1.0D)); kAuth.set("Jogadores." + p.getName(), null); save(); } public static void save() { try { kAuth.save(Auth); } catch(IOException e) { e.printStackTrace(); } } }
true
861d04a2b11fec3d2a6590d27d27177b48ca53f2
Java
Sabyh11/Java-SE8-OCP-Exam-1Z0-809
/ch04/44-Grouping-Partitioning-Mapping/TestClass.java
UTF-8
4,273
3.40625
3
[]
no_license
import java.util.stream.Stream; import java.util.stream.Collectors; import java.util.*; public class TestClass { public static void main(String[] args) { // Grouping -------------------------------------------------------------------------- // get groups of names by their length (grouped in a List by default) { Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); Map<Integer, List<String>> map = ohMy.collect(Collectors.groupingBy(String::length)); System.out.println(map); // {5=[lions, bears], 6=[tigers]} } // get groups of names by their length (grouped in a Set instead of List) { Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); Map<Integer, Set<String>> map = ohMy.collect(Collectors.groupingBy(String::length, Collectors.toSet())); System.out.println(map); // {5=[lions, bears], 6=[tigers]} } // get groups of names by their length (grouped in a Set, and specify the Map type) { Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); TreeMap<Integer, Set<String>> map = ohMy.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toSet())); System.out.println(map); // {5=[lions, bears], 6=[togers]} } // What if we want to change the type of Map returned but leave the type of values alone as a List? { Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); TreeMap<Integer, List<String>> map = ohMy.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList())); System.out.println(map); // {5=[lions, bears], 6=[tigers]} } // Partitioning (only two groups: true | false) ------------------------------------------------ // Split a list of animals names, one with names <= 5, an the other for the rest { Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); Map<Boolean, List<String>> map = ohMy.collect(Collectors.partitioningBy(s -> s.length() <=5)); System.out.println(map); // {false=[tigers], true=[lions, bears]} } // Split a list of animals names, now with names <= 7, an the other for the rest { Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); Map<Boolean, List<String>> map = ohMy.collect(Collectors.partitioningBy(s -> s.length()<=7)); System.out.println(map); // {false=[], true=[lions, tigers, bears]} } // Split a list of animals names (true|false), but change the type of List to something else { Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); Map<Boolean, Set<String>> map = ohMy.collect(Collectors.partitioningBy(s -> s.length() <= 7, Collectors.toSet())); System.out.println(map); // {false=[tigers], true=[lions, bears]} } // Grouping, Grouping ---------------------------------------------------------- // Group by the lengh of the animal name to see how many of each length we have { Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); Map<Integer, Long> map = ohMy.collect(Collectors.groupingBy(String::length, Collectors.counting())); System.out.println(map); // {5=2, 6=1} } // Collector(xxx,Collector) ---------------------------------------------------------- // Get the first letter of the first animal alphabetically of each length /*Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); Map<Integer, Optional<Character>> map = ohMy.collect(Collectors.groupingBy( String::length, Collectors.mapping(s -> s.charAt(0),Collectors.minBy(Comparator.naturalOrder())))); // The minBy example used to compile with earlier versions of Java 8, but no longer does. */ // collectors used with a static import to make the code shorter /* Stream<String> ohMy = Stream.of("lions", "tigers", "bears"); Map<Integer, Optional<Character>> map = ohMy.collect(groupingBy( String::length, mapping(s -> s.charAt(0), minBy(Comparator.naturalOrder())))); System.out.println(map); // {5=Optional[b], 6=Optional[t]} // The minBy example used to compile with earlier versions of Java 8, but no longer does. */ } }
true
9a1f14dd40e8dd4e6820df69047bfd4c080650f1
Java
Zamundaaa/Engine
/vr/VRTools.java
UTF-8
279
1.984375
2
[]
no_license
package vr; import org.joml.Matrix4f; import org.lwjgl.openvr.HmdMatrix34; public class VRTools { /** * will be implemented. Until then, RETURNS NULL!!! */ public static Matrix4f convert(HmdMatrix34 m, Matrix4f dest){ // return dest.m00(m.m(0)); return null; } }
true
65d4e2b670059dce3a0d1f5c1fe22b1e25ebd111
Java
tied/jira-plugins-mrimsender
/src/main/java/ru/mail/jira/plugins/mrimsender/protocol/events/ShowMenuEvent.java
UTF-8
451
1.914063
2
[]
no_license
package ru.mail.jira.plugins.mrimsender.protocol.events; import lombok.Getter; import lombok.Setter; import ru.mail.jira.plugins.mrimsender.icq.dto.events.NewMessageEvent; @Getter public class ShowMenuEvent { private final String userId; private final String chatId; public ShowMenuEvent(ChatMessageEvent chatMessageEvent) { this.userId = chatMessageEvent.getUerId(); this.chatId = chatMessageEvent.getChatId(); } }
true
5cb6a2285a9f5c5482c420ada2a94f39f009be23
Java
yuyee/nettyserver
/common/src/com/git/original/common/utils/DateUtils.java
UTF-8
1,427
2.90625
3
[]
no_license
/** * Copyright (c) www.netease.com 2010.<br> * Created on 2010-11-25 * * @author <a href="nisonghai@corp.netease.com">Ni Songhai</a> * @version $Revision: 1.0$ */ package com.git.original.common.utils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Date处理 * * @author linaoxiang */ public final class DateUtils { /** * 线程本地变量 */ private static ThreadLocal<DateFormat> dfLocal = new ThreadLocal<DateFormat>(); /** 构造函数 */ private DateUtils() { }; /** * Long类型转Date处理 * * @param timeMillis * @return */ public static Date getDate(Long timeMillis) { if (timeMillis == null || timeMillis == 0) { return null; } else { return new Date(timeMillis); } } /** * Date转Long类型处理 * * @param date * @return */ public static Long getTimeMillis(Date date) { if (date == null) { return null; } else { return date.getTime(); } } /** * 解析"yyyy-MM-dd"格式的字符串到日期对象 * <p> * 线程安全 * * @throws ParseException */ public static Date parseSimpleDateString(String source) throws ParseException { DateFormat df = dfLocal.get(); if (df == null) { df = new SimpleDateFormat("yyyy-MM-dd"); dfLocal.set(df); } return df.parse(source); } }
true
b416c8b865d771db1d5eb0c3ae97a029709418b4
Java
OUSSAMA-web/Pointeuse
/pointeuse/app/src/main/java/Activity/Pointeuse/HomePointeuse.java
UTF-8
3,788
2.15625
2
[]
no_license
package Activity.Pointeuse; import android.app.ProgressDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import com.j256.ormlite.android.apptools.OpenHelperManager; import com.j256.ormlite.dao.Dao; import Model.Absence; import Model.Absence_details; import Model.Classe; import Model.Etudiant; import Model.Prof; import database.ConnectDB; import database.DBManager; import database.DatabaseHelper; import wolfsoft1.pay2wallet.R; public class HomePointeuse extends AppCompatActivity { LinearLayout Pointer; LinearLayout SynchroniserDonnees; LinearLayout logout; private DatabaseHelper databaseHelper = null; final Etudiant etudiant = new Etudiant(); DBManager manager; ConnectDB connectDb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_pointeuse); manager = new DBManager(this); initView(); // synchroniser les donnée // si ls donnés sont déja synchornisé // if(manager.getAllClasses().size()==0){ manager.ClearData(); Synchroniser(); // } try { Dao<Etudiant, Integer> etudiantsDao = getHelper().getEtudiants(); Dao<Prof, Integer> profsDao = getHelper().getProfs(); Dao<Classe, Integer> classesDao = getHelper().getClasses(); Dao<Absence, Integer> AbsenceDao = getHelper().getAbsences(); Dao<Absence_details, Integer> absence_detailsDao = getHelper().getAbsencesDetails(); } catch (Exception e){} Pointer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(HomePointeuse.this,PointerDetails.class)); } }); SynchroniserDonnees.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Synchroniser(); // wrap thread around original code for progress button final ProgressDialog ringProgressDialog = ProgressDialog.show(HomePointeuse.this, "Sunchronisation !", "Attender un moment", true, false); ringProgressDialog.setIndeterminate(true); new Thread(new Runnable() { public void run() { try { Thread.sleep(4000); if (ringProgressDialog != null && ringProgressDialog.isShowing()) { ringProgressDialog.dismiss(); } } catch (Exception e) { } } }).start(); } }); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HomePointeuse.this.finish(); } }); } private DatabaseHelper getHelper() { if (databaseHelper == null) { databaseHelper = OpenHelperManager.getHelper(this,DatabaseHelper.class); } return databaseHelper; } void initView(){ SynchroniserDonnees = (LinearLayout) findViewById(R.id.synchoniser); Pointer = (LinearLayout) findViewById(R.id.Appele); logout = (LinearLayout) findViewById(R.id.logout); } void Synchroniser(){ manager.ClearData(); connectDb = new ConnectDB(HomePointeuse.this); connectDb.execute(); } }
true
33df04143cd5b4cac4ccc2e08c90b6cc35740d0c
Java
linhtop97/SoundCloundMusic_MVP
/app/src/main/java/linhnb/com/soundcloundmusic_mvp/ui/playmusic/PlayMusicFragment.java
UTF-8
19,338
1.796875
2
[]
no_license
package linhnb.com.soundcloundmusic_mvp.ui.playmusic; import android.content.ComponentName; import android.content.Context; import android.content.ServiceConnection; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.support.v7.widget.LinearLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.List; import linhnb.com.soundcloundmusic_mvp.Injection; import linhnb.com.soundcloundmusic_mvp.R; import linhnb.com.soundcloundmusic_mvp.data.model.Track; import linhnb.com.soundcloundmusic_mvp.data.source.PlayListsRepository; import linhnb.com.soundcloundmusic_mvp.data.source.local.PlayListLocalDataSource; import linhnb.com.soundcloundmusic_mvp.data.source.local.PreferenceManager; import linhnb.com.soundcloundmusic_mvp.data.source.remote.TrackDownloadManager; import linhnb.com.soundcloundmusic_mvp.ui.main.MainActivity; import linhnb.com.soundcloundmusic_mvp.ui.playmusic.listtrack.ListTrackFragment; import linhnb.com.soundcloundmusic_mvp.ui.playmusic.playanim.PlayAnimationFragment; import linhnb.com.soundcloundmusic_mvp.ui.playmusic.service.IPlay; import linhnb.com.soundcloundmusic_mvp.ui.playmusic.service.MusicService; import linhnb.com.soundcloundmusic_mvp.ui.playmusic.service.PlayMode; import linhnb.com.soundcloundmusic_mvp.utils.StringUtil; public class PlayMusicFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener, IPlay.Callback, PlayMusicContract.View, TrackDownloadManager.DownloadListener { private static final String TAG = "PlayMusicFragment"; private static final long UPDATE_PROGRESS_INTERVAL = 1000; private List<Track> mTracks; private int mCurrentPosition; private MainActivity mMainActivity; private ViewPager mViewPager; private PlayMusicPagerAdapter mPlayMusicPagerAdapter; private LinearLayout mSliderDots; private int mDotsCount; private ImageView[] mDotsView; private View mViewRoot; private TextView mTextTrackTitle; private TextView mTextArtist; private TextView mTextTotalTime; private TextView mTextCurrentTime; private ImageButton mImageButtonBack; private ImageButton mImageButtonPrevious; private ImageButton mImageButtonPlayToggle; private ImageButton mImageButtonNext; private ImageButton mImageButtonDownload; private ImageButton mImageButtonFavorite; private ImageButton mImageButtonPlayModeToggle; private ImageButton mImageButtonAlarm; private SeekBar mSeekBarProgress; private PlayMusicContract.Presenter mPresenter; private MusicService mPlayer; private Handler mHandler = new Handler(); private Runnable mProgressCallback = new Runnable() { @Override public void run() { if (isDetached()) return; if (mPlayer.isPlaying()) { int progress = (int) (mSeekBarProgress.getMax() * ((float) mPlayer.getProgress() / (float) getCurrentSongDuration())); updateProgressTextWithDuration(mPlayer.getProgress()); if (progress >= 0 && progress <= mSeekBarProgress.getMax()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mSeekBarProgress.setProgress(progress, true); } else { mSeekBarProgress.setProgress(progress); } mHandler.postDelayed(this, UPDATE_PROGRESS_INTERVAL); } } } }; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { MusicService.MusicBinder musicBinder = (MusicService.MusicBinder) iBinder; mPlayer = musicBinder.getService(); mPlayer.registerCallback(PlayMusicFragment.this); } @Override public void onServiceDisconnected(ComponentName componentName) { mPlayer = null; mPlayer.unregisterCallback(PlayMusicFragment.this); } }; public static PlayMusicFragment newInstance() { return new PlayMusicFragment(); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mViewRoot = inflater.inflate(R.layout.fragment_play_music, container, false); initView(); return mViewRoot; } private void initView() { mTracks = PreferenceManager.getListTrack(mMainActivity); mCurrentPosition = PreferenceManager.getLastPosition(getActivity()); mTextTrackTitle = mViewRoot.findViewById(R.id.text_track_title); mTextArtist = mViewRoot.findViewById(R.id.text_artist); mTextTotalTime = mViewRoot.findViewById(R.id.textview_total_time); mTextCurrentTime = mViewRoot.findViewById(R.id.textview_current_time); mSeekBarProgress = mViewRoot.findViewById(R.id.seekbar_song); mImageButtonBack = mViewRoot.findViewById(R.id.button_back); mImageButtonBack.setOnClickListener(this); mImageButtonPrevious = mViewRoot.findViewById(R.id.button_previous); mImageButtonPrevious.setOnClickListener(this); mImageButtonPlayToggle = mViewRoot.findViewById(R.id.button_play_toggle); mImageButtonPlayToggle.setOnClickListener(this); mImageButtonNext = mViewRoot.findViewById(R.id.button_next); mImageButtonNext.setOnClickListener(this); mImageButtonDownload = mViewRoot.findViewById(R.id.button_download); mImageButtonDownload.setOnClickListener(this); mImageButtonPlayModeToggle = mViewRoot.findViewById(R.id.button_play_mode_toggle); mImageButtonPlayModeToggle.setOnClickListener(this); mImageButtonAlarm = mViewRoot.findViewById(R.id.button_alarm); mImageButtonAlarm.setOnClickListener(this); mImageButtonFavorite = mViewRoot.findViewById(R.id.button_favorite); mImageButtonFavorite.setOnClickListener(this); mViewPager = mViewRoot.findViewById(R.id.vp_music); mPlayMusicPagerAdapter = new PlayMusicPagerAdapter(getChildFragmentManager()); mViewPager.setAdapter(mPlayMusicPagerAdapter); mViewPager.setCurrentItem(PageType.PLAY); setUpSliderDot(); mViewPager.addOnPageChangeListener(this); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mSeekBarProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { updateProgressTextWithProgress(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mProgressCallback); } @Override public void onStopTrackingTouch(SeekBar seekBar) { seekTo(getDuration(seekBar.getProgress())); if (mPlayer.isPlaying()) { mHandler.removeCallbacks(mProgressCallback); mHandler.post(mProgressCallback); } } }); new PlayMusicPresenter(getActivity(), mTracks, this).subscribe(); } @Override public void onAttach(Context context) { super.onAttach(context); mMainActivity = (MainActivity) context; } private void setUpSliderDot() { mSliderDots = mViewRoot.findViewById(R.id.slider_dots); mDotsCount = mPlayMusicPagerAdapter.getCount(); mDotsView = new ImageView[mDotsCount]; for (int i = 0; i < mDotsCount; i++) { mDotsView[i] = new ImageView(mMainActivity); mDotsView[i].setImageDrawable(ContextCompat.getDrawable(Injection.provideContext(), R.drawable.inactive_dot)); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(8, 0, 8, 0); mSliderDots.addView(mDotsView[i], params); } mDotsView[PageType.PLAY].setImageDrawable(ContextCompat.getDrawable(Injection.provideContext(), R.drawable.active_dot)); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (position != PageType.LIST) { Fragment fragment = getChildFragmentManager().findFragmentByTag("android:switcher:" + R.id.vp_music + ":" + mViewPager.getCurrentItem()); if (fragment != null && PageType.LIST == mViewPager.getCurrentItem()) { PreferenceManager.setImageUrl(getActivity(), PreferenceManager.getImageUrl(mMainActivity)); ListTrackFragment listTrackFragment = (ListTrackFragment) fragment; LinearLayoutManager linearLayoutManager = listTrackFragment.getLayoutManager(); linearLayoutManager.scrollToPosition(PreferenceManager.getLastPosition(mMainActivity)); } } if (position != PageType.PLAY) { mImageButtonDownload.setVisibility(View.GONE); mImageButtonAlarm.setVisibility(View.GONE); } else { Fragment fragment = getChildFragmentManager().findFragmentByTag("android:switcher:" + R.id.vp_music + ":" + mViewPager.getCurrentItem()); if (fragment != null && PageType.PLAY == mViewPager.getCurrentItem()) { PreferenceManager.setImageUrl(getActivity(), PreferenceManager.getImageUrl(mMainActivity)); PlayAnimationFragment playAnimationFragment = (PlayAnimationFragment) fragment; playAnimationFragment.setImage(); if (!mPlayer.isPlaying()) { playAnimationFragment.cancelAnimation(); } else { playAnimationFragment.startAnimation(); } } mImageButtonDownload.setVisibility(View.VISIBLE); mImageButtonAlarm.setVisibility(View.VISIBLE); } for (int i = 0; i < mDotsCount; i++) { mDotsView[i].setImageDrawable(ContextCompat.getDrawable(Injection.provideContext(), R.drawable.inactive_dot)); } mDotsView[position].setImageDrawable(ContextCompat.getDrawable(Injection.provideContext(), R.drawable.active_dot)); } @Override public void onPageScrollStateChanged(int state) { } @Override public void onClick(View view) { switch (view.getId()) { case R.id.button_back: getActivity().getSupportFragmentManager().popBackStackImmediate(); break; case R.id.button_play_toggle: if (mPlayer.isPlaying()) { mPlayer.pause(); mImageButtonPlayToggle.setImageResource(R.drawable.ic_play_toogle); } else { mPlayer.play(); mImageButtonPlayToggle.setImageResource(R.drawable.ic_pause); } break; case R.id.button_play_mode_toggle: if (mPlayer == null) return; PlayMode current = PreferenceManager.lastPlayMode(getActivity()); PlayMode newMode = PlayMode.switchNextMode(current); PreferenceManager.setPlayMode(getActivity(), newMode); mPlayer.setPlayMode(newMode); updatePlayMode(newMode); break; case R.id.button_next: if (mPlayer == null) return; mPlayer.playNext(); break; case R.id.button_previous: if (mPlayer == null) return; mPlayer.playPrevious(); break; case R.id.button_download: new TrackDownloadManager(getActivity(), PlayMusicFragment.this) .download(PreferenceManager.getListTrack(getActivity()).get(PreferenceManager.getLastPosition(getActivity()))); break; case R.id.button_favorite: // PlayListsRepository.getInstance(PlayListLocalDataSource.getInstance(mMainActivity)) // .addTrack("Favorite", mPlayer.getCurrentTrack()); break; default: break; } } private int getCurrentSongDuration() { Track currentTrack = mPlayer.getPlayingTrack(); int duration = 0; if (currentTrack != null) { duration = currentTrack.getDuration(); } return duration; } private void updateProgressTextWithProgress(int progress) { int targetDuration = getDuration(progress); mTextCurrentTime.setText(StringUtil.formatDuration(targetDuration)); } private void updateProgressTextWithDuration(int duration) { mTextCurrentTime.setText(StringUtil.formatDuration(duration)); } private int getDuration(int progress) { return (int) (getCurrentSongDuration() * ((float) progress / mSeekBarProgress.getMax())); } @Override public void onStart() { super.onStart(); if (mPlayer != null && mPlayer.isPlaying()) { mHandler.removeCallbacks(mProgressCallback); mHandler.post(mProgressCallback); } } @Override public void onResume() { super.onResume(); if (mPlayer != null) { onTrackUpdated(mPlayer.getPlayingTrack()); } } @Override public void onStop() { super.onStop(); mHandler.removeCallbacks(mProgressCallback); } @Override public void onDestroyView() { mPresenter.unsubscribe(); super.onDestroyView(); } @Override public void updatePlayMode(PlayMode playMode) { if (playMode == null) { playMode = PlayMode.getDefault(); } switch (playMode) { case LIST: mImageButtonPlayModeToggle.setImageResource(R.drawable.ic_play_mode_list); break; case LOOP: mImageButtonPlayModeToggle.setImageResource(R.drawable.ic_play_mode_loop); break; case SHUFFLE: mImageButtonPlayModeToggle.setImageResource(R.drawable.ic_play_mode_shuffle); break; case SINGLE: mImageButtonPlayModeToggle.setImageResource(R.drawable.ic_play_mode_single); break; } } public void updatePlayToggle(boolean play) { mImageButtonPlayToggle.setImageResource(play ? R.drawable.ic_pause : R.drawable.ic_play_toogle); } @Override public void onSwitchPrevious(@Nullable Track previous) { onTrackUpdated(previous); } @Override public void onSwitchNext(@Nullable Track next) { onTrackUpdated(next); } @Override public void onComplete(@Nullable Track next) { onTrackUpdated(next); } @Override public void onPlayStatusChanged(boolean isPlaying) { onTrackUpdated(mPlayer.getPlayingTrack()); updatePlayToggle(isPlaying); if (isPlaying) { mHandler.removeCallbacks(mProgressCallback); mHandler.post(mProgressCallback); } else { mHandler.removeCallbacks(mProgressCallback); } } private void seekTo(int duration) { mPlayer.seekTo(duration); } @Override public void onServiceBound(MusicService service) { mPlayer = service; mPlayer.registerCallback(this); } @Override public void onServiceUnbound() { mPlayer.unregisterCallback(this); mPlayer = null; } @Override public void onTrackUpdated(Track track) { if (track == null) { seekTo(0); mImageButtonPlayToggle.setImageResource(R.drawable.ic_play_toogle); mSeekBarProgress.setProgress(0); updateProgressTextWithProgress(0); mHandler.removeCallbacks(mProgressCallback); return; } mTextTrackTitle.setText(track.getTitle()); mTextArtist.setText(track.getUserName()); if (track.isDownloadable()) { mImageButtonDownload.setImageResource(R.drawable.ic_download); mImageButtonDownload.setClickable(true); } else { mImageButtonDownload.setImageResource(R.drawable.ic_download_grey); mImageButtonDownload.setClickable(false); } // Step 3: Duration mTextTotalTime.setText(StringUtil.formatDuration(track.getDuration())); mTextCurrentTime.setText(StringUtil.formatDuration(mPlayer.getProgress())); // set ảnh cho cái đĩa, chạy animation Fragment fragment = null; if (this.isAdded()) { fragment = getChildFragmentManager().findFragmentByTag("android:switcher:" + R.id.vp_music + ":" + mViewPager.getCurrentItem()); if (fragment != null && PageType.PLAY == mViewPager.getCurrentItem()) { PreferenceManager.setImageUrl(getActivity(), track.getArtworkUrl()); PlayAnimationFragment playAnimationFragment = (PlayAnimationFragment) fragment; playAnimationFragment.setImage(); playAnimationFragment.cancelAnimation(); } } mImageButtonPlayToggle.setImageResource(R.drawable.ic_play_toogle); mHandler.removeCallbacks(mProgressCallback); if (mPlayer.isPlaying()) { if (fragment != null && PageType.PLAY == mViewPager.getCurrentItem()) { PlayAnimationFragment playAnimationFragment = (PlayAnimationFragment) fragment; playAnimationFragment.setImage(); playAnimationFragment.startAnimation(); } mHandler.post(mProgressCallback); mImageButtonPlayToggle.setImageResource(R.drawable.ic_pause); } } @Override public void setPresenter(PlayMusicContract.Presenter presenter) { mPresenter = presenter; } @Override public void onDownloadError(String msg) { Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show(); } @Override public void onDownloading() { Toast.makeText(getActivity(), getActivity().getString(R.string.msg_downloading), Toast.LENGTH_SHORT).show(); } }
true
6208f1cc3199bbc5f838848ad4975bb49aea53d8
Java
UltraSoundX/Fucking-AJN-APP
/java/cn/sharesdk/tencent/qq/QQ.java
UTF-8
14,030
1.65625
2
[]
no_license
package cn.sharesdk.tencent.qq; import android.os.Bundle; import android.text.TextUtils; import cn.sharesdk.framework.Platform; import cn.sharesdk.framework.Platform.ShareParams; import cn.sharesdk.framework.PlatformActionListener; import cn.sharesdk.framework.authorize.AuthorizeListener; import cn.sharesdk.framework.b.b.f.a; import cn.sharesdk.framework.utils.SSDKLog; import com.mob.MobSDK; import com.mob.tools.utils.DeviceHelper; import com.mob.tools.utils.Hashon; import com.mob.tools.utils.ResHelper; import com.tencent.android.tpush.common.MessageKey; import java.util.HashMap; public class QQ extends Platform { public static final String NAME = QQ.class.getSimpleName(); private String a; private boolean b = true; private boolean c; /* access modifiers changed from: protected */ public void initDevInfo(String str) { this.a = getDevinfo("AppId"); this.c = "true".equals(getDevinfo("BypassApproval")); if (this.a == null || this.a.length() <= 0) { this.a = getDevinfo("QZone", "AppId"); if (this.a != null && this.a.length() > 0) { copyDevinfo("QZone", NAME); this.a = getDevinfo("AppId"); SSDKLog.b().d("Try to use the dev info of QZone, this will cause Id and SortId field are always 0.", new Object[0]); } } } public int getPlatformId() { return 24; } public String getName() { return NAME; } public int getVersion() { return 2; } /* access modifiers changed from: protected */ public void setNetworkDevinfo() { this.a = getNetworkDevinfo("app_id", "AppId"); if (this.a == null || this.a.length() <= 0) { this.a = getNetworkDevinfo(6, "app_id", "AppId"); if (this.a != null && this.a.length() > 0) { copyNetworkDevinfo(6, 24); this.a = getNetworkDevinfo("app_id", "AppId"); SSDKLog.b().d("Try to use the dev info of QZone, this will cause Id and SortId field are always 0.", new Object[0]); } } } public boolean isClientValid() { c a2 = c.a((Platform) this); a2.a(this.a); return a2.b(); } /* access modifiers changed from: protected */ public void doAuthorize(String[] strArr) { final c a2 = c.a((Platform) this); a2.a(this.a); a2.a(strArr); a2.a((AuthorizeListener) new AuthorizeListener() { public void onError(Throwable th) { if (QQ.this.listener != null) { QQ.this.listener.onError(QQ.this, 1, th); } } public void onComplete(Bundle bundle) { String string = bundle.getString("open_id"); String string2 = bundle.getString("access_token"); String string3 = bundle.getString("expires_in"); QQ.this.db.putToken(string2); QQ.this.db.putTokenSecret(""); try { QQ.this.db.putExpiresIn(ResHelper.parseLong(string3)); } catch (Throwable th) { SSDKLog.b().w(th); } QQ.this.db.putUserId(string); String string4 = bundle.getString("pf"); String string5 = bundle.getString("pfkey"); String string6 = bundle.getString("pay_token"); QQ.this.db.put("pf", string4); QQ.this.db.put("pfkey", string5); QQ.this.db.put("pay_token", string6); a2.b(string); a2.d(string2); a2.a(); QQ.this.afterRegister(1, null); } public void onCancel() { if (QQ.this.listener != null) { QQ.this.listener.onCancel(QQ.this, 1); } } }, isSSODisable()); } /* access modifiers changed from: protected */ public boolean checkAuthorize(int i, Object obj) { c a2 = c.a((Platform) this); if (a2.b() && this.c && i == 9) { return true; } if (isAuthValid() || (i == 9 && obj != null && (obj instanceof ShareParams) && !((ShareParams) obj).isShareTencentWeibo())) { a2.a(this.a); a2.b(this.db.getUserId()); a2.d(this.db.getToken()); return true; } innerAuthorize(i, obj); return false; } /* access modifiers changed from: protected */ public void doShare(ShareParams shareParams) { c a2 = c.a((Platform) this); if (!this.c || !a2.b()) { String title = shareParams.getTitle(); String text = shareParams.getText(); String imagePath = shareParams.getImagePath(); String imageUrl = shareParams.getImageUrl(); String musicUrl = shareParams.getMusicUrl(); String titleUrl = shareParams.getTitleUrl(); boolean isShareTencentWeibo = shareParams.isShareTencentWeibo(); int hidden = shareParams.getHidden(); String qQMiniProgramAppid = shareParams.getQQMiniProgramAppid(); String qQMiniProgramPath = shareParams.getQQMiniProgramPath(); String qQMiniProgramType = shareParams.getQQMiniProgramType(); int shareType = shareParams.getShareType(); if (!TextUtils.isEmpty(title) || !TextUtils.isEmpty(text) || !TextUtils.isEmpty(imagePath) || !TextUtils.isEmpty(imageUrl) || !TextUtils.isEmpty(musicUrl) || !TextUtils.isEmpty(qQMiniProgramAppid)) { if (!TextUtils.isEmpty(titleUrl)) { titleUrl = getShortLintk(titleUrl, false); shareParams.setTitleUrl(titleUrl); } if (!TextUtils.isEmpty(text)) { text = getShortLintk(text, false); shareParams.setText(text); } a2.a(title, titleUrl, text, imagePath, imageUrl, musicUrl, new PlatformActionListener() { public void onError(Platform platform, int i, Throwable th) { if (QQ.this.listener != null) { QQ.this.listener.onError(QQ.this, 9, th); } } public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) { HashMap hashMap2 = new HashMap(); if (hashMap != null) { hashMap2.putAll(hashMap); } if (QQ.this.listener != null) { QQ.this.listener.onComplete(QQ.this, 9, hashMap2); } } public void onCancel(Platform platform, int i) { if (QQ.this.listener != null) { QQ.this.listener.onCancel(QQ.this, 9); } } }, isShareTencentWeibo, hidden, qQMiniProgramAppid, qQMiniProgramPath, qQMiniProgramType, shareType); } else if (this.listener != null) { this.listener.onError(this, 9, new Throwable("qq share must have one param at least")); } } else { try { a2.a(this, shareParams, this.listener); } catch (Throwable th) { if (this.listener != null) { this.listener.onError(this, 9, th); } } } } /* access modifiers changed from: protected */ public void follow(String str) { if (this.listener != null) { this.listener.onCancel(this, 6); } } /* access modifiers changed from: protected */ public void timeline(int i, int i2, String str) { if (this.listener != null) { this.listener.onCancel(this, 7); } } /* access modifiers changed from: protected */ public void userInfor(String str) { if (str == null || str.length() < 0) { str = this.db.getUserId(); } if (str != null && str.length() >= 0) { try { HashMap e = c.a((Platform) this).e(str); if (e == null || e.size() <= 0) { if (this.listener != null) { this.listener.onError(this, 8, new Throwable()); } } else if (!e.containsKey("ret")) { if (this.listener != null) { this.listener.onError(this, 8, new Throwable()); } } else if (((Integer) e.get("ret")).intValue() == 0) { if (str == this.db.getUserId()) { this.db.put("nickname", String.valueOf(e.get("nickname"))); if (e.containsKey("figureurl_qq_2")) { this.db.put(MessageKey.MSG_ICON, String.valueOf(e.get("figureurl_qq_2"))); } else if (e.containsKey("figureurl_qq_1")) { this.db.put(MessageKey.MSG_ICON, String.valueOf(e.get("figureurl_qq_1"))); } if (e.containsKey("figureurl_2")) { this.db.put("iconQzone", String.valueOf(e.get("figureurl_2"))); } else if (e.containsKey("figureurl_1")) { this.db.put("iconQzone", String.valueOf(e.get("figureurl_1"))); } else if (e.containsKey("figureurl")) { this.db.put("iconQzone", String.valueOf(e.get("figureurl"))); } this.db.put("secretType", String.valueOf(e.get("is_yellow_vip"))); if (String.valueOf(e.get("is_yellow_vip")).equals("1")) { this.db.put("snsUserLevel", String.valueOf(e.get("level"))); } String valueOf = String.valueOf(e.get("gender")); int stringRes = ResHelper.getStringRes(MobSDK.getContext(), "ssdk_gender_male"); int stringRes2 = ResHelper.getStringRes(MobSDK.getContext(), "ssdk_gender_female"); if (valueOf.equals(MobSDK.getContext().getString(stringRes))) { this.db.put("gender", "0"); } else if (valueOf.equals(MobSDK.getContext().getString(stringRes2))) { this.db.put("gender", "1"); } else { this.db.put("gender", "2"); } } if (this.listener != null) { if (this.db.get("userTags") != null) { e.put("userTags", this.db.get("userTags")); } this.listener.onComplete(this, 8, e); } } else if (this.listener != null) { this.listener.onError(this, 8, new Throwable(new Hashon().fromHashMap(e))); } } catch (Throwable th) { if (this.listener != null) { this.listener.onError(this, 8, th); } } } else if (this.listener != null) { this.listener.onError(this, 8, new RuntimeException("qq account is null")); } } /* access modifiers changed from: protected */ public void getFriendList(int i, int i2, String str) { if (this.listener != null) { this.listener.onCancel(this, 2); } } /* access modifiers changed from: protected */ public void doCustomerProtocol(String str, String str2, int i, HashMap<String, Object> hashMap, HashMap<String, String> hashMap2) { if (this.listener != null) { this.listener.onCancel(this, i); } } /* access modifiers changed from: protected */ public a filterShareContent(ShareParams shareParams, HashMap<String, Object> hashMap) { a aVar = new a(); String titleUrl = shareParams.getTitleUrl(); aVar.c.add(titleUrl); aVar.a = this.a; String text = shareParams.getText(); if (!TextUtils.isEmpty(text)) { aVar.b = text; } String imageUrl = shareParams.getImageUrl(); String imagePath = shareParams.getImagePath(); if (!TextUtils.isEmpty(imagePath)) { aVar.e.add(imagePath); } else if (!TextUtils.isEmpty(imageUrl)) { aVar.d.add(imageUrl); } HashMap<String, Object> hashMap2 = new HashMap<>(); hashMap2.put("title", shareParams.getTitle()); hashMap2.put("url", titleUrl); hashMap2.put("imageLocalUrl", imagePath); hashMap2.put("summary", text); hashMap2.put("appName", DeviceHelper.getInstance(MobSDK.getContext()).getAppName()); aVar.g = hashMap2; return aVar; } /* access modifiers changed from: protected */ public String uploadImageToFileServer(String str) { return super.uploadImageToFileServer(str); } /* access modifiers changed from: protected */ public HashMap<String, Object> getFollowings(int i, int i2, String str) { return null; } /* access modifiers changed from: protected */ public HashMap<String, Object> getFollowers(int i, int i2, String str) { return null; } /* access modifiers changed from: protected */ public HashMap<String, Object> getBilaterals(int i, int i2, String str) { return null; } /* access modifiers changed from: protected */ public HashMap<String, Object> filterFriendshipInfo(int i, HashMap<String, Object> hashMap) { return null; } public boolean hasShareCallback() { return this.b; } }
true
31910404ca7979ba5058cefd7563ef266eedc398
Java
yuan-fei/Coding
/leetcode_java/src/2264.largest-3-same-digit-number-in-string.java
UTF-8
1,790
3.5
4
[]
no_license
/* * @lc app=leetcode id=2264 lang=java * * [2264] Largest 3-Same-Digit Number in String * * https://leetcode.com/problems/largest-3-same-digit-number-in-string/description/ * * algorithms * Easy (58.27%) * Likes: 55 * Dislikes: 3 * Total Accepted: 10.5K * Total Submissions: 18K * Testcase Example: '"6777133339"' * * You are given a string num representing a large integer. An integer is good * if it meets the following conditions: * * * It is a substring of num with length 3. * It consists of only one unique digit. * * * Return the maximum good integer as a string or an empty string "" if no such * integer exists. * * Note: * * * A substring is a contiguous sequence of characters within a string. * There may be leading zeroes in num or a good integer. * * * * Example 1: * * * Input: num = "6777133339" * Output: "777" * Explanation: There are two distinct good integers: "777" and "333". * "777" is the largest, so we return "777". * * * Example 2: * * * Input: num = "2300019" * Output: "000" * Explanation: "000" is the only good integer. * * * Example 3: * * * Input: num = "42352338" * Output: "" * Explanation: No substring of length 3 consists of only one unique digit. * Therefore, there are no good integers. * * * * Constraints: * * * 3 <= num.length <= 1000 * num only consists of digits. * * */ // @lc code=start class Solution { public String largestGoodInteger(String num) { String[] pattern = {"000", "111", "222", "333", "444", "555", "666", "777", "888", "999"}; for(int i = 9; i >= 0; i--){ if(num.indexOf(pattern[i]) >= 0){ return pattern[i]; } } return ""; } } // @lc code=end
true
e8050899f394daa3790bde78783af3b9af216eca
Java
Arunav27/SpringMVC_AND_REST
/src/main/java/com/myapp/spring/catalog/CatalogItemRepository.java
UTF-8
204
1.523438
2
[]
no_license
package com.myapp.spring.catalog; import org.springframework.data.jpa.repository.JpaRepository; public interface CatalogItemRepository extends JpaRepository<CatalogItemEntity, Integer> { }
true
781f81f501778d1afdb06cd9de5db7ad65de5d5f
Java
apache/storm
/storm-client/test/jvm/org/apache/storm/executor/ExecutorTransferMultiThreadingTest.java
UTF-8
9,598
1.796875
2
[ "BSD-3-Clause", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-only", "EPL-1.0", "MPL-1.1", "W3C", "Classpath-exception-2.0", "MPL-2.0", "EPL-2.0", "CDDL-1.0", "GPL-2.0-only", "LicenseRef-scancode-public-domain", "LGPL-2.1-or-later", "CC0-1.0", "CPL-1.0", "SAX-PD" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version * 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package org.apache.storm.executor; import java.lang.reflect.Field; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.storm.Constants; import org.apache.storm.daemon.worker.WorkerState; import org.apache.storm.daemon.worker.WorkerTransfer; import org.apache.storm.generated.StormTopology; import org.apache.storm.messaging.TaskMessage; import org.apache.storm.metrics2.StormMetricRegistry; import org.apache.storm.policy.WaitStrategyPark; import org.apache.storm.serialization.KryoTupleDeserializer; import org.apache.storm.task.GeneralTopologyContext; import org.apache.storm.task.WorkerTopologyContext; import org.apache.storm.testing.TestWordCounter; import org.apache.storm.testing.TestWordSpout; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.tuple.AddressedTuple; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Tuple; import org.apache.storm.tuple.TupleImpl; import org.apache.storm.tuple.Values; import org.apache.storm.utils.JCQueue; import org.apache.storm.utils.Utils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Some topologies might spawn extra threads inside components to perform real processing work and emit processed results. * This unit test is to mimic these scenarios in the {@link ExecutorTransfer} level * and make sure the tuples sent out in a multi-threading fashion to the workerTransferQueue * is properly handled and received by the remote Worker (consumer) * * The topology structure this test mimics is * {worker1: taskId=1, component="1"} --> {worker2: taskId=2, component="2"}. */ public class ExecutorTransferMultiThreadingTest { private WorkerState workerState; private Map<String, Object> topoConf; private JCQueue transferQueue; private GeneralTopologyContext generalTopologyContext; private final int selfTaskId = 1; private final String sourceComp = "1"; private final int remoteTaskId = 2; private final String destComp = "2"; private static final String value1 = "string-value"; private static final int value2 = 1234; @BeforeEach public void setup() throws NoSuchFieldException, IllegalAccessException { topoConf = Utils.readStormConfig(); String topologyId = "multi-threaded-topo-test"; StormTopology stormTopology = createStormTopology(); WorkerTopologyContext workerTopologyContext = mock(WorkerTopologyContext.class); when(workerTopologyContext.getRawTopology()).thenReturn(stormTopology); when(workerTopologyContext.getComponentId(selfTaskId)).thenReturn(sourceComp); when(workerTopologyContext.getComponentId(remoteTaskId)).thenReturn(destComp); workerState = mock(WorkerState.class); when(workerState.getWorkerTopologyContext()).thenReturn(workerTopologyContext); Map<Integer, JCQueue> receiveQMap = new HashMap<>(); //local recvQ is not important in this test; simple mock it receiveQMap.put(selfTaskId, mock(JCQueue.class)); when(workerState.getLocalReceiveQueues()).thenReturn(receiveQMap); when(workerState.getTopologyId()).thenReturn(topologyId); when(workerState.getPort()).thenReturn(6701); when(workerState.getMetricRegistry()).thenReturn(new StormMetricRegistry()); when(workerState.tryTransferRemote(any(), any(), any())).thenCallRealMethod(); //the actual worker transfer queue to be used in this test //taskId for worker transfer queue should be -1. //But there is already one worker transfer queue initialized by WorkerTransfer class (taskId=-1). //However the taskId is only used for metrics and it is not important here. Making it -100 to avoid collision. transferQueue = new JCQueue("worker-transfer-queue", "worker-transfer-queue", 1024, 0, 1, new WaitStrategyPark(100), workerState.getTopologyId(), Constants.SYSTEM_COMPONENT_ID, Collections.singletonList(-100), workerState.getPort(), workerState.getMetricRegistry()); //Replace the transferQueue inside WorkerTransfer (inside WorkerState) with the customized transferQueue to be used in this test WorkerTransfer workerTransfer = new WorkerTransfer(workerState, topoConf, 2); setPrivateField(workerTransfer, "transferQueue", transferQueue); setPrivateField(workerState, "workerTransfer", workerTransfer); generalTopologyContext = mock(GeneralTopologyContext.class); } private void setPrivateField(Object target, String fieldName, Object fieldValue) throws NoSuchFieldException, IllegalAccessException { Field privateField = target.getClass().getDeclaredField(fieldName); privateField.setAccessible(true); privateField.set(target, fieldValue); } @Test public void testExecutorTransfer() throws InterruptedException { //There is one ExecutorTransfer per executor ExecutorTransfer executorTransfer = new ExecutorTransfer(workerState, topoConf); executorTransfer.initLocalRecvQueues(); ExecutorService executorService = Executors.newFixedThreadPool(5); //There can be multiple producer threads sending out tuples inside each executor //This mimics the case of multi-threading components where a component spawns extra threads to emit tuples. int producerTaskNum = 10; Runnable[] producerTasks = new Runnable[producerTaskNum]; for (int i = 0; i < producerTaskNum; i++) { producerTasks[i] = createProducerTask(executorTransfer); } for (Runnable task : producerTasks) { executorService.submit(task); } //give producers enough time to insert messages into the queue executorService.awaitTermination(1000, TimeUnit.MILLISECONDS); //consume all the tuples in the queue and deserialize them one by one //this mimics a remote worker. KryoTupleDeserializer deserializer = new KryoTupleDeserializer(topoConf, workerState.getWorkerTopologyContext()); SingleThreadedConsumer consumer = new SingleThreadedConsumer(deserializer, producerTaskNum); transferQueue.consume(consumer); consumer.finalCheck(); executorService.shutdown(); } private Runnable createProducerTask(ExecutorTransfer executorTransfer) { return new Runnable() { final Tuple tuple = new TupleImpl(generalTopologyContext, new Values(value1, value2), sourceComp, selfTaskId, "default"); final AddressedTuple addressedTuple = new AddressedTuple(remoteTaskId, tuple); @Override public void run() { executorTransfer.tryTransfer(addressedTuple, null); } }; } private StormTopology createStormTopology() { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout(sourceComp, new TestWordSpout(true), 1); builder.setBolt(destComp, new TestWordCounter(), 1).fieldsGrouping(sourceComp, new Fields("word")); return builder.createTopology(); } private static class SingleThreadedConsumer implements JCQueue.Consumer { KryoTupleDeserializer deserializer; int numMessages; int msgCount = 0; public SingleThreadedConsumer(KryoTupleDeserializer deserializer, int numMessages) { this.deserializer = deserializer; this.numMessages = numMessages; } /** * There are multiple producers sending messages to the queue simultaneously. * The consumer receives messages one by one and tries to deserialize them. * If there is any issues/exceptions during the process, it basically means data corruption is happening. * @param o the received object */ @Override public void accept(Object o) { TaskMessage taskMessage = (TaskMessage) o; TupleImpl receivedTuple = deserializer.deserialize(taskMessage.message()); assertEquals(receivedTuple.getValue(0), value1); assertEquals(receivedTuple.getValue(1), value2); msgCount++; } /** * This makes sure every message sent by the producers are received by this consumer. */ public void finalCheck() { assertEquals(numMessages, msgCount); } @Override public void flush() { //no op } } }
true
4e9929c8ce794c4ac46fe7c996f40d6ff39df46e
Java
Sabaudo/Cadastro-de-contas-Heranca
/ContaPoupanca.java
UTF-8
372
2.59375
3
[]
no_license
import java.math.BigDecimal; public class ContaPoupanca extends ContaBancaria{ BigDecimal diaRendimento = new BigDecimal(0.11); public ContaPoupanca(String cliente, String numeroConta, BigDecimal saldo) { super(cliente, numeroConta, saldo); } public void calcularNovoSaldo() { BigDecimal m = diaRendimento.multiply(saldo); saldo = saldo.add(m); } }
true
4c50fd265e107e5d736d7d92df99509f724c37b0
Java
deadpassive/wcsclient
/src/main/java/uk/ac/glam/wcsclient/gml311/CurveArrayPropertyType.java
UTF-8
2,737
1.695313
2
[]
no_license
/** * <copyright> * </copyright> * * $Id$ */ package uk.ac.glam.wcsclient.gml311; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.FeatureMap; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Curve Array Property Type</b></em>'. * <!-- end-user-doc --> * * <!-- begin-model-doc --> * A container for an array of curves. The elements are always contained in the array property, referencing geometry elements * or arrays of geometry elements is not supported. * <!-- end-model-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link uk.ac.glam.wcsclient.gml311.CurveArrayPropertyType#getCurveGroup <em>Curve Group</em>}</li> * <li>{@link uk.ac.glam.wcsclient.gml311.CurveArrayPropertyType#getCurve <em>Curve</em>}</li> * </ul> * </p> * * @see uk.ac.glam.wcsclient.gml311.Gml311Package#getCurveArrayPropertyType() * @model extendedMetaData="name='CurveArrayPropertyType' kind='elementOnly'" * @generated */ public interface CurveArrayPropertyType extends EObject { /** * Returns the value of the '<em><b>Curve Group</b></em>' attribute list. * The list contents are of type {@link org.eclipse.emf.ecore.util.FeatureMap.Entry}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * The "_Curve" element is the abstract head of the substituition group for all (continuous) curve elements. * <!-- end-model-doc --> * @return the value of the '<em>Curve Group</em>' attribute list. * @see uk.ac.glam.wcsclient.gml311.Gml311Package#getCurveArrayPropertyType_CurveGroup() * @model unique="false" dataType="org.eclipse.emf.ecore.EFeatureMapEntry" many="true" * extendedMetaData="kind='group' name='_Curve:group' namespace='##targetNamespace'" * @generated */ FeatureMap getCurveGroup(); /** * Returns the value of the '<em><b>Curve</b></em>' containment reference list. * The list contents are of type {@link uk.ac.glam.wcsclient.gml311.AbstractCurveType}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * The "_Curve" element is the abstract head of the substituition group for all (continuous) curve elements. * <!-- end-model-doc --> * @return the value of the '<em>Curve</em>' containment reference list. * @see uk.ac.glam.wcsclient.gml311.Gml311Package#getCurveArrayPropertyType_Curve() * @model containment="true" transient="true" changeable="false" volatile="true" derived="true" * extendedMetaData="kind='element' name='_Curve' namespace='##targetNamespace' group='_Curve:group'" * @generated */ EList<AbstractCurveType> getCurve(); } // CurveArrayPropertyType
true
f1fd046eed7b0611aafc7b1ef1b43dc77d00fd7d
Java
Royk8/Log2Practica1
/src/Practica1.java
UTF-8
5,773
3.625
4
[]
no_license
import java.io.IOException; import java.util.InputMismatchException; import java.util.Scanner; import java.util.function.DoubleToIntFunction; public class Practica1 { Scanner leer = new Scanner(System.in); public void menu() throws IOException { Matriz matriz = new Matriz(); int opcion = 0; do { System.out.println("Bienvenido al gestor de matrices."); System.out.println("Seleccione una opcion ingresando su indice."); System.out.println("1. Mostrar Matriz"); System.out.println("2. Mostrar operaciones sobre toda la matriz"); System.out.println("3. Mostrar operaciones por filas o columnas"); System.out.println("4. Mostrar operaciones de ordenamiento"); System.out.println("0. Salir"); opcion = leerInt(0, 4); //Los numerales de la practica se dividieron en tres categorias para facilitar la visualizacion. switch (opcion) { case 1: matriz.mostrarMatriz(); break; case 2: menuOperacionesMatriz(matriz); break; case 3: menuOperacionesFilasColumnas(matriz); break; case 4: menuOperacionesOrdenamiento(matriz); break; case 0: System.out.println("Adios!"); break; } }while(opcion != 0); } public void menuOperacionesMatriz(Matriz matriz){ int opcion = 0; do { System.out.println("Seleccione la operacion que desea realizar."); System.out.println("1. Hallar la suma de los terminos de la matriz"); System.out.println("2. Hallar el mayor valor en la matriz"); System.out.println("3. Hallar el menor valor en la matriz"); System.out.println("4. Mostrar el numero de veces que se repite cada dato"); System.out.println("5. Mostrar el promedio de los datos de la tridiagonal principal"); System.out.println("0. Volver al menu principal"); opcion = leerInt(0,5); switch (opcion){ case 1: matriz.sumaDatosMatriz(); break; case 2: matriz.mayorValor(); break; case 3: matriz.menorValor(); break; case 4: matriz.repeticionDatos(); break; case 5: matriz.promedioTridiagonal(); break; } }while(opcion != 0); } public void menuOperacionesFilasColumnas(Matriz matriz){ int opcion = 0; do { System.out.println("Seleccione la operacion que desea realizar."); System.out.println("1. Mostrar el mayor dato de cada fila"); System.out.println("2. Mostrar el menor dato de cada columna"); System.out.println("3. Mostrar el dato con la mayor suma de digitos en cada fila"); System.out.println("4. Intercambiar los datos de una fila con los de una columna"); System.out.println("0. Volver al menu principal"); opcion = leerInt(0,4); switch (opcion){ case 1: matriz.mayorDatoCadaFila(); break; case 2: matriz.menorDatoCadaColumna(); break; case 3: matriz.datoMayorSumaDigitosCadaFila(); break; case 4: matriz.intercambiaUnaFilaConColumna(); break; } }while(opcion != 0); } public void menuOperacionesOrdenamiento(Matriz matriz){ int opcion = 0; do { System.out.println("Seleccione la operacion que desea realizar."); System.out.println("1. Ordenar la matriz ascendentemente por filas"); System.out.println("2. Ordenar cada fila descendentemente"); System.out.println("3. Ordenar descendentemente por fila 1?"); System.out.println("4. Ordenar ascendentemente los digitos de cada dato de la tridiagonal segundaria"); System.out.println("0. Volver al menu principal"); opcion = leerInt(0,4); switch (opcion){ case 1: matriz.ordenarAscendentePorFilas(); break; case 2: matriz.ordenarCadaFilaDescendente(); break; case 3: matriz.ordenarDescendentePorFilaUno(); break; case 4: matriz.ordenarAscendenteDigitosTridiagonalSegundaria(); break; } }while(opcion != 0); } public int leerInt(int min, int max){ //Metodo para leer un Entero ingresado por el usuario, valido en un intervalo y con manejo de excepciones. int n = min-1; while(true){ try{ n = Integer.parseInt(leer.nextLine()); }catch (InputMismatchException ex){ System.out.println("El numero debe estar entre "+min+" y "+ max); } if(n<= max && n>= min) break; System.out.println("El numero debe estar entre "+min+" y "+max); } return n; } public static void main(String[] args) throws IOException { Practica1 practica = new Practica1(); practica.menu(); } }
true
0a26a72f3c089be5c5025adbf3a8053b8c459008
Java
pankajmuneshwar/AndroidTestProject
/weather/src/main/java/com/weather/incube/weather/util/FontUtils.java
UTF-8
563
2.4375
2
[]
no_license
package com.weather.incube.weather.util; import android.content.Context; import android.content.ContextWrapper; import android.graphics.Typeface; import android.widget.TextView; public class FontUtils { public static String WEATHER_REGULAR = "fonts/weather.otf"; public static void setFont(Context context, TextView textView, String fontStyle, float size) { Typeface tf = Typeface.createFromAsset(((ContextWrapper) context) .getBaseContext().getAssets(), fontStyle); if (size != 0) textView.setTextSize(size); textView.setTypeface(tf); } }
true
c7f2b411a149f92260afcff4854719b0d5913ec5
Java
Siddharth1698/Firebase-App
/app/src/main/java/com/example/siddharthm/firebaseapp/MainActivity.java
UTF-8
1,402
2.1875
2
[ "Apache-2.0" ]
permissive
package com.example.siddharthm.firebaseapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.google.firebase.FirebaseApp; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class MainActivity extends AppCompatActivity { Button mSendData; EditText mtKey; EditText mtValue; private DatabaseReference mDb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSendData = (Button)findViewById(R.id.addString); mtKey = (EditText) findViewById(R.id.keytext); mtValue = (EditText)findViewById(R.id.valuetext); final DatabaseReference mRef = FirebaseDatabase.getInstance().getReference(); mSendData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String key = (String) mtKey.getText().toString(); String value = (String) mtValue.getText().toString(); DatabaseReference child = mRef.child(key); child.setValue(value); } }); } }
true
020160591f404b916a91931d63f96d06c3ba84b5
Java
gdincu/UBB_PostUni
/Sem2/Programare orientată obiect (Java)/Examen/Simulare/src/UI/Controller.java
UTF-8
4,764
2.40625
2
[ "MIT" ]
permissive
package UI; import Domain.DieselCar; import Domain.ElectricCar; import Service.DieselService; import Service.ElectricService; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import java.util.List; public class Controller { public TableView tableViewDieselCars; public TableColumn DieselID; public TableColumn DieselModel; public TableColumn DieselPret; public TableColumn DieselConsum; public TextField dieselId; public TextField dieselModel; public TextField dieselPret; public TextField dieselConsum; public TextField searchModelDiesel; public Button AddDiesel; public Button SortDiesel; public Button SearchDiesel; public Button RefreshDiesel; public TableView tableViewElectricCars; public TableColumn ElectricID; public TableColumn ElectricModel; public TableColumn ElectricPret; public TableColumn ElectricAutonomie; public TextField electricId; public TextField electricModel; public TextField electricPret; public TextField electricAutonomie; public TextField searchModelElectric; public Button AddElectric; public Button SortElectric; public Button SearchElectric; public Button RefreshElectric; private DieselService dieselService; private ObservableList<DieselCar> diesels = FXCollections.observableArrayList(); public void AddDiesel(ActionEvent actionEvent) { try { String id = dieselId.getText(); String model = dieselModel.getText(); double pret = Double.parseDouble(dieselPret.getText()); double consum = Double.parseDouble(dieselConsum.getText()); dieselService.add(id,model,pret,consum); dieselId.clear(); dieselModel.clear(); dieselPret.clear(); dieselConsum.clear(); diesels.clear(); diesels.addAll(dieselService.getAll()); } catch (RuntimeException ex) { Common.showValidationError(ex.getMessage()); } } public void setServices(DieselService dieselService, ElectricService electricService) { this.dieselService = dieselService; this.electricService = electricService; } @FXML private void initialize() { Platform.runLater(() -> { diesels.addAll(dieselService.getAll()); tableViewDieselCars.setItems(diesels); }); Platform.runLater(() -> { electrics.addAll(electricService.getAll()); tableViewElectricCars.setItems(electrics); }); } private ElectricService electricService; private ObservableList<ElectricCar> electrics = FXCollections.observableArrayList(); public void AddElectric(ActionEvent actionEvent) { try { String id = electricId.getText(); String model = electricModel.getText(); double pret = Double.parseDouble(electricPret.getText()); double autonomie = Double.parseDouble(electricAutonomie.getText()); electricService.add(id,model,pret,autonomie); electricId.clear(); electricModel.clear(); electricPret.clear(); electricAutonomie.clear(); electrics.clear(); electrics.addAll(electricService.getAll()); } catch (RuntimeException ex) { Common.showValidationError(ex.getMessage()); } } public void SortElectric (ActionEvent actionEvent) { electrics.clear(); List<ElectricCar> temp = electricService.sort(); electrics.addAll(temp); } public void SortDiesel (ActionEvent actionEvent) { diesels.clear(); List<DieselCar> temp = dieselService.sort(); diesels.addAll(temp); } public void RefreshDiesel (ActionEvent actionEvent) { diesels.clear(); diesels.addAll(dieselService.getAll()); } public void RefreshElectric (ActionEvent actionEvent) { electrics.clear(); electrics.addAll(electricService.getAll()); } public void SearchDiesel (ActionEvent actionEvent) { diesels.clear(); String model = searchModelDiesel.getText(); diesels.addAll(dieselService.cautareModel(model)); } public void SearchElectric (ActionEvent actionEvent) { electrics.clear(); String model = searchModelElectric.getText(); electrics.addAll(electricService.cautareModel(model)); } }
true
436ee8c540b58eec3a15072512e8e53e055a8b4d
Java
Eunbi117/Java
/0923/src/SingRobot.java
UHC
200
2.59375
3
[]
no_license
public class SingRobot extends Robot{ SingRobot(int price) { super(price); } //: toString public String toString(){//toString ̵ return "뷡 θϴ."; } }
true
e94b4478e9ae42aa1c81842322daae24541c83f6
Java
AndresPautrat/Topicos_Peces
/src/HostAgent.java
UTF-8
1,185
2.21875
2
[]
no_license
import java.util.ArrayList; import jade.core.Agent; import jade.core.behaviours.CyclicBehaviour; import jade.core.behaviours.ParallelBehaviour; import jade.domain.DFService; import jade.domain.FIPAAgentManagement.DFAgentDescription; public class HostAgent extends Agent { public static MainFrame frame = null; public static int numero_peces = 10; public static ArrayList<FishAgent> lista_peces = new ArrayList<FishAgent>(); public static boolean ENABLED = false; @Override public void setup() { try { DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(getAID()); DFService.register(this, dfd); frame = new MainFrame(this); frame.setVisible(true); ParallelBehaviour parallelBehaviour = new ParallelBehaviour(); parallelBehaviour.addSubBehaviour(new CyclicBehaviour() { @Override public void action() { frame.panel_principal.repaint(); } }); } catch (Exception e) { System.err.println("exception" + e); e.printStackTrace(); } } }
true
a4cd5f9d684658b6b491473377ab528a8d350556
Java
deamdornelles/ColecaoFilmesDrawer
/app/src/main/java/com/example/deam/colecaofilmesdrawer/Anuncio.java
UTF-8
1,089
2.484375
2
[]
no_license
package com.example.deam.colecaofilmesdrawer; /** * Created by Deam on 07/09/2017. */ public class Anuncio { String id; String descricao; String nomeFilme; String id_filme; String nome_usuario; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public String getNomeFilme() { return nomeFilme; } public void setNomeFilme(String nomeFilme) { this.nomeFilme = nomeFilme; } public String getId_filme() { return id_filme; } public void setId_filme(String id_filme) { this.id_filme = id_filme; } public String getNome_usuario() { return nome_usuario; } public void setNome_usuario(String nome_usuario) { this.nome_usuario = nome_usuario; } @Override public String toString() { return nomeFilme + " - " + descricao; } }
true
2f6b7e5a46ec1bdc7e72c66294998bd21d45ae81
Java
walle79/C1019I1_Nguyen_Hong_Son
/Module2/Bai4_KeThua/Bai_tap/src/Point__MoveablePoint/PointTest.java
UTF-8
426
2.875
3
[]
no_license
package Point__MoveablePoint; import java.util.Scanner; public class PointTest extends Point { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Point point = new Point(); System.out.print("Enter x: "); point.setX(sc.nextFloat()); System.out.print("Enter y: "); point.setY(sc.nextFloat()); System.out.println("(x,y): "+ point); } }
true
704e96c29c3d9b9cda8f55c5deda73e4daf786db
Java
buobao/OSChina
/app/src/main/java/com/turman/oschina/bean/Report.java
UTF-8
566
1.960938
2
[]
no_license
package com.turman.oschina.bean; import com.turman.oschina.bean.base.Entity; /** * 举报实体类 * * @author 火蚁(http://my.oschina.net/LittleDY) * @version 1.0 * @created 2014-02-13 */ public class Report extends Entity { private static final long serialVersionUID = 1L; public static final byte TYPE_QUESTION = 0x02;// 问题 public int objId;//需要举报的id public String url;// 举报的链接地址 public byte objType;// 举报的类型 public int reason;// 原因 public String otherReason;// 其他原因 }
true
5bc23cd8178b6766b82cdf1012fd0ed0488a7f2a
Java
kondareddy405/JavaProjects
/CollectionsTask-Kondareddy/src/com/collections/kondareddy/LinkedListToArray.java
UTF-8
417
2.953125
3
[]
no_license
package com.collections.kondareddy; import java.util.LinkedList; public class LinkedListToArray { public static void main(String[] args) { LinkedList<String> arr=new LinkedList<>(); arr.add("first"); arr.add("second"); arr.add("third"); System.out.println("ArrayList:" +arr); String[] Str=new String[arr.size()]; arr.toArray(Str); for(String str1:Str) { System.out.println( str1); } } }
true
473f6c230ca5163c0a35b1c431b9f725cc22362e
Java
coolboy2333/leetcode
/src/leetcode/Q17/letterCombinations.java
UTF-8
1,080
3.28125
3
[]
no_license
package leetcode.Q17; import java.util.ArrayList; import java.util.List; public class letterCombinations { static List<String> res = new ArrayList<>(); // static char[] str = new char[100]; static String dict[] = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; public static List<String> letterCombinations(String digits) { char[] str = new char[digits.length()]; if (digits.isEmpty()) return res; letterCombinationsDFS(digits, str, 0); return res; } public static void letterCombinationsDFS(String digits, char[] str, int step) { if (step == digits.length()) { // str[step] = '\0'; res.add(String.copyValueOf(str)); return; } int index = digits.charAt(step) - '0'; for (int i = 0; i < dict[index].length(); i++) { str[step] = dict[index].charAt(i); letterCombinationsDFS(digits, str, step + 1); } } public static void main(String[] args) { // TODO Auto-generated method stub letterCombinations(""); for (String s : res) { System.out.println(s); } } }
true
6efcba73f59f24223138defe99e34533f25cbd20
Java
GLescroel/MonEscalade
/src/main/java/glescroel/escalade/controller/FormVoieController.java
UTF-8
6,849
2.140625
2
[]
no_license
package glescroel.escalade.controller; import glescroel.escalade.dto.LongueurDto; import glescroel.escalade.dto.SecteurDto; import glescroel.escalade.dto.SiteDto; import glescroel.escalade.dto.VoieDto; import glescroel.escalade.service.LongueurService; import glescroel.escalade.service.SecteurService; import glescroel.escalade.service.SiteService; import glescroel.escalade.service.VoieService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.RequestParam; @Controller public class FormVoieController { private static final Logger LOGGER = LoggerFactory.getLogger(FormVoieController.class); @Autowired private SiteService siteService; @Autowired private SecteurService secteurService; @Autowired private VoieService voieService; @Autowired private LongueurService longueurService; /** * Affichage du forulaire de modification de la voie * @param idSite * @param idSecteur * @param idVoie * @param model * @return la page web du formulaire de la voie */ @GetMapping(value = "/modifSite/{idSite}/modifSecteur/{idSecteur}/modifVoie/{idVoie}") public String viewFormVoie(@PathVariable("idSite") String idSite, @PathVariable("idSecteur") String idSecteur, @PathVariable("idVoie") String idVoie, Model model) { LOGGER.info(">>>>> Dans FormVoieController - GetMapping"); SiteDto site = siteService.getSiteById(Integer.valueOf(idSite)); SecteurDto secteur = secteurService.getSecteurById(Integer.valueOf(idSecteur)); VoieDto voie = voieService.getVoieById(Integer.valueOf(idVoie)); model.addAttribute("site", site); model.addAttribute("secteur", secteur); model.addAttribute("voie", voie); model.addAttribute("longueurs", voie.getLongueurs()); model.addAttribute("suppression", false); return "formVoie"; } /** * Mise à jour de la voie * @param idSite * @param idSecteur * @param idVoie * @param model * @param nomVoie * @param voieEquipee * @param cotation * @return la page web du formulaire de la voie */ @PostMapping(value = "/modifSite/{idSite}/modifSecteur/{idSecteur}/modifVoie/{idVoie}/update") public String viewUpdateVoie(@PathVariable("idSite") String idSite, @PathVariable("idSecteur") String idSecteur, @PathVariable("idVoie") String idVoie, Model model, @RequestParam(required = true, name = "nomVoie") String nomVoie, @RequestParam(required = false, name = "voieEquipee") boolean voieEquipee, @RequestParam(required = false, name = "cotationVoie") String cotation) { LOGGER.info(">>>>> Dans FormVoieController - PostMapping update"); VoieDto voie = voieService.getVoieById(Integer.valueOf(idVoie)); voie.setNom(nomVoie); voie.setCotation(cotation); voie.setEquipee(voieEquipee); voie.setSecteur(secteurService.getSecteurById(Integer.valueOf(idSecteur))); voie = voieService.save(voie); model.addAttribute("site", siteService.getSiteById(Integer.valueOf(idSite))); model.addAttribute("secteur", secteurService.getSecteurById(Integer.valueOf(idSecteur))); model.addAttribute("voie", voie); model.addAttribute("longueurs", voie.getLongueurs()); model.addAttribute("suppression", false); return "formVoie"; } /** * Ajout d'une longueur dans la voie * @param idSite * @param idSecteur * @param idVoie * @param model * @param nomLongueur * @param cotation * @return la page web du formulaire de la voie */ @PostMapping(value = "/modifSite/{idSite}/modifSecteur/{idSecteur}/modifVoie/{idVoie}") public String viewAddLongueur(@PathVariable("idSite") String idSite, @PathVariable("idSecteur") String idSecteur, @PathVariable("idVoie") String idVoie, Model model, @RequestParam(required = true, name = "nomLongueur") String nomLongueur, @RequestParam(required = false, name = "cotation") String cotation) { LOGGER.info(">>>>> Dans FormVoieController - PostMapping"); SiteDto site = siteService.getSiteById(Integer.valueOf(idSite)); SecteurDto secteur = secteurService.getSecteurById(Integer.valueOf(idSecteur)); VoieDto voie = voieService.getVoieById(Integer.valueOf(idVoie)); LongueurDto longueur = new LongueurDto() .builder() .nom(nomLongueur) .voie(voie) .cotation(cotation) .build(); longueur = longueurService.save(longueur); voie.addLongueur(longueur); model.addAttribute("site", site); model.addAttribute("secteur", secteur); model.addAttribute("voie", voie); model.addAttribute("longueurs", voie.getLongueurs()); model.addAttribute("suppression", false); return "formVoie"; } /** * Suppression de la voie * @param idSite * @param idSecteur * @param idVoie * @param model * @return la page web du formulaire de la voie */ @GetMapping(value = "/modifSite/{idSite}/modifSecteur/{idSecteur}/modifVoie/{idVoie}/suppression") public String deleteSecteur(@PathVariable("idSite") String idSite, @PathVariable("idSecteur") String idSecteur, @PathVariable("idVoie") String idVoie, Model model) { LOGGER.info(">>>>> Dans FormVoieController - GetMapping - URL : /modifSite/{idSite}/modifSecteur/{idSecteur}/modifVoie/{idVoie}/suppression"); VoieDto voie = voieService.getVoieById(Integer.valueOf(idVoie)); voieService.delete(voie); model.addAttribute("suppression", true); model.addAttribute("voie", null); model.addAttribute("secteur", secteurService.getSecteurById(Integer.valueOf(idSecteur))); model.addAttribute("site", siteService.getSiteById(Integer.valueOf(idSite))); return "formVoie"; } }
true
7bbc899a8d9a79a6ea7f013d18e09a98a9a65f1f
Java
miki-java/springboot_dome
/src/main/java/com/example/demo/mapper/UserMapper.java
UTF-8
781
2.03125
2
[]
no_license
package com.example.demo.mapper; import com.example.demo.model.Person; import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by hmq on 2018/11/6. */ @Repository public interface UserMapper { @Select("select * from t_user") List<Person> findUsers(); @Select("select * from t_user where id = #{id}") Person findUserById(@Param("id") Integer id); @SelectProvider(type = UserProvider.class, method = "findUserByPersonInfoSql") List<Person> findUserByPersonInfo(Person person); @Insert("insert into t_user(name,age,birthday,description)values(#{name},#{age},null,#{description})") @Options(useGeneratedKeys=true, keyColumn="id") Integer insertUser(Person person); }
true
974fc7abddfdfbcaaa158aff2f194999528ffa16
Java
KingofCastle/iottest
/iot-web/src/main/java/com/xinguang/iot/client/vehicle/VehicleEditReq.java
UTF-8
1,304
1.96875
2
[]
no_license
package com.xinguang.iot.client.vehicle; import com.wordnik.swagger.annotations.ApiModelProperty; import com.xinguang.iot.client.ClientReq; /** * Created by jinx on 2017/4/27. */ public class VehicleEditReq extends ClientReq{ @ApiModelProperty("车牌") private String plant; @ApiModelProperty("车辆型号") private String model; @ApiModelProperty("司机") private String driver; @ApiModelProperty("司机联系方式") private String telephone; @ApiModelProperty("简介") private String introduction; public String getPlant() { return plant; } public void setPlant(String plant) { this.plant = plant; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } }
true
2c839b192f812ca1f436cb1e492f74463bbc82a4
Java
kumaratul60/Data-Structures-and-Algorithms
/DLL/DoublyLinkedList.java
UTF-8
2,214
3.609375
4
[]
no_license
package DLL; class Node { int data; Node next; Node prev; Node(int data) { this.data = data; this.next = null; this.prev = null; } } public class DoublyLinkedList { Node head = null; void reverse() { Node temp = null, current = head; while (current != null) { temp = current.prev; current.prev = current.next; current.next = temp; current = current.prev; } if (temp != null) head = temp.prev; } void insertBig(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; return; } newNode.next = head; head.prev = newNode; head = newNode; } void insertEnd(int data) { Node newNode = new Node(data); if (head == null) head = newNode; Node tempNode = head; while (tempNode.next != null) tempNode = tempNode.next; tempNode.next = newNode; newNode.prev = tempNode; } void insertAfter(int num, int data) { Node tempNode = head; Node newNode = new Node(data); if (head == null) { head = newNode; return; } while (tempNode != null && tempNode.data != num) tempNode = tempNode.next; newNode.next = tempNode.next; if (newNode.next != null) newNode.next.prev = newNode; tempNode.next = newNode; newNode.prev = tempNode; } void delete(int data) { if (head == null) { System.out.println("List is Empty"); return; } Node delNode = head; while (delNode != null && delNode.data != data) delNode = delNode.next; if (delNode == head) { head = head.next; head.prev = null; return; } delNode.prev.next = delNode.next; if (delNode.next != null) delNode.prev = delNode.prev; } static boolean findCycle(Node head) { Node slow = head, fast = head; while (slow != null && fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) return true; } return false; } int getCount() { Node tnode = head; if (head == null) return 0; int count = 0; while (tnode != null) { count++; tnode = tnode.next; } return count; } void printList() { Node currNode = head; while (currNode != null) { System.out.print(currNode.data + " "); currNode = currNode.next; } } }
true
2817aaf51c52f79756791ad98e2353ffbada89b2
Java
Devidence7/radtree
/RadTree/src/sistinfo/servlets/usuario/CambiarTipoUsuarioServlet.java
UTF-8
2,605
2.71875
3
[ "MIT" ]
permissive
package sistinfo.servlets.usuario; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import sistinfo.capadatos.vo.UsuarioVO; import sistinfo.capadatos.vo.UsuarioVO.TipoUsuario; import sistinfo.excepciones.ErrorInternoException; import sistinfo.excepciones.UsuarioYaExistenteException; import sistinfo.capadatos.dao.UsuarioDAO; @SuppressWarnings("serial") public class CambiarTipoUsuarioServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doPost(request, response); } /** * Edita los datos de un usuario ya registrado en el sistema según los datos pasados por la request * También informa de los errores mediante el atributo errores (mapa) */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); // Comprobar que el usuario está logueado y es administrador UsuarioVO usuario = (UsuarioVO)request.getSession().getAttribute("usuario"); if (usuario == null || usuario.getTipoUsuario() != TipoUsuario.ADMINISTRADOR) { response.sendRedirect(request.getContextPath() + "/error-interno"); } else { // Obtener alias del usuario a modificar String alias = request.getParameter("alias"); String tipoUsuario = request.getParameter("tipoUsuario"); if (alias == null || alias.trim().isEmpty() || tipoUsuario == null || (!tipoUsuario.equals("PARTICIPANTE") && !tipoUsuario.equals("CREADOR"))) { response.sendRedirect(request.getContextPath() + "/error-interno"); } else { // Obtener datos del usuario a modificar UsuarioDAO usuarioDAO = new UsuarioDAO(); try { // Modificar el usuario UsuarioVO usuarioModificar = usuarioDAO.getUsuarioByAlias(alias); if (usuarioModificar == null) { response.sendRedirect(request.getContextPath() + "/error-interno"); } else { usuarioModificar.setTipoUsuario(TipoUsuario.valueOf(tipoUsuario)); if (usuarioDAO.updateUsuario(usuarioModificar, false, false)) { request.getRequestDispatcher("/perfil").forward(request, response); } } } catch (ErrorInternoException | UsuarioYaExistenteException e) { response.sendRedirect(request.getContextPath() + "/error-interno"); } } } } }
true
eb7b3aaddef0512ee2bf960f31ab5733c9f6dfcb
Java
Park-JunHyung/poker
/src/main/java/com/edu/cnu/poker/UserException/NoSuchRankException.java
UTF-8
145
1.507813
2
[]
no_license
package com.edu.cnu.poker.UserException; /** * Created by cse on 2017-04-17. */ public class NoSuchRankException extends RuntimeException { }
true
ca8b7887162492c06f36baa4ca201384c1969eaa
Java
codehaus/prometheus
/src/test/org/codehaus/prometheus/references/TakebackAndResetThread.java
UTF-8
619
2.25
2
[ "MIT" ]
permissive
/* * Copyright (c) 2007 Peter Veentjer * * This program is made available under the terms of the MIT License. */ package org.codehaus.prometheus.references; import org.codehaus.prometheus.concurrenttesting.TestThread; public class TakebackAndResetThread<E> extends TestThread { private final LendableReference<E> lendableRef; private final E ref; public TakebackAndResetThread(LendableReference<E> lendableRef, E ref) { this.lendableRef = lendableRef; this.ref = ref; } @Override protected void runInternal() throws Exception { lendableRef.takebackAndReset(ref); } }
true
15af47f16b0787b1df8202d9e9814c1b23de4209
Java
amaldev1014/Playground
/Printing X pattern/Main.java
UTF-8
1,024
3.171875
3
[]
no_license
import java.util.Scanner; class Main { public static void main (String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int l=(n/2)+1; int m=1; int h=n-2; for(int i=1;i<=l;i++) { for(int j=1;j<m;j++) { System.out.print(" "); } System.out.print("*"); for(int g=1;g<=h;g++) { System.out.print(" "); } if(h>0){ System.out.print("*"); } System.out.println(); m++; h=h-2; } l=(n/2); m=n/3; h=1; for(int i=1;i<=l;i++) { for(int j=1;j<=m;j++) { System.out.print(" "); } System.out.print("*"); for(int g=1;g<=h;g++) { System.out.print(" "); } if(h>0){ System.out.print("*"); } System.out.println(); m--; h=h+2; } } }
true
78edc59d243dfc5f99284024c0a1b199244c8a7e
Java
Gperez88/SystemVD
/src/main/java/com/perezmejia/systemvd/view/SexView.java
UTF-8
476
2.578125
3
[]
no_license
package com.perezmejia.systemvd.view; /** * Created by Guil on 5/10/2016. */ public enum SexView { FEMENINO("F", "Femenino"), MASCULINO("M", "Masculino"); private final String id; private final String description; SexView(String id, String description) { this.id = id; this.description = description; } public String getId() { return id; } public String getDescription() { return description; } }
true
96a3b2512e4b5cec00f6d771ec84cef9282cfc67
Java
Mark-WJQ/firstTime
/com/NUH/io/TestFile2.java
UTF-8
1,842
2.890625
3
[]
no_license
package io; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 递归首先要找的条件事结束的条件 * * * * @author NUH-25 * */ public class TestFile2 { //表示文件深度 static int count = 0; public static void main(String[] args) { File file = new File("E:/workspace_juno/testProject/src/com/NUH"); getAllFile(file); //System.out.println(count); /*File[] files = file.listFiles(); for(File f : files){ System.out.println(f.getName()); }*/ } public static void getAllFile(File file){ if(file.isFile() || 0 == file.list().length){ outPuttab(count); System.out.println(file.getName()); }else{ File[] files = sortFile(file).toArray(new File[0]); outPuttab(count); System.out.println(file.getName()); for(File f : files){ // count ++; getAllFile(f); count --; } } } public static void outPuttab(int i){ for(int k = 0; k < i ; k++){ System.out.print(" "); } } public static List<File> sortFile(File file){ List<File> list = new ArrayList<File>(file.listFiles().length); File[] files1 = file.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { // TODO Auto-generated method stub if(pathname.isDirectory()) return true; return false; } }); //list.addAll(Arrays.asList()); for(File f : files1){ list.add(f); } File[] files = file.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { // TODO Auto-generated method stub if(pathname.isFile()) return true; return false; } }); for(File f : files){ list.add(f); } return list; } }
true
8fff60d8d2a25d71cea4ab08820c84b64799abf4
Java
yuliyachernook/PageObject
/src/main/java/wait/WaitForElementMethods.java
UTF-8
751
2.421875
2
[]
no_license
package wait; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; public class WaitForElementMethods { public static WebElement waitForElementLocatedBy(WebDriver driver, long time, By by) { return new WebDriverWait(driver, time) .until(ExpectedConditions.visibilityOfElementLocated(by)); } public static List<WebElement> waitForElementsLocatedBy(WebDriver driver, long time, By by) { return new WebDriverWait(driver, time) .until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)); } }
true
b9c96beb187f67d6bd14e26e0069dd75412f3720
Java
xy69/infomodsource
/src/main/java/insanusnatura/items/MysticalFlute.java
UTF-8
3,628
2.3125
2
[]
no_license
package insanusnatura.items; import insanusnatura.Main; import insanusnatura.commands.util.Teleport; import insanusnatura.init.ModCreativeTabs; import insanusnatura.init.ModItems; import insanusnatura.init.ModWorldGen; import insanusnatura.util.interfaces.IHasModel; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumHand; import net.minecraft.world.World; public class MysticalFlute extends Item implements IHasModel { private int initialCooldown = 100; private int cooldown = initialCooldown; private boolean charged = false; public MysticalFlute() { setUnlocalizedName("mysticalflute"); setRegistryName("mysticalflute"); setCreativeTab(ModCreativeTabs.MOD_TAB); maxStackSize = 1; setMaxDamage(5); ModItems.ITEMS.add(this); } @Override public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { // if player in overworld, tp to insanus natura and vice versa // only works if item is charged if (charged) { if (playerIn.dimension == 0) { Teleport.teleportToDimension(playerIn, ModWorldGen.INSANUSNATURA_DIM_ID, playerIn.getPosition().getX(), playerIn.getPosition().getY(), playerIn.getPosition().getZ()); } else if (playerIn.dimension == ModWorldGen.INSANUSNATURA_DIM_ID) { Teleport.teleportToDimension(playerIn, 0, playerIn.getPosition().getX(), playerIn.getPosition().getY(), playerIn.getPosition().getZ()); } } // use charge if rightclicked charged = false; // reset cooldown cooldown = initialCooldown; return super.onItemRightClick(worldIn, playerIn, handIn); } @Override public void registerModels() { Main.proxy.registerItemRenderer(this, 0, "inventory"); } @Override public void onUpdate(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) { // 2 states, is holding and is not holding if (isSelected && entityIn instanceof EntityPlayer) { // decrease cooldown if greater than 0 if (cooldown > 0) { cooldown--; } else { charged = true; } // give glow if charged if (charged) { if (!stack.isItemEnchanted()) stack.addEnchantment(Enchantment.getEnchantmentByID(-1), 0); } else { // remove enchantments if not charged if (stack.getTagCompound() != null) if (stack.getTagCompound().hasKey("ench")) stack.getTagCompound().removeTag("ench"); } // set durability in relation to cooldown remaining setDamage(stack, cooldown / 20); } else { // reset cooldown cooldown = initialCooldown; // set durability to full setDamage(stack, 0); // remove enchantments if any if (stack.getTagCompound() != null) if (stack.getTagCompound().hasKey("ench")) stack.getTagCompound().removeTag("ench"); // set charged to false charged = false; } super.onUpdate(stack, worldIn, entityIn, itemSlot, isSelected); } }
true
04f5a5b8a5ee602d67224a305517a5c45a6af711
Java
AmirhsseinIzadi/javaProject
/src/main/java/WildAnimal.java
UTF-8
1,851
3.34375
3
[]
no_license
import java.util.ArrayList; public class WildAnimal extends Animal { private static final ArrayList<WildAnimal> wildAnimalsInCage; private static final ArrayList<WildAnimal> wildAnimals; static { wildAnimals = new ArrayList<>(); } static { wildAnimalsInCage = new ArrayList<>(); } public boolean inCage = false; public int countForDie = 0; public int distanceOfWalk = 0; String[] names = {"Lion", "Bear", "Tiger"}; int damage = 0; public WildAnimal(String name, int health, int row, int col) { super(name, row, col); this.row = row; this.col = col; if (name.equals(names[1])) { this.damage = 100; } else if (name.equals(names[1])) { this.damage = 90; } else if (name.equals(names[2])) { this.damage = 80; } setName(name); setHealth(health); wildAnimals.add(this); } public static ArrayList<WildAnimal> getWildAnimals() { return wildAnimals; } public static ArrayList<WildAnimal> getWildAnimalInCage() { return wildAnimalsInCage; } public static WildAnimal getWildAnimalsInCageObject(ArrayList<String> bars) { for (WildAnimal wildAnimal : wildAnimalsInCage) { for (int i = 0; i < bars.size(); i++) { if (wildAnimal.getName().equalsIgnoreCase(bars.get(i))) { return wildAnimal; } } } return null; } @Override public int getRow() { return super.getRow(); } @Override public void setRow(int row) { super.setRow(row); } @Override public int getCol() { return super.getCol(); } @Override public void setCol(int col) { super.setCol(col); } }
true
c6cf2d374795462a965a221af200d3065a61e9fb
Java
PramitDutta/Coding-Practice
/src/LeetCode_Medium/CoinChange.java
UTF-8
832
3.40625
3
[]
no_license
package LeetCode_Medium; /* Let dp[v] to be the min num of coins needed to get amount v. * dp[i+a_coin]= min(dp[i+a_coin], dp[i]+1) if dp[i] is reachable * dp[i+a_coin]= dp[i+a_coin] if dp[i] is not reachable * * */ public class CoinChange { public int coinChange(int[] coins, int amount) { if (amount < 1) return 0; int[] dp = new int[amount + 1]; dp[0] = 0; // do not need any coin to get 0 amount for (int i = 1; i <= amount; i++) { dp[i] = Integer.MAX_VALUE; } for (int i = 0; i <= amount; i++) { for (int coin : coins) { if (i + coin <= amount) { if (dp[i] == Integer.MAX_VALUE) { dp[i + coin] = dp[i + coin]; } else { dp[i + coin] = Math.min(dp[i + coin], dp[i] + 1); } } } } if (dp[amount] >= Integer.MAX_VALUE) return -1; return dp[amount]; } }
true
cb8b247c572192a5311a23330baa51c604d8d83b
Java
andresbeckruiz/maps
/src/test/java/edu/brown/cs/mramesh4/stars3/StarsPBTTest.java
UTF-8
7,137
2.84375
3
[]
no_license
package edu.brown.cs.mramesh4.stars; import static org.junit.Assert.*; import org.junit.Test; import org.junit.Before; import org.junit.After; import java.util.*; import java.util.List; import java.util.ArrayList; import edu.brown.cs.mramesh4.stars.*; import edu.brown.cs.mramesh4.CSVParser.*; import edu.brown.cs.mramesh4.KDTree.*; import edu.brown.cs.mramesh4.Dimensional.*; public class StarsPBTTest { private StarsLogic _stars; private static final double DELTA = 1e-15; @Before public void setUp() { _stars = new StarsLogic(); CSVParser csv = new CSVParser(); _stars.fillStarsList(csv.parseCSV("data/stars/tie-star.csv")); } @Before public void setUp2() { _stars = new StarsLogic(); CSVParser csv = new CSVParser(); _stars.fillStarsList(csv.parseCSV("data/stars/stardata.csv")); } @After public void tearDown() { _stars = null; } @Test(timeout = 100000) public void PBTTestNearestNeighborsXYZ() { setUp(); assertEquals(_stars.getStarList().size(), 10); for(int j = 0; j < 100; j++) { double x = createInputForNeighbors(); double y = createInputForNeighbors(); double z = createInputForNeighbors(); int k = createInputForNearest(); Star toFind = _stars.findStar(x,y,z); assertNotNull(toFind); //run nearest neighbors List<Star> naive = _stars.naiveNearestNeighbors(k, x, y, z); List<Star> nonnaive = _stars.nearestNeighbors(k, x, y, z); if (k != 0) { assertFalse(naive.isEmpty()); assertFalse(nonnaive.isEmpty()); } assertEquals(naive.size(), nonnaive.size()); for (int i = 0; i < k; i++) { assertEquals(naive.get(i).calculateDistanceFromStar(toFind),nonnaive.get(i).calculateDistanceFromStar(toFind), DELTA); } } tearDown(); } @Test(timeout = 100000) public void PBTTestNearestRadiusXYZ() { setUp(); assertEquals(_stars.getStarList().size(), 10); for(int j = 0; j < 100; j++) { double x = createInputForNeighbors(); double y = createInputForNeighbors(); double z = createInputForNeighbors(); Star toFind = _stars.findStar(x,y,z); if (toFind!=null) { //assertNotNull(toFind); int r = createInputForNearest(); List<Star> naive = _stars.naiveNearestRadius(r, x, y, z); List<Star> nonnaive = _stars.nearestRadius(r, x, y, z); if (r != 0) { assertFalse(naive.isEmpty()); assertFalse(nonnaive.isEmpty()); } assertEquals(naive.size(), nonnaive.size()); for (int i = 0; i < r; i++) { assertEquals(naive.get(i).calculateDistanceFromStar(toFind), nonnaive.get(i).calculateDistanceFromStar(toFind), DELTA); } } } tearDown(); } @Test(timeout = 100000) public void PBTTestNearestRadiusXYZ2() { setUp2(); for(int j = 0; j < 2; j++) { double x = createInputForNeighbors(); double y = createInputForNeighbors(); double z = createInputForNeighbors(); Star toFind = _stars.findStar(x,y,z); if (toFind!=null) { //assertNotNull(toFind); int r = createInputForNearest(); List<Star> naive = _stars.naiveNearestRadius(r, x, y, z); List<Star> nonnaive = _stars.nearestRadius(r, x, y, z); if (r != 0) { assertFalse(naive.isEmpty()); assertFalse(nonnaive.isEmpty()); } assertEquals(naive.size(), nonnaive.size()); for (int i = 0; i < r; i++) { assertEquals(naive.get(i).calculateDistanceFromStar(toFind), nonnaive.get(i).calculateDistanceFromStar(toFind), DELTA); } } } tearDown(); } @Test(timeout = 100000) public void PBTTestNearestNeighborsXYZ2() { setUp2(); for(int j = 0; j < 2; j++) { double x = createInputForNeighbors(); double y = createInputForNeighbors(); double z = createInputForNeighbors(); Star toFind = _stars.findStar(x,y,z); if (toFind!=null) { //assertNotNull(toFind); int r = createInputForNearest(); List<Star> naive = _stars.naiveNearestNeighbors(r, x, y, z); List<Star> nonnaive = _stars.nearestNeighbors(r, x, y, z); if (r != 0) { assertFalse(naive.isEmpty()); assertFalse(nonnaive.isEmpty()); } assertEquals(naive.size(), nonnaive.size()); for (int i = 0; i < r; i++) { assertEquals(naive.get(i).calculateDistanceFromStar(toFind), nonnaive.get(i).calculateDistanceFromStar(toFind), DELTA); } } } tearDown(); } @Test(timeout = 100000) public void PBTTestNearestNeighborsName(){ setUp(); assertEquals(_stars.getStarList().size(), 10); for(int j = 0; j < 100; j++) { String name = createStarForNearest(); int k = createInputForNearest(); Star toFind = _stars.findStar(name); if(toFind!=null) { assertNotNull(toFind); //run nearest neighbors List<Star> naive = _stars.naiveNearestNeighbors(k, name); List<Star> nonnaive = _stars.nearestNeighbors(k, name); assertEquals(naive.size(), nonnaive.size()); for (int i = 0; i < k; i++) { assertEquals(naive.get(i).calculateDistanceFromStar(toFind), nonnaive.get(i).calculateDistanceFromStar(toFind), DELTA); } } } tearDown(); } @Test(timeout = 10000) public void PBTTestNearestRadius() { setUp(); for (int j = 0; j < 100; j++) { String name = createStarForNearest(); int k = createInputForNearest(); Star toFind = _stars.findStar(name); if(toFind!=null) { assertNotNull(toFind); //run nearest neighbors List<Star> naive; List<Star> nonnaive; naive = _stars.naiveNearestRadius(k, name); nonnaive = _stars.nearestRadius(k, name); assertEquals(naive.size(), nonnaive.size()); for (int i = 0; i < k; i++) { assertEquals(naive.get(i).calculateDistanceFromStar(toFind), nonnaive.get(i).calculateDistanceFromStar(toFind), DELTA); } } } tearDown(); } @Test(timeout = 100000) public void PBTTestPassNeighbors(){ setUp(); assertEquals(_stars.getStarList().size(), 10); for(int j = 0; j < 100; j++){ Star toFind = _stars.findStar(0,0,0); List<Star> naive = _stars.naiveNearestNeighbors(2, 0, 0, 0); List<Star> nonnaive = _stars.nearestNeighbors(2, 0, 0, 0); assertEquals(naive.size(), nonnaive.size()); for (int i = 0; i < 2; i++) { assertEquals(naive.get(i).calculateDistanceFromStar(toFind),nonnaive.get(i).calculateDistanceFromStar(toFind), DELTA); } } tearDown(); } public double createInputForNeighbors(){ return (double) (-500 + (Math.random() * (1000))); } public int createInputForNearest(){ return (int) Math.random() * 11; } public String createStarForNearest(){ String[] names = new String[]{"Colton", "Daphne", "Daniel", "Lulu", "Harvey", "Sweetie Pie", "Mystery", "Rocket", "Tommy", "Charli"}; int arg = (int) Math.random() * 10; return names[arg]; } }
true
98b554e49e9a74130cde15da015986ee620a8740
Java
usnistgov/elr-aphl-validation-plugins
/src/main/java/gov/nist/hit/elr/aphl/domain/Result.java
UTF-8
825
2.40625
2
[]
no_license
package gov.nist.hit.elr.aphl.domain; import java.util.List; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class Result<T> { private int count; private List<T> data; @JsonCreator public Result(@JsonProperty("count") int count, @JsonProperty("data") List<T> data) { super(); this.count = count; this.data = data; } @JsonGetter("count") public int getCount() { return count; } @JsonGetter("data") public List<T> getData() { return data; } @Override public String toString() { return "Result [count=" + count + ", data=" + data + "]"; } }
true
fa8d34f61cd95ceb92a0281b7e1ef843a7298dfb
Java
TIS2020-FMFI/rampa
/src/controllers/TechnickeUdajeController.java
UTF-8
6,945
2.453125
2
[]
no_license
package controllers; import excel.ExcelUtil; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import main.Main; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellUtil; import java.io.IOException; import java.net.URL; import java.util.*; public class TechnickeUdajeController implements Initializable { @FXML private ScrollPane scrollPane; @FXML private AnchorPane anchorPane; @FXML private VBox tableVbox; @FXML private Label appDateLb; @FXML private TextField appDateInput; @FXML private Label flowLb; @FXML private TextField flowInput; @FXML private Label heightGoodsLb; @FXML private TextField heightGoodsInput; @FXML private Label heightTruckLb; @FXML private TextField heightTruckInput; @FXML private Label length1Lb; @FXML private TextField length1Input; @FXML private Label length2Lb; @FXML private TextField length2Input; @FXML private Label exportLb; @FXML private TextField exportInput; @FXML private Label importLb; @FXML private TextField importInput; public List<Label> getLabels() { return labels; } public List<TextField> getInputs() { return inputs; } private List<Label> labels; private List<TextField> inputs; public TechnickeUdajeController() throws IOException { FXMLLoader loader = new FXMLLoader(getClass().getResource("../resources/fxml/technickeUdaje.fxml")); loader.setController(this); Main.technickeUdajeStage.setScene(new Scene(loader.load())); } public void potvrditBtnClick(MouseEvent mouseEvent) { Main.zadanieVstupovStage.show(); Main.technickeUdajeStage.hide(); } @Override public void initialize(URL url, ResourceBundle resourceBundle) { labels = new ArrayList<>( Arrays.asList(appDateLb, flowLb, exportLb, heightGoodsLb, importLb, heightTruckLb, length1Lb, length2Lb)); inputs = new ArrayList<>( Arrays.asList(appDateInput, flowInput, exportInput, heightGoodsInput, importInput, heightTruckInput, length1Input, length2Input)); } // vyexportuj tabulku technickych udajov public void writeTechnickeUdaje(Workbook workbook, Sheet sheet, int fromRow, int fromColumn) throws IOException { final int COLUMN_HEADER_SPAN = 4; // cez kolko stlpcov sa ma rozprestierat uvodny riadok "TECHNICAL CHARACTERISTICS OF THE FLOW" CellRangeAddress region = new CellRangeAddress(fromRow, fromRow, fromColumn, fromColumn + COLUMN_HEADER_SPAN); sheet.addMergedRegion(region); /* Vytvor header row, ten s napisom "TECHNICAL CHARACTERISTICS OF THE FLOW" */ Row headerRow = sheet.createRow(fromRow); //--------- vytvor style pre headerRow ---------------- Font boldFont = ExcelUtil.createBoldFont(workbook); CellStyle headerCellStyle = workbook.createCellStyle(); headerCellStyle.setFont(boldFont); headerCellStyle.setAlignment(HorizontalAlignment.CENTER); headerRow.setRowStyle(headerCellStyle); // ---------------------------------------------------- Cell cell = CellUtil.createCell(headerRow, fromColumn, "TECHNICAL CHARACTERISTICS OF THE FLOW"); cell.setCellStyle(ExcelUtil.getPreferredCellStyle(cell)); ExcelUtil.createBordersAroundRegion(region, sheet, BorderStyle.THICK); // ---------- zapis labels a inputs, ziskane z obrazovky "technicke udaje" do excelu --------------------------- final int SPACE_HEADER_ROW = 1; // medzera medzi header row a zvysnymi riadkami int rowNum = fromRow + SPACE_HEADER_ROW + 1; Row appDateAndFlowRow = sheet.createRow(fromRow + SPACE_HEADER_ROW + 1); createAppDate(appDateAndFlowRow, fromColumn, workbook); createFlow(appDateAndFlowRow, fromColumn + 3, workbook); rowNum += SPACE_HEADER_ROW + 1; Row exportGoodsRow = sheet.createRow(rowNum); createRestRows(exportGoodsRow, fromColumn, workbook, 2); createRestRows(exportGoodsRow, fromColumn + 3, workbook, 3); rowNum += 1; Row importHeightRow = sheet.createRow(rowNum); createRestRows(importHeightRow, fromColumn, workbook, 4); createRestRows(importHeightRow, fromColumn + 3, workbook, 5); rowNum += 1; Row length1Row = sheet.createRow(rowNum); createRestRows(length1Row, fromColumn + 3, workbook, 6); rowNum += 1; Row length2Row = sheet.createRow(rowNum); createRestRows(length2Row, fromColumn + 3, workbook, 7); ExcelUtil.resizeColumns(sheet, fromColumn, fromColumn + 19); ExcelUtil.createExcel("grafikon.xlsx", workbook); } public void createAppDate(Row row, int fromColumn, Workbook workbook) { Cell cellLabel = CellUtil.createCell(row, fromColumn, labels.get(0).getText()); Cell cellInput = CellUtil.createCell(row, fromColumn + 1, inputs.get(0).getText()); appDateAndFlowStyle(workbook, cellLabel, cellInput); } private void createFlow(Row row, int fromColumn, Workbook workbook) { Cell cellLabel = CellUtil.createCell(row, fromColumn, labels.get(1).getText()); Cell cellInput = CellUtil.createCell(row, fromColumn+ 1, inputs.get(1).getText()); appDateAndFlowStyle(workbook, cellLabel, cellInput); } private void appDateAndFlowStyle(Workbook workbook, Cell cellLabel, Cell cellInput) { CellStyle cellStyleLb = workbook.createCellStyle(); ExcelUtil.aplikujModrePozadieABoldText(cellStyleLb, workbook); cellLabel.setCellStyle(cellStyleLb); CellStyle cellStyleInput = workbook.createCellStyle(); ExcelUtil.aplikujModrePozadieABoldText(cellStyleInput, workbook); ExcelUtil.createBordersAroundCell(cellStyleInput, BorderStyle.THIN); cellInput.setCellStyle(cellStyleInput); CellUtil.setAlignment(cellInput, HorizontalAlignment.CENTER); } public void createRestRows(Row row, int fromColumn, Workbook workbook, int i) { Cell cellLabel = CellUtil.createCell(row, fromColumn, labels.get(i).getText()); Cell cellInput = CellUtil.createCell(row, fromColumn + 1, inputs.get(i).getText()); ExcelUtil.createBordersAroundCell(cellLabel, BorderStyle.THIN, workbook); ExcelUtil.createBordersAroundCell(cellInput, BorderStyle.THIN, workbook); CellUtil.setAlignment(cellLabel, HorizontalAlignment.CENTER); CellUtil.setAlignment(cellInput, HorizontalAlignment.CENTER); } }
true
6eac780bcbbb91d50a9db06e28e0a9fb6d12d1be
Java
printfcoder/java-micro
/core/broker/src/main/java/mu/micro/java/framework/core/broker/BrokerHelper.java
UTF-8
1,552
2.171875
2
[]
no_license
package mu.micro.java.framework.core.broker; import mu.micro.java.framework.core.codec.Marshaler; import mu.micro.java.framework.core.context.MicroContext; import mu.micro.java.framework.core.registry.Registry; public class BrokerHelper { public static SubscribeOptions newSubscribeOptions(SubscribeOption... opts) { SubscribeOptions opt = new SubscribeOptions(); opt.setAutoAck(true); for (SubscribeOption o : opts) { o.apply(opt); } return opt; } // Addrs sets the host addresses to be used by the broker public static Option addrs(String... addrs) { return o -> o.setAddrs(addrs); } // Codec sets the codec used for encoding/decoding used where // a broker does not support headers public static Option codec(Marshaler c) { return o -> o.setCodec(c); } // DisableAutoAck will disable auto acking of messages // after they have been handled. public static SubscribeOption disableAutoAck() { return o -> o.setAutoAck(false); } // Queue sets the name of the queue to share messages on public static SubscribeOption queue(String name) { return o -> o.setQueue(name); } public static Option registry(Registry r) { return o -> o.setContext(MicroContext.getContext().setValue(Constants.BROKER_REGISTRY_KEY, r)); } // Secure communication with the broker public static Option secure(boolean secure) { return o -> o.setSecure(secure); } // todo TLSConfig }
true
cc2cf58cdbcda45c1faec2b40caf3922da98eabc
Java
designomediaworks/Moviemade
/app/src/main/java/org/michaelbel/moviemade/ui/view/widget/AppBarLayoutBehavior.java
UTF-8
898
1.992188
2
[ "Apache-2.0" ]
permissive
package org.michaelbel.moviemade.ui.view.widget; import android.content.Context; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.util.AttributeSet; import android.view.View; @SuppressWarnings("all") public class AppBarLayoutBehavior extends AppBarLayout.Behavior { private boolean enabled; public AppBarLayoutBehavior(Context context, AttributeSet attrs) { super(context, attrs); } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled; } @Override public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child, View targetChild, View target, int nestedScrollAxes) { return enabled && super.onStartNestedScroll(parent, child, targetChild, target, nestedScrollAxes); } }
true
7463ca6ec9ff30ca3cf09f1a12d4c721b1f03ae2
Java
maningbo/testjavacode
/testjavacode/src/swing/test/PopupWindows.java
UTF-8
1,124
2.921875
3
[]
no_license
package swing.test; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; /** * PopupWindows.java * Description: * * CreateDate: 2016年9月11日 上午12:49:04 * @author 马宁波 */ public class PopupWindows { JFrame mainWindow; public PopupWindows(){ mainWindow = new JFrame("pop up window"); //mainWindow.setBounds(10,10,10,10); JButton JB = new JButton("PopUp"); JB.addActionListener(new creatNewWindow()); mainWindow.setVisible(true); mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainWindow.add(JB); mainWindow.pack(); } class creatNewWindow implements ActionListener{ public void actionPerformed(ActionEvent e){ new PopupWindows().mainWindow.setBounds(100,100,100,100); } } public static void main(String[] args) throws InterruptedException{ PopupWindows popupWindows = new PopupWindows(); // Thread.sleep(5000); // popupWindows.mainWindow.setVisible(false); } }
true
18ffdda09f68ce67d602921311611b8de91c13d4
Java
clgg/WorkingHelper
/niuco/src/cn/niuco/ui/bean/ProductBrief.java
UTF-8
2,660
2.265625
2
[]
no_license
package cn.niuco.ui.bean; import java.util.List; public class ProductBrief { // { // "id": 111, // "name": "HIRIS可穿戴套装", // "summary": "HIRIS支持追踪以及手势控制,是这个星球上最先进,最时尚的可穿戴计算机之一。", // "price": 0, // "fcount": 1, // "puid": 186895, // "nickname": "Star°时光", // "portrait": "http://q.qlogo.cn/qqapp/101204127/CE56A7DC0B2A6B9BE19EDAA16E6B89E1/100", // "isFavorite": false, // "photo": [ // "http://zy.lenovomm.com/images/products/wordpress_upload/2015/03/a61dd4d3-c55c-459d-9a96-78bd0af3185d_banner121.jpg", // "http://zy.lenovomm.com/images/products/wordpress_upload/2015/03/21b7b1e5-deb3-450f-af4f-e52dae5bf5fd_banner211.png", // "http://zy.lenovomm.com/images/products/wordpress_upload/2015/03/0654cc66-eab1-406d-a38e-446b76a25c10_banner321.jpg" // ] // } private int id; private String name; private String summary; private int price; private int fcount; private int puid; private String nickname; private String portrait; private boolean isFavorite; private List<String> photo; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getFcount() { return fcount; } public void setFcount(int fcount) { this.fcount = fcount; } public int getPuid() { return puid; } public void setPuid(int puid) { this.puid = puid; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPortrait() { return portrait; } public void setPortrait(String portrait) { this.portrait = portrait; } public boolean isFavorite() { return isFavorite; } public void setFavorite(boolean isFavorite) { this.isFavorite = isFavorite; } public List<String> getPhoto() { return photo; } public void setPhoto(List<String> photo) { this.photo = photo; } }
true
07ea5dcec435732963562f5e18026976e22a6cbe
Java
Haven-King/Conrad
/src/main/java/dev/inkwell/vivian/api/builders/CategoryBuilder.java
UTF-8
3,003
2.3125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2021 Haven King * * 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 dev.inkwell.vivian.api.builders; import dev.inkwell.vivian.api.context.WidgetComponentFactory; import dev.inkwell.vivian.api.screen.ConfigScreen; import dev.inkwell.vivian.api.util.Group; import dev.inkwell.vivian.api.widgets.LabelComponent; import dev.inkwell.vivian.api.widgets.SpacerComponent; import dev.inkwell.vivian.api.widgets.WidgetComponent; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import java.util.List; import java.util.function.BooleanSupplier; import java.util.function.Consumer; public class CategoryBuilder extends Group<WidgetComponentFactory> { private Runnable saveCallback = () -> { }; private BooleanSupplier condition = () -> true; public CategoryBuilder(MutableText name) { super(name); } public CategoryBuilder addTooltip(Text tooltip) { this.add(tooltip); return this; } public void addSection(Text name, List<Text> tooltips) { this.add((screen, x, y, width, consumer) -> { WidgetComponent component = new LabelComponent(screen, x, y + 20, width, 20, name.copy().styled(style -> style.withUnderline(true))).withTooltips(tooltips); consumer.accept(component); return component.getHeight() + 20; }); } public void addSection(Text name, Text... tooltips) { this.add((screen, x, y, width, consumer) -> { WidgetComponent component = new LabelComponent(screen, x, y + 20, width, 20, name.copy().styled(style -> style.withUnderline(true))).withTooltips(tooltips); consumer.accept(component); return component.getHeight() + 20; }); } public CategoryBuilder setSaveCallback(Runnable saveCallback) { this.saveCallback = saveCallback; return this; } public void setCondition(BooleanSupplier condition) { this.condition = condition; } public boolean shouldShow() { return this.condition.getAsBoolean(); } public void save() { this.saveCallback.run(); } public int build(ConfigScreen parent, int x, int width, int y, Consumer<WidgetComponent> consumer) { for (int i = 0; i < this.size(); ++i) { consumer.accept(new SpacerComponent(parent, x, y, width, 10)); y += 5; y += this.get(i).build(parent, x, y, width, consumer); } return y; } }
true
0ef8801823cc158fcba67c9601626a5808106d6b
Java
liubinchu/matching-system
/src/main/java/top/erricliu/huatai/matchingsystem/service/AddUserService.java
UTF-8
928
2.265625
2
[]
no_license
package top.erricliu.huatai.matchingsystem.service; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import top.erricliu.huatai.matchingsystem.entity.Responce; import top.erricliu.huatai.matchingsystem.entity.User; import top.erricliu.huatai.matchingsystem.repo.UserRepo; /** * @author liubi * @date 2019-10-08 15:31 **/ @Service @Log4j2 public class AddUserService { @Autowired private PreCheckService preCheckService; @Autowired private UserRepo userRepo; public Responce addUser(int money) { if (preCheckService.checkMoney(money)){ User user = new User(money); userRepo.add(user); log.info("user: "+user.toJson()); return Responce.build(2201, user); }else { return Responce.build(4202,"param: money="+money); } } }
true
36bb2b78e748bc689970e1bbd4647eafcd751b98
Java
samilathalyta/Aulas-Generation
/Dia 02.09/ex2dia0209.java
ISO-8859-1
567
3.484375
3
[]
no_license
package Dia0209; import java.util.Scanner; public class ex2dia0209 { public static void main(String[] args) { // TODO Auto-generated method stub int num,contPar=0,contImpar=0,x; Scanner leia = new Scanner(System.in); for(x=1;x<=10;x++) { System.out.println("\nInsira um nmero: "); num = leia.nextInt(); if(num % 2 == 0) { contPar++; } else { contImpar++; } } System.out.printf("\nA quantidade de nmeros pares %d.",contPar); System.out.printf("\nA quantidade de nmeros impares %d.",contImpar); } }
true
210e1dc99212ec27809e1092e32eed64250b98c4
Java
wunaixiaoguoshiye/AppInfoSystem
/src/cn/appsys/controller/develop/AppInfoController.java
UTF-8
11,349
1.8125
2
[]
no_license
package cn.appsys.controller.develop; import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import javax.mail.Multipart; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.alibaba.fastjson.JSONArray; import com.mysql.jdbc.StringUtils; import cn.appsys.pojo.AppCategory; import cn.appsys.pojo.AppInfo; import cn.appsys.pojo.DataDictionary; import cn.appsys.pojo.DevUser; import cn.appsys.service.appcategory.AppCategoryService; import cn.appsys.service.appinfo.AppinfoService; import cn.appsys.service.datadictionary.DataDictionaryService; import cn.appsys.tools.Constants; import cn.appsys.tools.PageSupport; @Controller @RequestMapping(value="/dev/flatform") public class AppInfoController { @Resource private AppinfoService appinfoService; @Resource private DataDictionaryService dataDictionaryService; @Resource private AppCategoryService appCategoryService; private Logger logger=Logger.getLogger(AppInfoController.class); //进入信息维护首页,查询app信息列表 @RequestMapping(value="/appList") public String appList(Model model,HttpSession session, @RequestParam(value="querySoftwareName",required=false) String _querySoftwareName, @RequestParam(value="queryStatus",required=false) String _queryStatus, @RequestParam(value="queryCategoryLevel1",required=false) String _queryCategoryLevel1, @RequestParam(value="queryCategoryLevel2",required=false) String _queryCategoryLevel2, @RequestParam(value="queryCategoryLevel3",required=false) String _queryCategoryLevel3, @RequestParam(value="queryFlatformId",required=false) String _queryFlatformId, @RequestParam(value="pageIndex",required=false) String _pageIndex ){ Integer devId=((DevUser)session.getAttribute(Constants.DEVUSER_SESSION)).getId(); List<AppInfo> appInfoList=null; //存储appinfo基础信息 List<DataDictionary> statusList=null; //存储app状态信息 List<DataDictionary> flatFormList=null; //存储app所属平台信息 //三级分类下拉框取值 ajax实现,选择下拉列表时获取 List<AppCategory> categorieLevel1List=null; List<AppCategory> categorieLevel2List=null; List<AppCategory> categorieLevel3List=null; //页面容量 int pageSize=Constants.pageSize; //定义当前页码 Integer currentPageNo=1; if (_pageIndex!=null) {//前台传入的页码 try { currentPageNo=Integer.valueOf(_pageIndex); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } //前台传入的值为字符串,在这里进行转换 Integer queryStatus=null; if (_queryStatus!=null && !("").equals(_queryStatus)) { queryStatus=Integer.parseInt(_queryStatus); } Integer queryCategoryLevel1=null; if (_queryCategoryLevel1!=null && !("").equals(_queryCategoryLevel1)) { queryCategoryLevel1=Integer.parseInt(_queryCategoryLevel1); } Integer queryCategoryLevel2=null; if (_queryCategoryLevel2!=null && !("").equals(_queryCategoryLevel2)) { queryCategoryLevel2=Integer.parseInt(_queryCategoryLevel2); } Integer queryCategoryLevel3=null; if (_queryCategoryLevel3!=null && !("").equals(_queryCategoryLevel3)) { queryCategoryLevel3=Integer.parseInt(_queryCategoryLevel3); } Integer queryFlatformId=null; if (_queryFlatformId!=null && !("").equals(_queryFlatformId)) { queryFlatformId=Integer.parseInt(_queryFlatformId); } //查询列表的总数量 Integer totalCount=0; try { totalCount=appinfoService.getAppInfoCount(_querySoftwareName, queryStatus, queryCategoryLevel1, queryCategoryLevel2, queryCategoryLevel3, queryFlatformId, devId); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } //总页数 PageSupport pages=new PageSupport(); pages.setCurrentPageNo(currentPageNo); pages.setPageSize(pageSize); pages.setTotalCount(totalCount); int totalPageCount=pages.getTotalPageCount(); //控制首页和尾页 if (currentPageNo<1) {//当前页码小于1 currentPageNo=1; }else if(currentPageNo>totalPageCount){//当前页码大于总页数 currentPageNo=totalPageCount; } try { appInfoList=appinfoService.getAppInfoList(_querySoftwareName, queryStatus, queryCategoryLevel1, queryCategoryLevel2, queryCategoryLevel3, queryFlatformId, devId, currentPageNo, pageSize); for (AppInfo appinfo : appInfoList) { logger.debug("所属平台:============>"+appinfo.getFlatformName()); } statusList=this.getDataDictionaryList("APP_STATUS"); flatFormList=this.getDataDictionaryList("APP_FLATFORM"); categorieLevel1List=appCategoryService.getAppCategoryListByParentId(null); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } model.addAttribute("appInfoList",appInfoList); model.addAttribute("statusList",statusList); model.addAttribute("flatFormList",flatFormList); model.addAttribute("categorieLevel1List",categorieLevel1List); model.addAttribute("pages",pages); model.addAttribute("queryStatus",queryStatus); model.addAttribute("_querySoftwareName",_querySoftwareName); model.addAttribute("queryCategoryLevel1",queryCategoryLevel1); model.addAttribute("queryCategoryLevel2",queryCategoryLevel2); model.addAttribute("queryCategoryLevel3",queryCategoryLevel3); model.addAttribute("queryFlatformId",queryFlatformId); return "developer/appinfolist"; } //根据类型编号查询对应数据字典,所属平台列表 public List<DataDictionary> getDataDictionaryList(String Code){ List<DataDictionary> dataDictionariesList=null; try { dataDictionariesList=dataDictionaryService.getDataDictionaryList(Code); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return dataDictionariesList; } //根据根据上一级的级别分类,查询下一级的级别分类,ajax @RequestMapping(value="categorylevellist.json",method=RequestMethod.GET) @ResponseBody public List<AppCategory> getAppCategoryList(@RequestParam("pid")String pid){ List<AppCategory> appCategoryList=null; try { logger.debug("pid==========>"+pid); appCategoryList=appCategoryService.getAppCategoryListByParentId(pid==null||pid.equals("")?null:Integer.parseInt(pid)); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return appCategoryList; } //进入添加APP信息页面 @RequestMapping(value="/appinfoadd",method=RequestMethod.GET) public String addAppInfoList(@ModelAttribute("apppInfo")AppInfo appInfo){ return "developer/appinfoadd"; } //ajax后台验证--APKName是否已存在 @RequestMapping(value="apkexist.json") @ResponseBody public Object apkNameIsExist(@RequestParam String APKName){ HashMap<String,String> resultMap=new HashMap<String, String>(); if (StringUtils.isNullOrEmpty(APKName)) {//是空值 resultMap.put("APKName","empty"); }else { AppInfo appInfo=null; appInfo=appinfoService.getAppInfoByApkName(null, APKName);//根据apkName查询是否重复信息 if (appInfo!=null) {//重复 resultMap.put("APKName","exist"); }else { resultMap.put("APKName","noexist"); } } return JSONArray.toJSONString(resultMap);//返回json对象 } /** * ajax进入添加app信息页面时加载所属平台列表 * @param tcode * @return */ @RequestMapping(value="datadictionarylist.json",method=RequestMethod.GET) @ResponseBody public List<DataDictionary> datadictionarylist(@RequestParam String tcode){ return this.getDataDictionaryList(tcode); } /** * 保存新增的数据 * */ @RequestMapping(value="appinfoaddsave",method=RequestMethod.POST) public String appinfoaddsave(AppInfo appInfo,HttpSession session, HttpServletRequest request, @RequestParam(value="a_logoPicPath",required=false) MultipartFile attach){ String logoPicPath=null; String logoLocPath=null; if (!attach.isEmpty()) { String path=request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles"); logger.debug("文件保存路径=============》"+path); String oldFileName=attach.getOriginalFilename();//原文件名 String prifix=FilenameUtils.getExtension(oldFileName);//文件后缀 int filesize=500000; if (attach.getSize()>filesize) {//文件大小不能超过50k request.setAttribute("fileUploadError", "上传大小不得超过500kb"); return "developer/appinfoadd"; }else if (prifix.equalsIgnoreCase("jpg") || prifix.equalsIgnoreCase("png") || prifix.equalsIgnoreCase("jepg") || prifix.equalsIgnoreCase("pneg")) {//文件上传格式 String fileName=appInfo.getAPKName()+"jpg";//上传logo图片名:apk名称 File file=new File(path,fileName); if (!file.exists()) { file.mkdirs(); } try { attach.transferTo(file); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); request.setAttribute("fileUploadError", "上传失败!"); } //LOGO图片url路径 logoPicPath=request.getContextPath()+"/statics/uploadfiles/"+fileName; //LOGO图片的服务器存储路径 logoLocPath=path+File.separator+fileName; }else { request.setAttribute("fileUploadError","文件格式不正确"); return "developer/appinfoadd"; } } appInfo.setCreatedBy(((DevUser)session.getAttribute(Constants.DEVUSER_SESSION)).getId()); appInfo.setCreationDate(new Date()); appInfo.setLogoLocPath(logoLocPath); appInfo.setLogoPicPath(logoPicPath); appInfo.setDevId(((DevUser)session.getAttribute(Constants.DEVUSER_SESSION)).getId()); appInfo.setStatus(1); try { if (appinfoService.add(appInfo)>0) {//新增app信息 return "redirect:/dev/flatform/appList"; } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return "developer/appinfoadd"; } //进入修改app基础信息页面,根据app信息id和未审核,审核未通过进行查找 @RequestMapping(value="/appinfomodify",method=RequestMethod.GET) public String appversionmodify(@RequestParam("id") String id,Model model){ AppInfo appInfo=null; try { //根据id查询app信息 appInfo=appinfoService.getAppInfoByApkName(Integer.parseInt(id), null); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } model.addAttribute("appInfo",appInfo); return "developer/appinfomodify"; } }
true
4e97b907f1876fa219145fbe79d333c169ebd821
Java
DaniCampos/cc3002-tarea2
/cc3002-tarea2/src/model/card/type/WildCard.java
UTF-8
926
3.09375
3
[]
no_license
package model.card.type; import controller.IController; import model.IGameLogic; /** * Class that implements the constructor and methods associated to the WildCard, extends Abstract Card * * @author Daniela Campos */ public class WildCard extends AbstractCard { /** * Constructor of an object of the WildCard Class * * @param color color of the card */ public WildCard() { this.symbol = Symbol.WILD; this.color = Color.NONE; } @Override public String toString() { return this.getSymbol().toString(); } @Override public boolean isFirstPlayable() { return false; } @Override public void executeAction(IGameLogic game, IController ctrl) { ctrl.showMessage("Se jugó" + " " + this.getSymbol().toString()); this.setColor(game.getCurrentPlayer().selectColor(game, ctrl)); ctrl.showMessage("Color elegido " + this.getColor().toString()); } }
true
91dea7c362cd3e6d83353a91d85dc812f25016f8
Java
iotsap/ngsi10testserver
/TestClientToNGSI10TestServer/src/test/java/com/sap/research/fiware/ngsi10/test/updatecontextsubscription/TestUnallowedMethodsOnUpdateContextSubscription.java
UTF-8
1,173
2.03125
2
[ "BSD-3-Clause" ]
permissive
package com.sap.research.fiware.ngsi10.test.updatecontextsubscription; import java.net.HttpURLConnection; import org.junit.Test; import com.sap.research.fiware.ngsi10.test.Constants; import com.sap.research.fiware.ngsi10.test.HttpRequestBuilder; import com.sap.research.fiware.ngsi10.test.TestHelpers; public class TestUnallowedMethodsOnUpdateContextSubscription { @Test public void getOnUpdateContextSubscriptionMustResultInNotAllowed() throws Exception { HttpURLConnection conn = HttpRequestBuilder.GET .url(Constants.URL_UDATE_CONTEXT_SUBSCRIPTION) .build(); TestHelpers.assertMethodNotAllowed(conn, "POST"); } @Test public void putOnUpdateContextSubscriptionMustResultInNotAllowed() throws Exception { HttpURLConnection conn = HttpRequestBuilder.PUT .url(Constants.URL_UDATE_CONTEXT_SUBSCRIPTION) .build(); TestHelpers.assertMethodNotAllowed(conn, "POST"); } @Test public void deleteOnUpdateContextSubscriptionMustResultInNotAllowed() throws Exception { HttpURLConnection conn = HttpRequestBuilder.DELETE .url(Constants.URL_UDATE_CONTEXT_SUBSCRIPTION) .build(); TestHelpers.assertMethodNotAllowed(conn, "POST"); } }
true
2f200252c335480799ccbd088e265b757806d89f
Java
pravinkumarbala/everydayprogram
/EveryDayProgram/src/com/everyday/Datastructures/Array/WaveformSort.java
UTF-8
935
3.921875
4
[]
no_license
package com.everyday.Datastructures.Array; import java.util.Arrays; import java.util.Scanner; public class WaveformSort { public void swap(int[] arr, int a , int b){ int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } public void sortInWave(int[] arr){ Arrays.sort(arr); for (int i = 0 ; i < arr.length - 1; i += 2) swap(arr, i, i + 1); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); WaveformSort obj = new WaveformSort(); System.out.println("Enter the Array Size : "); int size = scanner.nextInt(); int[] arrVal = new int[size]; System.out.println("Enter the Array values : "); for (int i = 0 ; i < size; i ++) arrVal[i] = scanner.nextInt(); obj.sortInWave(arrVal); for (int i : arrVal) System.out.print(i + ", "); } }
true
192580effec5a7b6a65e32b8bcb4cea0e3d8f740
Java
ligayan/JAVA
/Rozdział 6 - Wprowadzenie do klas/src/BoxDemo4.java
WINDOWS-1250
392
3.125
3
[]
no_license
public class BoxDemo4 { public static void main(String[] args) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; mybox1.setDim(20, 15, 5); mybox2.setDim(3, 6, 9); vol = mybox1.volumeRet(); System.out.println("Objto pudeka 1 = "+ vol); vol = mybox2.volumeRet(); System.out.println("Objto pudeka 1 = "+ vol); } }
true
1aeac5f805d1cdf888f5387802ca0434161f5e26
Java
chy123chy/FinalHuluwa
/FinalHuluwa/src/main/java/Gourd.java
UTF-8
340
2.078125
2
[]
no_license
import java.io.Serializable; import java.util.Random; public class Gourd extends GPlayer implements Serializable { private static final long serialVersionUID = -66019032085567574L; int rank; public Gourd(int x, int y, int rank, Field field) { super(x, y, 4, 6, rank+".png", field); this.rank = rank; } }
true
27ddf55bca241df5d829f0dc7d61572606a595e1
Java
camilap04/quiz1
/src/vista/main.java
UTF-8
393
1.914063
2
[]
no_license
package vista; import control.control; import processing.core.PApplet; public class main extends PApplet{ public static void main(String[] args) { PApplet.main(main.class.getName()); } public control control; public void settings() { size (800, 600); } public void setup () { control = new control(this); } public void draw () { background(0); control.pintar(); } }
true
06686f2b08f92bfdfb9636bdb0863798c80b6634
Java
lazycat-java/crotg-pay-master
/pay-service-test/src/main/java/com/crotg/pay/service/test/facaed/PayUserFacaedImpl.java
UTF-8
812
1.851563
2
[]
no_license
package com.crotg.pay.service.test.facaed; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.crotg.pay.facaed.test.facaed.PayUserFacaed; import com.crotg.pay.facaed.test.po.PayUser; import com.crotg.pay.service.test.service.PayUserService; @Path("users") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) @Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) public class PayUserFacaedImpl implements PayUserFacaed { @Autowired PayUserService payUserService; @Override public PayUser selectOne(long id) { // TODO Auto-generated method stub return payUserService.selectOne(id); } }
true
ef072cfa3fedaa72b2da1adbe88136ef6f242840
Java
asd80672315/smart
/src/com/zhzg/track/GetParameters.java
UTF-8
1,681
2.484375
2
[]
no_license
package com.zhzg.track; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.EnumMap; import com.zhzg.util.JDBCUtil; public class GetParameters implements ParaEnum { @Override public EnumMap<UserInfo, Object> getUserInfoByName(String SmartBallID) { EnumMap<UserInfo,Object> retMap = new EnumMap<UserInfo, Object>(UserInfo.class); retMap.put(UserInfo.SmartBallID,SmartBallID); //读数据库 Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql_1 = "SELECT ReservationID,startTime,endTime, FROM Visitors WHERE SmartBallID=? AND State=2"; String sql_2 = "SELECT SmartBallMAC FROM BallProperty WHERE SmartBallID=? "; try { conn = JDBCUtil.getConnection(); pstmt = conn.prepareStatement(sql_1); pstmt.setString(1,SmartBallID); rs = pstmt.executeQuery(); if(rs.next()){ retMap.put(UserInfo.ReservationID, rs.getInt("ReservationID")); retMap.put(UserInfo.startTime, rs.getDate("startTime")); retMap.put(UserInfo.endTime, rs.getDate("endTime")); } JDBCUtil.closePrepareStatement(pstmt); pstmt = conn.prepareStatement(sql_2); pstmt.setString(1,SmartBallID); if(rs.next()){ retMap.put(UserInfo.MAC, rs.getString("SmartBallMAC")); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtil.closeResultSet(rs); JDBCUtil.closePrepareStatement(pstmt); JDBCUtil.closeConnection(conn); } return retMap; } }
true
a3e7517094cf33dfd2761e475490afb62b939397
Java
UnicornTeamAreWe/PDMA
/code/PDMA_back/src/main/java/com/PDMA/service/WeiboService.java
UTF-8
190
1.710938
2
[]
no_license
package com.PDMA.service; import com.PDMA.entity.Weibo; import org.springframework.stereotype.Service; @Service public interface WeiboService { Weibo getWeibo(Long userId); }
true
08078abbf2ac19535abf7a3394679240d8309aaa
Java
Votrungtin2001/Food-Application-MobileProgramming
/app/src/main/java/com/example/foodapplication/account/fragment/AccountSettingsInfoOccupationFragment.java
UTF-8
7,255
2
2
[]
no_license
package com.example.foodapplication.account.fragment; import android.app.ProgressDialog; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.foodapplication.MainActivity; import com.example.foodapplication.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import static com.example.foodapplication.mySQL.MySQLQuerry.UpdateCustomerOccupation; public class AccountSettingsInfoOccupationFragment extends Fragment { TextView txtOccupationOffice, txtOccupationFree, txtOccupationStudent, txtOccupationHome, txtOccupationOther; int user_id = -1; String occupation = ""; private final String TAG = "AccountSettingIOF"; public AccountSettingsInfoOccupationFragment() { } public static AccountSettingsInfoOccupationFragment newInstance() { return new AccountSettingsInfoOccupationFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (MainActivity.customer_id > 0) user_id = MainActivity.customer_id; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_account_settings_info_occupation, container, false); Toolbar toolbar = view.findViewById(R.id.toolbar); ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar); ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.activity_account_settings_account_info_occupation)); toolbar.setNavigationOnClickListener(v -> { FragmentManager fragmentManager = getParentFragmentManager(); fragmentManager.popBackStack(null, 0); }); txtOccupationOffice = view.findViewById(R.id.txtOccupationOffice); txtOccupationOffice.setOnClickListener(onTextViewClick); txtOccupationFree = view.findViewById(R.id.txtOccupationFree); txtOccupationFree.setOnClickListener(onTextViewClick); txtOccupationStudent = view.findViewById(R.id.txtOccupationStudent); txtOccupationStudent.setOnClickListener(onTextViewClick); txtOccupationHome = view.findViewById(R.id.txtOccupationHome); txtOccupationHome.setOnClickListener(onTextViewClick); txtOccupationOther= view.findViewById(R.id.txtOccupationOther); txtOccupationOther.setOnClickListener(onTextViewClick); final ProgressDialog progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("Xin vui lòng chờ trong giây lát..."); progressDialog.show(); GetCustomerOccupation(user_id, progressDialog); return view; } View.OnClickListener onTextViewClick = v -> { if (user_id != -1) { TextView view = (TextView) v; final ProgressDialog progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("Xin vui lòng chờ trong giây lát..."); progressDialog.show(); UpdateCustomerOccupation(user_id, view.getText().toString(), progressDialog, TAG, getActivity()); FragmentManager fragmentManager = getParentFragmentManager(); fragmentManager.popBackStack(null, 0); } }; private void GetCustomerOccupation(int id, ProgressDialog progressDialog) { String url = "https://foodapplicationmobile.000webhostapp.com/getCustomerAccountInformation.php"; StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { progressDialog.dismiss(); try { JSONObject jsonObject = new JSONObject(response); String success = jsonObject.getString("success"); JSONArray jsonArray = jsonObject.getJSONArray("data"); if(success.equals("1")) { for(int i = 0; i < jsonArray.length(); i++) { JSONObject object = jsonArray.getJSONObject(i); occupation = object.getString("OCCUPATION"); if(!occupation.trim().equals("null") && !occupation.trim().equals("")) { switch (occupation) { case "Văn phòng": txtOccupationOffice.setBackgroundColor(getResources().getColor(R.color.quantum_bluegrey400)); break; case "Tự kinh doanh/Tự do": txtOccupationFree.setBackgroundColor(getResources().getColor(R.color.quantum_bluegrey400)); break; case "Sinh viên": txtOccupationStudent.setBackgroundColor(getResources().getColor(R.color.quantum_bluegrey400)); break; case "Ở nhà": txtOccupationHome.setBackgroundColor(getResources().getColor(R.color.quantum_bluegrey400)); break; case "Khác": txtOccupationOther.setBackgroundColor(getResources().getColor(R.color.quantum_bluegrey400)); break; } } } } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); Log.e(TAG, error.toString()); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("customer_id", String.valueOf(id)); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); requestQueue.add(request); } }
true
c6f3e77cb81dfb73128394eefdd1fbb02ea7d6f8
Java
kechoplay/Project-SEM2
/ComputerManagement/ComputerManagement/src/Product/FunctionProduct.java
UTF-8
2,706
2.53125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Product; import DatabaseConnection.Connects; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import Form.*; import Product.*; /** * * @author Admin */ public class FunctionProduct extends Connects { public static PreparedStatement pst; public static Statement st; public static ResultSet rs; public static Connection con = Connects.open(); public static void InsertPro(String proid, String proname, String photo, String price, String groid, String supid) { String sql = "INSERT INTO Product (Pro_ID,Pro_Name,Pro_Photo,Pro_Price,Gro_ID,Sup_ID) VALUES (?, ?,?,?,?,?)"; try { pst = con.prepareStatement(sql); pst.setString(1, proid); pst.setString(2, proname); pst.setString(3, photo); pst.setString(4, price); pst.setString(5, groid); pst.setString(6, supid); pst.executeUpdate(); JOptionPane.showMessageDialog(null, " added product success ", "Notification", 1); } catch (SQLException ex) { Logger.getLogger(FunctionProduct.class.getName()).log(Level.SEVERE, null, ex); } } public static void UpdatePro(String proid1, String proid, String proname, String photo, String price, String groid, String supid) { String sql = "UPDATE Product SET Pro_ID='" + proid + "', Pro_Name='" + proname + "', Pro_Photo='" + photo + "', Pro_Price='" + price + "'" + ", Gro_ID='" + groid + "', Sup_ID='" + supid + "' WHERE Pro_ID='" + proid1 + "'"; try { pst = con.prepareStatement(sql); pst.executeUpdate(); JOptionPane.showMessageDialog(null, "Update success", "Notification", 1); } catch (SQLException ex) { Logger.getLogger(FunctionProduct.class.getName()).log(Level.SEVERE, null, ex); } } public static void DeletePro(String proid) { String sql = "DELETE FROM Product WHERE Pro_ID='" + proid + "'"; try { pst = con.prepareStatement(sql); pst.executeUpdate(); JOptionPane.showMessageDialog(null, "removed successfully ", "Notification", 1); } catch (SQLException ex) { Logger.getLogger(FunctionProduct.class.getName()).log(Level.SEVERE, null, ex); } } }
true
49d143751859a82e1be80b3a73cbc20c98694f5e
Java
rzalegal/projecteuler
/src/main/java/projecteuler/util/log/Log.java
UTF-8
130
1.75
2
[]
no_license
package projecteuler.util.log; /** * @author Vladislav Simanov * 11.03.2021 */ public interface Log { void write(String output); }
true
2b65721a9e9214fb85a7e6a79f4b8c4567411515
Java
zhouxianjun/trc-java
/src/main/java/com/gary/trc/annotation/ThriftFilter.java
UTF-8
284
1.585938
2
[]
no_license
package com.gary.trc.annotation; import java.lang.annotation.*; /** * @author zhouxianjun(Gary) * @ClassName: * @Description: * @date 17-5-9 下午4:11 */ @Inherited @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ThriftFilter { }
true
472f21dd1cdcc6e1f59fc90d447421d4863c82f3
Java
harchani-ritik/skunkworks-crow
/skunkworks_crow/src/main/java/org/odk/share/adapters/basecursoradapter/ItemClickListener.java
UTF-8
156
1.671875
2
[ "Apache-2.0" ]
permissive
package org.odk.share.adapters.basecursoradapter; public interface ItemClickListener { void onItemClick(BaseCursorViewHolder holder, int position); }
true
be12bd45a898694fee32ceabf2ee69050ebf6e3e
Java
youkiaaa/bbs-
/src/main/java/com/atyume/modules/system/service/MoneyLogService.java
UTF-8
270
1.609375
2
[ "Apache-2.0" ]
permissive
package com.atyume.modules.system.service; import com.atyume.modules.base.service.IService; import com.atyume.modules.system.po.MoneyLog; public interface MoneyLogService extends IService<MoneyLog> { public void transfer(Long posuser,Long quauser,Double money); }
true
a89d82d64d1a18daeecc1087749775410ab4d1a8
Java
venu410/Microservices
/Cart-Service/src/main/java/venu/in/coding/microservices/cart/RibbonConfiguration.java
UTF-8
248
1.609375
2
[]
no_license
package venu.in.coding.microservices.cart; import org.springframework.context.annotation.Configuration; @Configuration public class RibbonConfiguration { /* * @Bean public IRule ribbonRule() { return new WeightedResponseTimeRule(); } */ }
true
03af695661ee43d9cb3e80dda514eae0c029e6ef
Java
sptrakesh/sptrwt
/src/app/com/sptci/rwt/webui/model/SequenceView.java
UTF-8
1,854
2.21875
2
[ "Apache-2.0" ]
permissive
package com.sptci.rwt.webui.model; import nextapp.echo2.app.Component; import nextapp.echo2.app.Grid; import echopointng.GroupBox; import com.sptci.echo2.Configuration; import com.sptci.rwt.SequenceMetaData; /** * A view component used to display the information contained in * {@link com.sptci.rwt.SequenceMetaData}. * * <p>&copy; Copyright 2007 Sans Pareil Technologies, Inc.</p> * @author Rakesh Vidyadharan 2007-10-07 * @version $Id: SequenceView.java 3577 2007-10-08 04:02:38Z rakesh $ */ public class SequenceView extends AbstractView { /** The meta data object whose details are to be displayed. */ private final SequenceMetaData metaData; /** * Create a new instance of the view using the specified model object. * * @param metaData The {@link #metaData} model object to use. */ public SequenceView( final SequenceMetaData metaData ) { this.metaData = metaData; } /** * Lifecycle method used to initialise component when added to a * container hierarchy. * * @see #createDetails */ @Override public void init() { removeAll(); add( createDetails() ); } /** * Create the component used to display the default limits enforced by * the database engine. * * @see #createLabels * @return The component that displays the limits information. */ protected Component createDetails() { Grid grid = new Grid(); createLabels( "name", metaData, grid ); createLabels( "dataType", metaData, grid ); createLabels( "minimum", metaData, grid ); createLabels( "maximum", metaData, grid ); createLabels( "increment", metaData, grid ); createLabels( "cyclePolicy", metaData, grid ); createLabels( "comment", metaData, grid ); GroupBox box = new GroupBox( Configuration.getString( this, "title" ) ); box.add( grid ); return box; } }
true
ff2a70a5298194fb435964d9f8fd736dd72221a8
Java
Teo-BH/android-study-jam
/projects/TickTockClock/app/src/main/java/br/com/teobaldo/ticktockclock/MinuteCountActivity.java
UTF-8
2,329
2.5625
3
[]
no_license
package br.com.teobaldo.ticktockclock; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; public class MinuteCountActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_minute_count); this.linkViews(); this.changeClockImage(); } private void linkViews() { this.imageView = (ImageView)findViewById(R.id.clock_image_view); this.textView = (TextView)findViewById(R.id.description_text_view); } private ImageView imageView; private TextView textView; int []imageArray = { R.drawable.clock_minute_00, R.drawable.clock_minute_05, R.drawable.clock_minute_10, R.drawable.clock_minute_15, R.drawable.clock_minute_20, R.drawable.clock_minute_25, R.drawable.clock_minute_30, R.drawable.clock_minute_35, R.drawable.clock_minute_40, R.drawable.clock_minute_45, R.drawable.clock_minute_50, R.drawable.clock_minute_55 }; int []textArray = { R.string.minute_zero, R.string.minute_five, R.string.minute_ten, R.string.minute_fifteen, R.string.minute_twenty, R.string.minute_twenty_five, R.string.minute_thirty, R.string.minute_thirty_five, R.string.minute_fourty, R.string.minute_fourty_five, R.string.minute_fifty, R.string.minute_fifty_five }; private void changeClockImage() { final Handler handler = new Handler(); Runnable runnable = new Runnable() { int i=0; public void run() { imageView.setImageResource(imageArray[i]); textView.setText(textArray[i]); i++; if(i>imageArray.length-1) { i=0; } handler.postDelayed(this, 3000); //for interval... } }; handler.postDelayed(runnable, 5000); //for initial delay.. } }
true
d804ac6cf682e03b26fe801c025a0bca9be7c323
Java
subhagho/codekutter
/common-lib/src/main/java/com/codekutter/common/stores/IDGenerator.java
UTF-8
6,370
1.875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (2020) Subhabrata Ghosh (subho dot ghosh at outlook dot com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.codekutter.common.stores; import com.codekutter.common.model.IEntity; import com.codekutter.common.stores.annotations.EGeneratedType; import com.codekutter.common.stores.annotations.GeneratedId; import com.codekutter.common.utils.LogUtils; import com.codekutter.common.utils.ReflectionUtils; import com.codekutter.common.utils.TypeUtils; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import org.hibernate.Session; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.MySQLDialect; import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.engine.spi.SessionFactoryImplementor; import javax.annotation.Nonnull; import javax.persistence.EmbeddedId; import javax.persistence.Id; import javax.persistence.Query; import java.lang.reflect.Field; import java.math.BigInteger; import java.util.List; import java.util.UUID; public class IDGenerator { public static void process(@Nonnull IEntity<?> entity, @Nonnull Session session) throws DataStoreException { Field[] fields = ReflectionUtils.getAllFields(entity.getClass()); if (fields != null && fields.length > 0) { for (Field field : fields) { if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)) { process(entity, field, session); break; } } } } public static void process(@Nonnull IEntity<?> entity, @Nonnull Field field, @Nonnull Session session) throws DataStoreException { Preconditions.checkArgument(field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)); try { if (field.isAnnotationPresent(Id.class)) { if (field.isAnnotationPresent(GeneratedId.class)) { GeneratedId gi = field.getAnnotation(GeneratedId.class); if (gi.type() == EGeneratedType.UUID) { ReflectionUtils.setObjectValue(entity, field, UUID.randomUUID().toString()); } else { Long value = nextSequenceValue(gi.sequence(), session); if (value != null) { ReflectionUtils.setObjectValue(entity, field, value); } } } } else { Class<?> type = field.getType(); Field[] fields = ReflectionUtils.getAllFields(type); if (fields != null && fields.length > 0) { for (Field f : fields) { if (f.isAnnotationPresent(GeneratedId.class)) { Object fv = ReflectionUtils.getFieldValue(entity, field); if (fv == null) { fv = TypeUtils.createInstance(field.getType()); ReflectionUtils.setObjectValue(entity, field, fv); } GeneratedId gi = f.getAnnotation(GeneratedId.class); if (gi.type() == EGeneratedType.UUID) { ReflectionUtils.setObjectValue(fv, f, UUID.randomUUID().toString()); } else { Long value = nextSequenceValue(gi.sequence(), session); if (value != null) { ReflectionUtils.setObjectValue(fv, f, value); } } break; } } } } } catch (Exception ex) { throw new DataStoreException(ex); } } private static Long nextSequenceValue(String sequence, Session session) throws DataStoreException { Preconditions.checkArgument(!Strings.isNullOrEmpty(sequence)); String sql = null; Dialect dialect = ((SessionFactoryImplementor) session.getSessionFactory()).getJdbcServices().getDialect(); if (dialect == null) { throw new DataStoreException("Error getting SQL dialect from Session..."); } if (dialect instanceof MySQLDialect) { sql = String.format("SELECT NEXT VALUE FOR %s", sequence); } else if (dialect instanceof Oracle8iDialect) { sql = String.format("SELECT %s.nextval FROM dual", sequence); } else { throw new DataStoreException( String.format("DB Dialect not supported for Generated ID. [dialect=%s]", dialect.getClass().getCanonicalName())); } Long value = null; if (!Strings.isNullOrEmpty(sql)) { Query query = session.createNativeQuery(sql); List<Object> result = query.getResultList(); if (result != null && !result.isEmpty()) { Object ret = result.get(0); if (ret instanceof BigInteger) { value = ((BigInteger) ret).longValue(); } else if (ret instanceof Long) { value = (Long) ret; } else if (ret instanceof Integer) { value = Long.valueOf((Integer) ret); } } } if (value == null) { throw new DataStoreException( String.format("Error fetching sequence value. [dialect=%s][sequence=%s]", dialect.getClass().getCanonicalName(), sequence)); } LogUtils.debug(IDGenerator.class, String.format("Fetched Sequence :[%s=%d]", sequence, value)); return value; } }
true
aac3447af9743ca7e0028ef0a7d5e97675c6346f
Java
mayuri5401/ChatBuddy
/app/src/main/java/com/example/chatbuddy/MainActivity.java
UTF-8
1,851
1.921875
2
[]
no_license
package com.example.chatbuddy; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.TextView; import com.airbnb.lottie.LottieAnimationView; public class MainActivity extends AppCompatActivity { private static int splash_timer = 3000; TextView powerByLine; //animation Animation sideanim, bottomanim; LottieAnimationView lottieAnimationView; TextView txt1, txt2, manu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); lottieAnimationView = findViewById(R.id.lottie); manu = findViewById(R.id.txtmanu); txt1 = findViewById(R.id.txt1); txt2 = findViewById(R.id.text2); //animation sideanim = AnimationUtils.loadAnimation(this, R.anim.side_anim); bottomanim = AnimationUtils.loadAnimation(this, R.anim.bottom_anim); lottieAnimationView.setAnimation(sideanim); manu.setAnimation(bottomanim); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(MainActivity.this, loginacitivity.class); startActivity(intent); finish(); } }, splash_timer); } }
true
4ef24cc9507e498301fff8702c64a8563e3ed88c
Java
mussa1996/Registration_management
/src/assignment/model/Faculty.java
UTF-8
1,030
2.328125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package assignment.model; import java.util.List; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; /** * * @author Mussa */ @Entity public class Faculty { @Id private String nfaculty; @OneToMany(mappedBy ="faculty" ) private List<Department> department; public String getNfaculty() { return nfaculty; } public void setNfaculty(String name_faculty) { this.nfaculty = name_faculty; } public List<Department> getDepartment() { return department; } public void setDepartment(List<Department> department) { this.department = department; } public Faculty(String nfaculty) { this.nfaculty = nfaculty; } public Faculty() { } }
true
9d2dfdac9452166b4be703e3fdea80746842162b
Java
airwide-store/bpmn2bpel
/org.opentosca.bpmn2bpel.converter/src/main/java/org/opentosca/bpmn2bpel/converter/Utils.java
UTF-8
4,535
2.8125
3
[ "Apache-2.0" ]
permissive
package org.opentosca.bpmn2bpel.converter; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.bpel.model.Condition; import org.eclipse.bpmn2.Expression; import org.eclipse.bpmn2.FormalExpression; import org.jbpt.graph.algo.rpst.RPSTNode; import org.jbpt.graph.algo.tctree.TCType; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; public class Utils { private static final XLogger logger = XLoggerFactory.getXLogger(Utils.class); /** * @return We need an ArrayList as the calling method checks with the index * if a last element is a sequence is found */ static ArrayList<RPSTNode> organizeRPST(RPSTNode parent, ArrayList<RPSTNode> children) { String rootName = ""; RPSTNode n = null; ArrayList<RPSTNode> childrenf = new ArrayList<RPSTNode>(); Set<RPSTNode> RPSTset = null; RPSTNode actualNode = null; // The Parent node is analyzed, when its of type Bond the order isn't // important if (parent.getType().equals(TCType.B)) { return children; } else { Map<String, Set<RPSTNode>> entry = new Hashtable<String, Set<RPSTNode>>(); // Fill Hash for (Object e : children) { n = (RPSTNode) e; String startn = n.getEntry().getName(); if (!entry.containsKey(startn)) { entry.put(startn, new HashSet<RPSTNode>()); } entry.get(startn).add(n); } // Get the name of the entry node rootName = parent.getEntry().getName(); // Organize the elements and add them to a list while (!rootName.equals(parent.getExit().getName())) { RPSTset = entry.get(rootName); Iterator<RPSTNode> it = RPSTset.iterator(); // First of all the cyclic components (if any) are added while (it.hasNext()) { actualNode = it.next(); if (rootName.equals(actualNode.getExit().getName())) { childrenf.add(actualNode); RPSTset.remove(actualNode); } } // Then the other. it = RPSTset.iterator(); while (it.hasNext()) { actualNode = it.next(); childrenf.add(actualNode); } rootName = actualNode.getExit().getName(); } return childrenf; // codigo nuevo**** } } private static String convertExpressionToString(Expression expression) { String res; if (expression instanceof FormalExpression) { Utils.logger.debug("Hit formal expression"); FormalExpression formalExpression = (FormalExpression) expression; res = formalExpression.getBody(); } else { Utils.logger.debug("Hit non-formal expression"); // in non-formal expressions, the "natural language text is captured using the documentation attribute" (BPMN // Spec 2.0, 8.3.6) List<org.eclipse.bpmn2.Documentation> documentation = expression.getDocumentation(); StringBuilder sb = new StringBuilder(); for (org.eclipse.bpmn2.Documentation doc : documentation) { sb.append(doc.getText()); } res = sb.toString(); if (res.isEmpty()) { Utils.logger.debug("Hit empty condition. Possibly, an invalid BPMN produced by Yaoqiang BPMN Editor 2.1.16 is used."); } } return res; } /** * @param expression * @return null if expression does not exist or is empty */ public static Condition convertExpressionToCondition(Expression expression) { if (expression == null) { return null; } String body = Utils.convertExpressionToString(expression); if (body.isEmpty()) { return null; } else { Condition cond = BPMNProcessTree.getBPELFactory().createCondition(); cond.setBody(body); return cond; } } /** * Converts a BPMN expression to a BPEL expression */ public static org.eclipse.bpel.model.Expression convertExpressionToExpression(org.eclipse.bpmn2.Expression expression) { org.eclipse.bpel.model.Expression res; if (expression == null) { res = null; } else { res = BPMNProcessTree.getBPELFactory().createExpression(); String body = Utils.convertExpressionToString(expression); res.setBody(body); } return res; } /** * * @param wfNode the current wfNode * @param activity the BPEL activity already converted based on bpmnTask, * this is MODIFIED */ public static void copyName(final WFNode wfNode, final org.eclipse.bpel.model.Activity bpelActivity) { String name = wfNode.getName(); if (!name.equals("")) { bpelActivity.setName(name); } } }
true
1ac21f47674a5ac4cb78ca15bdb7f8c98c6659b6
Java
a46461440/spring-cloud-all
/user/user-common/src/main/java/com/zxc/user/domain/po/UserInfoWithRole.java
UTF-8
647
1.742188
2
[]
no_license
package com.zxc.user.domain.po; import lombok.AllArgsConstructor; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * @author Zhou RunMing * @Date 2019-1-16 */ @Data @AllArgsConstructor public class UserInfoWithRole implements Serializable { private String id; private String username; private String password; /** * '微信openid' */ private String openid; /** * '1买家2卖家' */ private Integer role; /** * '创建时间' */ private Date createTime; /** * '修改时间' */ private Date updateTime; private String roles; }
true
bf4feff70dac3cae08cdf13b550b60c96e435031
Java
vinzee/apache-flink-playground
/src/main/java/com/windows_and_watermarks/DataServerTimed.java
UTF-8
1,154
2.859375
3
[ "Apache-2.0" ]
permissive
package com.windows_and_watermarks; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Random; public class DataServerTimed { public static void main(String[] args) throws IOException { ServerSocket listener = new ServerSocket(9090); try { Socket socket = listener.accept(); System.out.println("Got new connection: " + socket.toString()); try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); Random rand = new Random(); while (true) { int i = rand.nextInt(100); String s = "" + System.currentTimeMillis() + "," + i; System.out.println(s); /* <timestamp>,<random-number> */ out.println(s); Thread.sleep(50); } } finally { socket.close(); } } catch (Exception e) { e.printStackTrace(); } finally { listener.close(); } } }
true
84114cf3a34bb30e4d56ea9f532df645d6f96ba9
Java
novakcode/type-parser
/type-parser/src/main/java/com/typeconverter/TypeHolder.java
UTF-8
777
2.484375
2
[]
no_license
package com.typeconverter; import java.lang.reflect.Type; import java.util.List; public class TypeHolder { private TypeProcessor processor; private TypeCast caster; private TypeHolder(TypeProcessor processor, TypeCast caster) { this.processor = processor; this.splitter = caster.getSplitter(); this.caster = caster; } public static TypeHolder prepare(Type type, TypeCast caster) { return new TypeHolder(TypeProcessor.getProcessedClass(type), caster); } public Object parse(Class<?> cl, String val) { return caster.cast(cl, val); } @SuppressWarnings("unchecked") public <T> Class<T> getRaw() { return (Class<T>) processor.getRaw(); } public List<Class<?>> getParameters() { return processor.getParams(); } }
true
3b43891fb9c57e7ed1b696dc50af50d9e0dcd071
Java
laytonro/NeuralNets
/Neuron.java
UTF-8
1,135
3
3
[]
no_license
import java.util.Arrays; import java.util.Random; //Layton Rosenfeld public class Neuron { private double[] weights; private double output; private double bias; private double errorSignal; public Neuron(int numInputs) { this.weights = new double[numInputs]; } public double getBias() { return this.bias; } public void assignRandomWeights() { Random random = new Random(); for (int w = 0; w < weights.length; w+= 1) { double r = random.nextDouble(); this.weights[w] = -.05 + (r/10); } double biasWeight = random.nextDouble(); this.bias = -.05 + (biasWeight/10); } public void bias(double b) { this.bias += b; } public double[] weights() { return this.weights; } public double output() { return this.output; } public double getES() { return this.errorSignal; } public void es(double es) { this.errorSignal = es; } public double calcOutput(double[] inputList) { double outputNum = 0; for (int i=0; i<weights.length; i+=1) { outputNum += weights[i] * inputList[i]; } outputNum += bias; output = 1/(1+Math.exp(outputNum*-1)); return output; } }
true
45a9a95af051a7f2b37187cbcb93cc3fd3b53323
Java
UCSFMemoryAndAging/lava
/lava-crms/src/edu/ucsf/lava/crms/protocol/controller/BaseCompletionStatusHandler.java
UTF-8
12,922
1.71875
2
[ "BSD-2-Clause" ]
permissive
package edu.ucsf.lava.crms.protocol.controller; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.validation.BindingResult; import org.springframework.webflow.context.servlet.ServletExternalContext; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; import edu.ucsf.lava.core.action.ActionUtils; import edu.ucsf.lava.core.controller.ComponentCommand; import edu.ucsf.lava.core.controller.ScrollablePagedListHolder; import edu.ucsf.lava.core.dao.LavaDaoFilter; import edu.ucsf.lava.core.dao.LavaNonParamHandler; import edu.ucsf.lava.crms.assessment.model.Instrument; import edu.ucsf.lava.crms.controller.CrmsListComponentHandler; import edu.ucsf.lava.crms.enrollment.model.EnrollmentStatus; import edu.ucsf.lava.crms.protocol.dto.StatusListItemDto; import edu.ucsf.lava.crms.protocol.model.Protocol; import edu.ucsf.lava.crms.protocol.model.ProtocolNodeConfig; import edu.ucsf.lava.crms.protocol.model.ProtocolTracking; import edu.ucsf.lava.crms.session.CrmsSessionUtils; public class BaseCompletionStatusHandler extends BaseStatusListHandler { public BaseCompletionStatusHandler() { super(); defaultEvents.addAll(Arrays.asList("timepoint","visit","instrument","summary","expanded")); this.setSourceProvider(new BaseCompletionSourceProvider(this)); } public LavaDaoFilter extractFilterFromRequest(RequestContext context, Map components) { HttpServletRequest request = ((ServletExternalContext)context.getExternalContext()).getRequest(); LavaDaoFilter filter = Protocol.newFilterInstance(getCurrentUser(request)); // Quick Filters are configured in setupFilter method, as they are dependent upon the fmtGranularity // the user has chosen // default to showing those that are not complete, sorted in order of most overdue timepoints first filter.setActiveQuickFilter("Not Completed"); filter.addDefaultSort("collectWinStart",true); // default for fmtGranularity and fmtColumns here filter.setParam("fmtGranularity", "Timepoint"); filter.addParamHandler(new LavaNonParamHandler("fmtGranularity")); filter.setParam("fmtColumns", "Summary"); filter.addParamHandler(new LavaNonParamHandler("fmtColumns")); return filter; } public static class BaseCompletionSourceProvider extends BaseStatusListHandler.BaseStatusListSourceProvider { public BaseCompletionSourceProvider(CrmsListComponentHandler listHandler) { super(listHandler); } protected LavaDaoFilter setupFilter(LavaDaoFilter daoFilter, String fmtGranularity) { daoFilter.clearAliases(); daoFilter.setAlias("patient", "patient"); daoFilter.setAlias("config", "timepointConfig"); daoFilter.setAlias("parent", "protocol"); daoFilter.setAlias("protocol.config", "protocolConfig"); daoFilter.clearDaoProjections(); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("id")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("timepointConfig.id")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("patient.fullNameRevNoSuffix")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("projName")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("protocolConfig.label")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("protocol.currStatus")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("protocol.currReason")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("protocol.currNote")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("timepointConfig.label")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("timepointConfig.optional")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("compStatus")); daoFilter.clearQuickFilters(); List<ProtocolTracking> list = null; if (fmtGranularity.equals("Timepoint")) { if (this.sortContainsAlias("visitConfig", daoFilter) || this.sortContainsAlias("instrConfig", daoFilter)) { daoFilter.clearSort(); } // remove any filter parameters specific to "Visit" or "Instrument" granularity that may be set, // since they are not part of a Timepoint query daoFilter.clearParam("visitConfig.label"); daoFilter.clearParam("instrConfig.label"); // quick filter settings daoFilter.addQuickFilter("Not Started", daoFilter.daoEqualityParam("compStatus","Not Started")); daoFilter.addQuickFilter("Pending", daoFilter.daoEqualityParam("compStatus","Pending")); daoFilter.addQuickFilter("In Progress", daoFilter.daoEqualityParam("compStatus","In Progress")); daoFilter.addQuickFilter("Not Completed", daoFilter.daoEqualityParam("compStatus","Not Completed")); daoFilter.addQuickFilter("Completed", daoFilter.daoInParam("compStatus",new Object[]{"Completed","Partial"})); daoFilter.addQuickFilter("Completed (Partial)", daoFilter.daoEqualityParam("compStatus","Partial")); } else if (fmtGranularity.equals("Visit")) { if (this.sortContainsAlias("instrConfig", daoFilter)) { daoFilter.clearSort(); } // remove any filter parameters specific to "Instrument" granularity that may be set, // since they are not part of a "Vist" granularity query daoFilter.clearParam("instrConfig.label"); daoFilter.setAlias("children", "visit"); daoFilter.setAlias("visit.config", "visitConfig"); daoFilter.setAlias("visit.visit", "assignedVisit"); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("visit.id")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("visitConfig.id")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("visitConfig.label")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("visitConfig.optional")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("assignedVisit.id")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("visit.summary")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("visit.compStatus")); // quick filter settings daoFilter.addQuickFilter("Not Started", daoFilter.daoEqualityParam("visit.compStatus","Not Started")); daoFilter.addQuickFilter("Pending", daoFilter.daoEqualityParam("visit.compStatus","Pending")); daoFilter.addQuickFilter("In Progress", daoFilter.daoEqualityParam("visit.compStatus","In Progress")); daoFilter.addQuickFilter("Not Completed", daoFilter.daoEqualityParam("visit.compStatus","Not Completed")); daoFilter.addQuickFilter("Completed", daoFilter.daoInParam("visit.compStatus",new Object[]{"Completed","Partial"})); daoFilter.addQuickFilter("Completed (Partial)", daoFilter.daoEqualityParam("visit.compStatus","Partial")); } else if (fmtGranularity.equals("Instrument")) { daoFilter.setAlias("children", "visit"); daoFilter.setAlias("visit.config", "visitConfig"); daoFilter.setAlias("visit.children", "instr"); daoFilter.setAlias("visit.visit", "assignedVisit"); daoFilter.setAlias("instr.config", "instrConfig"); daoFilter.setAlias("instr.instrument", "assignedInstr"); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("visit.id")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("visitConfig.id")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("visitConfig.label")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("visitConfig.optional")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("assignedVisit.id")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("visit.summary")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("instr.id")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("instrConfig.id")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("instrConfig.label")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("instrConfig.optional")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("assignedInstr.id")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("assignedInstr.instrType")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("assignedInstr.instrVer")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("instr.summary")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("instr.compStatus")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("instr.compReason")); daoFilter.addDaoProjection(daoFilter.daoGroupProjection("instr.compNote")); // quick filter settings daoFilter.addQuickFilter("Not Started", daoFilter.daoEqualityParam("instr.compStatus","Not Started")); daoFilter.addQuickFilter("Pending", daoFilter.daoEqualityParam("instr.compStatus","Pending")); daoFilter.addQuickFilter("In Progress", daoFilter.daoEqualityParam("instr.compStatus","In Progress")); daoFilter.addQuickFilter("Not Completed", daoFilter.daoEqualityParam("instr.compStatus","Not Completed")); daoFilter.addQuickFilter("Completed", daoFilter.daoInParam("instr.compStatus",new Object[]{"Completed","Partial"})); daoFilter.addQuickFilter("Completed (Partial)", daoFilter.daoEqualityParam("instr.compStatus","Partial")); } daoFilter.convertParamsToDaoParams(); // query for ProtocolTimepoints only. these may be joined to ProtocolVisits and ProtocolInstruments // via filter aliases. the end result, since using a projection, is that the query will return a // row for every row of the query result, i.e. rather than just rows for each ProtocolTimepoint, it // returns rows for ProtocolTimepoint joined to all of its ProtocolVisits and each ProtocolVisit // joined to all of its ProtocolInstruments daoFilter.addDaoParam(daoFilter.daoEqualityParam("nodeType", ProtocolNodeConfig.TIMEPOINT_NODE)); return daoFilter; } protected List convertResultsToDto(List results, String fmtGranularity) { ArrayList dtoList = new ArrayList(results.size()); Boolean optional; for(Object result:results){ if(result.getClass().isArray()){ Object[] resultArray = (Object[])result; StatusListItemDto dto = new StatusListItemDto(); int i = 0; dto.setId((Long)resultArray[i++]); dto.setConfigId((Long)resultArray[i++]); dto.setFullNameRevNoSuffix((String)resultArray[i++]); dto.setProjName((String)resultArray[i++]); dto.setProtocolLabel((String)resultArray[i++]); dto.setCurrStatus((String)resultArray[i++]); dto.setCurrReason((String)resultArray[i++]); dto.setCurrNote((String)resultArray[i++]); dto.setTimepointLabel((String)resultArray[i++]); optional = (Boolean)resultArray[i++]; if (optional != null && optional) { dto.setTimepointOptional("Yes"); } dto.setTpCompStatus((String)resultArray[i++]); if (fmtGranularity.equals("Visit")) { dto.setVisitId((Long)resultArray[i++]); dto.setVisitConfigId((Long)resultArray[i++]); dto.setVisitLabel((String)resultArray[i++]); optional = (Boolean)resultArray[i++]; if (optional != null && optional) { dto.setVisitOptional("Yes"); } dto.setAssignedVisitId((Long)resultArray[i++]); dto.setVisitSummary((String)resultArray[i++]); dto.setVisitCompStatus((String)resultArray[i++]); } else if (fmtGranularity.equals("Instrument")) { dto.setVisitId((Long)resultArray[i++]); dto.setVisitConfigId((Long)resultArray[i++]); dto.setVisitLabel((String)resultArray[i++]); optional = (Boolean)resultArray[i++]; if (optional != null && optional) { dto.setVisitOptional("Yes"); } dto.setAssignedVisitId((Long)resultArray[i++]); dto.setVisitSummary((String)resultArray[i++]); dto.setInstrId((Long)resultArray[i++]); dto.setInstrConfigId((Long)resultArray[i++]); dto.setInstrLabel((String)resultArray[i++]); optional = (Boolean)resultArray[i++]; if (optional != null && optional) { dto.setInstrOptional("Yes"); } dto.setAssignedInstrId((Long)resultArray[i++]); String instrType = (String)resultArray[i++]; String instrVer = (String)resultArray[i++]; dto.setAssignedInstrTypeEncoded(new Instrument(instrType, instrVer){}.getInstrTypeEncoded()); dto.setInstrSummary((String)resultArray[i++]); dto.setInstrCompStatus((String)resultArray[i++]); dto.setInstrCompReason((String)resultArray[i++]); dto.setInstrCompNote((String)resultArray[i++]); } dtoList.add(dto); } } return dtoList; } } }
true
d84f20c78734feaf1ac290a9da2d6a74e15bcc24
Java
avihu111/OOP-Java-Project
/oop/ex6/Scopes/Scope.java
UTF-8
5,056
3.203125
3
[]
no_license
package oop.ex6.Scopes; import oop.ex6.Methods.Method; import oop.ex6.Methods.MethodException; import oop.ex6.Variables.Variable; import oop.ex6.Variables.VariableException; import oop.ex6.main.InvalidCodeException; import oop.ex6.main.LineReader; import java.util.HashMap; import java.util.LinkedHashMap; /** * this class represents a certain scope in the program. Scope can be nested, thus every scope has a * "pointer" ( by composition ) to its upper scope */ public class Scope { /** the upper scope of this scope */ public Scope parent; /* a line reader object - so the scope can read its own content */ private final LineReader lineReader; /* contains all variables relevant for this scope */ private final HashMap<String, Variable> variables; /* contains all methods relevant for this scope*/ private LinkedHashMap<String, Method> methods; /* scope type */ private final LineReader.ScopeType scopeType; /** * creates a new scope object for the program * @param parent the upper scope for this scope * @param scopeType scope type - (inner/ method / global) */ public Scope(Scope parent, LineReader.ScopeType scopeType) { this.parent = parent; this.lineReader = parent.lineReader; this.variables = new HashMap<>(); this.scopeType = scopeType; } /** * creates a new scope object for the program * @param lineReader a line reader object * @param scopeType the scope type */ public Scope(LineReader lineReader, LineReader.ScopeType scopeType) { this.lineReader = lineReader; this.variables = new HashMap<>(); this.methods = new LinkedHashMap<>(); this.scopeType = scopeType; } /** * in charge for reading the scope content * @throws InvalidCodeException if an error in scope is found */ public void readScope() throws InvalidCodeException { boolean isScopeOpen = true; while (isScopeOpen) { isScopeOpen = lineReader.readLine(this, scopeType); } } /** * * @param type the type of the method to search * @param name the name of the method to search * @throws InvalidCodeException in case of an error */ public void readMethod(String type, String name) throws InvalidCodeException { lineReader.goToMethod(type, name); readScope(); } /** * @param variableName variable name to be found * @return returns the requested variable if exists in the program */ public Variable getVariable(String variableName) { Scope current = this; while (current != null) { // searching in all upper scopes if (current.variables.containsKey(variableName)) { return current.variables.get(variableName); } current = current.parent; } return null; } /** * @param variableName the name of the variable to find. * @return the requested variable if exists in this scope */ public Variable getLocalVariable(String variableName) { return variables.get(variableName); } /** * @param variable the variable object to add to this scope * @throws InvalidCodeException if an error with addition occurs. */ public void addVariable(Variable variable) throws InvalidCodeException{ // if name exist in current scope or there is a method with this name already if (variables.containsKey(variable.getName()) || (methods != null && methods.containsKey(variable.getName()))){ throw new VariableException(variable.getName()); } this.variables.put(variable.getName(), variable); } /** * @param method the method object to add to this scope * @throws InvalidCodeException if an error with addition occurs. */ public void addMethod(Method method) throws InvalidCodeException{ if (methods.containsKey(method.getName())){ throw new MethodException(method.getName()); } this.methods.put(method.getName(), method); } /** * skipping a the lines of this scope for this read. * @throws InvalidCodeException if scope is not closed properly */ public void skipLines() throws InvalidCodeException { lineReader.skipLines(); } /** * @param methodName the name of the method to find. * @return the requested method if exists in this scope */ public Method getMethod(String methodName){ Scope current = this; while (current.parent != null) { current = current.parent; } return current.methods.get(methodName); } /** * @return all the methods in this scope */ public LinkedHashMap<String, Method> getAllMethods() { return methods; } }
true
be6b707375788921959f4a734344e10736149c5f
Java
StoneInCHN/YLY
/yly-mgmt-pom/yly-mgmt-entity/src/main/java/com/yly/entity/FormInstance.java
UTF-8
2,500
1.984375
2
[]
no_license
package com.yly.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.hibernate.annotations.Index; import com.yly.entity.base.BaseEntity; /** * 员工提交的表单 * * @author sujinxuan * */ @Entity @Table(name = "yly_form_instance") @SequenceGenerator(name = "sequenceGenerator", sequenceName = "yly_form_instance_sequence") public class FormInstance extends BaseEntity { private static final long serialVersionUID = 9114793424588879204L; /** * 租户ID */ private Long tenantID; /** * 提交表单员工 */ private TenantUser tenantUser; /** * 员工提交的表单详情 */ private Set<FormInstanceItem> formInstanceItems = new HashSet<FormInstanceItem>(); /** * 表单实例对应的流程任务实例 */ private WorkProcessInstance workProcessInstance; /** * 自定义表单 */ private FormTemplate formTemplate; /** * 表单类型 */ private SystemConfig formType; @OneToOne public WorkProcessInstance getWorkProcessInstance() { return workProcessInstance; } public void setWorkProcessInstance(WorkProcessInstance workProcessInstance) { this.workProcessInstance = workProcessInstance; } @ManyToOne public SystemConfig getFormType() { return formType; } public void setFormType(SystemConfig formType) { this.formType = formType; } @ManyToOne public FormTemplate getFormTemplate() { return formTemplate; } public void setFormTemplate(FormTemplate formTemplate) { this.formTemplate = formTemplate; } @OneToMany(mappedBy = "formInstance") public Set<FormInstanceItem> getFormInstanceItems() { return formInstanceItems; } public void setFormInstanceItems(Set<FormInstanceItem> formInstanceItems) { this.formInstanceItems = formInstanceItems; } @ManyToOne public TenantUser getTenantUser() { return tenantUser; } public void setTenantUser(TenantUser tenantUser) { this.tenantUser = tenantUser; } @Index(name = "form_instance_tenantid") public Long getTenantID() { return tenantID; } public void setTenantID(Long tenantID) { this.tenantID = tenantID; } }
true
b0724291cba0ae967d7189ee669169b8b9ef2622
Java
PayneYao/glin
/src/main/java/com/lozic/genpptx/html/Html2PptxTransformer.java
UTF-8
2,823
2.03125
2
[]
no_license
package com.lozic.genpptx.html; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.apache.commons.beanutils.BeanUtils; import org.jsoup.Jsoup; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.css.CSSStyleSheet; import com.lozic.genpptx.GenerationException; import com.lozic.genpptx.State; import com.lozic.genpptx.css.CssInline; import com.lozic.genpptx.css.CssProcessor; import com.lozic.genpptx.css.Style; public class Html2PptxTransformer implements Transformer { private Set<NodeSupport> supportSet; private CssInline cssInline; public Html2PptxTransformer(CssInline cssInline) { super(); this.cssInline = cssInline; } public void setSupportSet(NodeSupport... supports) { this.supportSet = new HashSet<>(Arrays.asList(supports)); } public void convert(State state, CSSStyleSheet css, String htmlString) throws GenerationException { org.jsoup.nodes.Document html = Jsoup.parse(htmlString); cssInline.applyCss(css, html); org.jsoup.nodes.Node body = html.body(); Document slideDoc = state.getSlideDoc(); Element p = slideDoc.createElement("a:p"); state.setP(p); state.getTxBody().appendChild(p); Element pPr = slideDoc.createElement("a:pPr"); p.appendChild(pPr); pPr.setAttribute("algn", "l"); iterate(state, body); } public void iterate(State state, org.jsoup.nodes.Node node) throws GenerationException { try { for (org.jsoup.nodes.Node htmlNode : node.childNodes()) { traverse(state, htmlNode); } } catch (Exception e) { throw new GenerationException(e); } } private void traverse(State state, org.jsoup.nodes.Node node) throws GenerationException { try { Style style = state.getStyle(); Style prevStyle = (Style) BeanUtils.cloneBean(style); String htmlStyle = node.attr("style"); CssProcessor.process(htmlStyle, style); NodeSupport support = null; for (NodeSupport sup : supportSet) { if (sup.supports(node)) { support = sup; break; } } if (support != null) { support.process(state, node); } else { iterate(state, node); } state.setStyle(prevStyle); } catch (GenerationException e) { throw e; } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) { throw new GenerationException(e); } } }
true
ed0575c59d8f6f60de5f64d8115ded342ceb8a13
Java
raafacachoeira/SCTIM
/DSI2014EJB/ejbModule/ejb/CepBeanLocal.java
UTF-8
316
1.929688
2
[]
no_license
package ejb; import java.util.List; import javax.ejb.Local; import javax.persistence.NoResultException; import dao.Cep; @Local public interface CepBeanLocal { public void save(Cep cep); public List<Cep> getAllCep(); public void remove (Cep cep); public Cep getCepByNumber(long number); }
true
1caf17cd6d29ea1d045ca3afc5e521ac6e278ad5
Java
savvari/snake
/src/com/andriod/games/Snake/game/Stain.java
UTF-8
501
2.546875
3
[]
no_license
package com.andriod.games.Snake.game; /** * Created with IntelliJ IDEA. * User: sridharavvari * Date: 01/10/2013 * Time: 21:49 * To change this template use File | Settings | File Templates. */ public class Stain { public static final int TYPE_1 = 0; public static final int TYPE_2 = 1; public static final int TYPE_3 = 2; public int x,y; public int type; public Stain(int x, int y, int type) { this.x = x; this.y = y; this.type = type; } }
true
e304a99b43647eb590983073f3e6e00e1f4ff297
Java
laxman1991/Selenium-automation
/CollectionTest/src/com/collection/chashmap/hashTable.java
UTF-8
409
2.90625
3
[]
no_license
package com.collection.chashmap; import java.util.Hashtable; public class hashTable { public static void main(String[] args) { Hashtable<Float,Boolean> hs=new Hashtable<Float,Boolean>(); hs.put(1202.11f,true); System.out.println(hs); System.out.println(hs.get(1202.11f)); System.out.println(hs.keySet());; System.out.println(hs.values()); } }
true
1595d638f5e14bb1a8911370eec02ffc2c1738bf
Java
arcadu22/flight_micro_backend
/src/main/java/com/example/demo/services/tiqueteServices.java
UTF-8
1,050
2.34375
2
[]
no_license
package com.example.demo.services; import java.util.ArrayList; import java.util.Optional; import com.example.demo.models.Tiquete; import com.example.demo.repositories.repositoriesTiquete; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class tiqueteServices { @Autowired repositoriesTiquete tiqueteRepositori; //Ver todos los Tiquetes public ArrayList<Tiquete> obtTiquete(){ return (ArrayList<Tiquete>) tiqueteRepositori.findAll(); } //Guardar Tiquete public Tiquete guardarTiquete(Tiquete tiquete){ return tiqueteRepositori.save(tiquete); } //Buscar por ID Tiquete public Optional<Tiquete>obtenerId(Long id){ return tiqueteRepositori.findById(id); } //Eliminar Tiquete public boolean EliminarTiquete(Long id){ try { tiqueteRepositori.deleteById(id); return true; } catch (Exception e) { return false; } } }
true
248807bfb6fb7ebd48d26ba0d9cfa04a0ea9c4c1
Java
alexismanin/http-range-example
/clients/src/main/java/fr/amanin/examples/httprange/clients/Webflux.java
UTF-8
609
2.21875
2
[]
no_license
package fr.amanin.examples.httprange.clients; import java.net.URI; import java.util.concurrent.CompletableFuture; import org.springframework.web.reactive.function.client.WebClient; public class Webflux extends RangeClient { final WebClient cli; public Webflux(URI uri, RangeUnit unit, WebClient cli) { super(uri, unit); this.cli = cli; } @Override CompletableFuture<byte[]> read(ByteRange... chunks) { return cli.get().header(RANGE_HEADER, buildRangeValue(chunks)) .retrieve() .bodyToMono(byte[].class) .toFuture(); } }
true
51a4e9dd29168539fade66c23cc414e8faea8844
Java
bhargavihoskoti/java_codes
/labOne/src/com/training/CurrencyConverter.java
UTF-8
128
2.140625
2
[]
no_license
package com.training; public class CurrencyConverter { public double inrThousd(double num){ return num/(73.68); } }
true
8e58edd1f93d4958bbfca1ed1eb5da98128f1492
Java
BulkSecurityGeneratorProject/Tp_Angular
/angulartp/src/main/java/com/mycompany/myapp/repository/HomeRepository.java
UTF-8
285
1.734375
2
[]
no_license
package com.mycompany.myapp.repository; import com.mycompany.myapp.domain.Home; import org.springframework.data.jpa.repository.*; import java.util.List; /** * Spring Data JPA repository for the Home entity. */ public interface HomeRepository extends JpaRepository<Home,Long> { }
true
07f4278afbaadf244ff3d42e7448e1867012cb08
Java
ParaskP7/sample-code-posts
/app/src/test/java/io/petros/posts/datastore/DatastoreAddActionsTest.java
UTF-8
1,978
2.09375
2
[ "Apache-2.0" ]
permissive
package io.petros.posts.datastore; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import io.petros.posts.PreconfiguredRobolectricTestRunner; import io.petros.posts.RobolectricGeneralTestHelper; import io.petros.posts.model.User; import io.realm.Realm; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; /** * This test is ignored until PowerMock is introduced, which will mock all the Realm objects. */ @Ignore("java.lang.NullPointerException at io.realm.BaseRealm.beginTransaction") @RunWith(PreconfiguredRobolectricTestRunner.class) public class DatastoreAddActionsTest extends RobolectricGeneralTestHelper { private DatastoreAddActions datastoreAddActions; @Mock private Realm realmMock; @Mock private User realmUserMock; @Before public void setUp() { setUpMocks(); setUpDatastoreActions(); } private void setUpDatastoreActions() { datastoreAddActions = new DatastoreAddActions(realmMock); } @Test public void addUserTest() { when(realmMock.createObject(User.class, user.getId())).thenReturn(realmUserMock); final boolean isSuccessful = datastoreAddActions.user(user); verify(realmMock, times(1)).beginTransaction(); verify(realmMock, times(1)).createObject(User.class, user.getId()); verify(realmUserMock, times(1)).setName(user.getName()); verify(realmUserMock, times(1)).setUsername(user.getUsername()); verify(realmUserMock, times(1)).setEmail(user.getEmail()); verifyNoMoreInteractions(realmUserMock); verify(realmMock, times(1)).commitTransaction(); verifyNoMoreInteractions(realmMock); assertThat(isSuccessful).isTrue(); } }
true
74d9df853765c6800d1b0e2bf0608d171db56ef8
Java
ConvergentMobile/lbl_pro_v1
/src/main/java/com/business/common/util/ActivationMail.java
UTF-8
1,930
2.328125
2
[]
no_license
package com.business.common.util; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.log4j.Logger; public class ActivationMail { static Logger logger = Logger.getLogger(ActivationMail.class); public static boolean sendMail(String toMail, String text,String sub,StringBuffer emailUrl){ logger.info("ActivationMail Start: Sending email"); boolean isMessageSent = false; logger.info("toMail:::::::::::::::::"+toMail); Properties props = new Properties(); props.put("mail.smtp.host", LBLConstants.MAIL_HOST); props.put("mail.smtp.socketFactory.port", LBLConstants.MAIL_PORT); props.put("mail.smtp.socketFactory.class",LBLConstants.MAIL_CLASS); props.put("mail.smtp.auth", LBLConstants.MAIL_AUTH); props.put("mail.smtp.port", LBLConstants.MAIL_PORT); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(LBLConstants.MAIL_EMAIL,LBLConstants.MAIL_PASSWORD); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(LBLConstants.MAIL_EMAIL)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail)); message.setText("Activation Link :"+emailUrl+ "\nUserName :"+text+"\nPassWord :"+sub); message.setSubject("LBL_PRO Reset Password"); Transport.send(message); isMessageSent = true; } catch (MessagingException e) { isMessageSent = false; e.printStackTrace(); } logger.info(" ActivationMail End: Email is Successfully sent"); return isMessageSent; } }
true
ba64e7540c8a1e861aa2a4458f3d9d67541da6f7
Java
wang-jingyi/dtmc.learn
/src/main/java/dtmc/learn/main/ActiveLearnExperiment.java
UTF-8
6,184
2.1875
2
[]
no_license
package dtmc.learn.main; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; import dtmc.learn.active.IDO; import dtmc.learn.estimator.Estimator; import dtmc.learn.models.Model; import dtmc.learn.utils.FileUtil; import dtmc.learn.utils.RandomUtil; public class ActiveLearnExperiment implements Experiment{ int batch_size = 100; int top_n_small = 10; public ActiveLearnExperiment(int batch_size, int top_n_small) { this.batch_size = batch_size; this.top_n_small = top_n_small; } public ActiveLearnExperiment() { } public ExperimentResult runExperiment(Config config, Estimator estimator) throws FileNotFoundException, ClassNotFoundException, IOException { // clean the gurobi log, it's really large file if not cleaned FileUtil.deleteFile(System.getProperty("user.dir")+"/optimize.initial.distribution.log"); Model model = config.getModel(); MarkovChain mc = config.buildMarkovChain(); int sample_length = config.getSample_length(); int init_sample_size = config.getInit_sample_size(); int more_sample_size = config.getMore_sample_size(); int reach_bounded_step = config.getReach_bounded_step(); List<Integer> init_states = getValidInitialStates(model); List<Double> init_states_probs = new ArrayList<Double>(); for(int i=0; i<mc.getInit_dist().getDimension(); i++){ if(mc.getInit_dist().getEntry(i)>0) init_states_probs.add(mc.getInit_dist().getEntry(i)); } List<Integer> target_states = model.getTarget_states(); Reachability actual_reach = new Reachability(mc.getTransitionMatrix(), init_states, init_states_probs, target_states, System.getProperty("user.dir")+"/resources/tmp/reach/"+model.getModel_name(), model.getModel_name()+"_actual", reach_bounded_step); List<Double> target_states_reach = actual_reach.computeReachability(); FileUtil.writeObject(GlobalConfigs.TMP_PATH+"/reach/"+model.getModel_name()+"/actual_reach", actual_reach); // get an initial estimate RealMatrix stats_matrix = mc.simulate(init_sample_size, sample_length); RealMatrix est_matrix = estimator.estimate(stats_matrix); // max min boolean stopping = false; int total_sample = 0; RealMatrix trans_stats_matrix = stats_matrix.copy(); RealMatrix trans_est_matrix = est_matrix.copy(); while(!stopping){ total_sample += batch_size; int target_optimize_state = getTargetOptimizeState(trans_stats_matrix, top_n_small); IDO ido = new IDO(target_optimize_state, trans_est_matrix, sample_length); RealVector optimal_init_dist = ido.computeOptimalInitialDistribution(init_states); mc.simulate(optimal_init_dist, trans_stats_matrix, batch_size, sample_length); trans_est_matrix = estimator.estimate(trans_stats_matrix); if(total_sample>=more_sample_size){ stopping = true; } } int min_visit = MetricComputing.calculateMinFreq(trans_stats_matrix); double mse = MetricComputing.calculateMSE(mc.getTransitionMatrix(), trans_est_matrix); Reachability active_learned_reach = new Reachability(trans_est_matrix, init_states, init_states_probs, target_states, System.getProperty("user.dir")+"/resources/tmp/active_learned_reach/"+model.getModel_name(), model.getModel_name()+"_reach", reach_bounded_step); List<Double> active_learned_target_states_reach = active_learned_reach.computeReachability(); FileUtil.writeObject(System.getProperty("user.dir")+"/resources/tmp/active_learned_reach/"+model.getModel_name()+"/active_reach", active_learned_reach); // max reach stopping = false; total_sample = 0; RealMatrix reach_stats_matrix = stats_matrix.copy(); RealMatrix reach_est_matrix = est_matrix.copy(); while(!stopping){ total_sample += batch_size; int target_optimize_state = getReachOptimizeState(target_states); IDO ido = new IDO(target_optimize_state, reach_est_matrix, sample_length); RealVector optimal_init_dist = ido.computeOptimalInitialDistribution(init_states); mc.simulate(optimal_init_dist, reach_stats_matrix, batch_size, sample_length); reach_est_matrix = estimator.estimate(reach_stats_matrix); if(total_sample>=more_sample_size){ stopping = true; } } Reachability active_learned_reach_2 = new Reachability(reach_est_matrix, init_states, init_states_probs, target_states, System.getProperty("user.dir")+"/resources/tmp/active_learned_reach_2/"+model.getModel_name(), model.getModel_name()+"_reach_2", reach_bounded_step); List<Double> active_learned_target_states_reach_2 = active_learned_reach_2.computeReachability(); FileUtil.writeObject(System.getProperty("user.dir")+"/resources/tmp/active_learned_reach_2/"+model.getModel_name()+"/active_reach_2", active_learned_reach_2); ExperimentResult er = new ExperimentResult(min_visit, mse, target_states, target_states_reach, active_learned_target_states_reach, active_learned_target_states_reach_2); System.out.println(config); System.out.println(er); return er; } private List<Integer> getValidInitialStates(Model model){ RealVector init_dist = model.getInit_dist(); List<Integer> init_states = new ArrayList<Integer>(); for(int i=0; i<init_dist.getDimension(); i++){ if(init_dist.getEntry(i)!=0){ init_states.add(i); } } return init_states; } private int getReachOptimizeState(List<Integer> target_states){ int i = RandomUtil.nextInt(0, target_states.size()-1); return target_states.get(i); } private int getTargetOptimizeState(RealMatrix stats_matrix, int top_n_min){ int node_number = stats_matrix.getRowDimension(); List<Integer> row_sums = new ArrayList<>(); Map<Integer, Integer> row_sum_map = new HashMap<>(); for(int i=0; i<node_number; i++){ int row_sum = 0; for(int j=0; j<node_number; j++){ row_sum += stats_matrix.getEntry(i, j); } row_sum_map.put(row_sum, i); row_sums.add(row_sum); } Collections.sort(row_sums); int target_state = row_sum_map.get(row_sums.get(RandomUtil.nextInt(0, top_n_min-1))); return target_state; } }
true
8a04ebcc158f59310f387d81ff36ceb16b4d1ad2
Java
SergioRamirez1999/AOC2020
/06-day/p1.java
UTF-8
1,440
2.6875
3
[]
no_license
import java.io.IOException; import java.lang.reflect.Array; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class p1 { public static void main(String[] args) { String filename = "pzzinput.txt"; try { String lines = Files.lines(Paths.get(filename)) .collect(Collectors.joining("\n")); List<Set<Character>> answers = Arrays.asList(lines.split("\n\\s*\n")) .stream() .map(x -> x.replace("\n", " ") .chars() .mapToObj(i -> (char)i) .filter(c -> c != ' ') .collect(Collectors.toSet())) .collect(Collectors.toList()); int c_yes = answers.stream().mapToInt(s -> s.size()).sum(); System.out.println(c_yes); } catch (IOException e) { e.printStackTrace(); } } }
true
31739f6a2567f3df65b3d40e3eb3fb596ba3f16f
Java
droidaika/2ndYearCS
/Tree/src/Tree/Testing.java
UTF-8
2,651
3.796875
4
[]
no_license
package Tree; import java.util.Scanner; public class Testing { //ALL NEW CODE public static void main(String[] args) { System.out.println("\nCreating a treee that looks like this:\n"); System.out.println(" c5 "); System.out.println(" / \\ "); // '\\' is the escape character for backslash System.out.println(" c4 c4 "); System.out.println(" / \\ / \\"); System.out.println("a1 b1 a1 b1 "); System.out.println(); //get height System.out.println("How high are your treeees?"); Scanner scan = new Scanner( System.in ); int x = scan.nextInt(); // Create a tree System.out.println("Constructing a test tree ..."); BinaryTree<String> testTree = new BinaryTree<String>(); createTree1(testTree, x); // BinaryTree<String> testTree = MMExtra.createRecursiveTree(3); // Display some statistics about it System.out.println("\nSome statistics about the test tree ..."); displayStats(testTree); // Perform in-order traversal System.out.println("\nIn-order traversal of the test tree, printing each node when visiting it ..."); testTree.inorderTraverse(); // Perform pre-order traversal System.out.println("\npre-order traversal of the test tree, printing each node when visiting it ..."); testTree.preorderTraverse(); // Perform post-order traversal System.out.println("\npost-order traversal of the test tree, printing each node when visiting it ..."); testTree.postorderTraverse(); // Perform breadth-first traversal System.out.println("\nbreadth-first traversal of the test tree, printing each node when visiting it ..."); testTree.breadthFirstTraverse(); } // end of main public static void createTree1(BinaryTree<String> tree, int height) { if(height > 1){ BinaryTree<String> leftNode = new BinaryTree<String>("a " + (height-1)); BinaryTree<String> rightNode = new BinaryTree<String>("b" + (height-1)); height--; createTree1(leftNode, (height)); createTree1(rightNode, (height)); tree.setTree("c "+ (height+1), leftNode, rightNode); } // First the leaves } // end createTree1 public static void displayStats(BinaryTree<String> tree) { if (tree.isEmpty()) System.out.println("The tree is empty"); else System.out.println("The tree is not empty"); System.out.println("Root of tree is " + tree.getRootData()); System.out.println("Height of tree is " + tree.getHeight()); System.out.println("No. of nodes in tree is " + tree.getNumberOfNodes()); } // end displayStats }
true
3f80e74a6c03043d46da536c8875f720fbb780f1
Java
giga1615/algorithm
/src/com/boj/silver3/백준_1003_피보나치함수.java
UTF-8
861
3.265625
3
[]
no_license
package com.boj.silver3; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class 백준_1003_피보나치함수 { static int dp[][]; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); dp = new int[41][2]; dp[0] = new int[] { 1, 0 }; dp[1] = new int[] { 0, 1 }; for (int i = 0; i < T; i++) { int answer[] = fibonacci(Integer.parseInt(br.readLine())); System.out.println(answer[0] + " " + answer[1]); } } private static int[] fibonacci(int n) { if (n >= 2 && dp[n][0] == 0 && dp[n][1] == 0) { int a[] = fibonacci(n - 1); int b[] = fibonacci(n - 2); dp[n][0] = a[0] + b[0]; dp[n][1] = a[1] + b[1]; } return dp[n]; } }
true
21d6b0f8c8e4686b27d130894d4f7e6406f901b7
Java
gustavoms11/message-scheduling-app
/src/main/java/com/gustavoms/messagescheduling/exception/BaseExceptionResponseDTOV1Builder.java
UTF-8
1,141
2.15625
2
[ "Apache-2.0" ]
permissive
package com.gustavoms.messagescheduling.exception; public final class BaseExceptionResponseDTOV1Builder { private BaseExceptionResponseDTOV1 baseExceptionResponseDTOV1; private BaseExceptionResponseDTOV1Builder() { baseExceptionResponseDTOV1 = new BaseExceptionResponseDTOV1(); } public static BaseExceptionResponseDTOV1Builder aBaseExceptionResponseDTOV1() { return new BaseExceptionResponseDTOV1Builder(); } public BaseExceptionResponseDTOV1Builder code(String code) { baseExceptionResponseDTOV1.setCode(code); return this; } public BaseExceptionResponseDTOV1Builder message(String message) { baseExceptionResponseDTOV1.setMessage(message); return this; } public BaseExceptionResponseDTOV1Builder detail(String detail) { baseExceptionResponseDTOV1.setDetail(detail); return this; } public BaseExceptionResponseDTOV1Builder time(String time) { baseExceptionResponseDTOV1.setTime(time); return this; } public BaseExceptionResponseDTOV1 build() { return baseExceptionResponseDTOV1; } }
true
9d4a08d4f3aa9cbf1f6980187f68a63d52089a8e
Java
JetBrains/intellij-community
/java/java-tests/testData/ig/com/siyeh/igtest/style/simplifiable_if_statement/IfMayBeConditional.java
UTF-8
1,683
3.046875
3
[ "Apache-2.0" ]
permissive
package com.siyeh.igtest.style.simplifiable_if_statement; public class IfMayBeConditional { void foo(int a, int b) { int c = 0; <warning descr="If statement can be replaced with '?:'">if</warning> (a < b) { c += a - b; } else { c -= b; } if (a < b) { c += a - b; } else { c *= b; } } void foo2(int a, int b) { int c = 0; <warning descr="If statement can be replaced with '?:'">if</warning> (a < b) { c += a - b; } else { c += b; } } void foo3(int i, StringBuilder sb) { <warning descr="If statement can be replaced with '?:'">if</warning> (i == 0) { sb.append("type.getConstructor()", 0, 1); } else { sb.append("DescriptorUtils.getFQName(cd)",0, 1); } } int foo4(int a, int b) { <warning descr="If statement can be replaced with '?:'">if</warning> (a < b) return a; else return b; } int foo5(int a, int b, int c) { if (a < b) { return a; } else { return b < c ? b : c; } } void foo6(int a, int b, int c) { int i; if (a < b) { i = a; } else { i = b < c ? b : c; } } void largeIf(boolean a, boolean b, boolean c) { final String value; if (a) { value = "a"; } else if (b) { value = "b"; } else if (c) { value = "c"; } else { value = "d"; } } void x() { String nullable = null; String a = nullable; if (a == null) { a = nullable(2); } } private String nullable(int i) { return null; } }
true
aa97f9b8a9705d20c5f610532a9fcd73246e4e63
Java
davidmoros/poc
/jwt-service/src/test/java/es/davidmoros/poc/jwt/service/JWTServiceTest.java
UTF-8
3,473
2.515625
3
[]
no_license
package es.davidmoros.poc.jwt.service; import static java.util.Collections.emptyList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import es.davidmoros.poc.jwt.model.JWTAuthData; public class JWTServiceTest { static Stream<JWTAuthData> jwtAuthDataProvider() { JWTAuthData jwtAuthData1 = new JWTAuthData(); jwtAuthData1.setUsername("username"); JWTAuthData jwtAuthData2 = new JWTAuthData("username"); JWTAuthData jwtAuthData3 = new JWTAuthData("username", emptyList()); JWTAuthData jwtAuthData4 = new JWTAuthData("username", Arrays.asList("role1", "role2")); return Stream.of(jwtAuthData1, jwtAuthData2, jwtAuthData3, jwtAuthData4); } @Test public void generateJWT_nulls_1() { assertThrows(NullPointerException.class, () -> { JWTService.generateJWT((String)null); }); } @Test public void generateJWT_nulls_2() { assertThrows(NullPointerException.class, () -> { JWTService.generateJWT(null, null); }); } @Test public void generateJWT_nulls_3() { assertThrows(NullPointerException.class, () -> { JWTService.generateJWT(null, emptyList()); }); } @Test public void generateJWT_nulls_4() { assertThrows(NullPointerException.class, () -> { JWTService.generateJWT("", null); }); } @Test public void generateJWT_nulls_5() { assertThrows(NullPointerException.class, () -> { JWTService.generateJWT((JWTAuthData)null); }); } @Test public void generateJWT_1() { String jwt = JWTService.generateJWT("username"); assertNotNull(jwt); assertFalse(jwt.isEmpty()); assertTrue(jwt.indexOf(".", jwt.indexOf("."))!=-1); } @Test public void generateJWT_2() { String jwt = JWTService.generateJWT("username", emptyList()); assertNotNull(jwt); assertFalse(jwt.isEmpty()); assertTrue(jwt.indexOf(".", jwt.indexOf("."))!=-1); } @Test public void generateJWT_3() { String jwt = JWTService.generateJWT("username", Arrays.asList("role1", "role2")); assertNotNull(jwt); assertFalse(jwt.isEmpty()); assertTrue(jwt.indexOf(".", jwt.indexOf("."))!=-1); } @ParameterizedTest @MethodSource("jwtAuthDataProvider") public void generateJWT_4(JWTAuthData jwtAuthData) { String jwt = JWTService.generateJWT(jwtAuthData); assertNotNull(jwt); assertFalse(jwt.isEmpty()); assertTrue(jwt.indexOf(".", jwt.indexOf("."))!=-1); } @Test public void parseJWT_nulls_1() { assertThrows(NullPointerException.class, () -> { JWTService.parseJWT(null); }); } @ParameterizedTest @MethodSource("jwtAuthDataProvider") public void parseJWT(JWTAuthData jwtAuthDataIn) { String jwt = JWTService.generateJWT(jwtAuthDataIn); JWTAuthData jwtAuthDataOut = JWTService.parseJWT(jwt); assertNotNull(jwtAuthDataOut); assertEquals(jwtAuthDataIn, jwtAuthDataOut); assertEquals(jwtAuthDataIn.getUsername(), jwtAuthDataOut.getUsername()); assertEquals(jwtAuthDataIn.getRoles(), jwtAuthDataOut.getRoles()); } }
true
cf6ca00b91f2f1a7aba40c56801bebde0a8b25bf
Java
krisfoster/spring-graal-feature
/spring-graalvm-native-feature/src/test/java/org/springframework/support/graal/TypeSystemTests.java
UTF-8
1,902
2.1875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.support.graal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.Collections; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.graalvm.type.Type; import org.springframework.graalvm.type.TypeSystem; public class TypeSystemTests { private static TypeSystem typeSystem; @BeforeClass public static void setup() throws Exception { File file = new File("./target/classes"); // System.out.println(file.getCanonicalPath()); typeSystem = new TypeSystem(Collections.singletonList(file.toString())); } @Test public void test() throws Exception { Type t= typeSystem.resolveName("java.lang.String"); assertNotNull(t); } @Test public void testArray() throws Exception { Type s = typeSystem.resolveName("java.lang.String"); assertEquals("Ljava/lang/String;", s.getDescriptor()); Type t = typeSystem.resolveName("java.lang.String[]"); assertNotNull(t); assertEquals(1,t.getDimensions()); assertTrue(t.isArray()); assertEquals("[Ljava/lang/String;",t.getDescriptor()); assertEquals("java/lang/String[]",t.getName()); assertEquals("java.lang.String[]",t.getDottedName()); } }
true
f030804f628bbc29c3c10347fdeb0c69b9ceb850
Java
onap/aai-graphadmin
/src/test/java/org/onap/aai/historytruncate/HistoryTruncateTest.java
UTF-8
13,416
1.890625
2
[ "Apache-2.0" ]
permissive
/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.aai.historytruncate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.janusgraph.core.JanusGraph; import org.janusgraph.core.JanusGraphTransaction; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.Ignore; import org.junit.runners.MethodSorters; import org.onap.aai.AAISetup; import org.onap.aai.dbmap.AAIGraph; import org.onap.aai.exceptions.AAIException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.*; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class HistoryTruncateTest extends AAISetup { private static final Logger logger = LoggerFactory.getLogger(HistoryTruncateTest.class); private HistoryTruncate historyTruncate; private long todayTs; private long todayMinusOneWeekTs; private long todayMinusOneMonthTs; private long todayMinusTwoMonthsTs; private long todayMinus55DaysTs; @Before public void setup() { historyTruncate = new HistoryTruncate(); String [] argsAr = {}; HistoryTruncate.main(argsAr); JanusGraphTransaction currentTransaction = AAIGraph.getInstance().getGraph().newTransaction(); boolean success = true; todayTs = System.currentTimeMillis(); todayMinusOneWeekTs = todayTs - (7 * 24 * 60 * 60L * 1000); todayMinusOneMonthTs = todayTs - (30 * 24 * 60 * 60L * 1000); todayMinusTwoMonthsTs = todayTs - (60 * 24 * 60 * 60L * 1000); todayMinus55DaysTs = todayTs - (55 * 24 * 60 * 60L * 1000); try { GraphTraversalSource g = currentTransaction.traversal(); // --------- These two have no end-ts Vertex cloudRegionVertex1 = g.addV() .property("aai-node-type", "cloud-region") .property("cloud-owner", "test-owner1") .property("cloud-region-id", "test-region1") .property("source-of-truth", "JUNIT") .property("aai-uri", "aai-uriX01") .property("aai-last-mod-ts","19191919").next(); Vertex tenantVertex1 = g.addV() .property("aai-node-type", "tenant") .property("tenant-id", "test-tenant1") .property("aai-uri", "aai-uriX21") .property("source-of-truth", "JUNIT").next(); // ---------- These two have end-ts one week ago Vertex cloudRegionVertex2 = g.addV() .property("aai-node-type", "cloud-region") .property("cloud-owner", "test-owner2") .property("cloud-region-id", "test-region2") .property("source-of-truth", "JUNIT") .property("aai-uri", "aai-uriX02") .property("end-ts", todayMinusOneWeekTs) .property("aai-last-mod-ts","19191919").next(); Vertex tenantVertex2 = g.addV() .property("aai-node-type", "tenant") .property("tenant-id", "test-tenant2") .property("aai-uri", "aai-uriX22") .property("end-ts", todayMinusOneWeekTs) .property("source-of-truth", "JUNIT").next(); // --------- These 7 have end-ts one month ago Vertex cloudRegionVertex3 = g.addV() .property("aai-node-type", "cloud-region") .property("cloud-owner", "test-owner3") .property("cloud-region-id", "test-region3") .property("source-of-truth", "JUNIT") .property("aai-uri", "aai-uriX03") .property("end-ts", todayMinusOneMonthTs) .property("aai-last-mod-ts","19191919").next(); Vertex tenantVertex3 = g.addV() .property("aai-node-type", "tenant") .property("tenant-id", "test-tenant3") .property("aai-uri", "aai-uriX23") .property("end-ts", todayMinusOneMonthTs) .property("source-of-truth", "JUNIT").next(); Vertex cloudRegionVertex4 = g.addV() .property("aai-node-type", "cloud-region") .property("cloud-owner", "test-owner4") .property("cloud-region-id", "test-region4") .property("source-of-truth", "JUNIT") .property("aai-uri", "aai-uriX04") .property("end-ts", todayMinusOneMonthTs) .property("aai-last-mod-ts","19191919").next(); Vertex tenantVertex4 = g.addV() .property("aai-node-type", "tenant") .property("tenant-id", "test-tenant4") .property("aai-uri", "aai-uriX24") .property("end-ts", todayMinusOneMonthTs) .property("source-of-truth", "JUNIT").next(); Vertex cloudRegionVertex5 = g.addV() .property("aai-node-type", "cloud-region") .property("cloud-owner", "test-owner5") .property("cloud-region-id", "test-region5") .property("source-of-truth", "JUNIT") .property("aai-uri", "aai-uriX05") .property("end-ts", todayMinusOneMonthTs) .property("aai-last-mod-ts","19191919").next(); Vertex tenantVertex5 = g.addV() .property("aai-node-type", "tenant") .property("tenant-id", "test-tenant5") .property("aai-uri", "aai-uriX25") .property("end-ts", todayMinusOneMonthTs) .property("source-of-truth", "JUNIT").next(); Vertex cloudRegionVertex6 = g.addV() .property("aai-node-type", "cloud-region") .property("cloud-owner", "test-owner6") .property("cloud-region-id", "test-region6") .property("source-of-truth", "JUNIT") .property("aai-uri", "aai-uriX06") .property("end-ts", todayMinusOneMonthTs) .property("aai-last-mod-ts","19191919").next(); } catch (Exception ex) { success = false; logger.error("Unable to create the vertexes", ex); } finally { if (success) { currentTransaction.commit(); } else { currentTransaction.rollback(); fail("Unable to setup the graph"); } } } @Test public void testZeroWindow() throws AAIException { JanusGraph jgraph = AAIGraph.getInstance().getGraph(); assertThat(historyTruncate.getCandidateEdgeCount(jgraph,0), is(0)); assertThat(historyTruncate.getCandidateVertexCount(jgraph,0), is(9)); } @Test public void test5DayWindow() throws AAIException { JanusGraph jgraph = AAIGraph.getInstance().getGraph(); assertThat(historyTruncate.getCandidateEdgeCount(jgraph,5), is(0)); assertThat(historyTruncate.getCandidateVertexCount(jgraph,5), is(9)); } @Test public void testTenDayWindow() throws AAIException { JanusGraph jgraph = AAIGraph.getInstance().getGraph(); assertThat(historyTruncate.getCandidateEdgeCount(jgraph,10), is(0)); assertThat(historyTruncate.getCandidateVertexCount(jgraph,10), is(7)); } @Test public void test90DayWindow() throws AAIException { JanusGraph jgraph = AAIGraph.getInstance().getGraph(); assertThat(historyTruncate.getCandidateEdgeCount(jgraph,40), is(0)); assertThat(historyTruncate.getCandidateVertexCount(jgraph,40), is(0)); } @Test public void testCalcTimeStamp() throws AAIException { long ts1 = historyTruncate.calculateTruncWindowEndTimeStamp(0); long ts2 = historyTruncate.calculateTruncWindowEndTimeStamp(10); assertTrue( 0L < ts2); assertTrue(ts2 < ts1); } @Test public void testProcessVerts() throws AAIException { JanusGraph jgraph = AAIGraph.getInstance().getGraph(); // - note - when commitBatchSize is set to "2", then this test makes sure that // batch processing works. // Create 7 records with end-ts of 2 months ago make7NodesWith60DayEndTs(); assertThat(historyTruncate.getCandidateVertexCount(jgraph,55), is(7)); // process those 7 records -first with only logging Boolean doLoggingFlag = true; Boolean doTheDeleteFlag = false; historyTruncate.processVerts(jgraph, todayMinus55DaysTs, doLoggingFlag, doTheDeleteFlag); // Nodes should still be there since doDelete was false assertThat(historyTruncate.getCandidateVertexCount(jgraph,55), is(7)); // process the 7 records, but do the delete doTheDeleteFlag = true; historyTruncate.processVerts(jgraph, todayMinus55DaysTs, doLoggingFlag, doTheDeleteFlag); // Check that they were deleted assertThat(historyTruncate.getCandidateVertexCount(jgraph,55), is(0)); } @Test public void test4BadArgs() throws AAIException { // try passing a bad mode String [] argsAr = {"-truncateWindowDays", "888","-truncateMode","badMode"}; assertFalse(historyTruncate.executeCommand(argsAr) ); // try passing a bad window value String [] argsAr2 = {"-truncateWindowDays", "88xx8","-truncateMode","LOG_ONLY"}; assertFalse(historyTruncate.executeCommand(argsAr2) ); // try passing a bad option name String [] argsAr3 = {"-trunxxxxxxxxxxxcateWindowDays", "888","-truncateMode","LOG_ONLY"}; assertFalse(historyTruncate.executeCommand(argsAr3) ); // try passing good things String [] argsAr4 = {"-truncateWindowDays", "888","-truncateMode","LOG_ONLY"}; assertTrue(historyTruncate.executeCommand(argsAr4) ); // try passing no args (should default to LOG_ONLY mode) String [] argsAr5 = {}; assertTrue(historyTruncate.executeCommand(argsAr5) ); } public void make7NodesWith60DayEndTs() { boolean success = true; JanusGraphTransaction transaction2 = AAIGraph.getInstance().getGraph().newTransaction(); try { GraphTraversalSource g2 = transaction2.traversal(); // --------- These have end-ts two months ago Vertex cloudRegionVertex991 = g2.addV() .property("aai-node-type", "cloud-region") .property("cloud-owner", "test-owner991") .property("cloud-region-id", "test-region991") .property("source-of-truth", "JUNIT") .property("aai-uri", "aai-uriX0991") .property("end-ts", todayMinusTwoMonthsTs) .property("aai-last-mod-ts","19191919").next(); Vertex tenantVertex991 = g2.addV() .property("aai-node-type", "tenant") .property("tenant-id", "test-tenant991") .property("aai-uri", "aai-uriX2991") .property("end-ts", todayMinusTwoMonthsTs) .property("source-of-truth", "JUNIT").next(); Vertex cloudRegionVertex992 = g2.addV() .property("aai-node-type", "cloud-region") .property("cloud-owner", "test-owner992") .property("cloud-region-id", "test-region992") .property("source-of-truth", "JUNIT") .property("aai-uri", "aai-uriX0992") .property("end-ts", todayMinusTwoMonthsTs) .property("aai-last-mod-ts","19191919").next(); Vertex tenantVertex992 = g2.addV() .property("aai-node-type", "tenant") .property("tenant-id", "test-tenant992") .property("aai-uri", "aai-uriX2992") .property("end-ts", todayMinusTwoMonthsTs) .property("source-of-truth", "JUNIT").next(); Vertex cloudRegionVertex993 = g2.addV() .property("aai-node-type", "cloud-region") .property("cloud-owner", "test-owner993") .property("cloud-region-id", "test-region993") .property("source-of-truth", "JUNIT") .property("aai-uri", "aai-uriX0993") .property("end-ts", todayMinusTwoMonthsTs) .property("aai-last-mod-ts","19191919").next(); Vertex tenantVertex993 = g2.addV() .property("aai-node-type", "tenant") .property("tenant-id", "test-tenant993") .property("aai-uri", "aai-uriX2993") .property("end-ts", todayMinusTwoMonthsTs) .property("source-of-truth", "JUNIT").next(); Vertex cloudRegionVertex994 = g2.addV() .property("aai-node-type", "cloud-region") .property("cloud-owner", "test-owner994") .property("cloud-region-id", "test-region994") .property("source-of-truth", "JUNIT") .property("aai-uri", "aai-uriX0994") .property("end-ts", todayMinusTwoMonthsTs) .property("aai-last-mod-ts","19191919").next(); } catch (Exception ex) { success = false; logger.error("Unable to create the 7 vertices with end-ts = 60 days. ", ex); } finally { if (success) { transaction2.commit(); } else { transaction2.rollback(); fail("Unable to setup the vertex with end-ts = 60 "); } } } @After public void tearDown() { JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction(); boolean success = true; try { GraphTraversalSource g = transaction.traversal(); g.V().has("source-of-truth", "JUNIT").toList().forEach(v -> v.remove()); } catch (Exception ex) { success = false; logger.error("Unable to remove the vertexes", ex); } finally { if (success) { transaction.commit(); } else { transaction.rollback(); fail("Unable to teardown the graph"); } } } }
true
95e3c1258f488bc4d5b7a70add99d9ca39af36e3
Java
xuchen70/Helper
/src/main/java/com/code/demo/utils/StringUtils.java
UTF-8
741
3.328125
3
[ "MIT" ]
permissive
package com.code.demo.utils; public class StringUtils { public static boolean isEmpty(String str){ return str == null || str.equals(""); } public static boolean notEmpty(String str){ return !isEmpty(str); } public static String padEnd(String str,int length,char padChar){ if (length < 0) throw new IllegalArgumentException("Desired length $length is less than zero."); if (length <= str.length()) return str.subSequence(0, str.length()).toString(); StringBuilder sb = new StringBuilder(length); sb.append(str); for (int i =1;i<(length - str.length());i++){ sb.append(padChar); } return sb.toString(); } }
true
3ddbb8371065725037b496278b2f58f6c3fa2ca4
Java
grzesiek-galezowski/TrainingExamples
/Java/messaging-patterns/src/main/java/messaging_channels/InvalidMessageChannel.java
UTF-8
1,838
2.484375
2
[]
no_license
package messaging_channels; import com.fasterxml.jackson.databind.ObjectMapper; import de.scravy.either.Either; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.Maybe; import messaging_channels.events.PurchaseMade; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static java.lang.System.out; public class InvalidMessageChannel { public static class Server { private static final ObjectMapper objectMapper = new ObjectMapper(); public Flowable<String> purchasesChannel() { return Flowable .interval(1, TimeUnit.SECONDS) .map(time -> { if( time % 3 == 0) { return objectMapper.writeValueAsString(new PurchaseMade()); } else { return "lolokimono"; } }); } } public static class Deserializer { private static final ObjectMapper objectMapper = new ObjectMapper(); public Either<PurchaseMade, String> deserialize(final String payload) { try { final PurchaseMade purchaseMade = objectMapper.readValue(payload, PurchaseMade.class); return Either.left(purchaseMade); } catch (Throwable e) { return Either.right(payload); } } } public static class PurchasesClient { public void onPurchaseMade(final PurchaseMade purchaseMade) { out.println("PURCHASE: " + purchaseMade); } } public static class InvalidMessagesClient { public void onInvalidMessage(final String invalidMessage) { out.println("INVALID: " + invalidMessage); } } }
true