text
stringlengths 10
2.72M
|
|---|
package com.example.hemil.papa_johns.AbstractFactory;
/**
* Created by hemil on 11/28/2015.
*/
public class Pepperoni implements Pizza {
double cost;
public Pepperoni(int size, int quantity){
if(size==1){ cost = quantity*6.99; }
else if(size ==2 ){ cost = quantity*9.99; }
else if(size ==3){ cost = quantity* 13.99; }
}
public String getName(){
return "Ultimate Pepperoni Feast Pizza";
}
public double getCost()
{
return cost;
}
}
|
package de.varylab.discreteconformal.adapter;
import java.util.HashMap;
import java.util.Map;
import de.jtem.halfedge.Edge;
import de.jtem.halfedge.Face;
import de.jtem.halfedge.Node;
import de.jtem.halfedge.Vertex;
import de.jtem.halfedgetools.adapter.AbstractAdapter;
import de.jtem.halfedgetools.adapter.AdapterSet;
import de.jtem.halfedgetools.adapter.type.Weight;
@Weight
public class MappedWeightAdapter extends AbstractAdapter<Double> {
private Map<Edge<?, ?, ?>, Double>
wMap = new HashMap<Edge<?,?,?>, Double>();
private String
name = "Weights";
public MappedWeightAdapter() {
super(Double.class, true, true);
}
@SuppressWarnings("unchecked")
public MappedWeightAdapter(Map<? extends Edge<?,?,?>, Double> map) {
super(Double.class, true, true);
this.wMap = (Map<Edge<?, ?, ?>, Double>)map;
}
public MappedWeightAdapter(Map<? extends Edge<?,?,?>, Double> map, String name) {
this(map);
this.name = name;
}
@Override
public <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> Double getE(E e, AdapterSet a) {
if (wMap.containsKey(e)) {
return wMap.get(e);
} else {
return 0.0;
}
}
@Override
public <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> void setE(E e, Double value, AdapterSet a) {
wMap.put(e, value);
wMap.put(e.getOppositeEdge(), value);
}
@Override
public <N extends Node<?, ?, ?>> boolean canAccept(Class<N> nodeClass) {
return Edge.class.isAssignableFrom(nodeClass);
}
@Override
public double getPriority() {
return 10;
}
@Override
public String toString() {
return name;
}
}
|
package jokes.gradle.udacity.com.jokepresenter;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Vlad
*/
public class JokePresenterFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_joke, container, false);
TextView jokeTextView = rootView.findViewById(R.id.joke_tv);
Intent intent = getActivity().getIntent();
String joke = null;
if (intent != null){
joke = intent.getStringExtra(getString(R.string.joke_key));
}
if (joke != null) {
jokeTextView.setText(joke);
}
else {
jokeTextView.setText("No joke passed through an Intent");
}
return rootView;
}
}
|
package com.mvc.model;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.mvc.baseinterface.IEventInterface;
import com.mvc.baseinterface.InterfaceDispatcher;
import com.mvc.contants.Events;
import android.content.Context;
public class MvcModelController extends InterfaceDispatcher{
MainActivityModel mainActivityModel;
Context mContext;
public MvcModelController(Context context) {
this.mContext =context;
mainActivityModel= new MainActivityModel(context);
}
public void changeData(String text){
try {
FileOutputStream fos = mContext.openFileOutput("1.txt", 0);
fos.write(text.getBytes());
fos.close();
} catch (FileNotFoundException e) {
fireOut(Events.CONTENT_WRITE_ERROR, "write error: FileNotFoundException");
} catch (IOException e) {
fireOut(Events.CONTENT_WRITE_ERROR, "write error: IOException");
}
loadData();
}
public void loadData() {
mainActivityModel.loadData();
}
@Override
public void addEventListener(IEventInterface iEventInterface) {
mainActivityModel.addEventListener(iEventInterface);
super.addEventListener(iEventInterface);
}
}
|
package com.ara.recipeplanner.controller;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;
import com.ara.recipeplanner.dto.SeasonDto;
import com.ara.recipeplanner.dto.SeasonDtoMapper;
import com.ara.recipeplanner.exception.EntityDuplicatedException;
import com.ara.recipeplanner.exception.EntityNotFoundException;
import com.ara.recipeplanner.service.SeasonService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/seasons")
@Validated
public class SeasonController {
private final SeasonService service;
public SeasonController(SeasonService service) {
this.service = service;
}
@GetMapping
public List<SeasonDto> indexController() {
return service.index().stream()
.map(SeasonDtoMapper::toDto).collect(Collectors.toList());
}
@GetMapping("/{id}")
public SeasonDto showController(@PathVariable Long id)
throws EntityNotFoundException {
return SeasonDtoMapper.toDto(service.show(id));
}
@PostMapping
public SeasonDto createController(
@Valid @RequestBody SeasonDto newSeason)
throws EntityDuplicatedException {
return SeasonDtoMapper.toDto(
service.create(SeasonDtoMapper.toModel(newSeason)));
}
@PutMapping("/{id}")
public SeasonDto updateController(
@Valid @RequestBody SeasonDto newSeason, @PathVariable Long id)
throws EntityNotFoundException, EntityDuplicatedException {
return SeasonDtoMapper.toDto(
service.update(SeasonDtoMapper.toModel(newSeason), id));
}
@DeleteMapping("/{id}")
public void deleteController(@PathVariable Long id)
throws EntityNotFoundException {
service.delete(id);
}
}
|
package org.spring.management.member.exception;
public class UserValidException extends RuntimeException {
String field;
public UserValidException(String field, String message) {
super(message);
this.field = field;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
}
|
package com.windtalker.ui;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.google.firebase.auth.FirebaseAuth;
import com.windtalker.R;
import com.windtalker.model.ModelApplication;
import com.windtalker.model.ModelChannel;
import com.windtalker.model.ModelMessage;
import com.windtalker.service.WindtalkerServiceChannel;
import com.windtalker.service.WindtalkerServiceMessaging;
import com.windtalker.ui.adapter.AdapterChannelChat;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by jaapo on 11-11-2017.
*/
public class FragmentChat extends Fragment implements ModelChannel.ListenerChannel {
@BindView(R.id.interact_recycler_chat)
RecyclerView mRecyclerChat;
@BindView(R.id.interact_edit_message)
EditText mEditMessage;
@BindView(R.id.interact_button_send)
Button mButtonSend;
WindtalkerServiceMessaging serviceMessaging;
private String mContactKey;
private AdapterChannelChat mAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_chat, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mButtonSend.setOnClickListener(b -> executeChat());
serviceMessaging = new WindtalkerServiceMessaging();
serviceMessaging.start();
WindtalkerServiceChannel.getInstance().getChannel("Default").addListenerChannel(this);
mAdapter = new AdapterChannelChat();
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerChat.setLayoutManager(layoutManager);
mRecyclerChat.setAdapter(mAdapter);
}
public void executeChat()
{
ModelMessage message = new ModelMessage(FirebaseAuth.getInstance().getUid());
message.setChannelKey("Default");
message.setChatMessage(mEditMessage.getText().toString());
mEditMessage.setText("");
if(!message.equals(""))
{
ModelApplication.getInstance(getContext()).sendPersonalMessage(FirebaseAuth.getInstance().getUid(), message);
}
}
@Override
public void updateChannel(ModelChannel channel) {
}
}
|
package com.sheygam.loginarchitectureexample.data.repositories.addContact.web;
import com.sheygam.loginarchitectureexample.data.dao.Contact;
import io.reactivex.Single;
import retrofit2.Response;
/**
* Created by Kate on 18.02.2018.
*/
public class AddContactRetrofitRepository implements IAddContactWebRepository {
private SaveApi saveApi;
public AddContactRetrofitRepository(SaveApi saveApi) {
this.saveApi = saveApi;
}
private String handleSaveResponse(Response<Void> response) throws Exception {
if(response.isSuccessful()){
return response.message();
}
else if(response.code() == 401){
throw new Exception("Wrong contact!");
}else{
throw new Exception("Server error");
}
}
@Override
public Single<String> saveContact(String token, Contact contact) {
return saveApi.saveContact(contact, token)
.doOnError(throwable -> {throw new Exception("Connection error!");})
.map(this::handleSaveResponse);
}
}
|
package test2;
//новый класс!
public class Funny {
String a1="1";
String b1="2";
public void take() {
System.out.println("Testing!");
//Создал новый коммент! + еще
if ((a1 == null && b1 == null) || a1 == b1) {
System.out.println("a=b");
//перенес коммент
}
else {
System.out.println("a<>b");
}
//Еще один коммент!
}
}
|
package com.silverway.mboychenko.silverthread.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.silverway.mboychenko.silverthread.R;
import com.silverway.mboychenko.silverthread.activities.MainActivity;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MeditationsFragment extends Fragment {
public static final String MEDITATIONS_FRAGMENT_TYPE = "meditations_fragment_type";
public static final int MEDITATIONS_PAGE = 0;
public static final int SPIRITUAL_PRACTICES = 1;
@Bind(R.id.meditations_view_pager)
ViewPager mMeditationsViewPager;
@Bind(R.id.sliding_tabs)
TabLayout tabLayout;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_meditations, container, false);
ButterKnife.bind(this, view);
MeditationsViewPagerAdapter adapter = new MeditationsViewPagerAdapter(getChildFragmentManager());
mMeditationsViewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(mMeditationsViewPager);
return view;
}
@Override
public void onStart() {
((MainActivity) getActivity()).collapsedAppBar();
super.onStart();
}
class MeditationsViewPagerAdapter extends FragmentPagerAdapter {
final int PAGES_COUNT = 2;
public MeditationsViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
MeditationsListFragment fragment = new MeditationsListFragment();
Bundle bundle = new Bundle();
bundle.putInt(MEDITATIONS_FRAGMENT_TYPE, position);
fragment.setArguments(bundle);
return fragment;
}
@Override
public int getCount() {
return PAGES_COUNT;
}
@Override
public CharSequence getPageTitle(int position) {
return position == 0 ? getResources().getString(R.string.meditations_title) : getResources().getString(R.string.spiritual_title);
}
}
}
|
package com.memory.platform.modules.system.base.service.impl;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.memory.platform.common.util.BrowserUtils;
import com.memory.platform.common.util.ConvertUtils;
import com.memory.platform.common.util.DataUtils;
import com.memory.platform.core.service.impl.BaseServiceImpl;
import com.memory.platform.core.springmvc.WebContextUtils;
import com.memory.platform.hibernate4.dao.IBaseDao;
import com.memory.platform.modules.system.base.model.SystemLog;
import com.memory.platform.modules.system.base.service.ISystemLogService;
@Service("systemLogServiceImpl")
public class SystemLogServiceImpl extends BaseServiceImpl<SystemLog> implements ISystemLogService{
@Autowired
@Qualifier("baseDaoImpl")
private IBaseDao baseDao;
@Override
public void addLog(String logcontent, int loglevel, int operatetype) {
HttpServletRequest request = WebContextUtils.getRequest();
String broswer = BrowserUtils.checkBrowse(request);
SystemLog log = new SystemLog();
log.setLogContent(logcontent);
log.setLogLevel(loglevel);
log.setOperateType(operatetype);
log.setNote(ConvertUtils.getIp());
log.setBroswer(broswer);
log.setOperateTime(DataUtils.gettimestamp());
log.setSystemUser(WebContextUtils.getSessionUser());
baseDao.save(log);
}
}
|
package com.ackd151.maintenancemeter;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class TopEndRebuild extends AppCompatActivity {
int profileIndex;
Machine profile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_end_rebuild);
profileIndex = getIntent().getIntExtra("profileIndex", -1);
profile = PreferencesMgr.getProfile(this, profileIndex);
screenBuilder();
}
public void rebuildTopEnd(View v) {
EditText leftIntake = findViewById(R.id.left_intake_meas);
EditText leftExhaust = findViewById(R.id.left_exhaust_meas);
EditText rightIntake = findViewById(R.id.right_intake_meas);
EditText rightExhaust = findViewById(R.id.right_exhaust_meas);
// Check for empty editText fields
float leftIntakeGap = leftIntake.getText().length() == 0 ?
0 : Float.valueOf(leftIntake.getText().toString());
float leftExhaustGap = leftExhaust.getText().length() == 0 ?
0 : Float.valueOf(leftExhaust.getText().toString());
float rightIntakeGap = rightIntake.getText().length() == 0 ?
0 : Float.valueOf(rightIntake.getText().toString());
float rightExhaustGap = rightExhaust.getText().length() == 0 ?
0 : Float.valueOf(rightExhaust.getText().toString());
profile.resetTopEnd(leftIntakeGap, rightIntakeGap, leftExhaustGap, rightExhaustGap);
PreferencesMgr.saveProfile(this, profileIndex, profile);
setResult(Activity.RESULT_OK);
finish();
}
public void screenBuilder() {
TextView lastLE = findViewById(R.id.last_LE), lastRE = findViewById(R.id.last_RE);
TextView lastLI = findViewById(R.id.last_LI), lastRI = findViewById(R.id.last_RI);
lastLE.setText(Float.toString(profile.getExhaustLeftShim()));
lastRE.setText(Float.toString(profile.getExhaustRightShim()));
lastLI.setText(Float.toString(profile.getIntakeLeftShim()));
lastRI.setText(Float.toString(profile.getIntakeRightShim()));
}
}
|
/**
* <copyright>
* </copyright>
*
*
*/
package ssl.resource.ssl;
public interface ISslHoverTextProvider {
public String getHoverText(org.eclipse.emf.ecore.EObject object);
}
|
package expansion.neto.com.mx.jefeapp.ui.rechazadas;
import android.content.Context;
import android.content.SharedPreferences;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.ArrayList;
import expansion.neto.com.mx.jefeapp.R;
import expansion.neto.com.mx.jefeapp.databinding.ActivityAutorizaBinding;
import expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.FragmentDialogMostrarTip;
import expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.mandarDatos.FragmentDatosConstruccion;
import expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.mandarDatos.FragmentDatosGeneralidades;
import expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.mandarDatos.FragmentDatosPropietario;
import expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.mandarDatos.FragmentDatosSitio;
import expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.mandarDatos.FragmentDatosSuperficie;
import expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.mandarDatos.FragmentDatosZonificacion;
import expansion.neto.com.mx.jefeapp.fragment.fragmentRechazadas.FragmentDialogCancelarMdRechazadas;
import expansion.neto.com.mx.jefeapp.fragment.fragmentRechazadas.FragmentModificar;
import expansion.neto.com.mx.jefeapp.modelView.crearModel.CrearDatosPropietario;
import expansion.neto.com.mx.jefeapp.modelView.crearModel.CrearDatosSitio;
import expansion.neto.com.mx.jefeapp.modelView.crearModel.CrearDatosSuperficie;
import expansion.neto.com.mx.jefeapp.modelView.crearModel.CrearGeneralidades;
import expansion.neto.com.mx.jefeapp.modelView.crearModel.Tips;
import expansion.neto.com.mx.jefeapp.provider.crearProvider.ProviderConsultaTips;
import static expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.FragmentDialogCancelarMd.cleanShared;
import static expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.guardarDatos.GuardarDatosConstruccion.obtenerConstruccion;
import static expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.guardarDatos.GuardarDatosGeneralidades.obtenerGeneralidades;
import static expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.guardarDatos.GuardarDatosPropietario.obtenerPropietario;
import static expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.guardarDatos.GuardarDatosSitio.obtenerSitio;
import static expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.guardarDatos.GuardarDatosSuperficie.obtenerSuperficie;
import static expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.modulos.guardarDatos.GuardarDatosZonificacion.obtenerZonificacion;
/**
* Created by marcosmarroquin on 23/03/18.
*/
public class ActivityDetalleModifica extends AppCompatActivity{
private ActivityAutorizaBinding binding;
private PageAdapter adapter;
private int currentItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
initDataBinding();
cleanShared(ActivityDetalleModifica.this);
currentItem = 0;
binding.anterior.setVisibility(View.INVISIBLE);
adapter = new PageAdapter(getSupportFragmentManager());
binding.pager.setAdapter(adapter);
binding.pager.setCurrentItem(currentItem);
setNavigator();
binding.help.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mostrarTip("1");
}
});
binding.pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
//TODO Crear condiciones para que se guarde solo cuando se avanza no cuando se regresa
final SharedPreferences preferences = getSharedPreferences("datosExpansion", Context.MODE_PRIVATE);
String mdId = preferences.getString("mdIdterminar", "");
if(mdId.length()==0 || mdId.equals("0")){
mdId = "";
}
if(position==0) {
binding.help.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mostrarTip("1");
}
});
}
if(position==1) {
binding.help.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mostrarTip("2");
}
});
CrearDatosSitio crearDatosPropietario = obtenerSitio(ActivityDetalleModifica.this);
if(crearDatosPropietario!=null || !crearDatosPropietario.getNombreSitio().equals("")){
FragmentDatosSitio crear = new FragmentDatosSitio(ActivityDetalleModifica.this);
crear.mandarDatos(crearDatosPropietario);
}
}
if(position==2){
binding.help.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mostrarTip("3");
}
});
if(!mdId.equals("") || mdId.equals("0")){
CrearDatosPropietario crearDatosPropietario = obtenerPropietario(ActivityDetalleModifica.this);
if(!crearDatosPropietario.getMdId().equals("") && crearDatosPropietario!=null){
FragmentDatosPropietario crear = new FragmentDatosPropietario(ActivityDetalleModifica.this);
crear.mandarDatosPropietario(crearDatosPropietario);
getSharedPreferences("datosPropietario", 0).edit().clear().apply();
}
}
}
if(position==3){
binding.help.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mostrarTip("4");
}
});
if(!mdId.equals("") || mdId.equals("0")){
CrearDatosSuperficie crearDatosSuperficie = obtenerSuperficie(ActivityDetalleModifica.this);
if(!crearDatosSuperficie.getMdId().equals("") && crearDatosSuperficie!=null){
crearDatosSuperficie.setMdId(mdId);
FragmentDatosSuperficie crear = new FragmentDatosSuperficie(ActivityDetalleModifica.this);
crear.mandarDatosSuperficie(crearDatosSuperficie);
getSharedPreferences("datosSuperficie", 0).edit().clear().apply();
}
}
}
if(position==4){
binding.help.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mostrarTip("5");
}
});
if(!mdId.equals("") || mdId.equals("0")) {
String json = obtenerZonificacion(ActivityDetalleModifica.this);
if (json.length() > 0 || !json.equals("")) {
FragmentDatosZonificacion crear = new FragmentDatosZonificacion(ActivityDetalleModifica.this);
crear.mandarDatosZonificacion(json);
getSharedPreferences("datosZonificacion", 0).edit().clear().apply();
}
}
}
if(position==5){
binding.help.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mostrarTip("6");
}
});
if(!mdId.equals("") || mdId.equals("0")){
String json = obtenerConstruccion(ActivityDetalleModifica.this);
if(json.length()>0 || !json.equals("")){
FragmentDatosConstruccion crear = new FragmentDatosConstruccion(ActivityDetalleModifica.this);
crear.mandarDatosConstruccion(json);
getSharedPreferences("datosConstruccion", 0).edit().clear().apply();
}
}
}
if(position==6){
binding.help.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mostrarTip("7");
}
});
if(!mdId.equals("") || mdId.equals("0")){
CrearGeneralidades generalidades = obtenerGeneralidades(ActivityDetalleModifica.this);
if(!generalidades.getMdId().equals("") && generalidades!=null){
FragmentDatosGeneralidades crear = new FragmentDatosGeneralidades(ActivityDetalleModifica.this);
crear.mandarDatosGeneralidades(generalidades);
getSharedPreferences("datosGeneralidades", 0).edit().clear().apply();
}
}
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int position) {
//Log.e("******", "swipe "+position);
// TODO Auto-generated method stub
if (binding.pager.getCurrentItem() == 0) {
binding.anterior.setVisibility(View.INVISIBLE);
//Log.e("******", "INVISIBLE "+position);
} else {
binding.anterior.setVisibility(View.VISIBLE);
//Log.e("******", "VISIBLE "+position);
}
if (binding.pager.getCurrentItem() == (binding.pager.getAdapter().getCount() - 1)) {
//Log.e("******", "FINISH "+position);
binding.siguiente.setText("FINISH");
} else {
// Log.e("******", "NEXT "+position);
binding.siguiente.setText("NEXT");
}
setNavigator();
}
});
binding.anterior.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (binding.pager.getCurrentItem() != 0) {
binding.pager.setCurrentItem(binding.pager.getCurrentItem() - 1);
}
setNavigator();
}
});
binding.siguiente.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (binding.pager.getCurrentItem() != (binding.pager.getAdapter().getCount() - 1)) {
binding.pager.setCurrentItem(binding.pager.getCurrentItem() + 1);
} else {
Toast.makeText(ActivityDetalleModifica.this, "Finish",
Toast.LENGTH_SHORT).show();
}
setNavigator();
}
});
}
public void setNavigator() {
String navigation = "";
for (int i = 0; i < adapter.getCount(); i++) {
if (i == binding.pager.getCurrentItem()) {
navigation += getString(R.string.material_icon_point_full)
+ " ";
} else {
navigation += getString(R.string.material_icon_point_empty)
+ " ";
}
}
binding.circuloPosicion.setText(navigation);
}
public void setCurrentSlidePosition(int position) {
this.currentItem = position;
}
public int getCurrentSlidePosition() {
return this.currentItem;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
public class PageAdapter extends FragmentPagerAdapter {
public PageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
@Override
public int getCount() {
return 7;
}
@Override
public Fragment getItem(int position) {
if (position == 0) {
return FragmentModificar.newInstance(position);
} else if (position == 1) {
return FragmentModificar.newInstance(position);
} else {
return FragmentModificar.newInstance(position);
}
}
}
/**
* método que setea la vista con el binding
*/
private void initDataBinding() {
binding = DataBindingUtil.setContentView(this, R.layout.activity_autoriza);
}
@Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
getSupportFragmentManager().popBackStack();
} else {
FragmentManager fm = getSupportFragmentManager();
FragmentDialogCancelarMdRechazadas dFragment = new FragmentDialogCancelarMdRechazadas();
dFragment.show(fm, "Dialog Fragment");
}
}
ArrayList<Tips.Tip> tips;
public void mostrarTip(String pantalla){
ProviderConsultaTips.getInstance(ActivityDetalleModifica.this).obtenerTips(pantalla, new ProviderConsultaTips.ConsultaTips() {
@Override
public void resolve(Tips tip) {
if(tip.getCodigo()==200){
tips = new ArrayList<>();
if(tip.getTips().size()>0){
for(int i=0;i<tip.getTips().size();i++){
tips.add(tip.getTips().get(i));
}
SharedPreferences preferences;
preferences = getSharedPreferences("datosExpansion", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(tips);
editor.putString("tips", json);
editor.apply();
FragmentManager fm = getSupportFragmentManager();
FragmentDialogMostrarTip dFragment = new FragmentDialogMostrarTip();
dFragment.show(fm, "Dialog Fragment");
}else{
Toast.makeText(ActivityDetalleModifica.this, "Aún no se agrega tip para esta opción",
Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(ActivityDetalleModifica.this, tip.getMensaje(),
Toast.LENGTH_SHORT).show();
}
}
@Override
public void reject(Exception e) {
}
});
}
}
|
package com.myvodafone.android.front.netperform;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ImageView;
import com.myvodafone.android.R;
import com.myvodafone.android.business.managers.MemoryCacheManager;
import com.myvodafone.android.front.VFGRFragment;
import com.myvodafone.android.front.settings.FragmentPrivacy;
import com.myvodafone.android.front.settings.FragmentPrivacyPolicy;
import com.myvodafone.android.front.soasta.OmnitureHelper;
import com.myvodafone.android.model.business.VFAccount;
import com.myvodafone.android.model.business.VFMobileAccount;
import com.myvodafone.android.model.business.VFMobileXGAccount;
import com.myvodafone.android.model.service.Login;
import com.myvodafone.android.model.service.UserTypeSmartResponse;
import com.myvodafone.android.utils.VFPreferences;
import com.tm.corelib.ROContext;
import com.tm.corelib.RODataMediator;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.myvodafone.android.utils.StaticTools;
public class FragmentNetUsage extends VFGRFragment implements NetPerformPermissions.NetPerformPermissionsCallbacks, DataLoadedListener {
private TextView headerMessageText, fromDate, toDate, usagePeriodLabel;
private buttonStates currentButtonState;
private boolean checkedForDeviceGpsSettings = false;
private boolean checkedForPermissions = false;
private boolean shouldShowNetworkMainDescription=true;
private Button btnStart, btnStartTrans;
private enum buttonStates {
BUTTON_STATE_PERMISSION,
BUTTON_STATE_GPS,
BUTTON_STATE_APP_SETTINGS,
BUTTON_STATE_NORMAL
}
interface NetUsageListener{
void setUpData();
}
private Typeface typefaceBold, typefaceNormal;
FragmentNetworkUsage fragmentNetworkUsage;
FragmentWifiUsage fragmentWifiUsage;
View tabNet, tabWifi, redArrow1, redArrow2, underLine1, underLine2, usageDate;
TextView tabWifiLabel, tabNetLabel, msisdnText, usernameText;
private ImageView imgProfile;
public static FragmentNetUsage newInstance() {
return new FragmentNetUsage();
}
@Override
public void onAttach(Context ctx) {
super.onAttach(ctx);
typefaceBold = Typeface.createFromAsset(activity.getAssets(), "fonts/VodafoneRg_Bd.ttf");
typefaceNormal = Typeface.createFromAsset(activity.getAssets(), "fonts/VodafoneRg.ttf");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_net_usage, container, false);
initViews(v);
v.findViewById(R.id.btnClearUsage).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearUsage(v);
}
});
OmnitureHelper.trackView("Network usage");
return v;
}
private void initViews(View v){
imgProfile = (ImageView) v.findViewById(R.id.profile_icon);
header = (TextView) v.findViewById(R.id.headerTitle);
activity.sideMenuHelper.setToggle(v.findViewById(R.id.toggleDrawer));
activity.sideMenuHelper.setBackButton(v.findViewById(R.id.back), activity);
tabNet = v.findViewById(R.id.network_tab_container);
tabWifi = v.findViewById(R.id.wifiTabContainer);
tabNetLabel = (TextView)v.findViewById(R.id.network_tab_label);
tabWifiLabel = (TextView)v.findViewById(R.id.wifiTabLabel);
fragmentNetworkUsage = new FragmentNetworkUsage();
fragmentWifiUsage = new FragmentWifiUsage();
redArrow1 = v.findViewById(R.id.redArrowTab1);
redArrow2 = v.findViewById(R.id.redArrowTab2);
underLine1 = v.findViewById(R.id.networkTabUnderline);
underLine2 = v.findViewById(R.id.wifiTabUnderline);
usernameText = (TextView) v.findViewById(R.id.txtUsername);
msisdnText = (TextView) v.findViewById(R.id.txtPhoneNumber);
msisdnText.setVisibility(View.VISIBLE);
usernameText.setVisibility(View.VISIBLE);
btnStart = (Button) v.findViewById(R.id.start_btn_red);
btnStartTrans = (Button) v.findViewById(R.id.start_btn);
headerMessageText = (TextView) v.findViewById(R.id.main_description_net_usage);
headerMessageText.setText(getStringSafe(R.string.network_usage_description_text));
btnStart.setVisibility(View.GONE);
btnStartTrans.setVisibility(View.VISIBLE);
btnStartTrans.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.replaceFragment(FragmentPrivacyPolicy.newInstance());
}
});
fromDate = (TextView) v.findViewById(R.id.text_usage_from_date);
toDate = (TextView) v.findViewById(R.id.text_usage_to_date);
usageDate = (View)v.findViewById(R.id.date_layout);
usagePeriodLabel = (TextView)v.findViewById(R.id.text_usage_from);
String currentDate = new SimpleDateFormat("dd/MM/yyyy").format(Calendar.getInstance().getTime());
toDate.setText(currentDate);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, -31);
Date fromDate = calendar.getTime();
String dateFrom = new SimpleDateFormat("dd/MM/yyyy").format(fromDate);
this.fromDate.setText(dateFrom);
redArrow1.setVisibility(View.VISIBLE);
underLine1.setVisibility(View.VISIBLE);
redArrow2.setVisibility(View.INVISIBLE);
underLine2.setVisibility(View.INVISIBLE);
tabNetLabel.setTypeface(typefaceBold, Typeface.BOLD);
tabWifiLabel.setTypeface(typefaceNormal, Typeface.NORMAL);
tabNet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Map<String, Object> contextData = new HashMap<String, Object>();
contextData.put("vfappcontent.tabselected", "Network usage xG");
OmnitureHelper.trackEvent("vfappcontent.TabSelection", contextData);
getChildFragmentManager().beginTransaction().replace(R.id.frameNetUsage, fragmentNetworkUsage).
commitNowAllowingStateLoss();
redArrow1.setVisibility(View.VISIBLE);
underLine1.setVisibility(View.VISIBLE);
redArrow2.setVisibility(View.INVISIBLE);
underLine2.setVisibility(View.INVISIBLE);
tabNetLabel.setTypeface(typefaceBold, Typeface.BOLD);
tabWifiLabel.setTypeface(typefaceNormal, Typeface.NORMAL);
if (shouldShowNetworkMainDescription)
headerMessageText.setText(getStringSafe(R.string.network_usage_description_text));
}
});
tabWifi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Map<String, Object> contextData = new HashMap<String, Object>();
contextData.put("vfappcontent.tabselected", "Network usage WiFi");
OmnitureHelper.trackEvent("vfappcontent.TabSelection", contextData);
getChildFragmentManager().beginTransaction().replace(R.id.frameNetUsage, fragmentWifiUsage).
commitNowAllowingStateLoss();
redArrow1.setVisibility(View.INVISIBLE);
underLine1.setVisibility(View.INVISIBLE);
redArrow2.setVisibility(View.VISIBLE);
underLine2.setVisibility(View.VISIBLE);
tabNetLabel.setTypeface(typefaceNormal, Typeface.NORMAL);
tabWifiLabel.setTypeface(typefaceBold, Typeface.BOLD);
if (shouldShowNetworkMainDescription)
headerMessageText.setText(getStringSafe(R.string.network_usage_description_text_wifi));
}
});
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (currentButtonState) {
case BUTTON_STATE_APP_SETTINGS:
activity.replaceFragment(FragmentPrivacy.newInstanceAndBackToNetUsage());
break;
case BUTTON_STATE_GPS:
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
break;
case BUTTON_STATE_NORMAL:
// Nothing, button is hidden
break;
case BUTTON_STATE_PERMISSION:
Intent myAppSettings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getContext().getApplicationContext().getPackageName()));
myAppSettings.addCategory(Intent.CATEGORY_DEFAULT);
myAppSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(myAppSettings);
break;
}
}
});
setUsernameAndMsisdn();
getChildFragmentManager().beginTransaction().replace(R.id.frameNetUsage, fragmentNetworkUsage).
commitNowAllowingStateLoss();
}
@Override
public void onResume() {
super.onResume();
setFragmentTitle();
//BG
StaticTools.setAppBackground(getContext(),StaticTools.BACKGROUND_TYPE_INSIDE,(ImageView)getView().findViewById(R.id.insideBG),null);
currentButtonState = buttonStates.BUTTON_STATE_NORMAL;
checkNetPerformRequiredPermissions();
}
@Override
public BackFragment getPreviousFragment() {
return BackFragment.FragmentHome;
}
@Override
public String getFragmentTitle() {
return getString(R.string.network_usage);
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void setUsernameAndMsisdn() {
String currentMsisdnNetPerform = NPUtils.getMsisdnUsedByNetPerform();
if (!StaticTools.isNullOrEmpty(currentMsisdnNetPerform)) {
boolean matchedAccount = false;
if (MemoryCacheManager.getProfile() != null) {
VFAccount account = null;
for (VFAccount vfAccount: MemoryCacheManager.getProfile().getAccountList()) {
if (currentMsisdnNetPerform.equals(StaticTools.getAccountMsisdn(vfAccount))) {
account = vfAccount;
break;
}
}
if (account != null) {
matchedAccount = true;
usernameText.setVisibility(View.VISIBLE);
msisdnText.setVisibility(View.VISIBLE);
loadProfileData(account, currentMsisdnNetPerform, imgProfile, usernameText, msisdnText);
}
}
if (!matchedAccount) {
if (usernameText != null && msisdnText != null && imgProfile != null) {
usernameText.setVisibility(View.GONE);
msisdnText.setVisibility(View.VISIBLE);
msisdnText.setText(currentMsisdnNetPerform);
loadProfileImage(currentMsisdnNetPerform);
}
}
} else {
if (usernameText != null && msisdnText != null && imgProfile != null){
usernameText.setVisibility(View.GONE);
msisdnText.setVisibility(View.GONE);
imgProfile.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.profile_icon));
}
}
}
public void loadProfileData(VFAccount vfAccount, String msisdn, ImageView profileIcon, TextView usernameText, TextView msisdnText) {
String firstName = "", lastName = "";
if (vfAccount != null) {
if (MemoryCacheManager.checkAccountType(vfAccount) == VFAccount.TYPE_MOBILE) {
Login login = ((VFMobileAccount) vfAccount).getMobileAccount();
if (login != null) {
firstName = login.getFirstName();
lastName = login.getLastName();
StaticTools.loadProfileImage(profileIcon, R.drawable.profile_icon, msisdn, activity);
}
} else if (MemoryCacheManager.checkAccountType(vfAccount) == VFAccount.TYPE_MOBILE_VF3G) {
UserTypeSmartResponse login = ((VFMobileXGAccount) vfAccount).getMobileAccount();
if (login != null) {
StaticTools.loadProfileImage(profileIcon, R.drawable.profile_icon, msisdn, activity);
}
}
}
String defaultName;
if (!StaticTools.isNullOrEmpty(firstName) && !StaticTools.isNullOrEmpty(lastName)) {
defaultName = firstName + " " + lastName;
} else {
defaultName = activity.getString(R.string.burger_menu_default);
}
if (vfAccount != null) {
StaticTools.loadFriendlyName(usernameText, vfAccount.getUsername(), msisdn, defaultName);
} else {
usernameText.setText(defaultName);
}
if (msisdnText != null) {
msisdnText.setText(msisdn);
}
}
private void setLabelsX(int id_min, int id_max, long[][] dataset) {
if (dataset != null) {
long xmin = dataset[0][0] - 86400000L / 2;
long xmax = dataset[0][0] + 30 * 86400000L + 86400000L / 2;
Date date_min = new Date(xmin);
Date date_max = new Date(xmax);
SimpleDateFormat df = new SimpleDateFormat("MMM d ");
TextView tv = (TextView) getView().findViewById(id_min);
tv.setText(df.format(date_min));
tv = (TextView) getView().findViewById(id_max);
tv.setText(df.format(date_max));
}
}
private synchronized void loadProfileImage(String msisdn) {
StaticTools.loadProfileImage(imgProfile, R.drawable.profile_icon, msisdn, getContext());
}
public void clearUsage(View v){
Runnable clearUsageRunnable = new Runnable() {
@Override
public void run() {
Map<String, Object> contextData = new HashMap<String, Object>();
contextData.put("vfappcontent.toolused", "Network usage");
OmnitureHelper.trackEvent("vfappcontent.ToolDeleteOldData", contextData);
RODataMediator dataMediator = RODataMediator.getInstance();
dataMediator.resetNetworkCounters();
Fragment fragment = getChildFragmentManager().findFragmentById(R.id.frameNetUsage);
if(fragment instanceof FragmentNetworkUsage){
((FragmentNetworkUsage)fragment).setUpData();
}
else if(fragment instanceof FragmentWifiUsage){
((FragmentWifiUsage)fragment).setUpData();
}
}
};
NPUtils.showNpGeneralPermissionDialog(activity, clearUsageRunnable, null, NPUtils.GeneralPermissionType.GENERAL_PERMISSION_TYPE_RESET_NETWORK);
}
@Override
public void onPermissionsDeclinedForever() {
headerMessageText.setText(getStringSafe(R.string.np_general_perm_settings_details));
btnStart.setText(getStringSafe(R.string.np_button_device_settings));
currentButtonState = buttonStates.BUTTON_STATE_PERMISSION;
btnStart.setVisibility(View.VISIBLE);
btnStartTrans.setVisibility(View.GONE);
usagePeriodLabel.setVisibility(View.GONE);
usageDate.setVisibility(View.GONE);
shouldShowNetworkMainDescription = false;
}
@Override
public void onPermissionsGranted() {
headerMessageText.setText(getStringSafe(R.string.network_usage_description_text));
//btnStart.setText(getStringSafe(R.string.np_speedcheck_btn_start));
currentButtonState = buttonStates.BUTTON_STATE_NORMAL;
btnStart.setVisibility(View.GONE);
btnStartTrans.setVisibility(View.VISIBLE);
usagePeriodLabel.setVisibility(View.VISIBLE);
usageDate.setVisibility(View.VISIBLE);
shouldShowNetworkMainDescription = true;
// mShouldChangeHeaderText = true;
}
@Override
public void onPermissionsDeclined() {
headerMessageText.setText(getStringSafe(R.string.np_general_perm_settings_details));
btnStart.setText(getStringSafe(R.string.np_button_device_settings));
currentButtonState = buttonStates.BUTTON_STATE_PERMISSION;
btnStart.setVisibility(View.VISIBLE);
btnStartTrans.setVisibility(View.GONE);
usagePeriodLabel.setVisibility(View.GONE);
usageDate.setVisibility(View.GONE);
shouldShowNetworkMainDescription = false;
}
private void checkNetPerformRequiredPermissions() {
// Location service enabled (device settings)
// Net perform permissions granted
// Network optimisation toggle enabled in app settings
if (!StaticTools.checkLocationServices(getContext())) {
// Location Device GPS Services
headerMessageText.setText(getStringSafe(R.string.np_net_usage_go_to_device_settings));
btnStart.setText(getStringSafe(R.string.np_button_device_settings));
currentButtonState = buttonStates.BUTTON_STATE_GPS;
btnStart.setVisibility(View.VISIBLE);
btnStartTrans.setVisibility(View.GONE);
usagePeriodLabel.setVisibility(View.GONE);
usageDate.setVisibility(View.GONE);
shouldShowNetworkMainDescription = false;
if (!checkedForDeviceGpsSettings) {
checkedForDeviceGpsSettings = true;
Runnable acceptRunnable = new Runnable() {
@Override
public void run() {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
};
NPUtils.showNpGeneralPermissionDialog(activity, acceptRunnable, null, NPUtils.GeneralPermissionType.GENERAL_PERMISSION_TYPE_LOCATION);
}
} else if (!ROContext.checkRequiredPermissions()) {
if (!checkedForPermissions) {
checkedForPermissions = true;
NetPerformPermissions.processNetPerformPermissions(activity, new WeakReference<NetPerformPermissions.NetPerformPermissionsCallbacks>(this));
} else {
headerMessageText.setText(getStringSafe(R.string.np_net_usage_go_to_permission_settings));
btnStart.setText(getStringSafe(R.string.np_button_device_settings));
currentButtonState = buttonStates.BUTTON_STATE_PERMISSION;
btnStart.setVisibility(View.VISIBLE);
btnStartTrans.setVisibility(View.GONE);
usagePeriodLabel.setVisibility(View.GONE);
usageDate.setVisibility(View.GONE);
shouldShowNetworkMainDescription = false;
}
} else if (!VFPreferences.isNetPerformTailoredServicesEnabled()) {
headerMessageText.setText(getStringSafe(R.string.np_net_usage_go_to_app_settings));
btnStart.setText(getStringSafe(R.string.np_button_app_settings));
currentButtonState = buttonStates.BUTTON_STATE_APP_SETTINGS;
btnStart.setVisibility(View.VISIBLE);
btnStartTrans.setVisibility(View.GONE);
usagePeriodLabel.setVisibility(View.GONE);
usageDate.setVisibility(View.GONE);
shouldShowNetworkMainDescription = false;
Runnable acceptRunnable = new Runnable() {
@Override
public void run() {
VFPreferences.setNetPerformNetworkOptimizationEnabled(true);
VFPreferences.setNetPerformTailoredServicesEnabled(true);
headerMessageText.setText(getStringSafe(R.string.network_usage_description_text));
currentButtonState = buttonStates.BUTTON_STATE_NORMAL;
btnStart.setVisibility(View.GONE);
btnStartTrans.setVisibility(View.VISIBLE);
usagePeriodLabel.setVisibility(View.VISIBLE);
usageDate.setVisibility(View.VISIBLE);
shouldShowNetworkMainDescription = true;
}
};
// Runnable cancelRunnable = new Runnable() {
// @Override
// public void run() {
// VFPreferences.setNetPerformNetworkOptimizationEnabled(true);
// headerMessageText.setText(getStringSafe(R.string.np_button_go_to_app_settings));
// btnStart.setText(getStringSafe(R.string.np_button_app_settings));
// currentButtonState = buttonStates.BUTTON_STATE_APP_SETTINGS;
// }
// };
NPUtils.showNpGeneralPermissionDialog(activity, acceptRunnable, null, NPUtils.GeneralPermissionType.GENERAL_PERMISSION_TYPE_TOGGLES_TAILORED);
} else {
// Normal state
headerMessageText.setText(getStringSafe(R.string.network_usage_description_text));
//btnStart.setText(getStringSafe(R.string.np_speedcheck_btn_start));
currentButtonState = buttonStates.BUTTON_STATE_NORMAL;
btnStart.setVisibility(View.GONE);
btnStartTrans.setVisibility(View.VISIBLE);
usagePeriodLabel.setVisibility(View.VISIBLE);
usageDate.setVisibility(View.VISIBLE);
shouldShowNetworkMainDescription = true;
}
}
@Override
public void onFailedNetwork(int countOfFailedCallsNetwork) {
if (countOfFailedCallsNetwork == 5 && shouldShowNetworkMainDescription){
if (headerMessageText != null && usagePeriodLabel != null && usageDate != null){
headerMessageText.setText(R.string.network_usage_generic_error_message_network);
usagePeriodLabel.setVisibility(View.GONE);
usageDate.setVisibility(View.GONE);
}
}
}
@Override
public void onFailedWiFi(int countOfFailedCallsWiFi) {
if (countOfFailedCallsWiFi == 2 && shouldShowNetworkMainDescription){
if (headerMessageText != null){
headerMessageText.setText(R.string.network_usage_generic_error_message_wifi);
}
}
}
}
//RODataMediator.getInstance().resetNetworkCounters();
|
package Lab8;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Assignment3 {
public static void main(String[] args) throws FileNotFoundException {
int countwords=0,countlines=0,countchar=0,array1=0;
File file= new File("C:\\Users\\vijsimha\\Desktop\\vijaya.txt");
Scanner scanner=new Scanner(file);
while(scanner.hasNextLine())
{
String line=scanner.nextLine();
String []words=line.split(" ");
countwords +=words.length;
countlines+=1;
countchar+=countwords;
}
System.out.println("number of words:" +countwords);
System.out.println(" number of lines: "+countlines);
System.out.println(" number of characters:" +countchar);
}
}
|
{{ hello }}
It's currently {% now | date_format: "yyyy-MM-dd 'at' HH:mm:ss" %}
Nested variable: {{ foo.bar }}
foreach 循环
{% for dude in guys %}
Current dude is {{ dude | uppercase }}...{% if dude == "matt" %} AWESOME!{% endif %}
{% if currentLoop.currentIndex == 0 %}
(the best!) {% comment %} Should only happen for Matt {% /comment %}
{% for 1 to 5 %}*{% endfor %}
{% endif %}
{% endfor %}
Last of the {{ guys.@count }} guys was {{ guys.@lastObject | pascalcased }}
表达式,标记语言 Markers look like {{ engine.delimiters.markerStart }} this {{ engine.delimiters.markerEnd }}
Variables look like {{ engine.delimiters.expressionStart }} this {{ engine.delimiters.expressionEnd }}
Filter delimiter is {{ engine.delimiters.filter }}
We also know about {{ YES }} and {{ NO }} or {{ true }} and {{ false }}
Is 1 less than 2? {% if 1 < 2 %} Yes! {% else %} No? {% endif %}
{% literal %}This text won't be {% now %} interpreted.{% /literal %}
For循环
{% for 1 to 5 %}{{ currentLoop.currentIndex }}{%if currentLoop.currentIndex % 2%}[ODD] {%else%}[EVEN] {%endif%}{% endfor %}
相反的排序
{% for 1 to 5 reversed %}{{ currentLoop.currentIndex }}{% cycle "[odd] " "[even] " %}{% endfor %}
And we're done.
{{ setting.Developer }}
{{ setting.CompanyName }}
{{ setting.CompanyCode }}
table name: {{ table.name }}
table schema: {{ table.schema }}
table meaning:{{ table.meaning }}
table description:{{ table.description }}
table isTenant:{{ table.isTenant }}
字段列表
{% for column in table.columns %}
Current column is {{ column.name | uppercase }} | {{ column.java }}| {{ column.isRequired }} | {{ column.type }} | {{ column.meaning }}
{% endfor %}
|
package com.example.android.appclient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import net.LoginResult;
import net.PersonIDResult;
import net.RegisterRequest;
import net.RegisterResult;
import java.net.URL;
import tree.Family;
import tree.Person;
public class LoginFragment extends Fragment {
private EditText serverHostEditText;
private EditText serverPortEditText;
private EditText userNameEditText;
private EditText passwordEditText;
private EditText emailEditText;
private EditText firstNameEditText;
private EditText lastNameEditText;
private RadioGroup genderRadioGroup;
private RadioButton maleButton;
private RadioButton femaleButton;
private View view;
private View loginButton;
private View registerButon;
private String authToken;
private String personID;
private Person person;
public LoginFragment() {
// Required empty public constructor
}
public static LoginFragment newInstance() {
LoginFragment fragment = new LoginFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_login, container, false);
serverHostEditText = view.findViewById(R.id.serverHostEditText);
serverPortEditText = view.findViewById(R.id.serverPortEditText);
userNameEditText = view.findViewById(R.id.userNameEditText);
passwordEditText = view.findViewById(R.id.passwordEditText);
emailEditText = view.findViewById(R.id.emailEditText);
firstNameEditText = view.findViewById(R.id.firstNameEditText);
lastNameEditText = view.findViewById(R.id.lastNameEditText);
genderRadioGroup = view.findViewById(R.id.genderRadioGroup);
maleButton = view.findViewById(R.id.maleButton);
femaleButton = view.findViewById(R.id.femaleButton);
loginButton = view.findViewById(R.id.loginButton);
registerButon = view.findViewById(R.id.registerButton);
maleButton.addTextChangedListener(textWatcher);
femaleButton.addTextChangedListener(textWatcher);
serverPortEditText.addTextChangedListener(textWatcher);
serverHostEditText.addTextChangedListener(textWatcher);
userNameEditText.addTextChangedListener(textWatcher);
passwordEditText.addTextChangedListener(textWatcher);
emailEditText.addTextChangedListener(textWatcher);
firstNameEditText.addTextChangedListener(textWatcher);
lastNameEditText.addTextChangedListener(textWatcher);
loginButton.setEnabled(false);
registerButon.setEnabled(false);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(serverHostEditText.getText().toString().equals("") || serverPortEditText.getText().toString().equals("") || userNameEditText.getText().toString().equals("") || passwordEditText.getText().toString().equals("")) {
Toast.makeText(getActivity(), R.string.toast_login_fail, Toast.LENGTH_SHORT).show();
}else{
loginButtonClicked();
}
}
});
registerButon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(serverHostEditText.getText().toString().equals("") || serverPortEditText.getText().toString().equals("") || userNameEditText.getText().toString().equals("") || passwordEditText.getText().toString().equals("") || emailEditText.getText().toString().equals("") || firstNameEditText.getText().toString().equals("") || lastNameEditText.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Register Failed", Toast.LENGTH_SHORT).show();
} else {
registerButtonClicked();
}
}
});
return view;
}
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
checkText();
}
@Override
public void afterTextChanged(Editable s) {
}
};
private void checkText(){
if(serverHostEditText.getText().toString().equals("") || serverPortEditText.getText().toString().equals("") || userNameEditText.getText().toString().equals("") || passwordEditText.getText().toString().equals("")) {
loginButton.setEnabled(false);
}else{
loginButton.setEnabled(true);
}
if(!maleButton.isChecked() && !femaleButton.isChecked()){
registerButon.setEnabled(false);
}else {
if (serverHostEditText.getText().toString().equals("") || serverPortEditText.getText().toString().equals("") || userNameEditText.getText().toString().equals("") || passwordEditText.getText().toString().equals("") || emailEditText.getText().toString().equals("") || firstNameEditText.getText().toString().equals("") || lastNameEditText.getText().toString().equals("")) {
registerButon.setEnabled(false);
} else {
registerButon.setEnabled(true);
}
}
}
private void loginButtonClicked(){
LoginTask task = new LoginTask();
task.execute();
}
public class LoginTask extends AsyncTask <URL, Void, LoginResult> {
@Override
protected LoginResult doInBackground(URL... urls) {
Client client = new Client();
LoginResult result = client.login(serverHostEditText.getText().toString(), serverPortEditText.getText().toString(), userNameEditText.getText().toString(), passwordEditText.getText().toString());
if(result == null){
return result;
}
if(result.getMessage() != null){
return result;
}
authToken = result.getAuthToken();
personID = result.getPersonID();
PersonIDResult personIDResult = client.getPerson(serverHostEditText.getText().toString(), serverPortEditText.getText().toString(), personID, authToken);
person = personIDResult.getPerson();
Family.getInstance().setPersonList(client.getPeople(serverHostEditText.getText().toString(), serverPortEditText.getText().toString(), authToken));
Family.getInstance().setEventList(client.getEvents(serverHostEditText.getText().toString(), serverPortEditText.getText().toString(), authToken));
return result;
}
@Override
protected void onPostExecute(LoginResult result){
if(result == null){
Toast.makeText(getActivity(), "Login failed", Toast.LENGTH_SHORT).show();
}else {
if (result.getMessage() != null) {
Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Login success. First name: " + person.getFirstName() + " Last name: " + person.getLastName(), Toast.LENGTH_SHORT).show();
MapFragment mapFragment = new MapFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.Fragment, mapFragment).commit();
}
}
}
}
private void registerButtonClicked(){
RegisterTask task = new RegisterTask();
task.execute();
}
public class RegisterTask extends AsyncTask <URL, Void, RegisterResult> {
@Override
protected RegisterResult doInBackground(URL... urls) {
Client client = new Client();
String gender;
if(maleButton.isChecked()){
gender = "m";
}else{
gender = "f";
}
RegisterRequest request = new RegisterRequest(userNameEditText.getText().toString(), passwordEditText.getText().toString(), emailEditText.getText().toString(), firstNameEditText.getText().toString(), lastNameEditText.getText().toString(), gender);
RegisterResult result = client.register(serverHostEditText.getText().toString(), serverPortEditText.getText().toString(), request);
if(result == null){
return result;
}
if(result.getMessage() != null){
return result;
}
Family.getInstance().setPersonList(client.getPeople(serverHostEditText.getText().toString(), serverPortEditText.getText().toString(), authToken));
Family.getInstance().setEventList(client.getEvents(serverHostEditText.getText().toString(), serverPortEditText.getText().toString(), authToken));
return result;
}
@Override
protected void onPostExecute(RegisterResult result){
if(result == null){
Toast.makeText(getActivity(), "Register failed", Toast.LENGTH_SHORT).show();
}else {
if (result.getMessage() != null) {
Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
} else {
authToken = result.getAuthToken();
Toast.makeText(getActivity(), "Register success. First Name: " + firstNameEditText.getText().toString() + " Last name: " + lastNameEditText.getText().toString(), Toast.LENGTH_SHORT).show();
MapFragment mapFragment = new MapFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.Fragment, mapFragment).commit();
}
}
}
}
public class DataSyncTask extends AsyncTask<URL , Void, Void>{
@Override
protected Void doInBackground(URL... urls) {
Client client = new Client();
Family.getInstance().setPersonList(client.getPeople(serverHostEditText.getText().toString(), serverPortEditText.getText().toString(), authToken));
Family.getInstance().setEventList(client.getEvents(serverHostEditText.getText().toString(), serverPortEditText.getText().toString(), authToken));
return null;
}
}
}
|
package com.iteaj.util.module.wechat.basictoken;
import com.iteaj.util.module.wechat.WechatApiResponse;
/**
* create time: 2018/4/14
*
* @author iteaj
* @version 1.0
* @since JDK1.7
*/
public class BasicToken extends WechatApiResponse {
private Integer expires_in;
private String access_token;
public BasicToken() {
}
public BasicToken(String errmsg, Integer errcode) {
this.setErrmsg(errmsg);
this.setErrcode(errcode);
}
/**
* access_token过期时间
* @return
*/
public Integer getExpires_in() {
return expires_in;
}
public void setExpires_in(Integer expires_in) {
this.expires_in = expires_in;
}
/**
* 微信访问令牌
* @return
*/
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
@Override
public String toString() {
return "BasicToken{" +
"errcode='" + getErrcode() + '\'' +
", errmsg='" + getErrmsg() + '\'' +
", expires_in='" + expires_in + '\'' +
", access_token='" + access_token + '\'' +
'}';
}
}
|
package tanks.model;
import Utils.Message;
import java.awt.*;
public class RectModel {
public static final int DIRECTION_FRONT = 1;
public static final int DIRECTION_STOP = 0;
public static final int DIRECTION_REVERSE = -1;
protected Rectangle hitbox;
protected int azimut;
protected int direction;
public RectModel(){
this(0, 0 ,0 ,0 ,0);
}
public RectModel(int azimut, int x, int y, int width, int height){
this.hitbox = new Rectangle(x, y, width, height);
this.azimut = azimut;
direction = DIRECTION_STOP;
}
public int getX() {
return hitbox.x;
}
public int getWidth() {
return hitbox.width;
}
public int getHeight() {
return hitbox.height;
}
public int getY() {
return hitbox.y;
}
public int getAzimutDeg(){
return azimut;
}
public double getAzimutRad(){
return Math.toRadians(azimut);
}
public Rectangle getHitbox() {
return hitbox;
}
public void update(int azimut, int x, int y, int width, int height) {
this.hitbox = new Rectangle(x, y, width, height);
this.azimut = azimut;
}
public void updateFromMessage(Message m){
try{
azimut = Integer.parseInt(m.getElement("azimut"));
hitbox.x = Integer.parseInt(m.getElement("x"));
hitbox.y = Integer.parseInt(m.getElement("y"));
hitbox.width = Integer.parseInt(m.getElement("width"));
hitbox.height = Integer.parseInt(m.getElement("height"));
direction = Integer.parseInt(m.getElement("direction"));
}catch(IndexOutOfBoundsException e) {
System.out.println("Wrong message, cant update object");
}
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
if(direction == DIRECTION_STOP ||
direction == DIRECTION_FRONT ||
direction == DIRECTION_REVERSE)
this.direction = direction;
}
public boolean doesCollide(RectModel model) {
return model.getHitbox().intersects(this.hitbox);
}
}
|
package hw1;
public class Types {
public static void main(String[] args) {
byte a = 127;
short b = -31872;
int c = 2000000;
long d = -345987239481L;
/*հարց1. եթե ամբողջ թվերի դեպքում մենք տառով վերջում նշում ենք առավելագույն թիվ վերագրելու հնարավորություն
տվող type-ում (long), ինչի է տրամաբանությունը փոխվում float type-ի դեպքում (float-ի վերջում ենք նշում
տիպի տառը, ոչ թե double-ի)?*/
float e = 4534.345F;
//double f = -36456395.34535645;//հարց2. ինչն ա պատճառը, որ կետը տեղափոխում է աջ?
double f = -364.34535645;
boolean g = true;
char h = '$';
//char h = '\uffff';//հարց3. սիմվոլը չի կարդում, ինչ-որ հատուկ շիֆրովկա են իրան անում?
System.out.println("byte data type ex.: "+a);
System.out.println("short data type ex.: "+b);
System.out.println("int data type ex.: "+c);
System.out.println("long data type ex.: "+d);
System.out.println("float data type ex.: "+e);
System.out.println("double data type ex.: "+f);
System.out.println("boolean data type ex.: "+g);
System.out.println("char data type ex.: "+h);
}
}
|
/* Copyright 2015 Esri
*
* 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.esri.arcgis.android.sample.simplemap;
import android.os.Bundle;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.Activity;
// A generic activity that can be inherited to provide an activity that loads a single fragment.
// This class uses the Fragment API available in Android API level 11 and later; however for devices
// with older APIs you could adapt this class to use the Android Support Library.
public abstract class SingleFragmentActivity extends Activity {
// Returns an instance of the fragment to be hosted in the activity.
protected abstract Fragment createFragment();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
// If the single contained fragment does not already exist then create it.
FragmentManager manager = getFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = createFragment();
manager.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
}
}
|
package net.siekiera.garbageNotifier.model;
import javax.persistence.*;
import java.util.Set;
/**
* Created by Eric on 04.02.2017.
*/
@Entity
@Table(name = "streets")
public class Street {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
private String name;
@ManyToOne
@JoinColumn(name="street_group_id")
private StreetGroup streetGroup;
@OneToMany(mappedBy = "street", cascade = CascadeType.ALL)
private Set<UserInfo> userInfos;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public StreetGroup getStreetGroup() {
return streetGroup;
}
public void setStreetGroup(StreetGroup streetGroup) {
this.streetGroup = streetGroup;
}
public Set<UserInfo> getUserInfos() {
return userInfos;
}
public void setUserInfos(Set<UserInfo> userInfos) {
this.userInfos = userInfos;
}
}
|
package diplomski.autoceste.repositories;
import diplomski.autoceste.models.Report;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ReportRepository extends JpaRepository<Report, Long> {
}
|
package com.bedroom.common.pojo;
import java.util.Date;
/**学院信息实体类
college_id int
college_name varchar
create_time datetime
introduction varchar
* @author Administrator
*
*/
public class College {
private Integer collegeId;
private String collegeName;
private Date createTime;
private String introduction;
//
public Integer getCollegeId() {
return collegeId;
}
public void setCollegeId(Integer collegeId) {
this.collegeId = collegeId;
}
public String getCollegeName() {
return collegeName;
}
public void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
//
@Override
public String toString() {
return "College [collegeId=" + collegeId + ", collegeName=" + collegeName + ", createTime=" + createTime
+ ", introduction=" + introduction + "]";
}
}
|
package br.com.poli.Jogador;
public class Info {
private String nome;
private int score;
private int tempo;
public Info(String nome, int score, int tempo) {
this.nome = nome;
this.score = score;
this.tempo = tempo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getTempo() {
return tempo;
}
public void setTempo(int tempo) {
this.tempo = tempo;
}
}
|
package com.nextLevel.hero.mnghumanResource.model.dao;
import java.sql.Date;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.nextLevel.hero.mngVacation.model.dto.AnnualVacationControlDTO;
import com.nextLevel.hero.mnghumanResource.model.dto.JobDTO;
import com.nextLevel.hero.mnghumanResource.model.dto.MemberListDTO;
import com.nextLevel.hero.mnghumanResource.model.dto.MngHumanResourceDTO;
import com.nextLevel.hero.mnghumanResource.model.dto.RankSalaryStepDTO;
import com.nextLevel.hero.mnghumanResource.model.dto.SalaryStepDTO;
import com.nextLevel.hero.mnghumanResource.model.dto.VacationControlDTO;
@Mapper
public interface MngHumanResourceMapper {
int insertMember(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //Member(유저) 테이블 인서트
int selectNewMemberNumber(); //맴버 번호(사번)를 조회
int insertEmployee(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //Employee(회원)테이블 인서트
int insertEmpUpdate(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //EmployeeUpdate(회원)테이블 인서트
int insertMemberCompany(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //MemberCompany테이블 인서트
int insertMilitary(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //MILITARY_SERVICE 테이블 인서트
int insertVeteran(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //Veteran 테이블 인서트
int insertAppointment(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //Appointment 테이블 인서트
int insertGraduated(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //Graduated 테이블 인서트
int insertCareer(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //Career 테이블 인서트
int insertFamily(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //Family 테이블 인서트
int selectFamilyUpdate(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //FamilyUpdate테이블 조회
int insertFamilyUpdate(MngHumanResourceDTO mngHumanResourceDTO, int companyNo, int familyNo); //FamilyUpdate테이블 인서트
int insertUserAuth(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //UserAuth 테이블에 인서트
List<VacationControlDTO> selectVacationControl(); //VacationControl 테이블 조회
int insertVacation(MngHumanResourceDTO mngHumanResourceDTO, int companyNo, int vacationCode, int vacationDays); //Vacation 테이블에 인서트
Date selectRankSalaryStep(int companyNo, MngHumanResourceDTO mngHumanResourceDTO); //RankSalaryStep 테이블 startDate 조회
MngHumanResourceDTO selectRank(int companyNo, MngHumanResourceDTO mngHumanResourceDTO ); //RankSalaryStep 테이블 조회
int insertEmpSalaryStep(MngHumanResourceDTO mngHumanResourceDTO, int companyNo, java.sql.Date startDate); //EmpSalaryStep 테이블에 인서트
int selectEmpSalaryStep(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //EmpSalaryStep 테이블에 조회
int insertEmpSalaryStepUpdate(MngHumanResourceDTO mngHumanResourceDTO, int companyNo, java.sql.Date startDate, int divNo); //EmpSalaryStepUpdate 테이블에 인서트
int insertFourInsuranceDeduct(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //FourInsuranceDeduct 테이블 인서트
int selectFourInsuranceDeduct(MngHumanResourceDTO mngHumanResourceDTO, int companyNo); //FourInsuranceDeduct 테이블 조회
int insertFourInsHistory(MngHumanResourceDTO mngHumanResourceDTO, int companyNo, int deductDivNo); //FourInsHistory 테이블 인서트
List<SalaryStepDTO> selectSalaryStep(int companyNo); //salaryStep 조회
List<JobDTO> selectJobList(int companyNo); //JobList 조회
List<MemberListDTO> selectMemberList(int companyNo); //memberList 조회
List<MngHumanResourceDTO> selectMemberHistoryList(int companyNo, int idNo); //memberHistoryList 조회
MngHumanResourceDTO selectMemberDetailList(int companyNo, int idNo); //memberDetailList 조회
MngHumanResourceDTO selectmemberHistoryDetailList(int companyNo, int idNo); //memberHistoryDetailList 조회
int updateEmp(int companyNo, int idNo, MngHumanResourceDTO mngHumanResourceDTO); //TBL_EMPLOYEE 테이블 업데이트
int updateEmpUpdate(int companyNo, int idNo, MngHumanResourceDTO mngHumanResourceDTO); //TBL_EMPLOYEEUpdate 테이블 업데이트
int updateMilitary(int companyNo, int idNo, MngHumanResourceDTO mngHumanResourceDTO); //Military 테이블 업데이트
int updateVeteran(int companyNo, int idNo, MngHumanResourceDTO mngHumanResourceDTO); //Veteran 테이블 업데이트
int updateAppointment(int companyNo, int idNo, MngHumanResourceDTO mngHumanResourceDTO); //Appointment 테이블 업데이트
int updateGraduated(int companyNo, int idNo, MngHumanResourceDTO mngHumanResourceDTO); //Graduated 테이블 업데이트
int updateCareer(int companyNo, int idNo, MngHumanResourceDTO mngHumanResourceDTO); //Career 테이블 업데이트
int updateFamily(int companyNo, int idNo, MngHumanResourceDTO mngHumanResourceDTO); //Family 테이블 업데이트
int selectFamilyNo(int companyNo, int idNo); //Family 테이블 조회
int updateFamilyUpdate(int companyNo, int idNo, MngHumanResourceDTO mngHumanResourceDTO,int familyNo); //FamilyUpdate 테이블 업데이트
int selectSalaryStepByRank(int companyNo, int idNo); //SalaryStepByRank 테이블 조회
int updateSalaryStep(int companyNo, int idNo, MngHumanResourceDTO mngHumanResourceDTO, int salaryStepByRank); //SalaryStep 테이블 업데이트
int selectSalaryStepNo(int companyNo, int idNo); //SalaryStep 테이블 조회
int updateSalaryStepUpdate(int companyNo, int idNo, int salaryStepByRank, int salaryStepNo); //SalaryStepUpdate 테이블 업데이트
MngHumanResourceDTO selectMemberRankList(int companyNo, int idNo, MngHumanResourceDTO mngHumanResourceDTO, int salaryStepByRank); //MemberRankList 조회
int selectMemberIdNo(int companyNo, MngHumanResourceDTO mngHumanResourceDTO); //MemberIdNo 조회
}
|
/*
* Created on 12/09/2008
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.citibank.ods.persistence.pl.dao;
import com.citibank.ods.common.dataset.DataSet;
/**
* @author lfabiano
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public interface TplCustomerPrvtTypeDAO
{
public DataSet loadDomain();
}
|
package com.example.sieunhan.github_client.core.commit;
import android.text.TextUtils;
import org.eclipse.egit.github.core.CommitComment;
import org.eclipse.egit.github.core.CommitFile;
import org.eclipse.egit.github.core.RepositoryCommit;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Commit model with comments
*/
public class FullCommit extends ArrayList<CommitComment> implements
Serializable {
private static final long serialVersionUID = 2470370479577730822L;
private final RepositoryCommit commit;
private final List<FullCommitFile> files;
/**
* Create commit with no comments
*
* @param commit
*/
public FullCommit(final RepositoryCommit commit) {
this.commit = commit;
List<CommitFile> rawFiles = commit.getFiles();
if (rawFiles != null && !rawFiles.isEmpty()) {
files = new ArrayList<FullCommitFile>(rawFiles.size());
for (CommitFile file : rawFiles)
files.add(new FullCommitFile(file));
} else
files = Collections.emptyList();
}
/**
* Create commit with comments
*
* @param commit
* @param comments
*/
public FullCommit(final RepositoryCommit commit,
final Collection<CommitComment> comments) {
this.commit = commit;
List<CommitFile> rawFiles = commit.getFiles();
boolean hasComments = comments != null && !comments.isEmpty();
boolean hasFiles = rawFiles != null && !rawFiles.isEmpty();
if (hasFiles) {
files = new ArrayList<FullCommitFile>(rawFiles.size());
if (hasComments) {
for (CommitFile file : rawFiles) {
Iterator<CommitComment> iterator = comments.iterator();
FullCommitFile full = new FullCommitFile(file);
while (iterator.hasNext()) {
CommitComment comment = iterator.next();
if (file.getFilename().equals(comment.getPath())) {
full.add(comment);
iterator.remove();
}
}
files.add(full);
}
hasComments = !comments.isEmpty();
} else
for (CommitFile file : rawFiles)
files.add(new FullCommitFile(file));
} else
files = Collections.emptyList();
if (hasComments)
addAll(comments);
}
@Override
public boolean add(final CommitComment comment) {
String path = comment.getPath();
if (TextUtils.isEmpty(path))
return super.add(comment);
else {
boolean added = false;
for (FullCommitFile file : files)
if (path.equals(file.getFile().getFilename())) {
file.add(comment);
added = true;
break;
}
if (!added)
added = super.add(comment);
return added;
}
}
/**
* @return files
*/
public List<FullCommitFile> getFiles() {
return files;
}
/**
* @return commit
*/
public RepositoryCommit getCommit() {
return commit;
}
}
|
package com.example.angela.avocadowe;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import org.json.JSONException;
import java.math.BigDecimal;
import java.util.ArrayList;
public class PersonActivity extends AppCompatActivity implements View.OnClickListener {
private String personName;
private TextView nameTextView;
private ListView oweListView;
private ArrayList<Owe> oweList;
private ArrayAdapter<Owe> oweAdapter;
private Person currentPerson;
private ImageButton helpPageButton;
private FloatingActionButton addAmountFloatingActionButton;
private ArrayList<Person> personList;
private int currentPersonPos, amountToPay;
public static final String SEND_KEY = "key2";
public static final String PAYPAL_CLIENT_ID = "AWDifm2bTvFUvwMR_A5z_C335nOmAfz9yUERxZEytDtNjXtfCKPG6zi8x582wMIzQD5LYufOeXDR49a8"; //Placeholder client
public static final int PAYPAL_REQUEST_CODE = 123; //PayPal request code for onActivityResult method
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(PayPalConfiguration.ENVIRONMENT_NO_NETWORK)
.clientId(PAYPAL_CLIENT_ID);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_person);
wiringWidgets();
setOnClickListeners();
Intent get = getIntent();
currentPerson = get.getParcelableExtra(MainActivity.EXTRA_KEY);
currentPersonPos = get.getIntExtra(MainActivity.POS_KEY, 0);
personName = currentPerson.getName();
nameTextView.setText(personName);
personList = get.getParcelableArrayListExtra(MainActivity.EXTRA_ARRAY_KEY);
oweList = currentPerson.getOweList();
adaptArray();
//start PayPal service
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
private void setOnClickListeners() {
addAmountFloatingActionButton.setOnClickListener(this);
helpPageButton.setOnClickListener(this);
}
private void adaptArray() {
oweAdapter = new ArrayAdapter<Owe>(this, R.layout.list_item_single_amount, oweList);
oweListView.setAdapter(oweAdapter);
oweListView.setOnItemClickListener(new ListView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
//what
viewOwe(pos);
}
});
oweListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long l) {
showMenu(view, pos);
return true;
}
});
}
private void showMenu(View view, final int pos){
PopupMenu deleteMenu = new PopupMenu(this, view);
deleteMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.pop_up_item_delete:
oweList.remove(pos);
currentPerson.setOweList(oweList);
personList.remove(currentPersonPos);
personList.add(currentPersonPos, currentPerson);
sort();
break;
}
return false;
}
});
deleteMenu.inflate(R.menu.pop_up_menu);
deleteMenu.show();
}
private void sort() {
oweAdapter.notifyDataSetChanged();
}
private void viewOwe(final int pos) {
AlertDialog.Builder viewOweBuilder = new AlertDialog.Builder(PersonActivity.this);
View viewOweView = getLayoutInflater().inflate(R.layout.pop_up_view_owe, null);
final AlertDialog dialog = viewOweBuilder.create();
final Owe currentOwe = oweList.get(pos);
//Wiring the dialog widgets
TextView oweDateTextView = viewOweView.findViewById(R.id.textView_owe_date);
TextView amountOwedTextView = viewOweView.findViewById(R.id.textView_pay_amount_owed);
TextView descriptionTextView = viewOweView.findViewById(R.id.textView_description);
final TextView amountPaidTextView = viewOweView.findViewById(R.id.textView_amount_paid);
final EditText amountToPayEditText = viewOweView.findViewById(R.id.editText_pay_owe);
Button pay = viewOweView.findViewById(R.id.button_pay);
Button done = viewOweView.findViewById(R.id.button_pay_done);
//Setting the textview text
descriptionTextView.setText("" + currentOwe.getDescription());
oweDateTextView.setText(currentOwe.getDate() + " - $" + currentOwe.getAmount());
amountOwedTextView.setText("Amount Still Owed: $" + (currentOwe.getAmount() - currentOwe.getAmountPaid()));
amountPaidTextView.setText("Amount Paid: $" + currentOwe.getAmountPaid());
Log.d("TAG", "viewOwe: " + currentOwe.getAmountPaid());
if(currentOwe.isPaid()) {
amountToPayEditText.setEnabled(false);
pay.setEnabled(false);
amountToPayEditText.setHint("Paid");
}
pay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!amountToPayEditText.getText().toString().isEmpty()) {
amountToPay = Integer.parseInt(amountToPayEditText.getText().toString());
if(currentOwe.getAmount() < amountToPay + currentOwe.getAmountPaid()){
Toast.makeText(PersonActivity.this, "Entered value too large", Toast.LENGTH_SHORT).show();
}
else {
if(currentOwe.getAmountPaid() + amountToPay == currentOwe.getAmount()) {
Toast.makeText(PersonActivity.this, "Paid!", Toast.LENGTH_SHORT).show();
Log.d("TAG", "viewOwe: " + currentOwe.getAmountPaid());
currentOwe.setAmountPaid(currentOwe.getAmount());
currentOwe.setPaid(true);
oweList.remove(pos);
oweList.add(pos, currentOwe);
currentPerson.setOweList(oweList);
personList.remove(currentPersonPos);
personList.add(currentPersonPos, currentPerson);
sort();
Log.d("TAG", "viewOwe: " + currentOwe.getAmountPaid());
}
else{
Toast.makeText(PersonActivity.this, "Paid " + amountToPay, Toast.LENGTH_SHORT).show();
Log.d("TAG", "viewOwe: " + currentOwe.getAmountPaid());
currentOwe.setAmountPaid(currentOwe.getAmountPaid() + amountToPay);
oweList.remove(pos);
oweList.add(pos, currentOwe);
currentPerson.setOweList(oweList);
personList.remove(currentPersonPos);
personList.add(currentPersonPos, currentPerson);
sort();
Log.d("TAG", "viewOwe: " + currentOwe.getAmountPaid());
}
getPayment();
amountPaidTextView.setText("" + currentOwe.getAmountPaid());
dialog.dismiss();
}
}
else {
Toast.makeText(PersonActivity.this, "Please enter amount to pay", Toast.LENGTH_SHORT).show();
}
}
});
//
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.setView(viewOweView);
dialog.show();
}
private void getPayment() { //new intent configuration to start PayPal
PayPalPayment payment = new PayPalPayment(new BigDecimal(String.valueOf(amountToPay)), "USD", "AvocadOwe Transferification",
PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
startActivityForResult(intent, PAYPAL_REQUEST_CODE); //invokes onActivityResult
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//If the result is from PayPal
if (requestCode == PAYPAL_REQUEST_CODE) {
//If the result is OK i.e. user has not canceled the payment
if (resultCode == Activity.RESULT_OK) {
//Getting the payment confirmation
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
//if confirmation is not null
if (confirm != null) {
try {
//Getting the payment details
String paymentDetails = confirm.toJSONObject().toString(4);
Log.i("paymentExample", paymentDetails);
} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("paymentExample", "The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i("paymentExample", "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
}
}
private void wiringWidgets() {
nameTextView = findViewById(R.id.textView_name);
oweListView = findViewById(R.id.listView_owes);
addAmountFloatingActionButton = findViewById(R.id.floatingActionButton_new_amount);
helpPageButton = findViewById(R.id.imageButton_help2);
}
@Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.floatingActionButton_new_amount:
addAmount();
break;
case R.id.imageButton_help2:
helpPage();
break;
default:
break;
}
}
public void onBackPressed() {
Intent sendBack = new Intent(PersonActivity.this, MainActivity.class);
sendBack.putExtra(SEND_KEY, personList);
startActivity(sendBack);
super.onBackPressed();
}
private void addAmount() {
AlertDialog.Builder addAmountBuilder = new AlertDialog.Builder(PersonActivity.this);
View addAmountView = getLayoutInflater().inflate(R.layout.pop_up_add_amount, null);
final AlertDialog dialog = addAmountBuilder.create();
//Wiring the dialog widgets
final EditText etAmountOwed = addAmountView.findViewById(R.id.editText_pop_up_add_amount_amount_owed);
final EditText etDate = addAmountView.findViewById(R.id.editText_pop_up_add_amount_date);
final EditText etDescription = addAmountView.findViewById(R.id.editText_pop_up_add_amount_description);
Button submit = addAmountView.findViewById(R.id.button_pop_up_add_amount_submit);
Button cancel = addAmountView.findViewById(R.id.button_pop_up_add_amount_cancel);
/**
* When submitted, we'll convert the data of our widget variables to be applicable for the 'Person' class
* The dialog will not accept an empty name field, all other fields are optional
*/
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!etAmountOwed.getText().toString().isEmpty()){ //if the name field is NOT empty
String sAmountOwed = etAmountOwed.getText().toString();
int iAmountOwed = Integer.parseInt(sAmountOwed);
String sDate = etDate.getText().toString();
String sDescription = etDescription.getText().toString();
if (!sDescription.equals("")) {
if (sDate.equals("")) {
Toast.makeText(PersonActivity.this, "Please enter a date", Toast.LENGTH_SHORT).show();
}
else {
oweList.add(new Owe(iAmountOwed, sDate, sDescription));
currentPerson.setOweList(oweList);
personList.remove(currentPersonPos);
personList.add(currentPersonPos, currentPerson);
sort();
dialog.dismiss();
}
}
else {
if(!sDate.equals("")){
oweList.add(new Owe(iAmountOwed, sDate));
currentPerson.setOweList(oweList);
personList.remove(currentPersonPos);
personList.add(currentPersonPos, currentPerson);
sort();
dialog.dismiss();
}
else {
Toast.makeText(PersonActivity.this, "Please enter a date", Toast.LENGTH_SHORT).show();
}
}
}
else {
Toast.makeText(PersonActivity.this, "Please fill in the amount field", Toast.LENGTH_SHORT).show();
}
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.setView(addAmountView);
dialog.show();
}
private void helpPage() {
AlertDialog.Builder helpPageBuilder = new AlertDialog.Builder(PersonActivity.this);
View helpPageView = getLayoutInflater().inflate(R.layout.help_page, null);
final AlertDialog dialog = helpPageBuilder.create();
dialog.setView(helpPageView);
dialog.show();
}
@Override
public void onDestroy() {
stopService(new Intent(this, PayPalService.class)); //destroy paypal service when closing the app
super.onDestroy();
}
}
|
/**
Permutation in a String (hard)
Given a string and a pattern, find out if the string contains any permutation of the pattern.
Permutation is defined as the re-arranging of the characters of the string. For example, “abc” has the following six permutations:
abc、acb、bac、bca、cab、cba
Input: String="oidbcaf", Pattern="abc"
Output: true
Explanation: The string contains "bca" which is a permutation of the given pattern.
Input: String="odicf", Pattern="dc"
Output: false
Explanation: No permutation of the pattern is present in the given string as a substring.
Input: String="aaacb", Pattern="abc"
Output: true
Explanation: The string contains "acb" which is a permutation of the given pattern.
* 解决问题:
从字符串中查找连续子串
* 窗口限制条件
窗口中字符 is permutation of the pattern
窗口中子字符串生成的map map(char, count) 与pattern生成的相同
* 如何满足条件
方法1:当windwodEnd>=pattern.length时,判断子串是否满足条件。
方法2:线性时间时间复杂度。
*/
import java.util.*;
class StringPermutation {
public static boolean findPermutation(String str, String pattern) {
Map<Character, Integer> charFrequencyMap = new HashMap<>();
for (char c : pattern.toCharArray()) {
charFrequencyMap.put(c, charFrequencyMap.getOrDefault(c, 0)+1);
}
int windowStart = 0, windowEnd = 0, matched = 0;
for (; windowEnd < str.length(); windowEnd++) {
char rightChar = str.charAt(windowEnd);
if(charFrequencyMap.containsKey(rightChar)){
int temp = charFrequencyMap.get(rightChar)-1;
charFrequencyMap.put(rightChar, temp);
if(temp == 0){
matched++;
}
if (matched == charFrequencyMap.size()) {
return true;
}
}
if (windowEnd >= pattern.length()-1){
//滑动窗口长度与pattern长度相同,但是不符合条件。移动windowStart
char leftChar = str.charAt(windowStart);
if (charFrequencyMap.containsKey(leftChar)){
int temp = charFrequencyMap.get(leftChar);
if (temp==0){
matched--;
}
charFrequencyMap.put(leftChar, temp+1);
}
windowStart++;
}
}
return false;
}
}
|
package com.ubuntu4u.ubuntu4u.ubuntu4u_client.activities;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.MainActivity;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.R;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.adapters.ContactsAdapter;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.data.ColorDataSet;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.extentions.SortBasedOnName;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.interfaces.ItemClickCallback;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.models.ActivityLogModel;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.models.ContactListItem;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.services.DataManager;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.state.AppState;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.viethoa.RecyclerViewFastScroller;
import com.viethoa.models.AlphabetItem;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
/**
* Created by Q. engelbrecht on 2017-06-19.
*/
public class ContactsActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ItemClickCallback {
private TextView icon;
private Typeface fontFamily;
private ListView listView;
private ArrayList<ContactListItem> contacts;
private SQLiteDatabase db;
private Cursor cursor;
private String state;
private LocationManager locationManager;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private String[] latlongs;
private ContactListItem contact;
private RecyclerView recView;
private ContactsAdapter adapter;
private static final int REQUEST_PERMISSIONS_LOCATION = 20;
private ContactListItem vipContact;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
this.state = intent.getStringExtra("State");
latlongs = new String[2];
ContactsTaskRunner runner = new ContactsTaskRunner();
runner.execute();
}
private void PresentData(final ArrayList<ContactListItem> contacts) {
//icon = (TextView)findViewById(R.id.tvIcon);
//fontFamily = Typeface.createFromAsset(this.getAssets(), "fonts/fontawesome-webfont.ttf");
//icon.setTypeface(fontFamily);
//icon.setText(Html.fromHtml(""));
recView = (RecyclerView)findViewById(R.id.lstContacts);
adapter = new ContactsAdapter(contacts, this, "Contacts", new ColorDataSet());
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
recView.addItemDecoration(new DividerItemDecoration(ContactsActivity.this, DividerItemDecoration.VERTICAL));
//Check out GridLayoutManager and StaggeredGridLayoutManager for more options
recView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
RecyclerViewFastScroller fastScroller = (RecyclerViewFastScroller) findViewById(R.id.fast_scroller);
fastScroller.setRecyclerView(recView);
ArrayList<AlphabetItem> mAlphabetItems = new ArrayList<>();
List<String> strAlphabets = new ArrayList<>();
for (int i = 0; i < contacts.size(); i++) {
String name = contacts.get(i).getTitle();
if (name == null || name.trim().isEmpty())
continue;
String word = name.substring(0, 1);
if (!strAlphabets.contains(word)) {
strAlphabets.add(word);
mAlphabetItems.add(new AlphabetItem(i, word, false));
}
}
fastScroller.setUpAlphabet(mAlphabetItems);
//SectionTitleIndicator sectionTitleIndicator = (SectionTitleIndicator) findViewById(R.id.fast_scroller_section_title_indicator);
// Connect the recycler to the scroller (to let the scroller scroll the list)
//fastScroller.setRecyclerView(recView);
// Connect the scroller to the recycler (to let the recycler scroll the scroller's handle)
//recView.setOnScrollListener(fastScroller.getOnScrollListener());
// Connect the section indicator to the scroller
//fastScroller.setSectionIndicator(sectionTitleIndicator);
}
private boolean DoesRecipientExist(String name, String number) {
db = openOrCreateDatabase("law4sho_db", Context.MODE_PRIVATE, null);
cursor = db.rawQuery("SELECT * FROM Recipients WHERE Number ='" + number + "' AND Name ='" + name +"'", null);
cursor.moveToFirst();
return (cursor.getCount() > 0);
}
private boolean DoesVIPExist(String name, String number) {
db = openOrCreateDatabase("law4sho_db", Context.MODE_PRIVATE, null);
cursor = db.rawQuery("SELECT * FROM VipContacts WHERE Number ='" + number + "' AND Name ='" + name +"'", null);
cursor.moveToFirst();
return (cursor.getCount() > 0);
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
InitialiseGoogleApiClient();
} else {
Toast.makeText(ContactsActivity.this, "To send a panic you need to allow us to use your location service :-)", Toast.LENGTH_LONG).show();
}
}
private void InitialiseGoogleApiClient() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!isLocationEnabled()) {
showAlert();
} else {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mGoogleApiClient.connect();
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
try {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
latlongs[0] = String.valueOf(mLastLocation.getLatitude());
latlongs[1] = String.valueOf(mLastLocation.getLongitude());
}
switch (state) {
case "FindYou":
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
SendRequestTaskRunner runner = new SendRequestTaskRunner(vipContact, ContactsActivity.this);
runner.execute();
}
break;
case "FindMe":
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
FindMeTaskRunner runner1 = new FindMeTaskRunner(contact, this);
runner1.execute();
}
break;
}
} finally {
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onItemClick(int p) {
}
@Override
public void onItemClick(int p, String type) {
switch (state) {
case "Panic":
ContactListItem recipient = contacts.get(p);
AddRecipientTaskRunner runner = new AddRecipientTaskRunner(recipient);
runner.execute();
break;
case "FindMe":
contact = contacts.get(p);
final AlertDialog.Builder dialog = new AlertDialog.Builder(ContactsActivity.this);
dialog.setTitle("Send Location")
.setMessage("Send my location to " + contact.getTitle() + "?")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
if ((ContextCompat.checkSelfPermission(ContactsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) +
ContextCompat.checkSelfPermission(ContactsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(ContactsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_PERMISSIONS_LOCATION);
} else {
InitialiseGoogleApiClient();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
break;
case "FindYou":
vipContact = contacts.get(p);
AlertDialog.Builder adb = new AlertDialog.Builder(ContactsActivity.this);
adb.setTitle("Send request?");
adb.setMessage("You are about to send a request to connect your device with " + vipContact.getTitle() + ". This will enable both you and " + vipContact.getTitle() + " to access each other's device location at any given time.");
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Continue", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
InitialiseGoogleApiClient();
}});
adb.show();
break;
}
}
@Override
public void onItemLongClick(int p) {
}
private class AddRecipientTaskRunner extends AsyncTask<String, String, String> {
private ContactListItem contact;
public AddRecipientTaskRunner(ContactListItem contact) {
this.contact = contact;
}
@Override
protected String doInBackground(String... params) {
if (!DoesRecipientExist(contact.getTitle(), contact.getNumber())) {
db = openOrCreateDatabase("law4sho_db", Context.MODE_PRIVATE, null);
cursor = db.rawQuery("SELECT * FROM AppState", null);
cursor.moveToFirst();
String query = "INSERT INTO Recipients (Name, Number, UserID) VALUES ('"+ contact.getTitle() +"', '"+ contact.getNumber() +"', '"+ cursor.getString(3) +"')";
db.execSQL(query);
} else {
return "Exists";
}
return "Proceed";
}
@Override
protected void onPostExecute(String result) {
if (result.equals("Exists"))
Toast.makeText(ContactsActivity.this, "Recipient exists...", Toast.LENGTH_LONG).show();
else
{
Toast.makeText(ContactsActivity.this, "Recipient added...", Toast.LENGTH_LONG).show();
finish();
}
}
}
private class FindMeTaskRunner extends AsyncTask<String, String, String> {
private ProgressDialog asyncDialog;
private ContactListItem contact;
private Context context;
public FindMeTaskRunner(ContactListItem contact, Context context) {
this.context = context;
asyncDialog = new ProgressDialog(ContactsActivity.this);
asyncDialog.setCanceledOnTouchOutside(false);
this.contact = contact;
}
@Override
protected String doInBackground(String... params) {
try {
db = openOrCreateDatabase("law4sho_db", Context.MODE_PRIVATE, null);
cursor = db.rawQuery("SELECT * FROM AppState", null);
cursor.moveToFirst();
DataManager dataManager = new DataManager();
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sendDate = sdf.format(c.getTime());
JSONObject jsonObject = new JSONObject();
jsonObject.put("TargetCellNumber", contact.getNumber().replace(" ", ""));
jsonObject.put("Latitude", latlongs[0]);
jsonObject.put("Longitude", latlongs[1]);
jsonObject.put("DisplayName", cursor.getString(4));
jsonObject.put("UserID", new DataManager().getConfiguration(context).UserID);
jsonObject.put("Type", "FindMe");
String responseCode = String.valueOf(dataManager.postData(jsonObject, "/NotificationsService/SendNotification"));
new ActivityLogModel("FindMe").LogModuleActiviy();
return "success";
} catch (Exception e) {
return "fail";
}
}
@Override
protected void onPreExecute() {
asyncDialog.setMessage(getString(R.string.loading_type));
asyncDialog.show();
}
@Override
protected void onPostExecute(String result) {
if (result == "success")
Toast.makeText(ContactsActivity.this, "Location sent...", Toast.LENGTH_LONG).show();
else
Toast.makeText(ContactsActivity.this, "Unsuccessful!", Toast.LENGTH_LONG).show();
asyncDialog.dismiss();
finish();
}
}
private class SendRequestTaskRunner extends AsyncTask<String, String, String> {
private ProgressDialog asyncDialog;
private ContactListItem contact;
private String resp;
private Context context;
public SendRequestTaskRunner(ContactListItem contact, Context context) {
this.context = context;
asyncDialog = new ProgressDialog(ContactsActivity.this);
asyncDialog.setCanceledOnTouchOutside(false);
this.contact = contact;
}
@Override
protected String doInBackground(String... params) {
try {
AppState configuration = new DataManager().getConfiguration(context);
DataManager dataManager = new DataManager();
JSONObject jsonObject = new JSONObject();
jsonObject.put("TargetCellNumber", contact.getNumber().replace(" ", ""));
jsonObject.put("RequestCellNumber", configuration.MobileNumber);
jsonObject.put("RequestDisplayName", configuration.DisplayName);
jsonObject.put("Latitude", latlongs[0]);
jsonObject.put("Longitude", latlongs[1]);
jsonObject.put("UserID", configuration.UserID);
jsonObject.put("Type", "PairingRequest");
resp = (String)dataManager.postData(jsonObject, "/RequestService/SendRequest");
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
@Override
protected void onPreExecute() {
asyncDialog.setMessage(getString(R.string.loading_type));
asyncDialog.show();
}
@Override
protected void onPostExecute(String result) {
switch (result) {
case "200":
Toast.makeText(ContactsActivity.this, "VIP request sent...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
break;
case "300":
Toast.makeText(ContactsActivity.this, "VIP exists...", Toast.LENGTH_LONG).show();
break;
case "404":
Toast.makeText(ContactsActivity.this, "Connection failure...", Toast.LENGTH_LONG).show();
break;
case "500":
Toast.makeText(ContactsActivity.this, "Server error...", Toast.LENGTH_LONG).show();
break;
}
asyncDialog.dismiss();
finish();
}
}
private class ContactsTaskRunner extends AsyncTask<String, String, String> {
private ProgressDialog asyncDialog;
public ContactsTaskRunner() {
asyncDialog = new ProgressDialog(ContactsActivity.this);
asyncDialog.setCanceledOnTouchOutside(false);
}
@Override
protected String doInBackground(String... params) {
try {
SQLiteDatabase db = openOrCreateDatabase("law4sho_db", Context.MODE_PRIVATE, null);
Cursor _contacts = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
contacts = new ArrayList<>();
while (_contacts.moveToNext())
{
ContactListItem item = new ContactListItem();
String name = _contacts.getString(_contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = _contacts.getString(_contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
item.setNumber(phoneNumber);
item.setTitle(name);
contacts.add(item);
}
Collections.sort(contacts, new SortBasedOnName());
_contacts.close();
} catch (Exception e) {
String test = e.toString();
}
return null;
}
@Override
protected void onPreExecute() {
asyncDialog.setMessage(getString(R.string.loading_type));
asyncDialog.show();
}
@Override
protected void onPostExecute(String result) {
try {
setContentView(R.layout.contacts);
} catch (Exception e) {
String test = e.toString();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Phonebook");
setSupportActionBar(toolbar);
PresentData(contacts);
asyncDialog.dismiss();
}
}
}
|
package com.example.prog3.alkasaffollowup.Model;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class DesignPayement {
@SerializedName("$id")
@Expose
private String $id;
@SerializedName("payment_type_list")
@Expose
private Object paymentTypeList;
@SerializedName("project_invoices")
@Expose
private List<Object> projectInvoices = null;
@SerializedName("project_payment_config")
@Expose
private Object projectPaymentConfig;
@SerializedName("project_payment_details")
@Expose
private List<Object> projectPaymentDetails = null;
@SerializedName("project")
@Expose
private Object project;
@SerializedName("project_visits")
@Expose
private List<Object> projectVisits = null;
@SerializedName("ID")
@Expose
private Integer iD;
@SerializedName("proj_id")
@Expose
private Integer projId;
@SerializedName("PaymentTypeID")
@Expose
private Integer paymentTypeID;
@SerializedName("PaymentIndex")
@Expose
private Integer paymentIndex;
@SerializedName("Perc")
@Expose
private Integer perc;
@SerializedName("Value")
@Expose
private Object value;
@SerializedName("DueAt")
@Expose
private Object dueAt;
@SerializedName("Conditions")
@Expose
private Object conditions;
@SerializedName("Notes")
@Expose
private String notes;
@SerializedName("CreatedAt")
@Expose
private Object createdAt;
@SerializedName("CreatedBy")
@Expose
private Object createdBy;
@SerializedName("UpdatedAt")
@Expose
private Object updatedAt;
@SerializedName("UpdatedBy")
@Expose
private Object updatedBy;
@SerializedName("ApprovedAt")
@Expose
private Object approvedAt;
@SerializedName("ApprovedBy")
@Expose
private Object approvedBy;
@SerializedName("ConditionTypeID")
@Expose
private Object conditionTypeID;
@SerializedName("PaymentConfigID")
@Expose
private Object paymentConfigID;
public String get$id() {
return $id;
}
public void set$id(String $id) {
this.$id = $id;
}
public Object getPaymentTypeList() {
return paymentTypeList;
}
public void setPaymentTypeList(Object paymentTypeList) {
this.paymentTypeList = paymentTypeList;
}
public List<Object> getProjectInvoices() {
return projectInvoices;
}
public void setProjectInvoices(List<Object> projectInvoices) {
this.projectInvoices = projectInvoices;
}
public Object getProjectPaymentConfig() {
return projectPaymentConfig;
}
public void setProjectPaymentConfig(Object projectPaymentConfig) {
this.projectPaymentConfig = projectPaymentConfig;
}
public List<Object> getProjectPaymentDetails() {
return projectPaymentDetails;
}
public void setProjectPaymentDetails(List<Object> projectPaymentDetails) {
this.projectPaymentDetails = projectPaymentDetails;
}
public Object getProject() {
return project;
}
public void setProject(Object project) {
this.project = project;
}
public List<Object> getProjectVisits() {
return projectVisits;
}
public void setProjectVisits(List<Object> projectVisits) {
this.projectVisits = projectVisits;
}
public Integer getID() {
return iD;
}
public void setID(Integer iD) {
this.iD = iD;
}
public Integer getProjId() {
return projId;
}
public void setProjId(Integer projId) {
this.projId = projId;
}
public Integer getPaymentTypeID() {
return paymentTypeID;
}
public void setPaymentTypeID(Integer paymentTypeID) {
this.paymentTypeID = paymentTypeID;
}
public Integer getPaymentIndex() {
return paymentIndex;
}
public void setPaymentIndex(Integer paymentIndex) {
this.paymentIndex = paymentIndex;
}
public Integer getPerc() {
return perc;
}
public void setPerc(Integer perc) {
this.perc = perc;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Object getDueAt() {
return dueAt;
}
public void setDueAt(Object dueAt) {
this.dueAt = dueAt;
}
public Object getConditions() {
return conditions;
}
public void setConditions(Object conditions) {
this.conditions = conditions;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Object getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Object createdAt) {
this.createdAt = createdAt;
}
public Object getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Object createdBy) {
this.createdBy = createdBy;
}
public Object getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Object updatedAt) {
this.updatedAt = updatedAt;
}
public Object getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(Object updatedBy) {
this.updatedBy = updatedBy;
}
public Object getApprovedAt() {
return approvedAt;
}
public void setApprovedAt(Object approvedAt) {
this.approvedAt = approvedAt;
}
public Object getApprovedBy() {
return approvedBy;
}
public void setApprovedBy(Object approvedBy) {
this.approvedBy = approvedBy;
}
public Object getConditionTypeID() {
return conditionTypeID;
}
public void setConditionTypeID(Object conditionTypeID) {
this.conditionTypeID = conditionTypeID;
}
public Object getPaymentConfigID() {
return paymentConfigID;
}
public void setPaymentConfigID(Object paymentConfigID) {
this.paymentConfigID = paymentConfigID;
}
}
|
package pom;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class QualificationsObj {
@FindBy(id="menu_admin_Qualifications")
public static WebElement qualification;
@FindBy(id="menu_admin_viewSkills")
public static WebElement skills;
@FindBy(id="btnAdd")
public static WebElement add2 ;
@FindBy(id="skill_name")
public static WebElement skname;
@FindBy(id="skill_description")
public static WebElement skdesc ;
@FindBy(name="btnSave")
public static WebElement savee;
@FindBy(id="menu_admin_viewEducation")
public static WebElement edc ;
@FindBy(id="btnAdd")
public static WebElement btad;
@FindBy(id="education_name")
public static WebElement level;
@FindBy(id="btnSave")
public static WebElement btsavee;
@FindBy(id="btnSave")
public static WebElement btsav;
}
|
package android.example.pietjesbak.constant;
public class Dices {
//contstante aanmaken die gebruikt kan worden in meerder classes
public static final int NUMBER_DICE = 3;
}
|
package ALIXAR;
import java.util.Scanner;
public class Ejercicio4 {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
int[][] numeros = new int[4][6];
System.out.println("Introduzca la posicion del numero que desea conseguir: ");
int posicion = teclado.nextInt();
for (int i = 0; i < numeros.length; i++) {
for (int j = 0; j < numeros[i].length ; j++) {
numeros[i][j] = (int) (Math.random()*(70-10)+10);
System.out.print(numeros[i][j] + " ");
}
System.out.println();
}
System.out.println(nEsimo(numeros, posicion));
}
public static int nEsimo(int[][] n, int posicion){
int resultado = 0;
int longitud = 0;
for (int i = 0; i < n.length; i++) {
for (int j = 0; j < n[i].length ; j++) {
longitud++;
}
}
System.out.println("Longitud de la array: " + longitud);
if (posicion <= longitud && posicion >= 0){
for (int i = 0; i < n.length; i++) {
for (int j = 0; j < n[i].length; j++) {
resultado = n[i][j];
}
}
}else{
resultado = -1;
}
return resultado;
}
}
|
import java.util.*;
class LongestCommonPrefix{
int n;
String[] words;
/* Declare an instance variable to store the list of strings */
LongestCommonPrefix(String listOfStrings){
}
public void augment(/* add required parameters */){
/*
Implement the augment method to augment/modify a string in the list of strings in order to
act as a utility method to solve the given question
*/
}
public String longestPrefixString(){
/* Complete the method to find longest prefix in all strings of the list of strings */
/* find out the shortest word. Here smallest is used to find the length of the smallest word */
int smallest = 0;
for (int i = 0; i < n; i++) {
if(i == 0)
{
smallest = words[0].length();
}
else if (smallest > words[i].length())
{
smallest = words[i].length();
}
}
/* take the first "smallest" letters of the first word. smallest turns into the longest possible prefix */
char[] prefix = new char[smallest];
words[0].getChars(0, smallest, prefix, 0);
/* 3. pop letters until all the words match */
for (int i = 1; i < n; i++) {
for (int j = 0; j < smallest; j++) {
if(prefix[j] != words[i].charAt(j)) {
smallest-- ;
i--;
break;
}
}
}
/* displaying things */
char[] final_prefix = new char[smallest];
for (int i = 0; i < smallest; i++) {
final_prefix[i] = prefix[i];
// System.out.print(prefix[i]);
}
if(smallest == 0) return "-";
return String.valueOf(final_prefix);
}
}
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LongestCommonPrefix obj = new LongestCommonPrefix("");
obj.n = sc.nextInt();
String[] words = new String[obj.n];
for (int i = 0; i < obj.n; i++) {
words[i] = sc.next();
}
obj.words = words;
System.out.println(obj.longestPrefixString());
// obj.longestPrefixString();
sc.close();
}
}
/* Algorithm
1. find out the shortest word
2. take all its letters
3. pop letters until all the words match
*/
|
package Stack;
import java.util.Stack;
/*Objective is to check if the input string of
* parentheses are in proper sequence or not
* Example :
* ( : Not in sequence.
* ()) : Not in sequence.
* (({(}))) : Not in sequence.
* (){}[] : In sequence.
* ({({[]})(){}}) : In sequence.
* */
public class StackBracketImplementation {
public static void main(String[] args) {
String data = "({({[]})(){}})";
boolean evalParanthesisVal = evalParanthesis(data);
if(evalParanthesisVal == true)
System.out.println("Brackets are in sequence.");
else
System.out.println("Brackets are not in sequence");
}
static boolean evalParanthesis(String string)
{
if(string == null)
return false;
if(string.length() % 2 != 0)
return false;
char[] brackets = string.toCharArray();
boolean IsBracesInSeq = false;
Stack<Character> stack = new Stack<Character>();
for(char bracket : brackets)
{
if(bracket == '(' || bracket == '{' || bracket == '['){
stack.push(bracket);
}
else if(bracket == ')' || bracket == '}' || bracket == ']')
{
if(!stack.isEmpty())
{
char bracketPopped = stack.pop();
if((bracket == ')' && bracketPopped == '('))
IsBracesInSeq = true;
else if((bracket == '}') && (bracketPopped == '{'))
IsBracesInSeq = true;
else if((bracket == ']') && (bracketPopped == '['))
IsBracesInSeq = true;
else
{
IsBracesInSeq = false;
break;
}
}
else
{
System.out.println("opening brackets stack empty");
IsBracesInSeq = false;
break;
}
}
}
if(IsBracesInSeq == false)
return false;
else
return true;
}
}
|
package Models;
import java.util.ArrayList;
import MVC.Product;
import MVC.ProductPart;
import MVC.Session;
import MVC.User;
public class ProductTemplateModel {
public ArrayList productArray;
public ArrayList productPartList;
public ArrayList partsList;
public productGatewaySQL gateway = new productGatewaySQL("ymd524", "ymd524", "HRqEF9KWp7MFw04SR0zZ");
public Product product;
public ProductPart productPart;
private int productId;
private int partId;
private int quantity;
private User user;
private Session session;
public void deleteProductById(int id){
gateway.deleteProductFromProductPartsById(id);
gateway.deleteProductById(id);
}
public void deleteProductPartById(int id){
gateway.deletePartFromProductPartsById(id);
}
public void addProduct(String num, String desc, ArrayList parts){
productId = gateway.addProductGetId(num, desc);
for(int i = 0; i< parts.size(); i++){
partId = gateway.getPartId(parts.get(i).toString());
gateway.addProductParts(partId, productId);
}
}
public void addProductPart(int partId, int productId){
gateway.addProductParts(partId, productId);
}
public void endSession(){
this.session = null;
}
public int checkNum(String num){
for(int i =0; i < productArray.size();i++){
if(productArray.get(i).equals(num)){
return 1;
}
}
return 0;
}
public void updateProductDesc(int id, String desc){
gateway.updateProductDesc(id, desc);
}
public void updateProductNum(int id, String num){
gateway.updateProductNum(id, num);
}
public void updateProductPartQuantity(int productId, int partId, int q){
gateway.updateProductPartQuantity(productId, partId, q);
}
/*
* setters
*/
public void setSession(Session session){
this.session = session;
}
public void setProductArray(){
productArray = gateway.getProductsArrayList();
}
public void setProductPartArray(int id){
productPartList = gateway.getAllProductParts(id);
}
public void setProductByNum(String num){
product = gateway.getProductObjectByNum(num);
}
public void setProductPartByName(String name){
productPart = gateway.getProductPartObjectByName(name);
}
public void setPartsList(){
partsList = gateway.getPartsArrayList();
}
/*
* getters
*/
public Session getSession(){
return session;
}
public int getPartId(String name){
return gateway.getPartId(name);
}
public ArrayList getPartsList(){
return partsList;
}
public ArrayList getProductArraylist(){
return productArray;
}
public Product getCurrentProductObject(){
return product;
}
public ProductPart getCurrentProductPartObject(){
return productPart;
}
public ArrayList getProductPartList(){
return productPartList;
}
public User getUserObjectByEmail(String email){
return gateway.getUserObject(email);
}
public int getQuantity(int productId, int partId){
return gateway.getQuantity(productId, partId);
}
}
|
package com.vasyaevstropov.newspoltava;
import android.app.Activity;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by вася on 04.02.2017.
*/
public class WeatherDownload extends AsyncTask<Void, Void, String>{
private Activity activity;
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
String LOG_TAG = "LOGGGG";
TextView navViewText , tvWind;
Double tempKelvin;
ImageView imgWeather;
String img_url = ("http://openweathermap.org/img/w/");
String imgName = "";
Double windSpeed;
NavigationView navigationView;
View header;
WeatherDownload(Activity activity){
this.activity = activity;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
navigationView = (NavigationView) activity.findViewById(R.id.nav_view);
header = ((NavigationView)activity.findViewById(R.id.nav_view)).getHeaderView(0);
navViewText = (TextView) header.findViewById(R.id.navViewText);
imgWeather = (ImageView) header.findViewById(R.id.imgWeather);
tvWind = (TextView) header.findViewById(R.id.tvWind);
}
@Override
protected String doInBackground(Void... params) {
try{
//URL url = new URL("http://androiddocs.ru/api/friends.json");
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?q=Poltava&APPID=60298f6dfc0aacaf2074e0e5d78f4516");
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null){
buffer.append(line);
}
resultJson = buffer.toString();
}catch (Exception e){
e.printStackTrace();
}
try{
urlConnection.disconnect();
}catch (Exception e){}
return resultJson;
}
@Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
Log.d("LOGGGG", strJson);
JSONObject dataJsonObj = null;
String secondName = "";
try {
dataJsonObj = new JSONObject(strJson);
JSONArray weather = dataJsonObj.getJSONArray("weather");
JSONObject weatherObj = weather.getJSONObject(0);
JSONObject wind = dataJsonObj.getJSONObject("wind");
JSONObject main = dataJsonObj.getJSONObject("main");
//JSONObject mainTemp = main.getJSONObject(1);
tempKelvin = main.getDouble("temp") - 273.15;
imgName = weatherObj.getString("icon");
windSpeed = wind.getDouble("speed");
} catch (JSONException e) {
e.printStackTrace();
}
navViewText.setText("Температура в Полтаві: " + Math.round(tempKelvin) + " °C");
Picasso.with(activity).load(img_url + imgName + ".png").into(imgWeather);
tvWind.setText("Швидкість вітру: " + windSpeed + " м/с");
}
}
|
//package bicycles.models;
//
////import bicycles.Bicycle;
//import bicycles.BicycleBase;
//
//public abstract class MountainBike extends BicycleBase {
//
// @Override
// public void accelerate() {
// changeSpeed(5);
// }
//
// @Override
// public void brake() {
// changeSpeed(-3);
// }
//
//}
|
package com.example.trialattemptone;
import android.app.Activity;
import android.app.AlarmManager;
public class AlarmReceiver extends Activity {
}
|
package com.horse.barrel;
public class Scoredetails {
/**
* @param args
*/
private String Firstname;
private String score;
private int scorer;
public int getScorer() {
return scorer;
}
public void setScorer(int scorer) {
this.scorer = scorer;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getFirstname() {
return Firstname;
}
public void setFirstname(String firstname) {
Firstname = firstname;
}
}
|
package com.revolut.moneytransfer.test;
import org.apache.http.client.HttpClient;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.revolut.moneytransfer.controller.AccountController;
import com.revolut.moneytransfer.controller.TransactionController;
import com.revolut.moneytransfer.controller.UserController;
import com.revolut.moneytransfer.exception.ServiceExceptionMapper;
import com.revolut.moneytransfer.factory.ConnectionFactory;
public class ServiceTest {
protected static Server server = null;
protected static PoolingHttpClientConnectionManager connManager;
protected static HttpClient client;
private static Logger logger = LoggerFactory.getLogger(ServiceTest.class);
@BeforeClass
public static void setup() throws Exception {
logger.info("ServiceTest setup started");
ConnectionFactory.createTestData();
startServer();
connManager = getHttpConnectionMan();
client = getHttpClient();
}
@AfterClass
public static void closeClient() throws Exception {
// server.stop();
HttpClientUtils.closeQuietly(client);
}
public static void startServer() throws Exception {
logger.info("ServiceTest server started");
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(3020);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
AccountController.class.getCanonicalName() + "," + TransactionController.class.getCanonicalName() + ","
+ UserController.class.getCanonicalName() + ","
+ ServiceExceptionMapper.class.getCanonicalName());
try {
jettyServer.start();
// jettyServer.join();
} finally {
// jettyServer.destroy();
}
}
public static URIBuilder createUriBuilder() {
return new URIBuilder().setScheme("http").setHost("localhost:3020");
}
public static HttpClient getHttpClient() {
return HttpClients.custom().setConnectionManager(connManager).setConnectionManagerShared(true).build();
}
public static PoolingHttpClientConnectionManager getHttpConnectionMan() {
connManager.setDefaultMaxPerRoute(100);
connManager.setMaxTotal(200);
return connManager;
}
}
|
package DAO;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import Entity.PhanQuyen;
import Entity.TaiKhoan;
import Implements.TaiKhoanImp;
@Repository
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TaiKhoanDao implements TaiKhoanImp {
@Autowired
SessionFactory sessionFactory;
@Transactional
public int KiemTraDangNhap(String user, String pass) {
Session session = sessionFactory.getCurrentSession();
try {
TaiKhoan taikhoan = (TaiKhoan) session.createQuery("from TAIKHOAN where tenTaiKhoan='"+user+"' and matKhau='"+pass+"'").getSingleResult();
if(taikhoan != null)
return taikhoan.getIdTaiKhoan();
}catch (Exception e) {
return 0;
}
return 0;
}
@Transactional
public boolean KiemTraDangKy(String user, String pass, int idQuyen) {
Session session = sessionFactory.getCurrentSession();
try {
TaiKhoan taikhoan = (TaiKhoan) session.createQuery("from TAIKHOAN where tenTaiKhoan='"+user+"'").uniqueResult();
if(taikhoan == null) {
TaiKhoan newTK = new TaiKhoan();
newTK.setTenTaiKhoan(user);
newTK.setMatKhau(pass);
newTK.setTinhTrang("Mở");
PhanQuyen pqNew = session.get(PhanQuyen.class, idQuyen);
newTK.setPhanQuyen(pqNew);
session.save(newTK);
return true;
}
}catch (Exception e) {
return false;
}
return false;
}
@Transactional
public TaiKhoan ShowTaiKhoan(int idTaiKhoan) {
Session session = sessionFactory.getCurrentSession();
TaiKhoan tk = (TaiKhoan) session.createQuery("from TAIKHOAN where idTaiKhoan='"+idTaiKhoan+"'").uniqueResult();
return tk;
}
@Transactional
public List<TaiKhoan> lstTK() {
Session session = sessionFactory.getCurrentSession();
List<TaiKhoan> lstTK = session.createQuery("from TAIKHOAN").getResultList();
return lstTK;
}
@Transactional
public int ShowTaiKhoanUser(String tenTaiKhoan) {
Session session = sessionFactory.getCurrentSession();
TaiKhoan tk = (TaiKhoan) session.createQuery("from TAIKHOAN where tenTaiKhoan='"+tenTaiKhoan+"'").uniqueResult();
return tk.getIdTaiKhoan();
}
@Transactional
public String update(TaiKhoan tk, int idTaiKhoan) {
Session session = sessionFactory.getCurrentSession();
TaiKhoan user = session.get(TaiKhoan.class, idTaiKhoan);
user.setHoTen(tk.getHoTen());
user.setGioiTinh(tk.getGioiTinh());
user.setSdt(tk.getSdt());
user.setEmail(tk.getEmail());
user.setDiaChi(tk.getDiaChi());
user.setMatKhau(tk.getMatKhau());
session.update(user);
return null;
}
@Transactional
public boolean checkTrangThai(String user) {
Session session = sessionFactory.getCurrentSession();
TaiKhoan tk = (TaiKhoan) session.createQuery("from TAIKHOAN where tenTaiKhoan='"+user+"'").uniqueResult();
if(tk.getTinhTrang().equals("Mở")) {
return true;
}
return false;
}
@Transactional
public String updateTrangThai(int idTaiKhoan, String trangThai) {
// TODO Auto-generated method stub
Session session = sessionFactory.getCurrentSession();
TaiKhoan tk = session.get(TaiKhoan.class, idTaiKhoan);
tk.setTinhTrang(trangThai);
return null;
}
}
|
package com.fanfte.algorithm.dp;
public class HouseRobber2 {
public static void main(String[] args) {
}
public int rob(int[] nums) {
return 0;
}
}
|
package ru.shikhovtsev.shade;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
List<Integer> example = new ArrayList<>();
IntStream.range(1, 10).forEach(example::add);
List<Integer> result = Lists.reverse(example);
System.out.println(result);
System.out.println("Hello, World. Shade test!");
}
}
|
package com.hcl.neo.cms.microservices.services;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;
import com.filenet.api.core.IndependentObject;
import com.hcl.cms.data.CmsDao;
import com.hcl.cms.data.impl.CmsDaoFactory;
import com.hcl.cms.data.params.CreateObjectParam;
import com.hcl.cms.data.params.CmsSessionParams;
import com.hcl.cms.data.params.DeleteObjectParam;
import com.hcl.cms.data.params.ObjectIdentity;
import com.hcl.cms.data.params.SearchObjectParam;
import com.hcl.cms.data.params.UpdateObjectParam;
import com.hcl.neo.cms.microservices.constants.Constants;
import com.hcl.neo.cms.microservices.exceptions.ServiceException;
import com.hcl.neo.cms.microservices.logger.ServiceLogger;
import com.hcl.neo.cms.microservices.model.DctmObject;
import com.hcl.neo.cms.microservices.model.ReadAttrParams;
import com.hcl.neo.cms.microservices.model.ServiceResponse;
import com.hcl.neo.cms.microservices.utils.DctmObjectMapper;
import com.hcl.neo.cms.microservices.utils.ServiceUtils;
import com.hcl.neo.eloader.common.JsonApi;
/**
* Service class for metadata opeations
* @author sakshi_ja
*
*/
@Service
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class DctmObjectService {
@Autowired
private DctmServiceHelper serviceHelper;
@Autowired
private DctmObjectMapper dctmObjectMapper;
@Value("${bulk.defaultImportLocation}")
private String defaultImportLocation;
@Value("${search.enableAttributeMapping}")
private boolean enableAttributeMapping;
@Value("${search.defaultObjectType}")
private String defaultSearchObjectType;
@Value("${filenet.uri}")
private String uri;
@Value("${filenet.username}")
private String userName;
@Value("${filenet.password}")
private String password;
@Value("${filenet.stanza}")
private String stanza;
/**
* Method to check attribute values passed through JSON and calls createObject DAO method.
* @param request
* @param repository
* @param jsonMetadata
* @param file
* @return
* @throws ServiceException
*/
@SuppressWarnings("unchecked")
public ServiceResponse<String> createDctmObject(HttpServletRequest request, String repository, String jsonMetadata,
MultipartFile file) throws ServiceException {
CmsDao cmsDao = null;
try {
CmsSessionParams sessionParams = toCmsSessionParams();
ServiceLogger.info(getClass(), sessionParams.toString());
cmsDao = CmsDaoFactory.createCmsDao();
cmsDao.setSessionParams(sessionParams);
Map<String, Object> requestAttrMap = new HashMap<String, Object>();
requestAttrMap = (Map<String, Object>) ServiceUtils.fromJson(jsonMetadata, requestAttrMap.getClass());
Map<String, Object> attrMap = null;
if (enableAttributeMapping) {
attrMap = dctmObjectMapper.toDctmAttributes(requestAttrMap);
} else {
attrMap = requestAttrMap;
}
if (null == attrMap.get(Constants.ATTR_R_FOLDER_PATH)) {
attrMap.put(Constants.ATTR_R_FOLDER_PATH, defaultImportLocation);
}
serviceHelper.createPath(cmsDao, attrMap.get(Constants.ATTR_R_FOLDER_PATH).toString(), repository);
CreateObjectParam params = toCreateObjectParam(attrMap, file, cmsDao);
String objectId = cmsDao.createObject(params, repository);
ServiceResponse<String> serviceRes = new ServiceResponse<String>();
serviceRes.setData(objectId);
if (objectId.equalsIgnoreCase("") || objectId.equalsIgnoreCase(" ") || (objectId == null)) {
serviceRes.setCode(HttpStatus.METHOD_FAILURE.value());
serviceRes.setMessage(Constants.MSG_ERROR);
} else {
serviceRes.setCode(HttpStatus.OK.value());
serviceRes.setMessage(Constants.MSG_OBJECT_CREATED);
}
return serviceRes;
} catch (ServiceException e) {
throw e;
} catch (Throwable e) {
ServiceLogger.error(getClass(), e, e.getMessage());
throw new ServiceException(e);
} finally {
if (null != cmsDao) {
cmsDao.releaseSession();
}
}
}
public CmsSessionParams toCmsSessionParams() throws Exception {
CmsSessionParams params = new CmsSessionParams();
params.setUri(uri);
params.setStanza(stanza);
params.setUser(userName);
params.setPassword(password);
return params;
}
/**
* Method to create ObjectIdentity object and return filenet object.
* @param request
* @param repository
* @param objectId
* @param objectType
* @return
* @throws ServiceException
*/
public ServiceResponse<DctmObject> getDctmObject(HttpServletRequest request, String repository, String objectId,
String objectType) throws ServiceException {
CmsDao cmsDao = null;
try {
CmsSessionParams sessionParams = toCmsSessionParams();
cmsDao = CmsDaoFactory.createCmsDao();
cmsDao.setSessionParams(sessionParams);
ObjectIdentity identity = ObjectIdentity.newObject(objectId, null, null, objectType);
IndependentObject object = cmsDao.getObjectByIdentity(identity, repository);
DctmObject dctmObject = ServiceUtils.toDctmObject(object);
ServiceResponse<DctmObject> serviceRes = new ServiceResponse<DctmObject>();
serviceRes.setData(dctmObject);
if (dctmObject == null) {
serviceRes.setCode(HttpStatus.METHOD_FAILURE.value());
serviceRes.setMessage(Constants.MSG_ERROR);
} else {
serviceRes.setCode(HttpStatus.OK.value());
serviceRes.setMessage(HttpStatus.OK.toString());
}
return serviceRes;
} catch (ServiceException e) {
throw e;
} catch (Throwable e) {
throw new ServiceException(e);
} finally {
if (null != cmsDao)
cmsDao.releaseSession();
}
}
/**
* Method to create UpdateObjectParam and calls updateObjectProps DAO method for updating metadata of object.
* @param request
* @param repository
* @param objectId
* @param jsonMetadata
* @param file
* @param objectType
* @return
* @throws ServiceException
*/
@SuppressWarnings("unchecked")
public ServiceResponse<Boolean> updateDctmObject(HttpServletRequest request, String repository, String objectId,
String jsonMetadata, MultipartFile file, String objectType) throws ServiceException {
CmsDao cmsDao = null;
try {
CmsSessionParams sessionParams = toCmsSessionParams();
cmsDao = CmsDaoFactory.createCmsDao();
cmsDao.setSessionParams(sessionParams);
Map<String, Object> attrMap = new HashMap<String, Object>();
attrMap = (Map<String, Object>) ServiceUtils.fromJson(jsonMetadata, attrMap.getClass());
UpdateObjectParam params = toUpdateObjectPropsParam(objectId, attrMap, file, objectType);
boolean updated = cmsDao.updateObjectProps(params, repository);
ServiceResponse<Boolean> serviceRes = new ServiceResponse<Boolean>();
serviceRes.setData(updated);
if (updated) {
serviceRes.setCode(HttpStatus.OK.value());
serviceRes.setMessage(Constants.MSG_OBJECT_UPDATED);
} else {
serviceRes.setCode(HttpStatus.METHOD_FAILURE.value());
serviceRes.setMessage(Constants.MSG_ERROR);
}
return serviceRes;
} catch (ServiceException e) {
throw e;
} catch (Throwable e) {
throw new ServiceException(e);
} finally {
if (null != cmsDao)
cmsDao.releaseSession();
}
}
/**
* Method to create DeleteObjectParam and calls deleteObject DAO method for deleteing filenet object.
* @param request
* @param repository
* @param objectId
* @param objectType
* @return
* @throws ServiceException
*/
public ServiceResponse<Boolean> deleteDctmObject(HttpServletRequest request, String repository, String objectId,
String objectType) throws ServiceException {
CmsDao cmsDao = null;
try {
CmsSessionParams sessionParams = toCmsSessionParams();
cmsDao = CmsDaoFactory.createCmsDao();
cmsDao.setSessionParams(sessionParams);
DeleteObjectParam params = toDeleteObjectParam(objectId, objectType);
boolean deleted = cmsDao.deleteObject(params, repository);
ServiceResponse<Boolean> serviceRes = new ServiceResponse<Boolean>();
serviceRes.setData(deleted);
if (deleted) {
serviceRes.setCode(HttpStatus.OK.value());
serviceRes.setMessage(Constants.MSG_OBJECT_DELETED);
}else{
serviceRes.setCode(HttpStatus.METHOD_FAILURE.value());
serviceRes.setMessage(Constants.MSG_ERROR);
}
return serviceRes;
} catch (ServiceException e) {
throw e;
} catch (Throwable e) {
throw new ServiceException(e);
} finally {
if (null != cmsDao)
cmsDao.releaseSession();
}
}
/**
* Method to create ObjectIdentity object and calls getPropertiesByIdentity DAO method for reading single filenet object metadata.
* @param request
* @param repository
* @param id
* @param objectType
* @return
* @throws ServiceException
*/
public ServiceResponse<Map<String, String>> readMetadata(HttpServletRequest request, String repository, String id,
String objectType) throws ServiceException {
CmsDao cmsDao = null;
ServiceResponse<Map<String, String>> response = null;
try {
CmsSessionParams sessionParams = toCmsSessionParams();
cmsDao = CmsDaoFactory.createCmsDao();
cmsDao.setSessionParams(sessionParams);
ObjectIdentity identity = new ObjectIdentity();
identity.setObjectId(id);
identity.setObjectType(objectType);
Map<String, String> data = cmsDao.getPropertiesByIdentity(identity, repository);
response = new ServiceResponse<Map<String, String>>();
response.setData(data);
if(data.size()>0){
response.setCode(HttpStatus.OK.value());
response.setMessage(Constants.MSG_OBJECT_METADATA_READ);
}else{
response.setCode(HttpStatus.METHOD_FAILURE.value());
response.setMessage(Constants.MSG_ERROR);
}
// Search result
return response;
} catch (ServiceException e) {
throw e;
} catch (Throwable e) {
throw new ServiceException(e);
} finally {
if (null != cmsDao)
cmsDao.releaseSession();
}
}
/**
* Method to create ObjectIdentity object and calls getPropertiesByIdentity DAO method for reading multiple filenet object metadata.
* @param request
* @param repository
* @param json
* @return
* @throws ServiceException
*/
public List<Map<String, String>> readBulkMetadata(HttpServletRequest request, String repository, String json)
throws ServiceException {
CmsDao cmsDao = null;
List<Map<String, String>> response = new ArrayList<Map<String, String>>();
try {
CmsSessionParams sessionParams = toCmsSessionParams();
cmsDao = CmsDaoFactory.createCmsDao();
cmsDao.setSessionParams(sessionParams);
ReadAttrParams params = JsonApi.fromJson(json, ReadAttrParams.class);
List<String> list = null;
List<String> selectAttrs = params.getAttrNames();
list = new ArrayList<String>();
if (null != selectAttrs) {
for (String attr : selectAttrs) {
String dctmAttribute = null;
if (enableAttributeMapping) {
dctmAttribute = dctmObjectMapper.toDctmAttribute(attr);
} else {
dctmAttribute = attr;
}
if (null != dctmAttribute) {
list.add(dctmAttribute);
} else {
ServiceLogger.info(getClass(), attr + " attribute is not mapped to dctm attribute.");
list.add(attr);
}
}
}
for (int count = 0; count < params.getIds().size(); count++) {
ObjectIdentity identity = new ObjectIdentity();
identity.setObjectId(params.getIds().get(count));
identity.setObjectType(params.getObjectType().get(count));
Map<String, String> result = cmsDao.getPropertiesByIdentity(identity, repository);
Map<String, String> newResult = new TreeMap<String, String>();
if (null != list) {
for (String attrName : list) {
if (enableAttributeMapping) {
String customAttribute = dctmObjectMapper.toCustomAttribute(attrName);
if (null == customAttribute) {
newResult.put(attrName, result.get(attrName));
} else {
newResult.put(customAttribute, result.get(attrName));
}
} else {
newResult.put(attrName, result.get(attrName));
}
}
} else {
newResult.putAll(result);
}
response.add(newResult);
}
// Search result
return response;
} catch (ServiceException e) {
throw e;
} catch (Throwable e) {
throw new ServiceException(e);
} finally {
if (null != cmsDao)
cmsDao.releaseSession();
}
}
/**
* Method to set parameters for create operation
* @param attrMap
* @param file
* @param cmsDao
* @return
* @throws Throwable
*/
private CreateObjectParam toCreateObjectParam(Map<String, Object> attrMap, MultipartFile file, CmsDao cmsDao)
throws Throwable {
Object temp = attrMap.get(Constants.ATTR_I_FOLDER_ID);
String linkFolderId = null == temp ? null : temp.toString();
temp = attrMap.get(Constants.ATTR_R_FOLDER_PATH);
String linkFolderPath = null == temp ? null : temp.toString();
temp = attrMap.get(Constants.ATTR_R_OBJECT_TYPE);
String type = null == temp ? Constants.TYPE_DOCUMENT : temp.toString();
ObjectIdentity destIdentity = ObjectIdentity.newObject(linkFolderId, linkFolderPath, null,
Constants.TYPE_FOLDER);
InputStream stream = null == file || null == file.getInputStream() ? null : file.getInputStream();
CreateObjectParam params = new CreateObjectParam();
params.setAttrMap(attrMap);
params.setObjectType(type);
params.setDestIdentity(destIdentity);
params.setStream(stream);
if (file != null) {
params.setContentType(
file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1));
params.setObjectName(file.getOriginalFilename());
}
return params;
}
/**
* Method to set parameters for update operation
* @param objectId
* @param attrMap
* @param file
* @param objectType
* @return
* @throws Throwable
*/
private UpdateObjectParam toUpdateObjectPropsParam(String objectId, Map<String, Object> attrMap, MultipartFile file,
String objectType) throws Throwable {
UpdateObjectParam params = new UpdateObjectParam();
params.setAttrMap(attrMap);
params.setObjectIdentity(ObjectIdentity.newObject(objectId, null, null, objectType));
InputStream stream = null == file || null == file.getInputStream() ? null : file.getInputStream();
params.setStream(stream);
if (file != null) {
params.setObjectName(file.getOriginalFilename());
params.setFileExtension(file.getContentType());
}
return params;
}
/**
* Method to set parameters for delete operation
* @param objectId
* @param objectType
* @return
*/
private DeleteObjectParam toDeleteObjectParam(String objectId, String objectType) {
DeleteObjectParam params = new DeleteObjectParam();
params.setObjectIdentity(ObjectIdentity.newObject(objectId, null, null, objectType));
return params;
}
/**
* Method to call getSearchResult method of CMS Dao for search operation.
* @param request
* @param repository
* @param params
* @return
* @throws ServiceException
*/
public List<Map<String, String>> doSearch(HttpServletRequest request, String repository, SearchObjectParam params) throws ServiceException{
CmsDao cmsDao = null;
try{
CmsSessionParams sessionParams = toCmsSessionParams();
cmsDao = CmsDaoFactory.createCmsDao();
cmsDao.setSessionParams(sessionParams);
if(null == params.getObjectType()){
params.setObjectType(defaultSearchObjectType);
}
//Search result
return toCustomObjectParams(cmsDao.getSearchResult(toSearchObjectParam(params),repository));
}
catch(ServiceException e){
throw e;
}
catch(Throwable e){
throw new ServiceException(e);
}
finally{
if(null != cmsDao) cmsDao.releaseSession();
}
}
/**
* Method to set parameters for search operation
* @param params
* @return
*/
private SearchObjectParam toSearchObjectParam(SearchObjectParam params){
if(enableAttributeMapping){
SearchObjectParam param = new SearchObjectParam();
Map<String, String> conAttrs = params.getConditionalAttributes();
Iterator<String> iterator = conAttrs.keySet().iterator();
Map<String, String> newConAttrs = new HashMap<String, String>();
while(iterator.hasNext()){
String key = iterator.next();
String dctmAttribute = dctmObjectMapper.toDctmAttribute(key);
if(null != dctmAttribute){
newConAttrs.put(dctmAttribute, conAttrs.get(key));
}else{
ServiceLogger.info(getClass(), key+ " attribute is not mapped to dctm attribute.");
newConAttrs.put(key, conAttrs.get(key));
}
}
param.setConditionalAttributes(newConAttrs);
param.setObjectType(params.getObjectType());
param.setQuery(params.getQuery());
List<String> selectAttrs = params.getSelectAttributes();
List<String> list = new ArrayList<String>();
if(null != selectAttrs){
for(String attr : selectAttrs){
String dctmAttribute = dctmObjectMapper.toDctmAttribute(attr);
if(null != dctmAttribute){
list.add(dctmAttribute);
}else{
ServiceLogger.info(getClass(), attr+ " attribute is not mapped to dctm attribute.");
list.add(attr);
}
}
}
param.setSelectAttributes(list);
param.setFtQueryString(params.getFtQueryString());
param.setFullTextFlag(params.isFullTextFlag());
return param;
}else {
return params;
}
}
/**
* Method to check attribute mapper file for attributes provided thorugh JSON
* @param result
* @return
*/
private List<Map<String, String>> toCustomObjectParams(List<Map<String, String>> result){
if(enableAttributeMapping){
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = new TreeMap<String, String>();
for(int index=0; index < result.size(); index++){
Map<String, String> objectAttrMap = result.get(index);
Iterator<String> iterator = objectAttrMap.keySet().iterator();
if(null != objectAttrMap){
while(iterator.hasNext()){
String key = iterator.next();
String customAttribute = dctmObjectMapper.toCustomAttribute(key);
if(null != customAttribute){
map.put(customAttribute, objectAttrMap.get(key));
}else{
ServiceLogger.info(getClass(), key+ " attribute is not mapped to service attribute.");
map.put(key, objectAttrMap.get(key));
}
}
list.add(map);
}
}
return list;
}else{
return result;
}
}
}
|
package com.wirelesscar.dynafleet.api;
/**
* Please modify this class to meet your needs
* This class is not complete
*/
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by Apache CXF 2.7.18
* 2017-06-30T14:30:13.326-05:00
* Generated source version: 2.7.18
*
*/
public final class TransportCustomerService_TransportCustomerServicePort_Client {
private static final QName SERVICE_NAME = new QName("http://wirelesscar.com/dynafleet/api", "DynafleetAPI");
private TransportCustomerService_TransportCustomerServicePort_Client() {
}
public static void main(String args[]) throws java.lang.Exception {
URL wsdlURL = DynafleetAPI.WSDL_LOCATION;
if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
DynafleetAPI ss = new DynafleetAPI(wsdlURL, SERVICE_NAME);
TransportCustomerService port = ss.getTransportCustomerServicePort();
{
System.out.println("Invoking modifyCustomer...");
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerModifyCustomerTO _modifyCustomer_apiTransportCustomerModifyCustomerTO1 = new com.wirelesscar.dynafleet.api.types.ApiTransportCustomerModifyCustomerTO();
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerTO _modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer = new com.wirelesscar.dynafleet.api.types.ApiTransportCustomerTO();
_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer.setAdditionalInfo("AdditionalInfo-874186373");
_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer.setContactName("ContactName1879920507");
com.wirelesscar.dynafleet.api.types.ApiDate _modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerCreateTime = new com.wirelesscar.dynafleet.api.types.ApiDate();
_modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerCreateTime.setValue(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-06-30T14:30:13.345-05:00"));
_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer.setCreateTime(_modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerCreateTime);
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerId _modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerCustomerId = new com.wirelesscar.dynafleet.api.types.ApiTransportCustomerId();
_modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerCustomerId.setId(-2664735957603029147l);
_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer.setCustomerId(_modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerCustomerId);
com.wirelesscar.dynafleet.api.types.ApiDate _modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerDeletedTime = new com.wirelesscar.dynafleet.api.types.ApiDate();
_modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerDeletedTime.setValue(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-06-30T14:30:13.345-05:00"));
_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer.setDeletedTime(_modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerDeletedTime);
_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer.setEmail("Email988952924");
_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer.setFaxNumber("FaxNumber1957799001");
com.wirelesscar.dynafleet.api.types.ApiDate _modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerLastModifiedTime = new com.wirelesscar.dynafleet.api.types.ApiDate();
_modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerLastModifiedTime.setValue(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-06-30T14:30:13.346-05:00"));
_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer.setLastModifiedTime(_modifyCustomer_apiTransportCustomerModifyCustomerTO1CustomerLastModifiedTime);
_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer.setName("Name1524948169");
_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer.setOpenHours("OpenHours579893863");
_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer.setPhoneNumber("PhoneNumber823889227");
_modifyCustomer_apiTransportCustomerModifyCustomerTO1.setCustomer(_modifyCustomer_apiTransportCustomerModifyCustomerTO1Customer);
com.wirelesscar.dynafleet.api.types.ApiSessionId _modifyCustomer_apiTransportCustomerModifyCustomerTO1SessionId = new com.wirelesscar.dynafleet.api.types.ApiSessionId();
_modifyCustomer_apiTransportCustomerModifyCustomerTO1SessionId.setId("Id1597960108");
_modifyCustomer_apiTransportCustomerModifyCustomerTO1.setSessionId(_modifyCustomer_apiTransportCustomerModifyCustomerTO1SessionId);
try {
port.modifyCustomer(_modifyCustomer_apiTransportCustomerModifyCustomerTO1);
} catch (DynafleetAPIException e) {
System.out.println("Expected exception: DynafleetAPIException has occurred.");
System.out.println(e.toString());
}
}
{
System.out.println("Invoking createCustomer...");
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerCreateCustomerTO _createCustomer_apiTransportCustomerCreateCustomerTO1 = new com.wirelesscar.dynafleet.api.types.ApiTransportCustomerCreateCustomerTO();
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerTO _createCustomer_apiTransportCustomerCreateCustomerTO1Customer = new com.wirelesscar.dynafleet.api.types.ApiTransportCustomerTO();
_createCustomer_apiTransportCustomerCreateCustomerTO1Customer.setAdditionalInfo("AdditionalInfo1545107213");
_createCustomer_apiTransportCustomerCreateCustomerTO1Customer.setContactName("ContactName-465975667");
com.wirelesscar.dynafleet.api.types.ApiDate _createCustomer_apiTransportCustomerCreateCustomerTO1CustomerCreateTime = new com.wirelesscar.dynafleet.api.types.ApiDate();
_createCustomer_apiTransportCustomerCreateCustomerTO1CustomerCreateTime.setValue(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-06-30T14:30:13.347-05:00"));
_createCustomer_apiTransportCustomerCreateCustomerTO1Customer.setCreateTime(_createCustomer_apiTransportCustomerCreateCustomerTO1CustomerCreateTime);
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerId _createCustomer_apiTransportCustomerCreateCustomerTO1CustomerCustomerId = new com.wirelesscar.dynafleet.api.types.ApiTransportCustomerId();
_createCustomer_apiTransportCustomerCreateCustomerTO1CustomerCustomerId.setId(-1289394918346938047l);
_createCustomer_apiTransportCustomerCreateCustomerTO1Customer.setCustomerId(_createCustomer_apiTransportCustomerCreateCustomerTO1CustomerCustomerId);
com.wirelesscar.dynafleet.api.types.ApiDate _createCustomer_apiTransportCustomerCreateCustomerTO1CustomerDeletedTime = new com.wirelesscar.dynafleet.api.types.ApiDate();
_createCustomer_apiTransportCustomerCreateCustomerTO1CustomerDeletedTime.setValue(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-06-30T14:30:13.347-05:00"));
_createCustomer_apiTransportCustomerCreateCustomerTO1Customer.setDeletedTime(_createCustomer_apiTransportCustomerCreateCustomerTO1CustomerDeletedTime);
_createCustomer_apiTransportCustomerCreateCustomerTO1Customer.setEmail("Email1583225513");
_createCustomer_apiTransportCustomerCreateCustomerTO1Customer.setFaxNumber("FaxNumber-1468531127");
com.wirelesscar.dynafleet.api.types.ApiDate _createCustomer_apiTransportCustomerCreateCustomerTO1CustomerLastModifiedTime = new com.wirelesscar.dynafleet.api.types.ApiDate();
_createCustomer_apiTransportCustomerCreateCustomerTO1CustomerLastModifiedTime.setValue(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-06-30T14:30:13.347-05:00"));
_createCustomer_apiTransportCustomerCreateCustomerTO1Customer.setLastModifiedTime(_createCustomer_apiTransportCustomerCreateCustomerTO1CustomerLastModifiedTime);
_createCustomer_apiTransportCustomerCreateCustomerTO1Customer.setName("Name678246735");
_createCustomer_apiTransportCustomerCreateCustomerTO1Customer.setOpenHours("OpenHours-70403653");
_createCustomer_apiTransportCustomerCreateCustomerTO1Customer.setPhoneNumber("PhoneNumber-349381995");
_createCustomer_apiTransportCustomerCreateCustomerTO1.setCustomer(_createCustomer_apiTransportCustomerCreateCustomerTO1Customer);
com.wirelesscar.dynafleet.api.types.ApiSessionId _createCustomer_apiTransportCustomerCreateCustomerTO1SessionId = new com.wirelesscar.dynafleet.api.types.ApiSessionId();
_createCustomer_apiTransportCustomerCreateCustomerTO1SessionId.setId("Id665607580");
_createCustomer_apiTransportCustomerCreateCustomerTO1.setSessionId(_createCustomer_apiTransportCustomerCreateCustomerTO1SessionId);
try {
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerId _createCustomer__return = port.createCustomer(_createCustomer_apiTransportCustomerCreateCustomerTO1);
System.out.println("createCustomer.result=" + _createCustomer__return);
} catch (DynafleetAPIException e) {
System.out.println("Expected exception: DynafleetAPIException has occurred.");
System.out.println(e.toString());
}
}
{
System.out.println("Invoking getCustomer...");
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerGetCustomerTO _getCustomer_apiTransportCustomerGetCustomerTO1 = new com.wirelesscar.dynafleet.api.types.ApiTransportCustomerGetCustomerTO();
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerId _getCustomer_apiTransportCustomerGetCustomerTO1CustomerId = new com.wirelesscar.dynafleet.api.types.ApiTransportCustomerId();
_getCustomer_apiTransportCustomerGetCustomerTO1CustomerId.setId(3990685372991490964l);
_getCustomer_apiTransportCustomerGetCustomerTO1.setCustomerId(_getCustomer_apiTransportCustomerGetCustomerTO1CustomerId);
com.wirelesscar.dynafleet.api.types.ApiSessionId _getCustomer_apiTransportCustomerGetCustomerTO1SessionId = new com.wirelesscar.dynafleet.api.types.ApiSessionId();
_getCustomer_apiTransportCustomerGetCustomerTO1SessionId.setId("Id-1877533604");
_getCustomer_apiTransportCustomerGetCustomerTO1.setSessionId(_getCustomer_apiTransportCustomerGetCustomerTO1SessionId);
try {
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerTO _getCustomer__return = port.getCustomer(_getCustomer_apiTransportCustomerGetCustomerTO1);
System.out.println("getCustomer.result=" + _getCustomer__return);
} catch (DynafleetAPIException e) {
System.out.println("Expected exception: DynafleetAPIException has occurred.");
System.out.println(e.toString());
}
}
{
System.out.println("Invoking getCustomers...");
com.wirelesscar.dynafleet.api.types.ApiSessionId _getCustomers_apiSessionId1 = new com.wirelesscar.dynafleet.api.types.ApiSessionId();
_getCustomers_apiSessionId1.setId("Id2001310907");
try {
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerArrayTO _getCustomers__return = port.getCustomers(_getCustomers_apiSessionId1);
System.out.println("getCustomers.result=" + _getCustomers__return);
} catch (DynafleetAPIException e) {
System.out.println("Expected exception: DynafleetAPIException has occurred.");
System.out.println(e.toString());
}
}
{
System.out.println("Invoking getModifiedCustomers...");
com.wirelesscar.dynafleet.api.types.ApiSessionId _getModifiedCustomers_apiSessionId1 = new com.wirelesscar.dynafleet.api.types.ApiSessionId();
_getModifiedCustomers_apiSessionId1.setId("Id-1292935383");
try {
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerArrayTO _getModifiedCustomers__return = port.getModifiedCustomers(_getModifiedCustomers_apiSessionId1);
System.out.println("getModifiedCustomers.result=" + _getModifiedCustomers__return);
} catch (DynafleetAPIException e) {
System.out.println("Expected exception: DynafleetAPIException has occurred.");
System.out.println(e.toString());
}
}
{
System.out.println("Invoking getDeletedCustomers...");
com.wirelesscar.dynafleet.api.types.ApiSessionId _getDeletedCustomers_apiSessionId1 = new com.wirelesscar.dynafleet.api.types.ApiSessionId();
_getDeletedCustomers_apiSessionId1.setId("Id2104567905");
try {
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerIdArrayTO _getDeletedCustomers__return = port.getDeletedCustomers(_getDeletedCustomers_apiSessionId1);
System.out.println("getDeletedCustomers.result=" + _getDeletedCustomers__return);
} catch (DynafleetAPIException e) {
System.out.println("Expected exception: DynafleetAPIException has occurred.");
System.out.println(e.toString());
}
}
{
System.out.println("Invoking deleteCustomer...");
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerDeleteCustomerTO _deleteCustomer_apiTransportCustomerDeleteCustomerTO1 = new com.wirelesscar.dynafleet.api.types.ApiTransportCustomerDeleteCustomerTO();
com.wirelesscar.dynafleet.api.types.ApiTransportCustomerId _deleteCustomer_apiTransportCustomerDeleteCustomerTO1CustomerId = new com.wirelesscar.dynafleet.api.types.ApiTransportCustomerId();
_deleteCustomer_apiTransportCustomerDeleteCustomerTO1CustomerId.setId(-6326600817966272273l);
_deleteCustomer_apiTransportCustomerDeleteCustomerTO1.setCustomerId(_deleteCustomer_apiTransportCustomerDeleteCustomerTO1CustomerId);
com.wirelesscar.dynafleet.api.types.ApiSessionId _deleteCustomer_apiTransportCustomerDeleteCustomerTO1SessionId = new com.wirelesscar.dynafleet.api.types.ApiSessionId();
_deleteCustomer_apiTransportCustomerDeleteCustomerTO1SessionId.setId("Id-214218627");
_deleteCustomer_apiTransportCustomerDeleteCustomerTO1.setSessionId(_deleteCustomer_apiTransportCustomerDeleteCustomerTO1SessionId);
try {
port.deleteCustomer(_deleteCustomer_apiTransportCustomerDeleteCustomerTO1);
} catch (DynafleetAPIException e) {
System.out.println("Expected exception: DynafleetAPIException has occurred.");
System.out.println(e.toString());
}
}
System.exit(0);
}
}
|
package lesson5.classbook;
/**
* Урок 5. Рекурсия.
* Листинг программы Рекурсивный двоичный поиск.
* Допустим, наш отсортированный массив содержит 10 элементов
* [-10, 20, 25, 26, 40, 45, 75, 80, 82, 91].
* Ищем элемент, равный 25. Он находится в третьей позиции.
*/
public class MyArrApp {
public static void main ( String [] args ) {
MyArr arr = new MyArr ( 10 );
arr . insert (- 10 );
arr . insert ( 45 );
arr . insert ( 26 );
arr . insert ( 20 );
arr . insert ( 25 );
arr . insert ( 40 );
arr . insert ( 75 );
arr . insert ( 80 );
arr . insert ( 82 );
arr . insert ( 91 );
int search = - 10;
System . out . println ( arr . binaryFind ( search ));
}
}
|
package com.itinerary.guest.profile.model;
/**
* @author nadubey ItineraryConstant.
*
*/
public final class ItineraryConstant {
/**
* private deafault constructor.
*/
private ItineraryConstant() {
// private deafault constructor
}
/**
* STATUS_CODE_403.
*/
public static final int STATUS_CODE_403 = 403;
/**
* STATUS_CODE_500.
*/
public static final int STATUS_CODE_500 = 500;
/**
* STATUS_CODE_200.
*/
public static final int STATUS_CODE_200 = 200;
/**
* STATUS_CODE_201.
*/
public static final int STATUS_CODE_201 = 201;
/**
* STATUS_SUCCESS.
*/
public static final String STATUS_SUCCESS = "OK.";
/**
* STATUS_INVALID_OR_EXIST_USER.
*/
public static final String STATUS_INVALID_OR_EXIST_USER = ""
+ "User is not valid, User already exists.";
/**
* STATUS_INVALID_USER.
*/
public static final String STATUS_INVALID_USER = "User is not valid.";
/**
* STATUS_ADDED_USER.
*/
public static final String STATUS_ADDED_USER = ""
+ "CREATED, Guest added successfully.";
/**
* STATUS_ERROR.
*/
public static final String STATUS_ERROR = "Server error.";
}
|
package controle.tarefascontrole;
import java.util.Scanner;
public class Tarefac1 {
public static void main(String[] args) {
/*
* 1. Criar um programa que receba um
* numero e verifique se ele esta entre
* 0 e 10 e ť par
*/
Scanner entrada = new Scanner(System.in);
System.out.println("Informe um numero: ");
int n = entrada.nextInt();
if(n>=0 && n<=10) {
System.out.printf("%d EstŠ Entre 0 e 10",n);
}
if(n % 2 == 0) {
System.out.printf("%d … Par!",n);
}
entrada.close();
}
}
|
package com.teamdev.webapp1.controller.response;
import com.teamdev.webapp1.model.product.Category;
import java.util.List;
public class CategoryChartInfo {
public Category category;
public List<ProductCountInfo> productsInfo;
public CategoryChartInfo(Category category, List<ProductCountInfo> productsInfo) {
this.category = category;
this.productsInfo = productsInfo;
}
}
|
package PACKAGE_NAME;
public class Buss {
}
|
package com.zc.pivas.docteradvice.dtsystem.autocheck.req;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
/**
*
* 处方信息
*
* @author cacabin
* @version 0.1
*/
@XmlAccessorType(XmlAccessType.FIELD)
public class Prescription
{
/**
* 处方号
*/
private String id = "";
/**
* 理由
*/
private String reason = "";
/**
* 是否当前处方(0/1)
*/
private String is_current = "";
/**
* 长期医嘱L/临时医嘱T
*/
private String pres_type = "";
/**
* 处方时间(YYYY-MM-DD HH:mm:SS)
*/
private String pres_time = "";
/**
* 药品信息
*/
@XmlElement(name = "medicine_data")
private Medicine_data medicine_data = new Medicine_data();
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getReason()
{
return reason;
}
public void setReason(String reason)
{
this.reason = reason;
}
public String getIs_current()
{
return is_current;
}
public void setIs_current(String is_current)
{
this.is_current = is_current;
}
public String getPres_type()
{
return pres_type;
}
public void setPres_type(String pres_type)
{
this.pres_type = pres_type;
}
public String getPres_time()
{
return pres_time;
}
public void setPres_time(String pres_time)
{
this.pres_time = pres_time;
}
public Medicine_data getMedicine_data()
{
return medicine_data;
}
public void setMedicine_data(Medicine_data medicine_data)
{
this.medicine_data = medicine_data;
}
}
|
package com.soldevelo.vmi.config.acs.model;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class HostParamsTest {
@Test
public void compareTest() {
HostParams hostParams1 = new HostParams();
HostParams hostParams2 = new HostParams();
hostParams1.setTagParam("192.168.1.1");
hostParams2.setTagParam("hostname:192.168.1.2");
assertEquals(0, hostParams1.compareTo(hostParams2));
hostParams2.setTagParam("subnet:192.168.1.0/24");
assertTrue(hostParams1.compareTo(hostParams2) < 0);
hostParams1.setTagParam("subnet:192.168.0.0/16");
assertTrue(hostParams1.compareTo(hostParams2) > 0);
}
}
|
/*
* 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 algoritmos.sort;
/**
*
* @author leona
*/
public class BubbleSort {
public static boolean sort(int[] vet) {
if(vet == null) return false;
for (int i = 0; i < vet.length - 1; i++) {
int trocas = 0;
for (int j = 0; j < vet.length - 1 - i; j++) {
if (vet[j] > vet[j + 1]) {
int temp = vet[j];
vet[j] = vet[j+1];
vet[j+1] = temp;
trocas++;
}
}
if(trocas == 0) break;
}
return true;
}
}
|
package Repository;
import Domain.Car;
import Domain.Category;
/**
* Created by Emma on 8/11/2018.
*/
public interface CarRepository extends CrudRepository <Car, Long>
{
Car create(Car car1);
Car read(String id);
Car update(Car carDetails);
void delete(String id);
Iterable<Car> readAll();
Iterable<Car> findAllById(Category category);;
}
|
package com.compania.vuelos.servicio.implementacion;
import java.time.LocalDate;
import java.time.LocalTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class BoletoServicioTest {
@Test
public void contextLoads()
{
System.out.println(LocalDate.now());
}
@Test
public void comprobarLocalDateTest()
{
Object fecha = LocalDate.now();
LocalTime horaActual = LocalTime.now();
System.out.println("\n\n\nSe imprime en consola de Spring Boot \n" + fecha + " hora Actual supuesta " + horaActual + "\n\n\n");
}
}
|
package com.getkhaki.api.bff.web.models;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.List;
import java.util.OptionalInt;
@Data
@NoArgsConstructor
@Accessors(chain = true)
public class OrganizersStatisticsResponseDto {
int page;
OptionalInt count;
List<OrganizerStatisticsResponseDto> organizersStatistics;
}
|
package com.sirma.itt.javacourse.objects.task3.supermarket.productObjects;
/**
* Class that describes the parameters of a Electronic product.
*
* @author simeon
*/
public class ElectronicProduct extends Product {
private String grade;
private float voltage;
private String shortDescriptiom;
private int warranty;
/**
* Getter method for grade.
*
* @return the grade
*/
public String getGrade() {
return grade;
}
/**
* Setter method for grade.
*
* @param grade
* the grade to set
*/
public void setGrade(String grade) {
this.grade = grade;
}
/**
* Getter method for voltage.
*
* @return the voltage
*/
public float getVoltage() {
return voltage;
}
/**
* Setter method for voltage.
*
* @param voltage
* the voltage to set
*/
public void setVoltage(float voltage) {
this.voltage = voltage;
}
/**
* Getter method for shortDescriptiom.
*
* @return the shortDescriptiom
*/
public String getShortDescriptiom() {
return shortDescriptiom;
}
/**
* Setter method for shortDescriptiom.
*
* @param shortDescriptiom
* the shortDescriptiom to set
*/
public void setShortDescriptiom(String shortDescriptiom) {
this.shortDescriptiom = shortDescriptiom;
}
/**
* Getter method for waranty.
*
* @return the waranty
*/
public int getWaranty() {
return warranty;
}
/**
* Setter method for waranty.
*
* @param waranty
* the waranty to set
*/
public void setWaranty(int waranty) {
this.warranty = waranty;
}
/**
* Constructor for Electronic Product.
*
* @param productName
* the name of the product.
* @param category
* the category of the product.
* @param vendor
* the vendor of the product.
* @param units
* the units in which the product is measured example (units, kilogram, grams)
* @param quantity
* the quantity of the product.
* @param sellingPrice
* the selling price per unit.
* @param grade
* the electricity usage grade of the product.
* @param voltage
* the voltage at which the device runs
* @param shortDescriptiom
* a short technical description of the product
* @param waranty
* the years of warranty for the product.
*/
public ElectronicProduct(String productName, String category, Vendor vendor, String units,
float quantity, float sellingPrice, String grade, float voltage,
String shortDescriptiom, int waranty) {
super(productName, category, vendor, units, quantity, sellingPrice);
this.grade = grade;
this.voltage = voltage;
this.shortDescriptiom = shortDescriptiom;
this.warranty = waranty;
}
}
|
package com.example.caxidy.agendacontactos;
import java.io.Serializable;
public class Foto implements Serializable {
int idFoto, idContacto;
String nombreFichero,descripcionFoto;
public Foto(){
idFoto=0;
idContacto=0;
nombreFichero=descripcionFoto="";
}
public Foto(int id, String nom,String desc,int idC){
idFoto=id;
idContacto=idC;
nombreFichero=nom;
descripcionFoto=desc;
}
public Foto(String nom,String desc){
idFoto=0;
idContacto=0;
nombreFichero=nom;
descripcionFoto=desc;
}
public int getId(){return idFoto;}
public int getIdContacto(){return idContacto;}
public String getNombreFichero(){return nombreFichero;}
public String getDescripcionFoto(){return descripcionFoto;}
}
|
import java.util.Collection;
public class ConsoleEventLogger implements EventLogger{
private Collection loggers;
public void logEvent(Event event){
System.out.println(event);
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export.annotation;
import org.springframework.jmx.IJmxTestBean;
import org.springframework.jmx.support.MetricType;
import org.springframework.stereotype.Service;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
@Service("testBean")
@ManagedResource(objectName = "bean:name=testBean4", description = "My Managed Bean", log = true,
logFile = "build/jmx.log", currencyTimeLimit = 15, persistPolicy = "OnUpdate", persistPeriod = 200,
persistLocation = "./foo", persistName = "bar.jmx")
@ManagedNotification(name = "My Notification", notificationTypes = { "type.foo", "type.bar" })
public class AnnotationTestBean implements IJmxTestBean {
private String name;
private String nickName;
private int age;
private boolean isSuperman;
@Override
@ManagedAttribute(description = "The Age Attribute", currencyTimeLimit = 15)
public int getAge() {
return age;
}
@Override
public void setAge(int age) {
this.age = age;
}
@Override
@ManagedOperation(currencyTimeLimit = 30)
public long myOperation() {
return 1L;
}
@Override
@ManagedAttribute(description = "The Name Attribute",
currencyTimeLimit = 20,
defaultValue = "bar",
persistPolicy = "OnUpdate")
public void setName(String name) {
this.name = name;
}
@Override
@ManagedAttribute(defaultValue = "foo", persistPeriod = 300)
public String getName() {
return name;
}
@ManagedAttribute(description = "The Nick Name Attribute")
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNickName() {
return this.nickName;
}
public void setSuperman(boolean superman) {
this.isSuperman = superman;
}
@ManagedAttribute(description = "The Is Superman Attribute")
public boolean isSuperman() {
return isSuperman;
}
@Override
@ManagedOperation(description = "Add Two Numbers Together")
@ManagedOperationParameter(name="x", description="Left operand")
@ManagedOperationParameter(name="y", description="Right operand")
public int add(int x, int y) {
return x + y;
}
/**
* Test method that is not exposed by the MetadataAssembler.
*/
@Override
public void dontExposeMe() {
throw new RuntimeException();
}
@ManagedMetric(description="The QueueSize metric", currencyTimeLimit = 20, persistPolicy="OnUpdate", persistPeriod=300,
category="utilization", metricType = MetricType.COUNTER, displayName="Queue Size", unit="messages")
public long getQueueSize() {
return 100L;
}
@ManagedMetric
public int getCacheEntries() {
return 3;
}
}
|
package com.example.demo.service;
import com.example.demo.entity.SysMonthlyReportMajor;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author zjp
* @since 2021-03-30
*/
public interface ISysMonthlyReportMajorService extends IService<SysMonthlyReportMajor> {
}
|
package com.novakivska.app.homework.homework15;
/**
* Created by Tas_ka on 5/9/2017.
*/
public class Flat {
private Furniture furniture;
private TVset tvSet;
public Flat(Furniture furniture){
this.furniture = furniture;
}
public Furniture getFurniture() {
return furniture;
}
public TVset getTvSet() {
return tvSet;
}
public void setTvSet(TVset tvSet) {
this.tvSet = tvSet;
}
}
|
package com.example.springhibernate.hibernate.repositories;
import com.example.springhibernate.hibernate.models.Book;
import com.example.springhibernate.hibernate.models.BookDetail;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BookDetailRepository extends JpaRepository<BookDetail, Long> {
}
|
/*
* 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 seatingsystem;
import java.util.*;
import java.io.*;
/**
*
* @author nathanphipps
*/
public class Database {
boolean enabled;
File database_directory;
String auditorium_extension;
String group_extension;
String chart_sequence_extension;
File version_directory;
public Database(){
System.out.println("Database Constructed");
File file = new File(System.getProperty("user.home"));
String database_folder = "Library/Application Support/SeatingSystem";
try {
file = new File(GUI.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
file = file.getParentFile();
database_folder = "Database";
}
catch (Exception e){
file = new File(System.getProperty("user.home"));
}
this.database_directory = new File(
file,
database_folder);
if (!this.database_directory.exists()){
this.database_directory.mkdir();
}
this.version_directory = new File(this.database_directory,
"v_0_0_1_a");
if (!this.version_directory.exists()){
this.version_directory.mkdir();
}
this.auditorium_extension = "auditorium";
this.group_extension = "group";
this.chart_sequence_extension = "chart_sequence";
this.enabled = true;
}
//------------------------------------------------------------------------------------------------
private boolean removeAuditorium(Auditorium auditorium){
File file = new File(this.version_directory,
auditorium.getUUID()+"."+this.auditorium_extension);
if (file.exists()){
System.out.println("DELETED");
file.delete();
}
return true;
}
private boolean removeGroup(Group group){
File file = new File(this.version_directory,
group.getUUID()+"."+this.group_extension);
if (file.exists()){
file.delete();
}
return true;
}
private boolean removeChartSequence(ChartSequence chart_sequence){
File file = new File(this.version_directory,
chart_sequence.getUUID()+"."+this.chart_sequence_extension);
if (file.exists()){
file.delete();
}
return true;
}
//------------------------------------------------------------------------------------------------
private boolean saveAuditorium(Auditorium auditorium){
try {
FileOutputStream fos = new FileOutputStream(
this.version_directory.getPath() + "/" +
auditorium.getUUID().toString() + "." + this.auditorium_extension);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(auditorium);
oos.close();
fos.close();
}
catch (Exception e){
e.printStackTrace();
return false;
}
return true;
}
private boolean saveGroup(Group group){
try {
FileOutputStream fos = new FileOutputStream(
this.version_directory.getPath() + "/" +
group.getUUID().toString() + "." + this.group_extension);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(group);
oos.close();
fos.close();
}
catch (Exception e){
e.printStackTrace();
return false;
}
return true;
}
private boolean saveChartSequence(ChartSequence chart_sequence){
try {
FileOutputStream fos = new FileOutputStream(
this.version_directory.getPath() + "/" +
chart_sequence.getUUID().toString() + "." + this.chart_sequence_extension);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(chart_sequence);
oos.close();
fos.close();
}
catch (Exception e){
e.printStackTrace();
return false;
}
return true;
}
//------------------------------------------------------------------------------------------------
public void setEnabled(boolean value){
this.enabled = value;
}
public boolean saveObject(Object object){
if (!this.enabled){
return false;
}
if (object instanceof Auditorium){
return this.saveAuditorium((Auditorium)object);
}
if (object instanceof Group){
return this.saveGroup((Group)object);
}
if (object instanceof ChartSequence){
return this.saveChartSequence((ChartSequence)object);
}
return false;
}
public boolean removeObject(Object object){
if (!this.enabled){
return false;
}
if (object instanceof Auditorium){
return this.removeAuditorium((Auditorium)object);
}
else if (object instanceof Group){
return this.removeGroup((Group)object);
}
else if (object instanceof ChartSequence){
return this.removeChartSequence((ChartSequence)object);
}
return false;
}
public void printDirectoryContents(){
if (!this.enabled){
return;
}
for (File file : this.version_directory.listFiles()){
if (file.getName().contains(".")){
String extension = file.getName().substring(
file.getName().indexOf('.')+1, file.getName().length());
if (extension.equalsIgnoreCase(this.auditorium_extension)){
System.out.println("Auditorium: "+file.getName());
}
else if (extension.equalsIgnoreCase(this.group_extension)){
System.out.println("Group: "+file.getName());
}
else if (extension.equalsIgnoreCase(this.chart_sequence_extension)){
System.out.println("Chart Sequence: "+file.getName());
}
else {
System.out.println("Unknown: "+file.getName());
}
}else {
System.out.println("Unknown: "+file.getName());
}
}
}
public ArrayList<Auditorium> getAuditoriumList(){
if (!this.enabled){
return null;
}
ArrayList<Auditorium> auditoriums = new ArrayList<Auditorium>();
try {
FileInputStream fis; // = new FileInputStream(this.database_directory.getPath() + "/");
ObjectInputStream ois; // new ObjectInputStream(fis);
for (File file : this.version_directory.listFiles()) {
if (file.getName().contains(".")) {
String extension = file.getName().substring(
file.getName().indexOf('.') + 1, file.getName().length());
if (extension.equalsIgnoreCase(this.auditorium_extension)) {
//System.out.println("Found Auditorium: " + file.getName());
fis = new FileInputStream(this.version_directory.getPath() + "/" +
file.getName());
ois = new ObjectInputStream(fis);
auditoriums.add((Auditorium)ois.readObject());
ois.close();
fis.close();
}
}
}
}
catch (Exception e){
e.printStackTrace();
}
return auditoriums;
}
public ArrayList<Group> getGroupList(){
if (!this.enabled){
return null;
}
ArrayList<Group> groups = new ArrayList<Group>();
try {
FileInputStream fis; // = new FileInputStream(this.database_directory.getPath() + "/");
ObjectInputStream ois; // new ObjectInputStream(fis);
for (File file : this.version_directory.listFiles()) {
if (file.getName().contains(".")) {
String extension = file.getName().substring(
file.getName().indexOf('.') + 1, file.getName().length());
if (extension.equalsIgnoreCase(this.group_extension)) {
//System.out.println("Found Group: " + file.getName());
fis = new FileInputStream(this.version_directory.getPath() + "/" +
file.getName());
ois = new ObjectInputStream(fis);
groups.add((Group)ois.readObject());
ois.close();
fis.close();
}
}
}
}
catch (Exception e){
e.printStackTrace();
}
return groups;
}
public ArrayList<ChartSequence> getChartSequenceList(){
if (!this.enabled){
return null;
}
ArrayList<ChartSequence> chart_sequencs = new ArrayList<ChartSequence>();
try {
FileInputStream fis; // = new FileInputStream(this.database_directory.getPath() + "/");
ObjectInputStream ois; // new ObjectInputStream(fis);
for (File file : this.version_directory.listFiles()) {
if (file.getName().contains(".")) {
String extension = file.getName().substring(
file.getName().indexOf('.') + 1, file.getName().length());
if (extension.equalsIgnoreCase(this.chart_sequence_extension)) {
//System.out.println("Found Chart Sequence: " + file.getName());
fis = new FileInputStream(this.version_directory.getPath() + "/" +
file.getName());
ois = new ObjectInputStream(fis);
chart_sequencs.add((ChartSequence) ois.readObject());
ois.close();
fis.close();
}
}
}
}
catch (Exception e){
e.printStackTrace();
}
return chart_sequencs;
}
}
|
package fm.ua.bacs.testtaskrestservice.controller;
import fm.ua.bacs.testtaskrestservice.helpers.FTP;
import fm.ua.bacs.testtaskrestservice.helpers.Props;
import org.apache.commons.net.ftp.FTPFile;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import static fm.ua.bacs.testtaskrestservice.helpers.Helper.FILE_COUNTER;
public class OutCheckerController {
public void checkOutFolder() {
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
System.out.println("Checking out folder");
try {
checker();
} catch (IOException e) {
e.printStackTrace();
}
}
},
0,
5000
);
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
System.out.println(FILE_COUNTER + " files already have been proceed");
}
},
0,
60000
);
}
private void checker() throws IOException {
FTP ftp = new FTP();
Props props = new Props();
FTPFile[] files = ftp.getFiles(props.getProperties().getProperty("ftp.out"));
for (FTPFile file : files) {
if (!file.isDirectory()) {
if (ftp.downloadFromFTP(props.getProperties().getProperty("ftp.out") + file.getName(), new File(props.getProperties().getProperty("local.ready") + file.getName()))) {
ftp.copyFile(props.getProperties().getProperty("ftp.out") + file.getName(), props.getProperties().getProperty("ftp.ready") + file.getName(), true);
ftp.copyFile(props.getProperties().getProperty("ftp.ready") + file.getName(), props.getProperties().getProperty("ftp.bkp") + file.getName(), false);
fm.ua.bacs.testtaskrestservice.helpers.Response response = new fm.ua.bacs.testtaskrestservice.helpers.Response();
System.out.println(response.makeResponse(file.getName(), "File is ready", 200));
}
}
}
}
}
|
/*
* 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 uniza.diss.one.utils;
import uniza.diss.one.app.App;
/**
* Trieda, ktora tvori komunikacnu vrstvu medzi biznis logikou aplikacie
* a uzivatelskym rozhranim
*
* @author mariokemen
*/
public final class AppOutput {
private static App app;
public static void setApp(App pApp) {
app = pApp;
}
/**
* Pridanie jednej repliky strategie 1 do grafu.
*
* @param x
* @param y
*/
public static void addReplicaStrategy1(int x, double y) {
app.addReplicaStrategy1(x, y);
}
/**
* Pridanie jednej repliky strategie 2 do grafu.
*
* @param x
* @param y
*/
public static void addReplicaStrategy2(int x, double y) {
app.addReplicaStrategy2(x, y);
}
}
|
import java.util.*;
/**
* Main World Class
*
* @author Ezekiel Elin
* @author Unknown Author
* @version 11/02/2016
*/
public class World {
private List<List<Cell>> board;
private int lightEnergy;
private int steps;
public World(int width, int height, int light) {
lightEnergy = light;
steps = 0;
board = new ArrayList<List<Cell>>();
for(int i = 0; i < width; i++) {
board.add(new ArrayList<Cell>());
for(int j = 0; j < height; j++) {
board.get(i).add(new Cell(this));
board.get(i).get(j).setLocation(new Point(i, j));
}
}
}
public int getLightEnergy() {
return lightEnergy;
}
public Cell get(int x, int y) {
return this.board.get(x).get(y);
}
public int getWidth() {
return this.board.size();
}
public int getHeight() {
return this.board.get(0).size();
}
public int getSteps() {
return this.steps;
}
/**
* Goes through each cell and runs the activities for each species
* Also adds a new element to the birth and death lists so they can be tracker for the turn
*/
public void turn() {
int curSteps = this.getSteps();
if(Species.getDeaths().size() == curSteps) {
Species.getDeaths().add(new ArrayList<Integer>());
for(int i = 0; i < Species.getSpecies().size(); i++) {
Species.getDeaths().get(curSteps).add(0);
}
}
if(Species.getBirths().size() == curSteps) {
Species.getBirths().add(new ArrayList<Integer>());
for(int i = 0; i < Species.getSpecies().size(); i++) {
Species.getBirths().get(curSteps).add(0);
}
}
for(int i = 0; i < board.size(); i++) {
List<Cell> column = board.get(i);
for(int j = 0; j < column.size(); j++) {
Cell cell = column.get(j);
if(cell.getAnimal() != null) {
cell.getAnimal().activity();
}
if(cell.getPlant() != null) {
cell.getPlant().activity();
}
}
}
steps++;
}
/**
* Prints the board in an easy to view way
*/
public void print() {
for(int y = 0; y < this.getHeight(); y++) {
System.out.print("|");
for(int x = 0; x < this.getWidth(); x++) {
Cell cell = this.get(x, y);
String message = "";
if (cell.isMountain()) {
message += "MNT";
}
if (cell.flag) {
message += "!!!";
}
if(cell.getAnimal() != null) {
message += cell.getAnimal().getRepresentation();
}
if(message.length() > 0 && cell.getPlant() != null) {
message += "/";
}
if(cell.getPlant() != null) {
message += cell.getPlant().getRepresentation();
}
System.out.print(message + "\t|");
}
System.out.println();
System.out.println("-----------------------------------------------------------------------------------------------------");
}
}
/**
* Takes a species and generates random coordinates until it finds an empty cell for it
* @param Species s - the species that should be randomly added to the world
*/
public void randomAddToWorld(Species s) {
Random generator = new Random(Simulation.SEED);
boolean found = false;
int count = 0; //Prevents infinite loop in case more species are trying to be added than there are spaces for them
while(!found && count < 10000) {
count++;
int x = generator.nextInt(this.board.size());
int y = generator.nextInt(this.board.get(0).size());
Cell cell = this.board.get(x).get(y);
/* cannot use mountain spaces */
if (cell.isMountain()) {
continue;
}
if(s instanceof Animal) {
if(cell.getAnimal() == null) {
cell.setAnimal((Animal)s);
s.setCell(cell);
found = true;
}
} else if(s instanceof Plant) {
if(cell.getPlant() == null) {
cell.setPlant((Plant)s);
s.setCell(cell);
found = true;
}
}
}
}
}
|
package tp.pr1.managers;
public class SuncoinManager {
private int numeroSoles;
public SuncoinManager() {
numeroSoles = 50;
}
public void setSoles(int numSoles) { //suma al número de soles los que han generado los girasoles en ese ciclo
numeroSoles += numSoles;
}
public int getNumeroSoles() { //devuelve el numero de soles
return numeroSoles;
}
public void restarSoles(int precio) { // Esta funcion es llamada cuando se compra una planta => resta el coste de la planta al total de soles
numeroSoles -= precio;
}
}
|
public class Stack {
private static final int CAPACITY = 1000;
private int[] data;
private int top = -1;
public Stack() {
this(CAPACITY);
}
public Stack(int capacity) {
data = new int[capacity];
}
public int size() {
return (top + 1);
}
public boolean isEmpty() {
return (top == -1);
}
public void push(int value) throws IllegalStateException {
if (size() == data.length) {
throw new IllegalStateException("StackOvarflowException");
}
top++;
data[top] = value;
}
public int top() throws IllegalStateException {
if (isEmpty()) {
throw new IllegalStateException("StackEmptyException");
}
return data[top];
}
public int pop() {
if (isEmpty()) {
throw new IllegalStateException("StackEmptyException");
}
int topVal = data[top];
top--;
return topVal;
}
public void print() {
for (int i = top; i > -1; i--) {
System.out.print(" " + data[i]);
}
}
public static void main(String[] args) {
Stack s = new Stack(1000);
for (int i = 1; i <= 100; i++) {
s.push(i);
}
for (int i = 1; i <= 50; i++) {
s.pop();
}
s.print();
}
}
|
package cn.kitho.core.config;
import java.util.HashMap;
import java.util.Map;
/**
* 关键字的范围类型
* Created by lingkitho on 2017/2/17.
*/
public enum KeyWordsRangeType {
ARTICLE(0,"文章"),
DAIRY(1,"日记");
KeyWordsRangeType(int statusIndex, String statusName) {
this.statusIndex = statusIndex;
this.statusName = statusName;
}
/** 状态下标 */
private int statusIndex;
/** 状态名称 */
private String statusName;
public int getStatusIndex() {
return statusIndex;
}
public void setStatusIndex(int statusIndex) {
this.statusIndex = statusIndex;
}
public String getStatusName() {
return statusName;
}
public void setStatusName(String statusName) {
this.statusName = statusName;
}
/**
* 根据范围类型ID类型获取枚举对象
* @param orderStatusIndex 支付类型值
* @return
*/
public static KeyWordsRangeType typeOf(int orderStatusIndex){
KeyWordsRangeType[] KeyWordsRangeTypes = KeyWordsRangeType.values();
for(KeyWordsRangeType KeyWordsRangeType: KeyWordsRangeTypes){
if(KeyWordsRangeType.getStatusIndex() == orderStatusIndex){
return KeyWordsRangeType;
}
}
throw new IllegalArgumentException("非法订单类型: " + orderStatusIndex);
}
/**
* 枚举转Map
* @return Map
*/
public static Map<Integer,String> convertToMap(){
Map<Integer,String> KeyWordsRangeTypeMap = new HashMap<Integer, String>();
KeyWordsRangeType[] KeyWordsRangeTypes = KeyWordsRangeType.values();
for(KeyWordsRangeType KeyWordsRangeType : KeyWordsRangeTypes){
KeyWordsRangeTypeMap.put(KeyWordsRangeType.getStatusIndex(),KeyWordsRangeType.getStatusName());
}
return KeyWordsRangeTypeMap;
}
}
|
package com.metoo.foundation.test;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
public class TestDate {
/**
* @param args
*/
public static void main(String[] args) {
Calendar cal = Calendar. getInstance ();
System.out.println(cal.getTime());
cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE)+20);
System.out.println(cal.getTime());
}
}
|
package com.example.android.arthistoryquiz;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class PaintingActivity extends MainActivity {
static final String QUESTION_ONE = "q1check";
static final String QUESTION_TWO = "q2check";
static final String QUESTION_THREE = "q3check";
static final String QUESTION_FOUR = "q4check";
static final String QUESTION_FIVE = "q5check";
static final String QUESTION_SIX = "q6check";
static final String QUESTION_SEVEN = "q7check";
static final String QUESTION_EIGHT = "q8check";
static final String QUESTION_NINE = "q9check";
static final String QUESTION_TEN = "q10check";
private int q1score;
private int q2score;
private int q3score;
private int q4score;
private int q5score;
private int q6score;
private int q7score;
private int q8score;
private int q9score;
private int q10score;
private String q1check;
private String q2check;
private String q3check;
private String q4check;
private String q5check;
private String q6check;
private String q7check;
private String q8check;
private String q9check;
private String q10check;
RadioButton paintingQ1A1;
RadioButton paintingQ2A1;
RadioButton paintingQ3A3;
RadioButton paintingQ4A3;
RadioButton paintingQ5A3;
CheckBox paintingQ6A1;
CheckBox paintingQ6A2;
CheckBox paintingQ6A3;
RadioButton paintingQ7A1;
RadioButton paintingQ8A1;
RadioButton paintingQ9A3;
EditText paintingQ10A1;
TextView paintingQ1Verify;
TextView paintingQ2Verify;
TextView paintingQ3Verify;
TextView paintingQ4Verify;
TextView paintingQ5Verify;
TextView paintingQ6Verify;
TextView paintingQ7Verify;
TextView paintingQ8Verify;
TextView paintingQ9Verify;
TextView paintingQ10Verify;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.painting);
paintingQ1A1 = findViewById(R.id.paintingQ1A1);
paintingQ2A1 = findViewById(R.id.paintingQ2A1);
paintingQ3A3 = findViewById(R.id.paintingQ3A3);
paintingQ4A3 = findViewById(R.id.paintingQ4A3);
paintingQ5A3 = findViewById(R.id.paintingQ5A3);
paintingQ6A1 = findViewById(R.id.paintingQ6A1);
paintingQ6A2 = findViewById(R.id.paintingQ6A2);
paintingQ6A3 = findViewById(R.id.paintingQ6A3);
paintingQ7A1 = findViewById(R.id.paintingQ7A1);
paintingQ8A1 = findViewById(R.id.paintingQ8A1);
paintingQ9A3 = findViewById(R.id.paintingQ9A3);
paintingQ10A1 = findViewById(R.id.paintingQ10A1);
paintingQ1Verify = findViewById(R.id.paintingQ1Verify);
paintingQ2Verify = findViewById(R.id.paintingQ2Verify);
paintingQ3Verify = findViewById(R.id.paintingQ3Verify);
paintingQ4Verify = findViewById(R.id.paintingQ4Verify);
paintingQ5Verify = findViewById(R.id.paintingQ5Verify);
paintingQ6Verify = findViewById(R.id.paintingQ6Verify);
paintingQ7Verify = findViewById(R.id.paintingQ7Verify);
paintingQ8Verify = findViewById(R.id.paintingQ8Verify);
paintingQ9Verify = findViewById(R.id.paintingQ9Verify);
paintingQ10Verify = findViewById(R.id.paintingQ10Verify);
}
/**
* This method saves the state of textView that displays if the
* answers are correct or wrong.
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(QUESTION_ONE, q1check);
outState.putString(QUESTION_TWO, q2check);
outState.putString(QUESTION_THREE, q3check);
outState.putString(QUESTION_FOUR, q4check);
outState.putString(QUESTION_FIVE, q5check);
outState.putString(QUESTION_SIX, q6check);
outState.putString(QUESTION_SEVEN, q7check);
outState.putString(QUESTION_EIGHT, q8check);
outState.putString(QUESTION_NINE, q9check);
outState.putString(QUESTION_TEN, q10check);
}
/**
* This method restores the state of textView that displays if the
* answers are correct or wrong.
*/
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
q1check = savedInstanceState.getString(QUESTION_ONE);
q2check = savedInstanceState.getString(QUESTION_TWO);
q3check = savedInstanceState.getString(QUESTION_THREE);
q4check = savedInstanceState.getString(QUESTION_FOUR);
q5check = savedInstanceState.getString(QUESTION_FIVE);
q6check = savedInstanceState.getString(QUESTION_SIX);
q7check = savedInstanceState.getString(QUESTION_SEVEN);
q8check = savedInstanceState.getString(QUESTION_EIGHT);
q9check = savedInstanceState.getString(QUESTION_NINE);
q10check = savedInstanceState.getString(QUESTION_TEN);
displayQ1Check();
displayQ2Check();
displayQ3Check();
displayQ4Check();
displayQ5Check();
displayQ6Check();
displayQ7Check();
displayQ8Check();
displayQ9Check();
displayQ10Check();
}
/**
* This method hides keyboard when EditText lose focus.
* The source of this method is:
* https://stackoverflow.com/questions/8697499/hide-keyboard-when-user-taps-anywhere-else-on-the-screen-in-android/37390091#37390091
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
View view = getCurrentFocus();
if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
int scrcoords[] = new int[2];
view.getLocationOnScreen(scrcoords);
float x = ev.getRawX() + view.getLeft() - scrcoords[0];
float y = ev.getRawY() + view.getTop() - scrcoords[1];
if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
}
return super.dispatchTouchEvent(ev);
}
/**
* This method checks the answers if are correct or wrong.
*/
public void submitAnswers(View view) {
if (paintingQ1A1.isChecked()) {
q1score = 1;
q1check = getString(R.string.correct);
displayQ1Check();
}
else {
q1score = 0;
q1check = getString(R.string.wrong);
displayQ1Check();
}
if (paintingQ2A1.isChecked()) {
q2score = 1;
q2check = getString(R.string.correct);
displayQ2Check();
}
else {
q2score = 0;
q2check = getString(R.string.wrong);
displayQ2Check();
}
if (paintingQ3A3.isChecked()) {
q3score = 1;
q3check = getString(R.string.correct);
displayQ3Check();
}
else {
q3score = 0;
q3check = getString(R.string.wrong);
displayQ3Check();
}
if (paintingQ4A3.isChecked()) {
q4score = 1;
q4check = getString(R.string.correct);
displayQ4Check();
}
else {
q4score = 0;
q4check = getString(R.string.wrong);
displayQ4Check();
}
if (paintingQ5A3.isChecked()) {
q5score = 1;
q5check = getString(R.string.correct);
displayQ5Check();
}
else {
q5score = 0;
q5check = getString(R.string.wrong);
displayQ5Check();
}
if (paintingQ6A1.isChecked() && paintingQ6A2.isChecked() && !paintingQ6A3.isChecked()) {
q6score = 1;
q6check = getString(R.string.correct);
displayQ6Check();
}
else {
q6score = 0;
q6check = getString(R.string.wrong);
displayQ6Check();
}
if (paintingQ7A1.isChecked()) {
q7score = 1;
q7check = getString(R.string.correct);
displayQ7Check();
}
else {
q7score = 0;
q7check = getString(R.string.wrong);
displayQ7Check();
}
if (paintingQ8A1.isChecked()) {
q8score = 1;
q8check = getString(R.string.correct);
displayQ8Check();
}
else {
q8score = 0;
q8check = getString(R.string.wrong);
displayQ8Check();
}
if (paintingQ9A3.isChecked()) {
q9score = 1;
q9check = getString(R.string.correct);
displayQ9Check();
}
else {
q9score = 0;
q9check = getString(R.string.wrong);
displayQ9Check();
}
String paintingQ10A1Text = paintingQ10A1.getText().toString();
if (paintingQ10A1Text.equals(getString(R.string.paintingQ10A))) {
q10score = 1;
q10check = getString(R.string.correct);
displayQ10Check();
}
else {
q10score = 0;
q10check = getString(R.string.wrong);
displayQ10Check();
}
int paintingScore = calculateScore(
q1score,
q2score,
q3score,
q4score,
q5score,
q6score,
q7score,
q8score,
q9score,
q10score
);
saveScore(paintingScore);
viewScore(paintingScore);
}
/**
* This method calculate the score.
*/
public int calculateScore(
int q1score,
int q2score,
int q3score,
int q4score,
int q5score,
int q6score,
int q7score,
int q8score,
int q9score,
int q10score
){
int score;
score = q1score + q2score + q3score + q4score + q5score + q6score + q7score + q8score + q9score + q10score;
return score;
}
/**
* This method save the last score on SharedPreferences.
*/
public void saveScore(int score) {
SharedPreferences myPreferences
= PreferenceManager.getDefaultSharedPreferences(PaintingActivity.this);
SharedPreferences.Editor myEditor = myPreferences.edit();
myEditor.putInt("PAINTING", score);
myEditor.commit();
}
/**
* This method show the score in ScoreActivity.
*/
public void viewScore(int score) {
String yourScore = getString(R.string.you_answered, score);
yourScore += getString(R.string.of_questions);
Toast.makeText(this, yourScore, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, ScoreActivity.class);
intent.putExtra("SCORE", score);
startActivity(intent);
}
/**
* This method sets and display text if answer for question 1 is correct or wrong.
*/
public void displayQ1Check() {
if (q1check.equals(getString(R.string.correct))){
paintingQ1Verify.setText(q1check);
paintingQ1Verify.setTextColor(getResources().getColor(R.color.correct));
}
else if (q1check.equals(getString(R.string.wrong))) {
String q1wrong = q1check;
q1wrong += "\n" + getString(R.string.correct_answer);
q1wrong += " " + getString(R.string.paintingQ1A1);
paintingQ1Verify.setText(q1wrong);
paintingQ1Verify.setTextColor(getResources().getColor(R.color.wrong));
}
}
/**
* This method sets and display text if answer for question 2 is correct or wrong.
*/
public void displayQ2Check() {
if (q2check.equals(getString(R.string.correct))){
paintingQ2Verify.setText(q2check);
paintingQ2Verify.setTextColor(getResources().getColor(R.color.correct));
}
else if (q2check.equals(getString(R.string.wrong))) {
String q2wrong = q2check;
q2wrong += "\n" + getString(R.string.correct_answer);
q2wrong += " " + getString(R.string.paintingQ2A1);
paintingQ2Verify.setText(q2wrong);
paintingQ2Verify.setTextColor(getResources().getColor(R.color.wrong));
}
}
/**
* This method sets and display text if answer for question 3 is correct or wrong.
*/
public void displayQ3Check() {
if (q3check.equals(getString(R.string.correct))){
paintingQ3Verify.setText(q3check);
paintingQ3Verify.setTextColor(getResources().getColor(R.color.correct));
}
else if (q3check.equals(getString(R.string.wrong))) {
String q3wrong = q3check;
q3wrong += "\n" + getString(R.string.correct_answer);
q3wrong += " " + getString(R.string.paintingQ3A3);
paintingQ3Verify.setText(q3wrong);
paintingQ3Verify.setTextColor(getResources().getColor(R.color.wrong));
}
}
/**
* This method sets and display text if answer for question 4 is correct or wrong.
*/
public void displayQ4Check() {
if (q4check.equals(getString(R.string.correct))){
paintingQ4Verify.setText(q4check);
paintingQ4Verify.setTextColor(getResources().getColor(R.color.correct));
}
else if (q4check.equals(getString(R.string.wrong))) {
String q4wrong = q4check;
q4wrong += "\n" + getString(R.string.correct_answer);
q4wrong += " " + getString(R.string.paintingQ4A3);
paintingQ4Verify.setText(q4wrong);
paintingQ4Verify.setTextColor(getResources().getColor(R.color.wrong));
}
}
/**
* This method sets and display text if answer for question 5 is correct or wrong.
*/
public void displayQ5Check() {
if (q5check.equals(getString(R.string.correct))){
paintingQ5Verify.setText(q5check);
paintingQ5Verify.setTextColor(getResources().getColor(R.color.correct));
}
else if (q5check.equals(getString(R.string.wrong))) {
String q5wrong = q5check;
q5wrong += "\n" + getString(R.string.correct_answer);
q5wrong += " " + getString(R.string.paintingQ5A3);
paintingQ5Verify.setText(q5wrong);
paintingQ5Verify.setTextColor(getResources().getColor(R.color.wrong));
}
}
/**
* This method sets and display text if answer for question 6 is correct or wrong.
*/
public void displayQ6Check() {
if (q6check.equals(getString(R.string.correct))){
paintingQ6Verify.setText(q5check);
paintingQ6Verify.setTextColor(getResources().getColor(R.color.correct));
}
else if (q6check.equals(getString(R.string.wrong))) {
String q6wrong = q6check;
q6wrong += "\n" + getString(R.string.correct_answer);
q6wrong += " " + getString(R.string.paintingQ6A1);
q6wrong += " " + getString(R.string.paintingQ6A2);
paintingQ6Verify.setText(q6wrong);
paintingQ6Verify.setTextColor(getResources().getColor(R.color.wrong));
}
}
/**
* This method sets and display text if answer for question 7 is correct or wrong.
*/
public void displayQ7Check() {
if (q7check.equals(getString(R.string.correct))){
paintingQ7Verify.setText(q7check);
paintingQ7Verify.setTextColor(getResources().getColor(R.color.correct));
}
else if (q7check.equals(getString(R.string.wrong))) {
String q7wrong = q7check;
q7wrong += "\n" + getString(R.string.correct_answer);
q7wrong += " " + getString(R.string.paintingQ7A1);
paintingQ7Verify.setText(q7wrong);
paintingQ7Verify.setTextColor(getResources().getColor(R.color.wrong));
}
}
/**
* This method sets and display text if answer for question 8 is correct or wrong.
*/
public void displayQ8Check() {
if (q8check.equals(getString(R.string.correct))){
paintingQ8Verify.setText(q8check);
paintingQ8Verify.setTextColor(getResources().getColor(R.color.correct));
}
else if (q8check.equals(getString(R.string.wrong))) {
String q8wrong = q8check;
q8wrong += "\n" + getString(R.string.correct_answer);
q8wrong += " " + getString(R.string.paintingQ8A1);
paintingQ8Verify.setText(q8wrong);
paintingQ8Verify.setTextColor(getResources().getColor(R.color.wrong));
}
}
/**
* This method sets and display text if answer for question 9 is correct or wrong.
*/
public void displayQ9Check() {
if (q9check.equals(getString(R.string.correct))){
paintingQ9Verify.setText(q9check);
paintingQ9Verify.setTextColor(getResources().getColor(R.color.correct));
}
else if (q9check.equals(getString(R.string.wrong))) {
String q9wrong = q9check;
q9wrong += "\n" + getString(R.string.correct_answer);
q9wrong += " " + getString(R.string.paintingQ9A3);
paintingQ9Verify.setText(q9wrong);
paintingQ9Verify.setTextColor(getResources().getColor(R.color.wrong));
}
}
/**
* This method sets and display text if answer for question 10 is correct or wrong.
*/
public void displayQ10Check() {
if (q10check.equals(getString(R.string.correct))){
paintingQ10Verify.setText(q10check);
paintingQ10Verify.setTextColor(getResources().getColor(R.color.correct));
}
else if (q10check.equals(getString(R.string.wrong))) {
String q10wrong = q10check;
q10wrong += "\n" + getString(R.string.correct_answer);
q10wrong += " " + getString(R.string.paintingQ10A);
paintingQ10Verify.setText(q10wrong);
paintingQ10Verify.setTextColor(getResources().getColor(R.color.wrong));
}
}
}
|
package br.com.lucro.server.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
*
* @author taylor
*
*/
@Entity
@Table(name="acquirer")
public class Acquirer {
public static final int CIELO = 1;
public static final int REDE_CARD = 2;
@Id
@SequenceGenerator(name="ACQUIRER_ID_GENERATOR", sequenceName="ACQUIRER_ID_SEQ", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ACQUIRER_ID_GENERATOR")
private Integer id;
@Column
private String name;
public Acquirer() {}
public Acquirer(Integer id) {this.id = id;}
public static String getAcquirer(int id){
switch(id){
case CIELO: return "CIELO";
case REDE_CARD: return "REDE CARD";
default: return "";
}
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
|
package com.cloudinte.modules.xingzhengguanli.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.cloudinte.modules.xingzhengguanli.entity.EducationProjectExpenditureDetails;
import com.cloudinte.modules.xingzhengguanli.dao.EducationProjectExpenditureDetailsDao;
/**
* 项目支出明细Service
* @author dcl
* @version 2019-12-13
*/
@Service
@Transactional(readOnly = true)
public class EducationProjectExpenditureDetailsService extends CrudService<EducationProjectExpenditureDetailsDao, EducationProjectExpenditureDetails> {
public Page<EducationProjectExpenditureDetails> findPage(Page<EducationProjectExpenditureDetails> page, EducationProjectExpenditureDetails educationProjectExpenditureDetails) {
page.setCount(dao.findCount(educationProjectExpenditureDetails));
return super.findPage(page, educationProjectExpenditureDetails);
}
@Transactional(readOnly = false)
public void disable(EducationProjectExpenditureDetails educationProjectExpenditureDetails) {
dao.disable(educationProjectExpenditureDetails);
}
/*
@Transactional(readOnly = false)
public void deleteByIds(String[] ids) {
if (ids == null || ids.length < 1) {
return;
}
dao.deleteByIds(ids);
}
*/
@Transactional(readOnly = false)
public void deleteByIds(EducationProjectExpenditureDetails educationProjectExpenditureDetails) {
if (educationProjectExpenditureDetails == null || educationProjectExpenditureDetails.getIds() == null || educationProjectExpenditureDetails.getIds().length < 1) {
return;
}
dao.deleteByIds(educationProjectExpenditureDetails);
}
@Transactional(readOnly = false)
public void batchInsert(List<EducationProjectExpenditureDetails> objlist) {
dao.batchInsert(objlist);
}
@Transactional(readOnly = false)
public void batchUpdate(List<EducationProjectExpenditureDetails> objlist) {
dao.batchUpdate(objlist);
}
@Transactional(readOnly = false)
public void batchInsertUpdate(List<EducationProjectExpenditureDetails> objlist) {
dao.batchInsertUpdate(objlist);
}
}
|
package leetCode.copy.List;
import leetCode.copy.common.ListNode;
/**
* https://leetcode-cn.com/problems/reverse-linked-list/
* https://github.com/azl397985856/leetcode/blob/master/problems/206.reverse-linked-list.md
*/
public class no206_reverse_linked_list {
// 方法1 递归
public ListNode reverseList(ListNode head) {
if (head == null) return head;
return reverseListDeep(null, head);
}
public ListNode reverseListDeep(ListNode pre, ListNode head) {
if (head == null) return pre;
ListNode next = head.next;
head.next = pre;
if (next == null)
return head;
return reverseListDeep(head, next);
}
// 方法2 迭代
public ListNode reverseList1(ListNode head) {
ListNode pre = null;
if (head == null || head.next == null)
return head;
ListNode curr = head;
while (curr != null) {
ListNode temp = curr.next;
curr.next = pre;
pre = curr;
curr = temp;
}
return pre;
}
}
|
package com.xixiwan.platform.annotation;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Operation {
String describe() default "";
}
|
package assignment5;
import java.util.*;
public class test {
public static void main (String[] args) {
Assignment5 obj= new Assignment5 ();
Scanner input = new Scanner(System.in);
String decision = " ";
do {
System.out.println("Select an operation to perform");
String choice = input.next();
switch(choice){
case "table": {
System.out.println("Enter number to find the table");
int n = input.nextInt();
obj.printTable (n);
break;
}
case "factorial" :
System.out.println("Enter number to find the factorial");
int n = input.nextInt();
obj.Factorial(n);
break;
case "prime" :
System.out.println("Enter number to find the factorial");
n = input.nextInt();
Object ob;
break;
case "reverse" :
System.out.println("Enter number to reverse");
n= input.nextInt();
obj.findReverse(n);
break;
case "Addition" :
System.out.println("Enter digit to provide sum of each provided number ");
n= input.nextInt();
obj.Addition(n);
break;
default :
System.out.println("wrong choice!");
}
System.out.println("Do you want to Continue?");
decision = input.next();
}while (decision.equals ("Yes"));
System.out.println("Okay.Thank you");
}
}
|
package registraclinic.anamnese;
import registraclinic.atendimento.*;
import javax.swing.JOptionPane;
import registraclinic.atendimento.Atendimento;
import registraclinic.util.GenericDAO;
/**
*
* @author root
*/
public class AnamneseDAO extends GenericDAO<Anamnese> {
public AnamneseDAO() {
super(Anamnese.class);
}
public boolean salvar(Anamnese anamnese) {
Object[] options = {"Sim", "Não"};
if (anamnese.getIdAnamnese() == 0) {
if (adicionar(anamnese)) {
JOptionPane.showMessageDialog(null, "Anamnese cadastrada com sucesso!");
return true;
}
} else if (JOptionPane.showOptionDialog(null, "Deseja mesmo realizar essa edição"
+ "?", "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]) == JOptionPane.YES_OPTION) {
if (atualizar(anamnese)) {
JOptionPane.showMessageDialog(null, "Anamnese editada com sucesso!");
return true;
}
} else {
JOptionPane.showMessageDialog(null, "A edição foi cancelada!");
}
return false;
}
public boolean excluir(Anamnese anamnese) {
Object[] options = {"Sim", "Não"};
if (anamnese.getIdAnamnese() != 0) {
if (JOptionPane.showOptionDialog(null, "Deseja excluir a Anamnese"
+ "?", "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]) == JOptionPane.YES_OPTION) {
if (remover(anamnese)) {
JOptionPane.showMessageDialog(null, "Anamnese excluída com sucesso!");
} else {
JOptionPane.showMessageDialog(null, "Não foi possível excluir a Anamnese ",
"Erro ao Excluir", JOptionPane.ERROR_MESSAGE);
return false;
}
} else {
JOptionPane.showMessageDialog(null, "A exclusão foi cancelada!");
}
}
return true;
}
}
|
package com.kplex.util;
import java.util.List;
import java.util.stream.IntStream;
import static com.kplex.config.Constants.BOUNDARY_MAX;
import static com.kplex.config.Constants.BOUNDARY_MIN;
public class Utils {
public static double boxed(double original) {
return boxed(original, BOUNDARY_MIN, BOUNDARY_MAX);
}
public static double boxed(double original, double min, double max) {
return Math.min(Math.max(original, min), max);
}
public static double euclideanDistance(List<Double> first, List<Double> second) {
if (first.size() != second.size()) {
throw new RuntimeException();
}
return Math.sqrt(
IntStream.range(0, first.size())
.mapToDouble(value -> Math.pow(first.get(value) - second.get(value), 2))
.sum()
);
}
}
|
package by.academy.homework.homework5;
import java.util.HashMap;
import java.util.Map;
public class Task5 {
public static void main(String[] args) {
String text = "Три котенка - черный, серый и белый - увидели мышь и бросились за ней! Мышь прыгнула банку с мукой. Котята - за ней! "
+ "Мышь убежала из банки вылезли три белых котенка. Три белых котенка увидели на дворе лягушку и бросились за ней! "
+ "Лягушка прыгнула в старую самоварную трубу. Котята - за ней! Лягушка ускакала, а из трубы вылезли три черных котенка. "
+ "Три черных котенка увидели в пруду рыбу и бросились за ней! Рыба уплыла, а из воды вынырнули три мокрых котенка. Три мокрых котенка пошли домой. "
+ "По дороге они обсохли и стали как были: черный, серый и белый.";
char[] textInChar = text.replaceAll("[^A-Za-zА-Яа-я]", "").toCharArray();
Map<Character, Integer> hashMap = new HashMap<Character, Integer>();
for (Character symbol : textInChar) {
if (!hashMap.containsKey(symbol)) {
hashMap.put(symbol, 0);
}
hashMap.put(symbol, hashMap.get(symbol) + 1);
}
for (Character symbol : hashMap.keySet()) {
System.out.println("Символ " + symbol + " - " + hashMap.get(symbol));
}
}
}
|
package com.teste.southsystem.person.rabbitmq.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Value("${config.rabbit.account.queue}")
public String accountQueue;
@Value("${config.rabbit.account.exchange}")
public String accountExchange;
@Bean
public Queue pushQueue() { return QueueBuilder.durable(accountQueue).build(); }
@Bean
public DirectExchange exchange() { return ExchangeBuilder.directExchange(accountExchange).build(); }
@Bean
public Binding binding(){
return BindingBuilder.bind(this.pushQueue()).to(this.exchange()).with(this.accountQueue);
}
}
|
package net.kkolyan.elements.engine.utils;
/**
* @author nplekhanov
*/
public class ResourceNameDemo {
public static void main(String[] args) {
String regex = ".*\\.([0-9]+)x([0-9]+)\\.[A-z0-9]+";
String regex2 = ".*\\.([0-9]+)x([0-9]+)\\.o([0-9]+)x([0-9]+).[A-z0-9]+";
System.out.println(RegexHelper.find("tower.64x64.o24x32.png", regex));
System.out.println(RegexHelper.find("tower_fire.96x64.o24x32.png", regex2));
System.out.println("tower.64x64.o24x32.png".matches(regex));
System.out.println("tower.64x64.o24x32.png".matches(regex2));
}
}
|
package com.telekomatrix.hadoop.solution.files;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ByteWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.telekomatrix.hadoop.solution.files.handlers.FilesHandlerUtils;
import com.telekomatrix.hadoop.solution.mr.CustomInputFileFormat;
import com.telekomatrix.hadoop.solution.mr.HadoopConf;
import com.telekomatrix.hadoop.solution.mr.WordCountMapper;
import com.telekomatrix.hadoop.solution.mr.WordCountReducer;
@Component
public class SmallFileHandler extends Configured {
private HadoopConf hadoopConf;
@Autowired
public SmallFileHandler(HadoopConf hadoopConf) {
this.hadoopConf = hadoopConf;
}
public void combinedSmallFiles() throws Exception {
System.out.println("input path = "+ hadoopConf.getInput());
System.out.println("output path = "+ hadoopConf.getOutput());
// System.out.println("Config path =" + hadoopConf.getLocalHadoopConf());
Configuration conf = hadoopConf.getLocalHadoopConf();//getConf();
Job job = new Job(conf);
job.setJobName("SmallFileHandler");
// add jars in hdfs:///lib/*.jar to Hadoop's DistributedCache
// we place all our jars into HDFS's /lib/ directory
FilesHandlerUtils.addJarsToDistributedCache(job, "/lib/");
// define your custom plugin class for input format
job.setInputFormatClass(CustomInputFileFormat.class);
// define mapper's output (K,V)
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(ByteWritable.class);
// define map() and reduce() functions
job.setMapperClass(WordCountMapper.class);
job.setReducerClass(WordCountReducer.class);
//job.setNumReduceTasks(13);
// define I/O
Path inputPath = new Path(hadoopConf.getInput());
Path outputPath = new Path(hadoopConf.getOutput());
FileInputFormat.addInputPath(job, inputPath);
FileOutputFormat.setOutputPath(job, outputPath);
// submit job and wait for its completion
job.submit();
job.waitForCompletion(true);
}
}
|
package com.jgw.supercodeplatform.project.zaoyangpeach.schedule;
import com.jgw.supercodeplatform.trace.dao.mapper1.storedprocedure.DataSyncMapper;
import com.jgw.supercodeplatform.trace.service.tracefun.TraceBatchRelationEsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Configuration
//打开quartz定时器总开关
@EnableScheduling
public class DataSyncSchedule {
private static Logger logger= LoggerFactory.getLogger(DataSyncSchedule.class);
@Autowired
private DataSyncMapper dataSyncMapper;
@Scheduled(cron = "0 0 18 * * ?")
public void myTest1() {
logger.debug("开始同步:");
Map<String,String> params=new HashMap<String,String>();
params.put("startdate","2019-04-20");
//dataSyncMapper.execute(params);
logger.debug("同步完成");
}
}
|
package com.gaby.mybatis.base.service.impl;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gaby.mybatis.base.entity.IEntity;
import com.gaby.mybatis.base.mapper.SqlDao;
import com.gaby.mybatis.base.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
/**
*@discrption:service的顶层实现
*@user:Gaby
*@createTime:2019-03-18 23:32
*/
public class BaseServiceImpl<M extends BaseMapper<T>,T extends IEntity> extends ServiceImpl<M,T> implements BaseService<T> {
@Autowired(required = false)
private SqlDao sqlDao;
@Override
public boolean insertVal(T t) {
int result =this.baseMapper.insert(t);
t.pkVal(sqlDao.selectLastId());
return retBool(result);
}
}
|
package com.company;
/**
*
*/
public class Player {
private int points;
protected Logger logger;
private Orangutan myOran;
public Player()
{
logger=new Logger();
}
public int getPoints() {
logger.depthP();
logger.writeMessage(this.toString()+".getPoints()");
logger.depthM();
return points;
}
public void setPoints(int points) {
logger.depthP();
logger.writeMessage(this.toString()+".setPoints("+points+")");
this.points = points;
logger.depthM();
}
public Orangutan getMyOran() {
logger.depthP();
logger.writeMessage(this.toString()+".getMyOran()");
logger.depthM();
return myOran;
}
public void setMyOran(Orangutan myOran) {
logger.depthP();
logger.writeMessage(this.toString()+".setMyOran()");
logger.depthM();
this.myOran = myOran;
}
public void givePoints(int i) {
logger.depthP();
logger.writeMessage(this.toString()+".givePoints("+i+")");
points += i;
logger.depthM();
}//Pontok hozzáadása
}
|
package org.redi.school;
/**
* Created by redi on 5/18/17.
*/
public class Office {
}
|
package com.openfarmanager.android.dialogs;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import com.openfarmanager.android.App;
import com.openfarmanager.android.R;
import com.openfarmanager.android.controllers.FileSystemController;
import com.openfarmanager.android.model.exeptions.InAppAuthException;
import com.openfarmanager.android.utils.Extensions;
/**
* @author Vlad Namashko
*/
public class SftpAuthDialog extends FtpAuthDialog {
public SftpAuthDialog(Context context, Handler handler) {
super(context, handler);
}
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialogView = View.inflate(App.sInstance.getApplicationContext(), R.layout.dialog_sftp_authentication, null);
mServer = (EditText) mDialogView.findViewById(R.id.ftp_server);
mPort = (EditText) mDialogView.findViewById(R.id.ftp_port);
mUserName = (EditText) mDialogView.findViewById(R.id.ftp_username);
mPassword = (EditText) mDialogView.findViewById(R.id.ftp_password);
mError = (TextView) mDialogView.findViewById(R.id.error);
mDialogView.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
mDialogView.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearError();
if (!validate()) {
return;
}
connect();
}
});
setContentView(mDialogView);
}
@Override
protected Runnable getConnectRunnable() {
return mConnectRunnable;
}
Runnable mConnectRunnable = new Runnable() {
@Override
public void run() {
try {
App.sInstance.getSftpApi().connectAndSave(mServer.getText().toString(), Extensions.tryParse(mPort.getText().toString(), 21),
mUserName.getText().toString(), mPassword.getText().toString(), false, null);
} catch (InAppAuthException e) {
setErrorMessage(e.getErrorMessage());
setLoading(false);
return;
}
dismiss();
mHandler.sendEmptyMessage(FileSystemController.SFTP_CONNECTED);
}
};
}
|
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public abstract class Server {
protected final int port;
protected volatile AtomicLong timeForTask = new AtomicLong();
protected volatile AtomicLong timeForClient = new AtomicLong();
protected volatile AtomicInteger countOfTask = new AtomicInteger();
protected Server(int port) {
this.port = port;
}
public abstract void start() throws IOException;
public abstract void stop();
public long getTimeForTask() {
return timeForTask.get()/countOfTask.get();
}
public long getTimeForClient() {
return timeForClient.get()/countOfTask.get();
}
protected ArrayProto.Array sort(ArrayProto.Array array) {
ArrayProto.Array res;
List<Integer> list = array.getDataList();
System.err.println("Sort " + list.size());
ArrayList<Integer> arrayToSort = new ArrayList<>();
for (Integer aList : list) {
arrayToSort.add(aList);
}
for (int i = 0; i < arrayToSort.size(); ++i) {
for (int j = 1; j < arrayToSort.size(); ++j) {
if (arrayToSort.get(j - 1) > arrayToSort.get(j)) {
int k = arrayToSort.get(j - 1);
arrayToSort.set(j - 1, arrayToSort.get(j));
arrayToSort.set(j, k);
}
}
}
res = ArrayProto.Array.newBuilder().addAllData(arrayToSort).build();
return res;
}
}
|
package gov.nih.mipav.model.dicomcomm;
/**
* DICOMPDUTypeBase abstract base class that is extended by DICOMPDUType and DICOMPDUItemType.
*
* <hr>
*
* This DICOM communication package was originally based on the Java Dicom Package, whose license is below:
*
* <pre>
* Java Dicom Package (com.zmed.dicom)
*
* Copyright (c) 1996-1997 Z Medical Imaging Systems, Inc.
*
* This software is provided, as is, for non-commercial educational
* purposes only. Use or incorporation of this software or derivative
* works in commercial applications requires written consent from
* Z Medical Imaging Systems, Inc.
*
* Z MEDICAL IMAGING SYSTEMS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT
* THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR CONFORMANCE TO ANY
* SPECIFICATION OR STANDARD. Z MEDICAL IMAGING SYSTEMS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING OR
* MODIFYING THIS SOFTWARE OR ITS DERIVATIVES.
*
* =============================================================================
*
* This software package is implemented similarly to the UC Davis public
* domain C++ DICOM implementation which contains the following copyright
* notice:
*
* Copyright (C) 1995, University of California, Davis
*
* THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
* OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
* PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
* USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
* SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
* THE SOFTWARE IS WITH THE USER.
*
* Copyright of the software and supporting documentation is
* owned by the University of California, and free access
* is hereby granted as a license to use this software, copy this
* software and prepare derivative works based upon this software.
* However, any distribution of this software source code or
* supporting documentation or derivative works (source code and
* supporting documentation) must include this copyright notice.
*
* The UC Davis C++ source code is publicly available from the following
* anonymous ftp site:
*
* ftp://imrad.ucdmc.ucdavis.edu/pub/dicom/UCDMC/
* </pre>
*/
public abstract class DICOM_PDUTypeBase {
// ~ Static fields/initializers
// -------------------------------------------------------------------------------------
/** DOCUMENT ME! */
public static final byte RESERVED = 0;
/** DOCUMENT ME! */
public static final byte PDUTYPE_UNKNOWN = 0x00;
/** DOCUMENT ME! */
public static final byte PDUTYPE_AAssociateRQ = 0x01;
/** DOCUMENT ME! */
public static final byte PDUTYPE_AAssociateAC = 0x02;
/** DOCUMENT ME! */
public static final byte PDUTYPE_AAssociateRJ = 0x03;
/** DOCUMENT ME! */
public static final byte PDUTYPE_PDataTF = 0x04;
/** DOCUMENT ME! */
public static final byte PDUTYPE_AReleaseRQ = 0x05;
/** DOCUMENT ME! */
public static final byte PDUTYPE_AReleaseRSP = 0x06;
/** DOCUMENT ME! */
public static final byte PDUTYPE_AAbortRQ = 0x07;
/** DOCUMENT ME! */
public static final byte PDUTYPE_ApplicationContext = 0x10;
/** DOCUMENT ME! */
public static final byte PDUTYPE_PresentationContext = 0x20;
/** DOCUMENT ME! */
public static final byte PDUTYPE_PresentationContextAccept = 0x21;
/** DOCUMENT ME! */
public static final byte PDUTYPE_AbstractSyntax = 0x30;
/** DOCUMENT ME! */
public static final byte PDUTYPE_TransferSyntax = 0x40;
/** DOCUMENT ME! */
public static final byte PDUTYPE_UserInformation = 0x50;
/** DOCUMENT ME! */
public static final byte PDUTYPE_MaximumSubLength = 0x51;
/** DOCUMENT ME! */
public static final byte PDUTYPE_ImplementationClass = 0x52;
/** DOCUMENT ME! */
public static final byte PDUTYPE_AsyncOpWindowSubItem = 0x53;
/** DOCUMENT ME! */
public static final byte PDUTYPE_SCPSCURoleSelect = 0x54;
/** DOCUMENT ME! */
public static final byte PDUTYPE_ImplementationVersion = 0x55;
// ~ Instance fields
// ------------------------------------------------------------------------------------------------
/** DOCUMENT ME! */
protected byte itemType = DICOM_PDUTypeBase.PDUTYPE_UNKNOWN;
/** DOCUMENT ME! */
protected int length = 0;
/** DOCUMENT ME! */
protected byte reserved1 = DICOM_PDUTypeBase.RESERVED;
/** DOCUMENT ME! */
protected byte reserved2 = DICOM_PDUTypeBase.RESERVED;
/** DOCUMENT ME! */
protected byte reserved3 = DICOM_PDUTypeBase.RESERVED;
/** DOCUMENT ME! */
protected byte reserved4 = DICOM_PDUTypeBase.RESERVED;
/** DOCUMENT ME! */
protected String UID = "";
// ~ Methods
// --------------------------------------------------------------------------------------------------------
/**
* These methods must be implemented by each class that extends this class.
*
* @return DOCUMENT ME!
*/
public abstract int calcSize();
/**
* DOCUMENT ME!
*
* @param connection DOCUMENT ME!
*
* @throws DICOM_Exception DOCUMENT ME!
*/
public abstract void readBody(DICOM_Comms connection) throws DICOM_Exception;
/**
* DOCUMENT ME!
*
* @param connection DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws DICOM_Exception DOCUMENT ME!
*/
public abstract byte readHeader(DICOM_Comms connection) throws DICOM_Exception;
/**
* DOCUMENT ME!
*
* @param connection DOCUMENT ME!
*
* @throws DICOM_Exception DOCUMENT ME!
*/
public abstract void writeBody(DICOM_Comms connection) throws DICOM_Exception;
/**
* DOCUMENT ME!
*
* @param connection DOCUMENT ME!
*
* @throws DICOM_Exception DOCUMENT ME!
*/
public abstract void writeHeader(DICOM_Comms connection) throws DICOM_Exception;
/**
* Converts item type to a readable string.
*
* @param itemType type defined above
*
* @return readable item type string
*/
public static String convertItemTypeToString(final byte itemType) {
switch (itemType) {
case PDUTYPE_UNKNOWN:
return (new String("Unknown"));
case PDUTYPE_AAssociateRQ:
return (new String("AAssociateRQ"));
case PDUTYPE_AAssociateAC:
return (new String("AAssociateAC"));
case PDUTYPE_AAssociateRJ:
return (new String("AAssociateRJ"));
case PDUTYPE_PDataTF:
return (new String("PDataTF"));
case PDUTYPE_AReleaseRQ:
return (new String("AReleaseRQ"));
case PDUTYPE_AReleaseRSP:
return (new String("AReleaseRSP"));
case PDUTYPE_AAbortRQ:
return (new String("AAbortRQ"));
case PDUTYPE_ApplicationContext:
return (new String("ApplicationContext"));
case PDUTYPE_PresentationContext:
return (new String("PresentationContext"));
case PDUTYPE_PresentationContextAccept:
return (new String("PresentationContextAccept"));
case PDUTYPE_AbstractSyntax:
return (new String("AbstractSyntax"));
case PDUTYPE_TransferSyntax:
return (new String("TransferSyntax"));
case PDUTYPE_UserInformation:
return (new String("UserInformation"));
case PDUTYPE_MaximumSubLength:
return (new String("MaximumSubLength"));
case PDUTYPE_ImplementationClass:
return (new String("ImplementationClass"));
case PDUTYPE_SCPSCURoleSelect:
return (new String("SCPSCURoleSelect"));
case PDUTYPE_ImplementationVersion:
return (new String("ImplementationVersion"));
default:
return (new String("Unknown"));
}
}
/**
* Gets the UID for a simple PDU type.
*
* @return the UID
*/
public String getUID() {
return (UID);
}
/**
* Calculates the PDU item's body size (not including the header).
*
* @return the UID's length
*/
public int length() {
return (UID.length());
}
/**
* Reads the header and body of the PDU message from the connection.
*
* @param connection the connection where the data is read in
*
* @throws DICOM_Exception DOCUMENT ME!
*/
public void read(final DICOM_Comms connection) throws DICOM_Exception {
readHeader(connection); // is defined in the class the extends this class
readBody(connection); // is defined in the class the extends this class
}
/**
* Sets the UID for a simple PDU type.
*
* @param UID DOCUMENT ME!
*/
public void setUID(final String UID) {
this.UID = UID;
}
/**
* Writes the header and body of the PDU messages.
*
* @param connection the connection where the data sent out
*
* @throws DICOM_Exception DOCUMENT ME!
*/
public void write(final DICOM_Comms connection) throws DICOM_Exception {
writeHeader(connection); // is defined in the class the extends this class
writeBody(connection); // is defined in the class the extends this class
// connection.flush();
}
}
|
package com.hcl.cms.data.impl;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.constants.ReservationType;
import com.filenet.api.core.Connection;
import com.filenet.api.core.ContentTransfer;
import com.hcl.cms.data.constants.Constants;
import com.hcl.cms.data.exceptions.CmsException;
import com.hcl.cms.data.params.ExportContentParams;
import com.hcl.cms.data.params.CmsSessionObjectParams;
import com.hcl.cms.data.params.ObjectIdentity;
import com.hcl.cms.data.params.OperationObjectDetail;
import com.hcl.cms.data.params.OperationStatus;
import com.hcl.cms.data.session.CEConnectionManager;
import com.filenet.api.core.Document;
import com.filenet.api.core.Factory;
import com.filenet.api.core.Folder;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.util.Id;
@SuppressWarnings("unused")
class CmsExportContentImpl extends CmsImplBase {
List<OperationObjectDetail> operationObjectList = new ArrayList<>();
ObjectStore objectStore = null;
boolean isCheckout = false;
public CmsExportContentImpl(Connection connection) {
super(connection);
}
public OperationStatus export(ExportContentParams params) {
OperationStatus operationStatus = new OperationStatus();
boolean status = false;
try {
Document document = null;
if (Constants.CHECKOUT.equals(params.getJobType())) {
isCheckout = true;
}
CEConnectionManager conManager = new CEConnectionManager(getSession());
CmsSessionObjectParams objectStoreParams = conManager.getObjectStore(params.getRepository());
objectStore = objectStoreParams.getStore();
for (ObjectIdentity identity : params.getObjectList()) {
if (null == identity) {
throw new IllegalArgumentException("DocumentIdentity is not valid - " + identity);
}
boolean isFolder = fetchFolder(identity.getObjectPath());
boolean isDocument = fetchDocument(identity.getObjectPath());
if (isFolder) {
status = exportFolder(identity, params.getDestDir() + "/");
}
if (isDocument) {
status = exportDocument(identity, params.getDestDir() + "/");
}
if (!isFolder && !isDocument) {
status = false;
}
}
} catch (Throwable ex) {
ex.printStackTrace();
OperationObjectDetail errorDetail = new OperationObjectDetail();
errorDetail.setError(true);
errorDetail.setMessage(ex.getMessage());
operationObjectList.add(errorDetail);
} finally {
operationStatus.setOperationObjectDetails(operationObjectList);
operationStatus.setStatus(status);
}
return operationStatus;
}
private boolean exportFolder(ObjectIdentity identity, String destDir) throws Exception {
boolean status = true;
Folder parent = null;
OperationObjectDetail objectDetail = new OperationObjectDetail();
objectDetail.setSourcePath(identity.getObjectPath());
objectDetail.setTargetPath(destDir);
objectDetail.setCreationDate(new Date());
try{
if (createFolderPath(destDir)) {
if (isNotNull(identity.getGuid())) {
parent = Factory.Folder.fetchInstance(objectStore, new Id(identity.getGuid()), null);
} else if (isNotNull(identity.getObjectPath())) {
parent = Factory.Folder.fetchInstance(objectStore, identity.getObjectPath(), null);
}
objectDetail.setObjectName(parent.get_Name());
Iterator<?> docIter = parent.get_ContainedDocuments().iterator();
while (docIter.hasNext()) {
final Document doc = (Document) docIter.next();
ObjectIdentity objectIdentity = ObjectIdentity.newObject();
objectIdentity.setGuid(doc.get_Id().toString());
exportDocument(objectIdentity, destDir);
}
Iterator<?> folderIter = parent.get_SubFolders().iterator();
while (folderIter.hasNext()) {
final Folder folder = (Folder) folderIter.next();
destDir = destDir + folder.get_Name() + "/";
ObjectIdentity objectIdentity = ObjectIdentity.newObject();
objectIdentity.setGuid(folder.get_Id().toString());
objectIdentity.setObjectPath(folder.get_PathName());
exportFolder(objectIdentity, destDir);
}
} else {
status = false;
throw new Exception("Unable to create/access directory " + destDir);
}
} catch (Throwable e) {
status = false;
objectDetail.setError(true);
objectDetail.setMessage(e.getMessage());
} finally {
operationObjectList.add(objectDetail);
}
return status;
}
private boolean exportDocument(ObjectIdentity identity, String destDir) throws Exception {
boolean status = true;
Document document = null;
OperationObjectDetail objectDetail = new OperationObjectDetail();
objectDetail.setSourcePath(identity.getObjectPath());
objectDetail.setCreationDate(new Date());
try {
if (isNotNull(identity.getGuid())) {
document = Factory.Document.fetchInstance(objectStore, new Id(identity.getGuid()), null);
} else if (isNotNull(identity.getObjectPath())) {
document = Factory.Document.fetchInstance(objectStore, identity.getObjectPath(), null);
}
objectDetail.setObjectName(document.get_Name());
objectDetail.setTargetPath(destDir + document.get_Name());
if (createFolderPath(destDir)) {
File file = new File(destDir + document.get_Name());
file.createNewFile();
ContentElementList docContentList = document.get_ContentElements();
Iterator<?> iter = docContentList.iterator();
ContentTransfer ct = (ContentTransfer) iter.next();
InputStream fileStream = ct.accessContentStream();
FileOutputStream fos = new FileOutputStream(file);
byte byteArray[] = new byte[4096];
int read = 0;
while ((read = fileStream.read(byteArray)) > 0) {
fos.write(byteArray, 0, read);
}
fos.close();
if (isCheckout && !document.get_IsReserved()) {
document.checkout(ReservationType.EXCLUSIVE, null, document.getClassName(),
document.getProperties());
document.save(RefreshMode.NO_REFRESH);
}
}
} catch (Throwable e) {
status = false;
objectDetail.setError(true);
objectDetail.setMessage(e.getMessage());
} finally {
operationObjectList.add(objectDetail);
}
return status;
}
/* private boolean doExport(ExportContentParams params, ArrayList<Document> objects) {
boolean status = true;
try {
if (createFolderPath(params.getDestDir())) {
for (Document doc : objects) {
File file = new File(params.getDestDir() + doc.get_Name());
file.createNewFile();
ContentElementList docContentList = doc.get_ContentElements();
Iterator<?> iter = docContentList.iterator();
ContentTransfer ct = (ContentTransfer) iter.next();
InputStream fileStream = ct.accessContentStream();
FileOutputStream fos = new FileOutputStream(file);
byte byteArray[] = new byte[4096];
int read = 0;
while ((read = fileStream.read(byteArray)) > 0) {
fos.write(byteArray, 0, read);
}
fos.close();
}
}
} catch (Exception e) {
status = false;
}
return status;
}*/
private boolean createFolderPath(String dirPath) {
boolean dirCreated = false;
File file = new File(dirPath);
if (null != file) {
dirCreated = file.exists() ? true : file.mkdirs();
}
return dirCreated;
}
public boolean fetchFolder(String path) throws Exception {
try {
Factory.Folder.fetchInstance(objectStore, path, null);
return true;
} catch (Exception e) {
return false;
}
}
public boolean fetchDocument(String path) throws Exception {
try {
Factory.Document.fetchInstance(objectStore, path, null);
return true;
} catch (Exception e) {
return false;
}
}
}
|
package bd.edu.httpdaffodilvarsity.jobtrack.model;
/**
* Created by mahmud on 12/15/16.
*/
//import javax.persistence.Embeddable;
//import javax.persistence.Entity;
//import javax.persistence.Id;
//import javax.persistence.Table;
//@Entity
//@Embeddable
//@Table(name = "hrm_role")
public class Role {
//@Id
private int role_id;
private String role;
public Role() {
super();
}
public Role(int role_id, String role) {
this.role_id = role_id;
this.role = role;
}
public int getRole_id() {
return role_id;
}
public void setRole_id(int role_id) {
this.role_id = role_id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
|
package com.gaoshin.onsaleflyer.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import common.db.entity.DbEntity;
@Entity
@Table
@XmlRootElement
public class Asset extends DbEntity {
@Column(nullable = false, length = 64)
private String name;
@Column(nullable=true, length=64) private String type;
@Column(nullable = false, length = 128)
private String userId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
package com.codingapi.djl.example;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DjlExampleApplicationTests {
@Test
void contextLoads() {
}
}
|
package fr.sfvl.testunit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class SetterRecorderTest {
public static class MonObjet {
public MonObjet(String nom, int age) {
super();
this.nom = nom;
this.age = age;
}
public MonObjet() {
// TODO Auto-generated constructor stub
}
private String nom;
private int age;
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@Test
public void testGetterSetterSetValeur() {
MonObjet monObjet = new MonObjet();
SetterRecorder<MonObjet> assertGetSet = new SetterRecorder<MonObjet>(monObjet);
assertGetSet.set("ma valeur").getNom();
assertGetSet.set(30).getAge();
assertEquals("ma valeur", monObjet.getNom());
assertEquals(30, monObjet.getAge());
}
@Test
public void testGetterSetterObjetDifferent() {
MonObjet monObjet = new MonObjet();
SetterRecorder<MonObjet> assertGetSet = new SetterRecorder<MonObjet>(monObjet);
assertGetSet.set("ma valeur").getNom();
assertGetSet.set(30).getAge();
assertGetSet.assertEquals(new MonObjet("ma valeur", 30));
// Pas d'exception, les objets sont égaux
boolean exceptionLeve = false;
try {
assertGetSet.assertEquals(new MonObjet("autre valeur", 30));
} catch (Throwable t) {
exceptionLeve = true;
}
assertTrue("Une exception aurait du être levé", exceptionLeve);
try {
assertGetSet.assertEquals(new MonObjet("ma valeur", 40));
} catch (Throwable t) {
exceptionLeve = true;
}
assertTrue("Une exception aurait du être levé", exceptionLeve);
}
}
|
package collections.demo;
public class LinkedhashmapBook {
int id;
int quantity;
String author,publisher;
public LinkedhashmapBook(int id,String author,String publisher,int quantity) {
this.id=id;
this.author=author;
this.publisher=publisher;
this.quantity=quantity;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.