blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
75f66247736c73bbb8e446091208d2651bada49a | Java | ZulmaCoronel/ProyectoUnidad2_GestorObra_ZulmaCoronel | /app/src/main/java/mx/edu/ittepic/proyectounidad2_zulmacoronel/ConexionSQLiteHelper.java | UTF-8 | 6,586 | 2.34375 | 2 | [] | no_license | package mx.edu.ittepic.proyectounidad2_zulmacoronel;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Zulma on 15/03/2018.
*/
public class ConexionSQLiteHelper extends SQLiteOpenHelper {
public SQLiteDatabase myDB;
public ConexionSQLiteHelper(Context context) {
super(context, "DBarquitectos", null, 1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREAR_TABLA_CLIENTE = "" +
"CREATE TABLE CLIENTE(" +
" ID_CLIENTE INTEGER PRIMARY KEY AUTOINCREMENT, " +
"NOMBRE TEXT, " +
"DOMICILIO TEXT, " +
"TELEFONO TEXT, " +
"CORREO TEXT )";
sqLiteDatabase.execSQL(CREAR_TABLA_CLIENTE);
String CREAR_TABLA_EMPLADO = "" +
"CREATE TABLE EMPLEADO (" +
" ID_EMPLEADO INTEGER PRIMARY KEY AUTOINCREMENT, " +
"NOMBRE TEXT, " +
"CEL TEXT )";
sqLiteDatabase.execSQL(CREAR_TABLA_EMPLADO);
String CREAR_TABLA_OBRA = "" +
"CREATE TABLE OBRA (" +
" ID_OBRA INTEGER PRIMARY KEY AUTOINCREMENT, " +
"DESCRIPCION TEXT, " +
"MONTO TEXT, " +
"FINALIZADA BOOLEAN, " +
"FECHA_INI DATE, " +
"FECHA_FIN DATE, " +
" ID_CLIENTE INTEGER, FOREIGN KEY(ID_CLIENTE) REFERENCES CLIENTE(ID_CLIENTE))";
sqLiteDatabase.execSQL(CREAR_TABLA_OBRA);
String CREAR_TABLA_OBRA_EMPLEADO = "" +
"CREATE TABLE OBRA_EMPLEADO (" +
" ID_OBRA_EMPLEADO INTEGER PRIMARY KEY AUTOINCREMENT, " +
"ACTIVIDAD TEXT, " +
"PAGO TEXT, " +
" ID_EMPLEADO INTEGER ,ID_OBRA INTEGER , FOREIGN KEY(ID_EMPLEADO) REFERENCES EMPLEADO(ID_EMPLEADO)," +
" FOREIGN KEY(ID_OBRA) REFERENCES OBRA(ID_OBRA))";
sqLiteDatabase.execSQL(CREAR_TABLA_OBRA_EMPLEADO);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void openDB() {
myDB = getWritableDatabase();
}
public void closeDB() {
if (myDB != null && myDB.isOpen()) {
myDB.close();
}
}
/*CRU CLIENTES*/
public Cursor getAllClientes() {
String query = "SELECT * FROM CLIENTE ORDER BY NOMBRE asc";
return myDB.rawQuery(query, null);
}
public Cursor getAllClientesID(String id) {
String query = "SELECT * FROM CLIENTE WHERE ID_CLIENTE=" + id;
return myDB.rawQuery(query, null);
}
public Cursor getAllClientesMax() {
String query = "SELECT MAX(ID_CLIENTE) as maximo FROM CLIENTE";
return myDB.rawQuery(query, null);
}
public long insertCliente(String nombre, String domicilio, String telefono, String Correo) {
ContentValues cv = new ContentValues();
cv.put("NOMBRE", nombre);
cv.put("DOMICILIO", domicilio);
cv.put("TELEFONO", telefono);
cv.put("CORREO", Correo);
return myDB.insert("CLIENTE", null, cv);
}
public long updateCliente(String id, String nombre, String domicilio, String telefono, String Correo) {
ContentValues cv = new ContentValues();
cv.put("NOMBRE", nombre);
cv.put("DOMICILIO", domicilio);
cv.put("TELEFONO", telefono);
cv.put("CORREO", Correo);
return myDB.update("CLIENTE", cv, "ID_CLIENTE=" + id, null);
}
/*CRU EMPLEADOS*/
public Cursor getAllEmpleados() {
String query = "SELECT * FROM EMPLEADO ORDER BY NOMBRE asc";
return myDB.rawQuery(query, null);
}
public Cursor getAllEmpleadosid(String id) {
String query = "SELECT * FROM EMPLEADO WHERE ID_EMPLEADO=" + id;
return myDB.rawQuery(query, null);
}
public Cursor getAllEmpleadosidObra(String id) {
String query = "SELECT * FROM EMPLEADO as EM,OBRA_EMPLEADO as OE WHERE EM.ID_EMPLEADO=OE.ID_EMPLEADO AND OE.ID_OBRA="+id;
return myDB.rawQuery(query, null);
}
public long updateEmpleado(int id, String nombree, String celular) {
ContentValues cv = new ContentValues();
cv.put("NOMBRE", nombree);
cv.put("CEL", celular);
return myDB.update("EMPLEADO", cv, "ID_EMPLEADO=" + id, null);
}
public long insertEmpleado(String nombree, String celular) {
ContentValues cv = new ContentValues();
cv.put("NOMBRE", nombree);
cv.put("CEL", celular);
return myDB.insert("EMPLEADO", null, cv);
}
public Cursor getAllObra() {
String query = "SELECT * FROM OBRA";
return myDB.rawQuery(query, null);
}
public Cursor getAllObraEmpleado() {
String query = "SELECT * FROM OBRA as O,CLIENTE as C where C.ID_CLIENTE=O.ID_CLIENTE ";
return myDB.rawQuery(query, null);
}
public Cursor getAllObraID(String id) {
String query = "SELECT * FROM OBRA where ID_OBRA="+id;
return myDB.rawQuery(query, null);
}
public long insertObra(String descripcion, String monto, int finalizada, String fecha_i, String fecha_f, int ID_cliente) {
ContentValues cv = new ContentValues();
cv.put("DESCRIPCION", descripcion);
cv.put("MONTO", monto);
cv.put("FINALIZADA", finalizada);
cv.put("FECHA_INI", fecha_i);
cv.put("FECHA_FIN", fecha_f);
cv.put("ID_CLIENTE", ID_cliente);
return myDB.insert("OBRA", null, cv);
}
public long updateObra(String descripcion, String monto, int finalizada, String fecha_i, String fecha_f, int idobra) {
ContentValues cv = new ContentValues();
cv.put("DESCRIPCION", descripcion);
cv.put("MONTO", monto);
cv.put("FINALIZADA", finalizada);
cv.put("FECHA_INI", fecha_i);
cv.put("FECHA_FIN", fecha_f);
return myDB.update("OBRA",cv,"ID_OBRA="+idobra,null);
}
/* Relacion obra---Empleado*/
public long insertarObraEmpleado(String actividad, String pago, int idempleado, int idobra) {
ContentValues cv = new ContentValues();
cv.put("ACTIVIDAD", actividad);
cv.put("PAGO", pago);
cv.put("ID_EMPLEADO", idempleado);
cv.put("ID_OBRA", idobra);
return myDB.insert("OBRA_EMPLEADO", null, cv);
}
}
| true |
423b8b2f35a548dcf0b166090627f6233bd43d18 | Java | vparihar01/bat-monitoring-android | /src/com/webonise/bat_monitoring/MainActivity.java | UTF-8 | 3,758 | 2.234375 | 2 | [] | no_license | package com.webonise.bat_monitoring;
import java.util.Iterator;
import java.util.List;
import org.apache.http.NameValuePair;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gcm.GCMRegistrar;
public class MainActivity extends Activity implements WebserviceInterface{
static final String SENDER_ID = "482695649816";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerGCMService();
initViews();
}
private void registerGCMService() {
AsyncTask<Void, Void, Void> mRegisterTask;
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
System.out.println("================"+regId);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(this, SENDER_ID);
System.out.println("================= IN IF ===================="+regId);
} else {
// Device is already registered on GCM
System.out.println("================= IN ELSE ===================="+regId);
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
System.out.println("================= IN ELSE IF ===================="+regId);
Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
System.out.println("================= IN IF ELSE ===================="+regId);
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
registerToserver();
}
}
}
private void registerToserver() {
String url ="";
WebService webService = new WebService(this);
webService.registerGCMToServer(url, true);
}
private void initViews() {
String url = "";
/*List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", username.trim()));*/
WebService webService = new WebService(this);
webService.GETStringRequest(url, this, true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResponse(String response) {
// TODO Auto-generated method stub
}
@Override
public void onError(String error) {
// TODO Auto-generated method stub
}
public static String requestGETUrl(List<NameValuePair> params, String baseUrl) {
if ( params != null && !params.isEmpty() ) {
baseUrl += "?";
Iterator<NameValuePair> iter = params.iterator();
while ( iter.hasNext() ) {
NameValuePair nvp = iter.next();
baseUrl += nvp.getName();
baseUrl += "=";
baseUrl += nvp.getValue();
if ( iter.hasNext() )
baseUrl += "&";
}
}
return baseUrl;
}
}
| true |
5f151fec70327e0e0a2295497409e4d46f1b547e | Java | ibvisuals/RoadTrip | /app/src/main/java/com/example/roadtrip/DestinationsAdapter.java | UTF-8 | 2,232 | 2.171875 | 2 | [] | no_license | package com.example.roadtrip;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class DestinationsAdapter extends RecyclerView.Adapter<DestinationsAdapter.DestinationsHolder> {
ArrayList<Destinations> mDestinations;
private SharedViewModel model;
public DestinationsAdapter(ArrayList <Destinations> destinations, SharedViewModel model) {
mDestinations = destinations;
this.model = model;
}
@NonNull
@Override
public DestinationsAdapter.DestinationsHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.destinations_item, parent, false);
return new DestinationsAdapter.DestinationsHolder(view);
}
@Override
public void onBindViewHolder(@NonNull DestinationsAdapter.DestinationsHolder holder, int position) {
Destinations destinations = mDestinations.get(position);
holder.mName.setText(destinations.getName());
holder.mItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
model.select(destinations);
Navigation.findNavController(view).navigate(R.id.action_homeFragment_to_destinationsDetailsFragment);
}
});
}
@Override
public int getItemCount() { return mDestinations.size(); }
static class DestinationsHolder extends RecyclerView.ViewHolder {
TextView mName;
ImageView mPoster;
ConstraintLayout mItem;
public DestinationsHolder(View view) {
super(view);
mName = view.findViewById(R.id.destinations_item_name);
mPoster = view.findViewById(R.id.destinations_item_image);
mItem = view.findViewById(R.id.destinations_item);
}
}
}
| true |
73e4337f18cf5abf646e1f38ce913ed17f725a17 | Java | livepvrdata-oss/livepvrdata-svc | /src/main/java/com/github/livepvrdata/common/data/req/OverrideConfirmationRequest.java | UTF-8 | 1,382 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | /*
Copyright 2016 Battams, Derek
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.github.livepvrdata.common.data.req;
public class OverrideConfirmationRequest implements Request {
private String email;
private String id;
@SuppressWarnings("unused")
private OverrideConfirmationRequest() {}
public OverrideConfirmationRequest(String email, String id) {
this.email = email;
this.id = id;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("OverrideConfirmationRequest [email=");
builder.append(email);
builder.append(", id=");
builder.append(id);
builder.append("]");
return builder.toString();
}
}
| true |
cab74c32dc7e2fd96800de2949e0fc4f3ba2dd29 | Java | DominicPrzygonski/BookBag-App-Mobile-Programming-Term-3 | /app/src/main/java/DominicPrzygonski/BookBag/Menu.java | UTF-8 | 2,812 | 2.25 | 2 | [] | no_license | package DominicPrzygonski.BookBag;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
public class Menu extends AppCompatActivity {
private Button ViewButton, AddDataButton, LogoutButton, ListButton;
//Animation Background
private ConstraintLayout base_layout;
private AnimationDrawable animDrawable;
private Animation anim;
private LinearLayout stripes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
//Creating background animation -Gradient-
base_layout = (ConstraintLayout) findViewById(R.id.base_layout1);
animDrawable = (AnimationDrawable) base_layout.getBackground();
animDrawable.setEnterFadeDuration(10);
animDrawable.setExitFadeDuration(5000);
animDrawable.start();
//-Stripes-
stripes = (LinearLayout) findViewById(R.id.stripes);
anim = (Animation) AnimationUtils.loadAnimation(this, R.anim.strip_anim);
stripes.startAnimation(anim);
//Initialising
ViewButton = (Button) findViewById(R.id.ViewButton);
AddDataButton = (Button) findViewById(R.id.AddDataButton);
LogoutButton = (Button) findViewById(R.id.LogoutButton);
ListButton = (Button) findViewById(R.id.ListButton);
//Onclick for buttons
ViewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Menu.this, ViewData.class);
startActivity(intent);
}
});
AddDataButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Menu.this, AddData.class);
startActivity(intent);
}
});
LogoutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Menu.this, Launcher.class);
startActivity(intent);
}
});
ListButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Menu.this, BookListView.class);
startActivity(intent);
}
});
}
} | true |
6c53f14aca5ff60dd6f56ecac239407fdd44e97e | Java | peclevens/bowling-scoring | /domain/src/main/java/com/clivenspetit/bowlingscoring/domain/game/AbstractScoreProcessor.java | UTF-8 | 2,023 | 3 | 3 | [] | no_license | package com.clivenspetit.bowlingscoring.domain.game;
import com.clivenspetit.bowlingscoring.domain.parser.ScoreParser;
import com.google.common.cache.Cache;
import java.util.List;
import java.util.Map;
/**
* @author Clivens Petit <clivens.petit@magicsoftbay.com>
*/
public abstract class AbstractScoreProcessor {
private final ScoreParser scoreParser;
private final Cache<Integer, Map<String, List<String>>> parsedGameCache;
private final Cache<Integer, List<Player>> playersCache;
public AbstractScoreProcessor(
ScoreParser scoreParser, Cache<Integer, Map<String, List<String>>> parsedGameCache,
Cache<Integer, List<Player>> playersCache) {
this.scoreParser = scoreParser;
this.parsedGameCache = parsedGameCache;
this.playersCache = playersCache;
}
/**
* Process and calculate player scores.
*
* @return
*/
public List<Player> process(String content) {
// Calculate a unique key for this content
Integer contentKey = content.hashCode();
// Try to retrieve parse content from cache
Map<String, List<String>> scores = parsedGameCache.getIfPresent(contentKey);
// Game content is not cached yet, parse and cache it
if (scores == null) {
scores = scoreParser.parse(content);
// Cache game content
parsedGameCache.put(contentKey, scores);
}
// Try to retrieve players from cache
List<Player> players = playersCache.getIfPresent(contentKey);
// No players found, process the game
if (players == null) {
// Calculate player score
players = this.process(scores);
// Cache players for this game
playersCache.put(contentKey, players);
}
return players;
}
/**
* Process and calculate player scores.
*
* @param playerScores
* @return
*/
protected abstract List<Player> process(final Map<String, List<String>> playerScores);
}
| true |
26bc4eca820b42358cb851571308b4982292bf25 | Java | moutainhigh/xrate-1 | /xrate-spring-cloud-demo/xrate_spring_cloud_demo_merchant/src/main/java/com/xerecter/xrate_spring_cloud_demo/merchant/controller/MerchantController.java | UTF-8 | 1,038 | 1.742188 | 2 | [] | no_license | package com.xerecter.xrate_spring_cloud_demo.merchant.controller;
import com.xerecter.xrate_spring_cloud_demo.merchant.service.IMerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author xdd
* @since 2019-11-09
*/
@RestController
@RequestMapping("/merchant")
public class MerchantController {
@Autowired
IMerchantService merchantService;
@PostMapping("/plusMerchantBalance")
public Boolean plusMerchantBalance(
@RequestParam(value = "merchantId", required = false) Long merchantId,
@RequestParam(value = "amount", required = false) Double amount
) {
return merchantService.plusMerchantBalance(merchantId, amount);
}
}
| true |
6e1882377d5d3ffcec3376ed8bfe7a2eb8559d4d | Java | stevenwuzheng/GOF23-Design-Mode | /GOF23-Design-Mode/src/xingwei/memento/Client.java | UTF-8 | 715 | 2.90625 | 3 | [] | no_license | package xingwei.memento;
public class Client {
public static void main(String[] args) {
Emp emp = new Emp();
emp.setName("wz");
emp.setSalary(10000);
System.out.println("第1次打印 emp = " + emp);
//备份下
EmpMemento memento = emp.memento();
MementoManager manager = new MementoManager();
manager.addMemento(memento);
emp.setSalary(20000);
System.out.println("第2次打印 emp = " + emp);
System.out.println("-----------恢复数据------------");
EmpMemento memento1 = manager.popMemento();
Emp emp1 = memento1.recover();
System.out.println("第3次打印 emp1 = " + emp1);
}
}
| true |
119fca3adb440fae38639e56b3d39232d90b47dc | Java | Saber0120/SpringBoot | /springboot-freemarker/src/main/java/com/saber/controller/TestController.java | UTF-8 | 462 | 1.867188 | 2 | [] | no_license | package com.saber.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
// 访问 http://localhost:8888/test
@RequestMapping("/test")
public String testFreeMarker(ModelMap modelMap) {
modelMap.addAttribute("msg", "Hello Saber, this is freemarker");
return "freemarker";
}
}
| true |
41ca98827794427939cec3e7c3e13fb23515fe7b | Java | WarunaS/carbon-device-mgt-plugins | /components/mobile-plugins/mobile-base-plugin/org.wso2.carbon.device.mgt.mobile/src/main/java/org/wso2/carbon/device/mgt/mobile/config/datasource/DataSourceConfigAdapter.java | UTF-8 | 2,060 | 2 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.mobile.config.datasource;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DataSourceConfigAdapter
extends XmlAdapter<MobileDataSourceConfigurations, Map<String, MobileDataSourceConfig>> {
@Override
public Map<String, MobileDataSourceConfig> unmarshal(MobileDataSourceConfigurations mobileDataSourceConfigurations)
throws Exception {
Map<String, MobileDataSourceConfig> mobileDataSourceConfigMap = new HashMap<String, MobileDataSourceConfig>();
for (MobileDataSourceConfig mobileDataSourceConfig : mobileDataSourceConfigurations
.getMobileDataSourceConfigs()) {
mobileDataSourceConfigMap.put(mobileDataSourceConfig.getType(), mobileDataSourceConfig);
}
return mobileDataSourceConfigMap;
}
@Override
public MobileDataSourceConfigurations marshal(Map<String, MobileDataSourceConfig> mobileDataSourceConfigMap)
throws Exception {
MobileDataSourceConfigurations mobileDataSourceConfigurations = new MobileDataSourceConfigurations();
mobileDataSourceConfigurations.setMobileDataSourceConfigs(
(List<MobileDataSourceConfig>) mobileDataSourceConfigMap.values());
return mobileDataSourceConfigurations;
}
}
| true |
094a8a40b8264b35dbaf2c47dc58b19ca8adff83 | Java | mihajlo-perendija/SBNZ | /CarRR-app/src/main/java/main/dto/SearchDTO.java | UTF-8 | 3,906 | 2.265625 | 2 | [] | no_license | package main.dto;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import main.facts.*;
public class SearchDTO {
private UserDTO customer;
private List<Category> categories;
private List<Tag> tags;
private List<BrandDTO> brands;
private List<CarModelDTO> models;
private List<Fuel> fuels;
private List<Transmission> transmissions;
private List<Integer> seatsNo;
private List<Integer> doorNo;
private List<Double> fuelConsumptions;
private Integer scaleFactor;
// private Customer realCustomerForRules;
public SearchDTO() {
super();
this.categories = new ArrayList<Category>();
this.tags = new ArrayList<Tag>();
this.brands = new ArrayList<BrandDTO>();
this.models = new ArrayList<CarModelDTO>();
this.fuels = new ArrayList<Fuel>();
this.transmissions = new ArrayList<Transmission>();
this.seatsNo = new ArrayList<Integer>();
this.doorNo = new ArrayList<Integer>();
this.fuelConsumptions = new ArrayList<Double>();
this.scaleFactor = 1;
}
public SearchDTO(UserDTO customer, List<Category> categories, List<Tag> tags, List<BrandDTO> brands,
List<CarModelDTO> models, List<Fuel> fuels, List<Transmission> transmissions, List<Integer> seatsNo,
List<Integer> doorNo, List<Double> fuelConsumptions, Integer scaleFactor) {
super();
this.customer = customer;
this.categories = categories;
this.tags = tags;
this.brands = brands;
this.models = models;
this.fuels = fuels;
this.transmissions = transmissions;
this.seatsNo = seatsNo;
this.doorNo = doorNo;
this.fuelConsumptions = fuelConsumptions;
this.scaleFactor = scaleFactor;
// this.realCustomerForRules = realCustomerForRules;
}
public UserDTO getCustomer() {
return customer;
}
public void setCustomer(UserDTO customer) {
this.customer = customer;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public List<BrandDTO> getBrands() {
return brands;
}
public void setBrands(List<BrandDTO> brands) {
this.brands = brands;
}
public List<CarModelDTO> getModels() {
return models;
}
public void setModels(List<CarModelDTO> models) {
this.models = models;
}
public List<Fuel> getFuels() {
return fuels;
}
public void setFuels(List<Fuel> fuels) {
this.fuels = fuels;
}
public List<Transmission> getTransmissions() {
return transmissions;
}
public void setTransmissions(List<Transmission> transmissions) {
this.transmissions = transmissions;
}
public List<Integer> getSeatsNo() {
return seatsNo;
}
public void setSeatsNo(List<Integer> seatsNo) {
this.seatsNo = seatsNo;
}
public List<Integer> getDoorNo() {
return doorNo;
}
public void setDoorNo(List<Integer> doorNo) {
this.doorNo = doorNo;
}
public List<Double> getFuelConsumptions() {
return fuelConsumptions;
}
public void setFuelConsumptions(List<Double> fuelConsumptions) {
this.fuelConsumptions = fuelConsumptions;
}
public int getScaleFactor() {
return scaleFactor;
}
public void setScaleFactor(Integer scaleFactor) {
this.scaleFactor = scaleFactor;
}
// public Customer getRealCustomerForRules() {
// return realCustomerForRules;
// }
//
// public void setRealCustomerForRules(Customer realCustomerForRules) {
// this.realCustomerForRules = realCustomerForRules;
// }
@Override
public String toString() {
return "SearchDTO{" +
"customer=" + customer +
", categories=" + categories +
", tags=" + tags +
", brands=" + brands +
", models=" + models +
", fuels=" + fuels +
", transmissions=" + transmissions +
", seatsNo=" + seatsNo +
", doorNo=" + doorNo +
", fuelConsumptions=" + fuelConsumptions +
", scaleFactor=" + scaleFactor +
'}';
}
}
| true |
2bef7455f5c10b97086d97cfecccb9187dae45be | Java | gautum/BattleBusDriver | /src/main/java/com/nwjefferies/battleBusDriver/eventListeners/messageHandlers/ChannelHandler.java | UTF-8 | 1,548 | 2.6875 | 3 | [] | no_license | package com.nwjefferies.battleBusDriver.eventListeners.messageHandlers;
import com.nwjefferies.battleBusDriver.databaseConnection.DatabaseLookupService;
import com.nwjefferies.battleBusDriver.eventListeners.messageUtils.Command;
import com.nwjefferies.battleBusDriver.eventListeners.messageUtils.Response;
import com.nwjefferies.epicTools.EpicUser;
import sx.blah.discord.api.IDiscordClient;
import java.util.Calendar;
public class ChannelHandler extends CommandHandler{
public ChannelHandler(IDiscordClient client, DatabaseLookupService databaseLookupService) {
super(client, databaseLookupService);
}
@Override
public Response processCommand(Command command) {
if(!command.isValidCommand()) {
return null;
}
String text = "";
System.out.println("[" + Calendar.getInstance().getTime() + "][RemoveHandler] Processing remove command");
long guildID = command.getGuildId();
if(command.getNumArguments() > 2) {
text = "Unable to set channel: Too many arguments passed";
}
else {
// check if server owner
if(!command.isServerOwner()) {
text = "Unable to set channel: You must be the server owner to use this command";
}
else {
text = "Success! This channel has been set to #" + command.getChannelName();
databaseLookupService.setChannel(guildID, command.getChannelId());
}
}
return new Response(text);
}
}
| true |
6088bffee611a76b14f4cfca492a513eac5a8428 | Java | suazen/KTZS_app | /app/src/main/java/me/daylight/ktzs/utils/SharedPreferencesUtil.java | UTF-8 | 1,612 | 2.546875 | 3 | [] | no_license | package me.daylight.ktzs.utils;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Set;
public class SharedPreferencesUtil {
private static SharedPreferences getSP(Context context, String table) {
return context.getSharedPreferences(table, Context.MODE_PRIVATE);
}
public static void putValue(Context context, String table, String key, int value) {
getSP(context, table).edit().putInt(key, value).apply();
}
public static void putValue(Context context, String table, String key, String value) {
getSP(context, table).edit().putString(key, value).apply();
}
public static void putValue(Context context, String table, String key, boolean value) {
getSP(context, table).edit().putBoolean(key, value).apply();
}
public static void putValue(Context context, String table, String key, Set<String> value) {
getSP(context, table).edit().putStringSet(key, value).apply();
}
public static int getInt(Context context, String table, String key) {
return getSP(context, table).getInt(key, 0);
}
public static String getString(Context context, String table, String kye) {
return getSP(context, table).getString(kye, "");
}
public static boolean getBoolean(Context context, String table, String key) {
return getSP(context, table).getBoolean(key, false);
}
public static Set<String> getSet(Context context,String table,String key){
return getSP(context,table).getStringSet(key,null);
}
}
| true |
0aa342503195984f26840a5b06e86008b33f4487 | Java | bellmit/kernel | /bsoft-api/src/main/java/com/bsoft/work/service/OriginalCertificateService.java | UTF-8 | 1,347 | 2.03125 | 2 | [] | no_license | package com.bsoft.work.service;
import com.bsoft.common.dto.PublicDicDTO;
import com.bsoft.common.result.Result;
import com.bsoft.work.dto.OriginalCertificateDTO;
import com.bsoft.work.dto.OriginalCertificateQueryCndDTO;
import java.util.List;
/**
* @author: zy
* @date: 2020/9/10
* @description 证书原件管理
*/
public interface OriginalCertificateService {
/**
* 根据名字获取证书信息
* @return com.bsoft.work.dto.OriginalCertificateDTO
*/
OriginalCertificateDTO getByName(String userId, String name);
/**
* 获取证书原件列表
* @param userId
* @param queryCndDTO
* @return Result<com.bsoft.work.dto.OriginalCertificateDTO>
*/
Result<OriginalCertificateDTO> listByLimits(String userId, OriginalCertificateQueryCndDTO queryCndDTO);
/**
* 保存证书原件信息
* @param userId
* @param originalCertificateDTO
*/
void save(String userId, OriginalCertificateDTO originalCertificateDTO);
/**
* 修改证书原件信息
* @param userId
* @param originalCertificateDTO
*/
void update(String userId, OriginalCertificateDTO originalCertificateDTO);
/**
* 获取证书类别
* @return List<import com.bsoft.common.dto.PublicDicDTO;>
*/
List<PublicDicDTO> listCertType(String userId);
}
| true |
82bcaa820f661a41b393edd6dc2d5debc6247aa6 | Java | josiepollard/MyFirstJava | /src/BankAccountTest.java | UTF-8 | 730 | 2.9375 | 3 | [] | no_license | import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class BankAccountTest {
@Test
public void balanceIsZero() {
BankAccount testBankAccount = new BankAccount();
int balance = testBankAccount.balance;
assertEquals(0, balance);
}
@Test
public void depositMoney() {
BankAccount testBankAccount = new BankAccount();
testBankAccount.deposit(15);
assertEquals(15, testBankAccount.balance);
}
@Test
public void withdrawMoney() {
BankAccount testBankAccount = new BankAccount();
testBankAccount.deposit(10);
testBankAccount.withdraw(10);
assertEquals(0, testBankAccount.balance);
}
}
| true |
9a836d5a74f1ececcf2c0440601b643c0d28ed81 | Java | sebaspala02/crud_user_login_Sprign_MongoDB | /crudUserLoginSinToken/src/main/java/com/redhat/bluesmile/crudUserLogin/security/SecurityConstants.java | UTF-8 | 403 | 1.695313 | 2 | [] | no_license | //package com.redhat.bluesmile.crudUserLogin.security;
//
//public class SecurityConstants {
//
// public static final String SECRET = "SecretKeyToGenJWTs";
// public static final long EXPIRATION_TIME = 864_000; // 10 minutes
// public static final String TOKEN_PREFIX = "";
// public static final String HEADER_STRING = "x-auth-token";
// public static final String SIGN_UP_URL = "/api/sign-up";
//
//} | true |
9d281a4869ea1a1315e26fddddbf495dd80dcea8 | Java | liangjingyang/JForexKit | /src/main/java/com/jforexcn/inbox/indicator/TripleEMAIndicator.java | UTF-8 | 4,895 | 2.640625 | 3 | [] | no_license | package com.jforexcn.inbox.indicator;
/**
* Created by simple on 03/03/2017.
*/
import com.dukascopy.api.indicators.*;
public class TripleEMAIndicator implements IIndicator {
private IndicatorInfo indicatorInfo;
private InputParameterInfo[] inputParameterInfos;
private OptInputParameterInfo[] optInputParameterInfos;
private OutputParameterInfo[] outputParameterInfos;
private double[][] inputs = new double[1][];
private int[] timePeriod = new int[1];
private double[][] outputs = new double[1][];
private IIndicator ema;
public void onStart(IIndicatorContext context) {
IIndicatorsProvider indicatorsProvider = context.getIndicatorsProvider();
ema = indicatorsProvider.getIndicator("EMA");
indicatorInfo = new IndicatorInfo("THREEEMA", "Shows three different EMA indicator", "My indicator",
true, false, true, 1, 3, 3);
inputParameterInfos = new InputParameterInfo[] {new InputParameterInfo("Input data", InputParameterInfo.Type.DOUBLE)};
optInputParameterInfos = new OptInputParameterInfo[] {
// new OptInputParameterInfo(
// "Time cPeriod EMA1",
// OptInputParameterInfo.Type.OTHER,
// new IntegerRangeDescription(5, 2, 1000, 1)
// ),
// new OptInputParameterInfo(
// "Time cPeriod EMA2",
// OptInputParameterInfo.Type.OTHER,
// new IntegerRangeDescription(10, 2, 1000, 1)
// ),
new OptInputParameterInfo(
"Time cPeriod EMA3",
OptInputParameterInfo.Type.OTHER,
new IntegerRangeDescription(20, 2, 1000, 1)
)
};
outputParameterInfos = new OutputParameterInfo[] {
// new OutputParameterInfo(
// "EMA1",
// OutputParameterInfo.Type.DOUBLE,
// OutputParameterInfo.DrawingStyle.LINE
// ),
// new OutputParameterInfo(
// "EMA2",
// OutputParameterInfo.Type.DOUBLE,
// OutputParameterInfo.DrawingStyle.LINE
// ),
new OutputParameterInfo(
"EMA3",
OutputParameterInfo.Type.DOUBLE,
OutputParameterInfo.DrawingStyle.LINE
)
};
}
public IndicatorResult calculate(int startIndex, int endIndex) {
//calculating startIndex taking into account lookback value
if (startIndex - getLookback() < 0) {
startIndex -= startIndex - getLookback();
}
ema.setInputParameter(0, inputs[0]);
//calculate first ema
ema.setOptInputParameter(0, timePeriod[0]);
ema.setOutputParameter(0, outputs[0]);
ema.calculate(startIndex, endIndex);
//calculate second ema
ema.setOptInputParameter(0, timePeriod[1]);
ema.setOutputParameter(0, outputs[1]);
ema.calculate(startIndex, endIndex);
//calculate third ema
ema.setOptInputParameter(0, timePeriod[2]);
ema.setOutputParameter(0, outputs[2]);
return ema.calculate(startIndex, endIndex);
}
public IndicatorInfo getIndicatorInfo() {
return indicatorInfo;
}
public InputParameterInfo getInputParameterInfo(int index) {
if (index <= inputParameterInfos.length) {
return inputParameterInfos[index];
}
return null;
}
public int getLookback() {
ema.setOptInputParameter(0, timePeriod[0]);
int ema1Lookback = ema.getLookback();
ema.setOptInputParameter(0, timePeriod[1]);
int ema2Lookback = ema.getLookback();
ema.setOptInputParameter(0, timePeriod[2]);
int ema3Lookback = ema.getLookback();
return Math.max(ema1Lookback, Math.max(ema2Lookback, ema3Lookback));
}
public int getLookforward() {
return 0;
}
public OptInputParameterInfo getOptInputParameterInfo(int index) {
if (index <= optInputParameterInfos.length) {
return optInputParameterInfos[index];
}
return null;
}
public OutputParameterInfo getOutputParameterInfo(int index) {
if (index <= outputParameterInfos.length) {
return outputParameterInfos[index];
}
return null;
}
public void setInputParameter(int index, Object array) {
inputs[index] = (double[]) array;
}
public void setOptInputParameter(int index, Object value) {
timePeriod[index] = (Integer) value;
}
public void setOutputParameter(int index, Object array) {
outputs[index] = (double[]) array;
}
}
| true |
8c6dfbb1322b95d96e6b34a78b096d3f4452411b | Java | weitie1990/MyONE | /DoAPP/src/com/lanxiao/doapp/activity/PersonSigninLogActivity.java | UTF-8 | 4,894 | 2.1875 | 2 | [] | no_license | package com.lanxiao.doapp.activity;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.doapp.R;
import com.lanxiao.doapp.adapter.PersonSignInLogAdapter;
import com.lanxiao.doapp.entity.PersonSignInLogItem;
import com.lanxiao.doapp.untils.DateUntils;
import com.umeng.analytics.MobclickAgent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
public class PersonSigninLogActivity extends BaseActivity {
@InjectView(R.id.signin_log_person_back)
ImageView signinLogPersonBack;
@InjectView(R.id.signin_log_person_statistic)
TextView signinLogPersonStatistic;
@InjectView(R.id.signin_log_person_time)
TextView signinLogPersonTime;
@InjectView(R.id.signin_log_person_selecttime)
TextView signinLogPersonSelecttime;
@InjectView(R.id.lv_signinLog_person)
ListView lvSigninLogPerson;
List<PersonSignInLogItem> list;
PersonSignInLogAdapter personSignInLogAdapter;
String data=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_person_signin_log);
ButterKnife.inject(this);
init();
}
private void init() {
data=DateUntils.getDate(new Date());
String week=DateUntils.getWeekOfDate(new Date());
signinLogPersonTime.setText(week+" "+data);
list=new ArrayList<>();
PersonSignInLogItem personSignInLogItem1=new PersonSignInLogItem();
personSignInLogItem1.setSignaddress("上海市杨浦区68号");
personSignInLogItem1.setSignbeiju("加急急");
personSignInLogItem1.setSingintime("14:16");
personSignInLogItem1.setUserName("魏铁");
PersonSignInLogItem personSignInLogItem2=new PersonSignInLogItem();
personSignInLogItem2.setSignaddress("上海市浦东新区龙东大道948号");
personSignInLogItem2.setSignbeiju("今天在这");
personSignInLogItem2.setSingintime("14:20");
personSignInLogItem2.setUserName("张三");
list.add(personSignInLogItem1);
list.add(personSignInLogItem2);
personSignInLogAdapter=new PersonSignInLogAdapter(this,list);
lvSigninLogPerson.setAdapter(personSignInLogAdapter);
}
@OnClick({R.id.signin_log_person_back, R.id.signin_log_person_statistic, R.id.signin_log_person_selecttime})
public void onClick(View view) {
switch (view.getId()) {
case R.id.signin_log_person_back:
finish();
break;
case R.id.signin_log_person_statistic:
break;
case R.id.signin_log_person_selecttime:
DateDiogAlret(signinLogPersonTime);
break;
}
}
//处理所有输入框的diogalrt
public void DateDiogAlret(final TextView tv) {
//初始化Calendar日历对象
final Calendar mycalendar=Calendar.getInstance(Locale.CHINA);
mycalendar.setTime(getNowData(data));////为Calendar对象设置时间为当前日期
myear=mycalendar.get(Calendar.YEAR); //获取Calendar对象中的年
mmonth=mycalendar.get(Calendar.MONTH);//获取Calendar对象中的月
mday=mycalendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天
DatePickerDialog dp=new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar calendar=Calendar.getInstance(Locale.CHINA);
calendar.set(year,month,day);
mweek= DateUntils.getWeekOfDate(calendar.getTime());
myear=year;
mmonth=month;
mday=day;
data=myear+"-"+(mmonth+1)+"-"+mday;
tv.setText(mweek+" "+data);
}
}, myear, mmonth,
mday);
dp.show();
}
private Date getNowData(String day){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date nowDate = null;
try {
nowDate = df.parse(day);
} catch (ParseException e) {
e.printStackTrace();
}
return nowDate;
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onResume(this);
}
}
| true |
a19d9431a68111a35f2d072aabde780ab7e3a07e | Java | KrishieldKyle/devans | /src/main/java/com/haphor/social/service/PostServiceImpl.java | UTF-8 | 10,289 | 2.25 | 2 | [] | no_license | package com.haphor.social.service;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import com.haphor.social.dao.PostDAO;
import com.haphor.social.dao.TechnologyDAO;
import com.haphor.social.dto.LikeDTO;
import com.haphor.social.dto.PostDTO;
import com.haphor.social.dto.TechnologyDTO;
import com.haphor.social.dto.request.AddOrUpdatePostRequestDTO;
import com.haphor.social.dto.request.AddTechnologiesToPostRequestDTO;
import com.haphor.social.dto.request.DeleteTechnologiesFromPostRequestDTO;
import com.haphor.social.dto.response.AllPostsResponseDTO;
import com.haphor.social.dto.response.DeletePostResponseDTO;
import com.haphor.social.dto.response.PostResponseDTO;
import com.haphor.social.dto.response.PostTechnologyResponseDTO;
import com.haphor.social.model.Post;
import com.haphor.social.model.Technology;
import com.haphor.social.model.User;
import com.haphor.social.util.converter.dto.ConvertDTO;
import com.haphor.social.util.converter.entity.ConvertEntity;
import com.haphor.social.util.jwt.AccessToken;
@Service
public class PostServiceImpl implements PostService {
@Autowired
private PostDAO postDao;
@Autowired
private TechnologyDAO technologyDao;
@Autowired
private AccessToken accessToken;
@Autowired
private ConvertEntity convertEntity;
@Autowired
private ConvertDTO convertDTO;
@Override
public AllPostsResponseDTO getAllPost() {
List<Post> posts = postDao.findAll();
Set<LikeDTO> likesDto = new HashSet<>();
Set<TechnologyDTO> technologiesDto = new HashSet<>();
Set<PostDTO> postsDto = new HashSet<>();
for(Post post : posts) {
likesDto = convertEntity.toLikeDTOs(post.getLikes());
technologiesDto = convertEntity.toTechnologyDTOs(post.getTechnologies());
// Construct the post for response
PostDTO postDto = new PostDTO(post.getPostId(), post.getUser().getUserId(), post.getSubject(), post.getContent(),
likesDto, technologiesDto, post.getCreatedAt(), post.getUpdatedAt());
postsDto.add(postDto);
likesDto = new HashSet<>();
technologiesDto = new HashSet<>();
}
return new AllPostsResponseDTO(postsDto, true, "All posts have been fetched", HttpStatus.OK);
}
@Override
public PostResponseDTO getPost(int postId) {
Optional<Post> maybePost = postDao.findById(postId);
if(maybePost.isPresent()) {
Post post = maybePost.get();
// Construct the likes for the post response
Set<LikeDTO> likesDto = new HashSet<>();
Set<TechnologyDTO> technologiesDto = new HashSet<>();
likesDto = convertEntity.toLikeDTOs(post.getLikes());
technologiesDto = convertEntity.toTechnologyDTOs(post.getTechnologies());
// Construct the post for response
PostDTO postDto = new PostDTO(post.getPostId(), post.getUser().getUserId(), post.getSubject(), post.getContent(),
likesDto, technologiesDto, post.getCreatedAt(), post.getUpdatedAt());
return new PostResponseDTO(postDto, true, "Post successfully fetched", HttpStatus.OK);
}
return new PostResponseDTO(new PostDTO(), false, "Post not found.", HttpStatus.NOT_FOUND);
}
@Override
public PostResponseDTO saveOrUpdatePost(AddOrUpdatePostRequestDTO addOrUpdatePostRequestDTO) {
User user = accessToken.getUserFromToken();
if(user.getUserId() != addOrUpdatePostRequestDTO.getUserId()) {
return new PostResponseDTO(new PostDTO(), false, "User ID does not match the currently logged in user", HttpStatus.UNAUTHORIZED);
}
Optional<Post> maybePost = postDao.findById(addOrUpdatePostRequestDTO.getPostId());
// Check if there is an existing post with the given id
if(maybePost.isPresent()) {
Post post = maybePost.get();
// Check if the post belongs to the currently logged in user
if(post.getUser().getUserId() != user.getUserId()) {
return new PostResponseDTO(new PostDTO(), false, "You are not authorized to update this post", HttpStatus.UNAUTHORIZED);
}
// Update the post
post.setSubject(addOrUpdatePostRequestDTO.getSubject());
post.setContent(addOrUpdatePostRequestDTO.getContent());
Set<Technology> currentTechnologies = post.getTechnologies();
Set<Technology> newTechnologies = convertDTO.toTechnologyEntities(addOrUpdatePostRequestDTO.getTechnologies());
technologyDao.saveAll(newTechnologies);
currentTechnologies.addAll(newTechnologies);
post.setTechnologies(currentTechnologies);
// Persist the post
Post newPost = postDao.save(post);
Set<LikeDTO> likesDto = convertEntity.toLikeDTOs(newPost.getLikes());
Set<TechnologyDTO> technologiesDto = convertEntity.toTechnologyDTOs(newPost.getTechnologies());
PostDTO postDto = new PostDTO(newPost.getPostId(), newPost.getUser().getUserId(), newPost.getSubject(), newPost.getContent(),
likesDto, technologiesDto, newPost.getCreatedAt(), newPost.getUpdatedAt());
return new PostResponseDTO(postDto, true, "Post has been updated.", HttpStatus.OK);
}
// New post
Set<Technology> newTechnologies = convertDTO.toTechnologyEntities(addOrUpdatePostRequestDTO.getTechnologies());
technologyDao.saveAll(newTechnologies);
Post post = new Post();
post.setSubject(addOrUpdatePostRequestDTO.getSubject());
post.setContent(addOrUpdatePostRequestDTO.getContent());
post.setTechnologies(newTechnologies);
post.setUser(user);
Post newPost = postDao.save(post);
Set<TechnologyDTO> technologiesDto = convertEntity.toTechnologyDTOs(newPost.getTechnologies());
PostDTO postDto = new PostDTO(newPost.getPostId(), newPost.getUser().getUserId(), newPost.getSubject(),
newPost.getContent(), new HashSet<>(), technologiesDto, newPost.getCreatedAt(), newPost.getUpdatedAt());
return new PostResponseDTO(postDto, true, "Post has been created.", HttpStatus.OK);
}
@Override
public DeletePostResponseDTO deletePost(int postId) {
User user = accessToken.getUserFromToken();
Optional<Post> post = postDao.findById(postId);
if(post.isPresent() && post.get().getUser().getUserId() == user.getUserId()) {
postDao.deleteById(postId);
return new DeletePostResponseDTO(postId, true, "Post has been deleted.", HttpStatus.OK);
}
return new DeletePostResponseDTO(postId, false, "You are not authorized to delete this post", HttpStatus.UNAUTHORIZED);
}
@Override
public PostTechnologyResponseDTO addTechnologiesToPost(AddTechnologiesToPostRequestDTO addTechnologyToPostRequestDTO) {
User user = accessToken.getUserFromToken();
if(user.getUserId() != addTechnologyToPostRequestDTO.getUserId()) {
return new PostTechnologyResponseDTO(false, "User ID does not match the currently logged in user",
addTechnologyToPostRequestDTO.getPostId(), new HashSet<>(), HttpStatus.UNAUTHORIZED);
}
if(addTechnologyToPostRequestDTO.getTechnologies().isEmpty()) {
return new PostTechnologyResponseDTO(true, "No technology has been added",
addTechnologyToPostRequestDTO.getPostId(), new HashSet<>(), HttpStatus.OK);
}
Optional<Post> maybePost = postDao.findById(addTechnologyToPostRequestDTO.getPostId());
if(maybePost.isPresent() && maybePost.get().getUser().getUserId() == user.getUserId()) {
Post post = maybePost.get();
Set<Technology> newTechnologies = convertDTO.toTechnologyEntities(addTechnologyToPostRequestDTO.getTechnologies());
newTechnologies = new HashSet<>(technologyDao.saveAll(newTechnologies));
Set<Technology> currentTechnologies = post.getTechnologies();
currentTechnologies.addAll(newTechnologies);
post.setTechnologies(currentTechnologies);
Post newPost = postDao.save(post);
Set<TechnologyDTO> technologiesDto = convertEntity.toTechnologyDTOs(newPost.getTechnologies());
return new PostTechnologyResponseDTO(true, "Successfully added technologies to the post",
addTechnologyToPostRequestDTO.getPostId(), technologiesDto, HttpStatus.OK);
}
return new PostTechnologyResponseDTO(false, "You are not authorized to add technologies to this post.",
addTechnologyToPostRequestDTO.getPostId(), new HashSet<>(), HttpStatus.UNAUTHORIZED);
}
@Override
public PostTechnologyResponseDTO deleteTechnologiesFromPost(DeleteTechnologiesFromPostRequestDTO deleteTechnologiesFromPostRequestDTO) {
User user = accessToken.getUserFromToken();
if(user.getUserId() != deleteTechnologiesFromPostRequestDTO.getUserId()) {
return new PostTechnologyResponseDTO(false, "User ID does not match the currently logged in user",
deleteTechnologiesFromPostRequestDTO.getPostId(), new HashSet<>(), HttpStatus.UNAUTHORIZED);
}
if(deleteTechnologiesFromPostRequestDTO.getTechnologies().isEmpty()) {
return new PostTechnologyResponseDTO(true, "No technology has been deleted",
deleteTechnologiesFromPostRequestDTO.getPostId(), new HashSet<>(), HttpStatus.OK);
}
Optional<Post> maybePost = postDao.findById(deleteTechnologiesFromPostRequestDTO.getPostId());
if(maybePost.isPresent() && maybePost.get().getUser().getUserId() == user.getUserId()) {
Post post = maybePost.get();
Set<Technology> newTechnologies = post.getTechnologies();
for(TechnologyDTO technologyDto : deleteTechnologiesFromPostRequestDTO.getTechnologies()) {
for(Technology postTechnology : post.getTechnologies()) {
if(technologyDto.getTechnologyId() == postTechnology.getTechnologyId()) {
newTechnologies.remove(postTechnology);
break;
}
}
}
post.setTechnologies(newTechnologies);
Post newPost = postDao.save(post);
Set<TechnologyDTO> technologiesDto = convertEntity.toTechnologyDTOs(newPost.getTechnologies());
return new PostTechnologyResponseDTO(true, "Technologies have been added.",
deleteTechnologiesFromPostRequestDTO.getPostId(), technologiesDto, HttpStatus.OK);
}
return new PostTechnologyResponseDTO(false, "You are not authorized to delete a technology from this post",
deleteTechnologiesFromPostRequestDTO.getPostId(), new HashSet<>(), HttpStatus.UNAUTHORIZED);
}
}
| true |
fcad6cb1d36b15df2d085af42d73c2186f377bd0 | Java | AleksVuk/BILD-IT-Zadaci | /src/miniProjekat03/ticTacToe.java | UTF-8 | 6,718 | 3.546875 | 4 | [] | no_license | package miniProjekat03;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ticTacToe {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean worksAplication = true;
//loop which controls application
while (worksAplication) {
char[][] ticTacToe = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}} ;
System.out.println("Welcome to the TicTacToe game. ");
System.out.println("1.Play new game.");
System.out.println("2.Exit.");
int choice1 = 0;
boolean works1 = true;
//loop which controls correct choice in the first window
while (works1){
try{
System.out.print("Choose: ");
choice1 = input.nextInt();
if (choice1 == 1 || choice1 == 2){
break;
}
else{
System.out.println("Enter 1 or 2!");
input.nextLine();
continue;
}
}catch(InputMismatchException ex){
System.out.println("Invalid input!");
input.nextLine();
}
}
if (choice1 == 1){
for (int i = 1; i <= 10; i++) {
//print tic-tac-toe matrix before every turn
for (int row = 0; row < 3; row++) {
System.out.println("-------------");
for (int column = 0; column < 3; column++) {
System.out.printf("| %-2s", ticTacToe[row][column]);
}
System.out.println("|");
}
System.out.println("-------------");
if (i > 4) {
//after the fifth turn check if there is a winner
if (checkRows(ticTacToe) == 'X' || checkColumns(ticTacToe) == 'X' || checkMainDiagonal(ticTacToe) == 'X'
|| checkSecondalDiagonal(ticTacToe) == 'X') {
System.out.println("Player X won the game! Congratulations :) ");
System.out.println("-------------------------------------------");
break;
} else if (checkRows(ticTacToe) == 'O' || checkColumns(ticTacToe) == 'O'
|| checkMainDiagonal(ticTacToe) == 'O' || checkSecondalDiagonal(ticTacToe) == 'O') {
System.out.println("Player O won the game! Congratulations :) ");
System.out.println("-------------------------------------------");
break;
}
}
//after nine turns check if there is a winner or the game is draw
if (i == 10) {
if (checkRows(ticTacToe) == 'D' || checkColumns(ticTacToe) == 'D' || checkMainDiagonal(ticTacToe) == 'D'
|| checkSecondalDiagonal(ticTacToe) == 'D') {
System.out.println("Draw :(");
System.out.println("-------------------------------------------");
}
break;
}
//player X turn
if (i % 2 != 0) {
boolean works2 = true;
//loop which controls correct choice of the location for player X
while(works2){
try{
int [] a = new int [2];
System.out.println("Player X: ");
System.out.print("Choose row and column (0, 1, or 2): ");
a[0] = input.nextInt();
a[1] = input.nextInt();
if (a[0] >= 0 && a[1] >= 0 && a[0] <= 2 && a[1] <= 2){
if (ticTacToe[a[0]][a[1]] == ' '){
ticTacToe[a[0]][a[1]] = 'X';
input.nextLine();
break;
}
else{
System.out.println("This place is already choosen! Try again.");
input.nextLine();
continue;
}
}
else{
System.out.println("Wrong input!");
input.nextLine();
continue;
}
}catch (InputMismatchException ex){
System.out.println("Invalid input!");
input.nextLine();
}
}
}
//player O turn
else if (i % 2 == 0) {
boolean works3 = true;
//loop which controls correct choice of the location for player 0
while (works3) {
try{
int [] b = new int [2];
System.out.println("Player O: ");
System.out.print("Choose row and column (0, 1, or 2): ");
b[0] = input.nextInt();
b[1] = input.nextInt();
if (b[0] >= 0 && b[1] >= 0 && b[0] <= 2 && b[1] <= 2){
if (ticTacToe[b[0]][b[1]] == ' '){
ticTacToe[b[0]][b[1]] = 'O';
input.nextLine();
break;
}
else{
System.out.println("This place is already choosen! Try again.");
input.nextLine();
continue;
}
}
else{
System.out.println("Wrong input!");
input.nextLine();
continue;
}
}catch (InputMismatchException ex){
System.out.println("Invalid input!");
input.nextLine();
}
}
System.out.println();
}
}
}
else if (choice1 == 2){
break;
}
}
System.out.println("Thank you for playing tic-tac-toe game :)");
input.close();
}
//check if there are three same characters in any row
public static char checkRows(char[][] m) {
char x = 'X';
char o = 'O';
for (int i = 0; i < 3; i++) {
int countX = 0;
int countO = 0;
for (int j = 0; j < 3; j++) {
if (m[i][j] == x) {
countX++;
}
if (m[i][j] == o) {
countO++;
}
}
if (countX == 3) {
return 'X';
} else if (countO == 3) {
return 'O';
}
}
return 'D';
}
//check if there are three same characters in any column
public static char checkColumns(char[][] m) {
char x = 'X';
char o = 'O';
for (int i = 0; i < 3; i++) {
int countX = 0;
int countO = 0;
for (int j = 0; j < 3; j++) {
if (m[j][i] == x) {
countX++;
}
if (m[j][i] == o) {
countO++;
}
}
if (countX == 3) {
return 'X';
} else if (countO == 3) {
return 'O';
}
}
return 'D';
}
//check if there are three same characters on the main diagonal
public static char checkMainDiagonal(char[][] m) {
char x = 'X';
char o = 'O';
int countX = 0;
int countO = 0;
for (int i = 0; i < 3; i++) {
if (m[i][i] == x) {
countX++;
}
if (m[i][i] == o) {
countO++;
}
}
if (countX == 3) {
return 'X';
} else if (countO == 3) {
return 'O';
}
return 'D';
}
//check if there are three same characters on the secondal diagonal
public static char checkSecondalDiagonal(char[][] m) {
char x = 'X';
char o = 'O';
int countX = 0;
int countO = 0;
int j = 2;
for (int i = 0; i < 3; i++) {
if (m[i][j] == x) {
countX++;
}
if (m[i][j] == o) {
countO++;
}
j--;
}
if (countX == 3) {
return 'X';
} else if (countO == 3) {
return 'O';
}
return 'D';
}
}
| true |
ec25c25af0d075fdfde79d43a14e3a610504cf69 | Java | EPIICTHUNDERCAT/Snowanimals | /src/main/java/com/github/epiicthundercat/snowanimals/entity/passive/EntityHarpSeal.java | UTF-8 | 3,422 | 2.078125 | 2 | [
"MIT"
] | permissive | package com.github.epiicthundercat.snowanimals.entity.passive;
import java.util.Set;
import javax.annotation.Nullable;
import com.github.epiicthundercat.snowanimals.Reference;
import com.google.common.collect.Sets;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.entity.ai.EntityAIFollowParent;
import net.minecraft.entity.ai.EntityAILookIdle;
import net.minecraft.entity.ai.EntityAIMate;
import net.minecraft.entity.ai.EntityAIPanic;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.EntityAITempt;
import net.minecraft.entity.ai.EntityAIWander;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.pathfinding.PathNodeType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class EntityHarpSeal extends EntityAnimal {
private static final Set<Item> TEMPTATION_ITEMS = Sets
.newHashSet(new Item[] { Items.FISH, Items.COOKED_FISH });
public static final ResourceLocation LOOT_SEAL = new ResourceLocation(Reference.ID, "entities/harp_seal");
public EntityHarpSeal(World worldIn) {
super(worldIn);
setSize(0.999F, 0.8F);
if (this.isChild()){
setSize(1.999F, 1.8F);
}
experienceValue = 10;
this.setPathPriority(PathNodeType.WATER, 0.0F);
}
@Override
protected void initEntityAI() {
this.tasks.addTask(0, new EntityAISwimming(this));
this.tasks.addTask(1, new EntityAIPanic(this, 1.4D));
this.tasks.addTask(2, new EntityAIMate(this, 1.0D));
this.tasks.addTask(3, new EntityAITempt(this, 1.0D, false, TEMPTATION_ITEMS));
this.tasks.addTask(4, new EntityAIFollowParent(this, 1.1D));
this.tasks.addTask(5, new EntityAIWander(this, 1.0D));
this.tasks.addTask(6, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F));
this.tasks.addTask(7, new EntityAILookIdle(this));
this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F));
this.tasks.addTask(9, new EntityAILookIdle(this));
}
@Override
protected void entityInit() {
super.entityInit();
}
protected void applyEntityAttributes() {
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(40.0D);
this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.25D);
}
public boolean isInWater() {
return super.isInWater();
}
@Override
public EntityHarpSeal createChild(EntityAgeable ageable) {
return new EntityHarpSeal(this.worldObj);
}
public float getEyeHeight() {
return this.height;
}
public boolean isBreedingItem(@Nullable ItemStack stack) {
return stack != null && TEMPTATION_ITEMS.contains(stack.getItem());
}
@Nullable
protected ResourceLocation getLootTable() {
return LOOT_SEAL;
}
}
| true |
bdbbf0dc470e6495d072f211c46b741445c4fff4 | Java | EvandroAlessi/ControleFluxoCaixa | /src/Views/CadastroReceitaFX.java | UTF-8 | 13,661 | 2.171875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Views;
import Controllers.CategoriaContaController;
import Controllers.ReceitaController;
import Controllers.SubCategoriaController;
import CrossCutting.Enums.FormaPagamento;
import CrossCutting.Mensagem;
import Models.CategoriaConta;
import Models.Receita;
import Models.SubCategoria;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.RowConstraints;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Modality;
import javafx.stage.Stage;
/**
* View com formulário de cadastro para Receitas.
* Diretamente ligada ao Stage provido pela ReceitaFX
* Utiliza o controlador de CategoriaConta, SubCategoria e Receita
* @author Evandro Alessi
* @author Eric Ueta
* @see CategoriaConta
* @see SubCategoria
* @see Receita
* @see ReceitaController
* @see CategoriaContaController
* @see SubCategoriaController
* @see ReceitaFX
*/
public class CadastroReceitaFX {
private final Label lbData, lbSubCategoria, lbDescricao, lbValor, lbPagamento, lbTitle, lbCategoria;
private final TextField tfDescricao, tfValor;
private final DatePicker dpCalendario;
private final Button btnCadastrar, btnCancelar;
private final SubCategoriaController subCategoriaController;
private final CategoriaContaController categoriaController;
private final List<SubCategoria> subCategorias;
private final List<CategoriaConta> categoriasConta;
private ComboBox<FormaPagamento> cbPagamento;
private ComboBox<SubCategoria> cbSubCategoria;
private final ComboBox<CategoriaConta> cbCategoria;
private ReceitaController receitaController;
private Stage dialog;
private Receita receitaCriada;
public CadastroReceitaFX() {
receitaCriada = null;
lbDescricao = new Label("Descrição:");
tfDescricao = new TextField();
tfValor = new TextField();
lbTitle = new Label("Nova Receita");
lbData = new Label("Ocorrência:");
lbSubCategoria = new Label("Categoria:");
lbCategoria = new Label("Tipo Receita:");
lbValor = new Label("Valor:");
lbPagamento = new Label("Pagamento:");
btnCadastrar = new Button("Cadastrar");
btnCancelar = new Button("Cancelar");
dpCalendario = new DatePicker();
subCategoriaController = new SubCategoriaController();
categoriaController = new CategoriaContaController();
receitaController = new ReceitaController();
subCategorias = subCategoriaController.getAll();
categoriasConta = categoriaController.getAll();
cbSubCategoria = new ComboBox();
cbPagamento = new ComboBox();
cbCategoria = new ComboBox();
btnCadastrar.setOnAction(e -> {
boolean ok = false;
if (tfDescricao.getText().trim().length() > 0 && tfDescricao.getText() != null) {
if (tfValor.getText().trim().length() > 0 && tfValor.getText() != null) {
if (cbSubCategoria.getSelectionModel().getSelectedItem() != null) {
ok = true;
} else {
Mensagem.aviso("A Receita deve ter um Categoria.");
}
} else {
tfValor.setStyle("-fx-text-box-border: red ;"
+ " -fx-focus-color: red ;");
Mensagem.informacao("A Receita deve ter um valor!");
}
} else {
tfDescricao.setStyle("-fx-text-box-border: red ;"
+ " -fx-focus-color: red ;");
Mensagem.informacao("A Receita deve ter uma Descrição!");
if (cbSubCategoria.getSelectionModel().getSelectedItem() == null) {
Mensagem.aviso("A Receita deve ter um Categoria.");
}
if (tfValor.getText().trim().length() == 0 || tfValor.getText() == null) {
tfValor.setStyle("-fx-text-box-border: red ;"
+ " -fx-focus-color: red ;");
Mensagem.informacao("A Receita deve ter um valor!");
}
}
if (ok) {
ok = false;
if (receitaCriada == null) {
Receita nReceita = new Receita();
try {
nReceita.setDescricao(tfDescricao.getText());
nReceita.setDataOcorrencia(dpCalendario.getValue());
nReceita.setValor(Double.parseDouble(tfValor.getText()));
nReceita.setFormaPagamento(cbPagamento.getSelectionModel().getSelectedItem().getValue());
nReceita.setSubCategoria(cbSubCategoria.getSelectionModel().getSelectedItem());
receitaCriada = receitaController.create(nReceita);
if (receitaCriada != null) {
ok = true;
}
} catch (Exception ex) {
Mensagem.informacao("O valor deve ser um número!");
}
} else {
try {
receitaCriada.setDescricao(tfDescricao.getText());
receitaCriada.setDataOcorrencia(dpCalendario.getValue());
receitaCriada.setValor(Double.parseDouble(tfValor.getText()));
receitaCriada.setFormaPagamento(cbPagamento.getSelectionModel().getSelectedItem().getValue());
receitaCriada.setSubCategoria(cbSubCategoria.getSelectionModel().getSelectedItem());
receitaCriada = receitaController.update(receitaCriada);
if (receitaCriada != null) {
ok = true;
}
} catch (Exception ex) {
Mensagem.informacao("O valor deve ser um número!");
}
}
if (ok) {
dialog.close();
}
}
});
btnCancelar.setOnAction(e -> {
dialog.close();
});
}
public void start(Stage mainStage, Receita receitaCriada) throws Exception {
dialog = new Stage();
GridPane painel = criarFormulario(receitaCriada);
dialog.initOwner(mainStage);
dialog.initModality(Modality.APPLICATION_MODAL);
Scene scene = new Scene(painel, 400, 420);
dialog.setResizable(false);
dialog.setMaxHeight(420);
dialog.setMaxWidth(400);
dialog.setMinHeight(420);
dialog.setMinWidth(400);
dialog.setScene(scene);
dialog.showAndWait();
}
private GridPane criarFormulario(Receita receitaCriada) {
GridPane pane = new GridPane();
HBox l1 = new HBox();
List<SubCategoria> subCatReceita = new ArrayList<>();
for (SubCategoria receita : subCategorias) {
if (receita.getCategoriaConta().isPositiva()) {
subCatReceita.add(receita);
}
}
List<CategoriaConta> catReceita = new ArrayList<>();
for (CategoriaConta receita : categoriasConta) {
if (receita.isPositiva()) {
catReceita.add(receita);
}
}
ListIterator<SubCategoria> subIte = subCatReceita.listIterator();
pane.setAlignment(Pos.TOP_CENTER);
pane.setHgap(10);
pane.setVgap(10);
pane.setPadding(new Insets(25, 10, 25, 25));
cbPagamento.getItems().addAll(FormaPagamento.values());
cbCategoria.setItems(FXCollections.observableArrayList(catReceita));
cbSubCategoria.setDisable(false);
cbCategoria.getSelectionModel().selectedItemProperty().addListener((opcoes, valorAntigo, valorNovo) -> {
List<SubCategoria> subCatReceitaSelected = new ArrayList<>();
for (SubCategoria receita : subCatReceita) {
if (receita.getCategoriaConta().getCategoriaContaID() == valorNovo.getCategoriaContaID()) {
subCatReceitaSelected.add(receita);
}
}
cbSubCategoria.setItems(FXCollections.observableArrayList(subCatReceitaSelected));
if (subCatReceitaSelected.size() > 0) {
cbSubCategoria.setDisable(false);
cbSubCategoria.getSelectionModel().selectFirst();
} else {
cbSubCategoria.setDisable(true);
}
});
ColumnConstraints c1 = new ColumnConstraints();
//c1.setHgrow(Priority.ALWAYS);
c1.setHalignment(HPos.CENTER);
RowConstraints r1 = new RowConstraints();
//r1.setVgrow(Priority.ALWAYS);
r1.setValignment(VPos.CENTER);
pane.getColumnConstraints().add(c1);
pane.getRowConstraints().add(r1);
cbCategoria.getSelectionModel().selectFirst();
l1.getChildren().addAll(btnCadastrar, btnCancelar);
l1.setSpacing(10);
l1.setPadding(new Insets(35, 0, -10, 0));
l1.setAlignment(Pos.CENTER);
lbTitle.setPadding(new Insets(0, 0, 25, 0));
lbTitle.setAlignment(Pos.CENTER);
cbPagamento.getSelectionModel().selectFirst();
dpCalendario.setValue(LocalDate.now());
cbCategoria.setPrefWidth(200);
cbSubCategoria.setPrefWidth(200);
cbPagamento.setPrefWidth(200);
tfDescricao.setPrefWidth(200);
tfValor.setPrefWidth(200);
dpCalendario.setPrefWidth(200);
tfValor.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
try {
Double.parseDouble(tfValor.getText());
} catch (Exception e) {
tfValor.setText(tfValor.getText().substring(0, tfValor.getText().length() - 1));
}
finally{
if (tfValor.getText().length() > 7) {
String s = tfValor.getText().substring(0, 7);
tfValor.setText(s);
}
}
}
});
pane.add(lbTitle, 0, 0, 4, 1);
pane.add(lbCategoria, 0, 1);
pane.add(cbCategoria, 1, 1);
pane.add(lbSubCategoria, 0, 2);
pane.add(cbSubCategoria, 1, 2);
pane.add(lbDescricao, 0, 3);
pane.add(tfDescricao, 1, 3);
pane.add(lbValor, 0, 4);
pane.add(tfValor, 1, 4);
pane.add(lbData, 0, 5);
pane.add(dpCalendario, 1, 5);
pane.add(lbPagamento, 0, 6);
pane.add(cbPagamento, 1, 6);
pane.add(l1, 0, 7, 2, 1);
lbTitle.setFont(Font.font("Arial", FontWeight.NORMAL, 23));
lbDescricao.setFont(Font.font("Arial", FontWeight.NORMAL, 17));
lbCategoria.setFont(Font.font("Arial", FontWeight.NORMAL, 17));
lbData.setFont(Font.font("Arial", FontWeight.NORMAL, 17));
lbPagamento.setFont(Font.font("Arial", FontWeight.NORMAL, 17));
lbSubCategoria.setFont(Font.font("Arial", FontWeight.NORMAL, 17));
lbValor.setFont(Font.font("Arial", FontWeight.NORMAL, 17));
btnCadastrar.setFont(Font.font("Arial", FontWeight.NORMAL, 15));
btnCancelar.setFont(Font.font("Arial", FontWeight.NORMAL, 15));
if (receitaCriada != null) {
this.receitaCriada = receitaCriada;
this.lbTitle.setText("Editar Receita");
btnCadastrar.setText("Salvar");
this.dpCalendario.setValue(receitaCriada.getDataOcorrencia());
this.tfDescricao.setText(receitaCriada.getDescricao());
this.tfValor.setText(String.valueOf(receitaCriada.getValor()));
this.cbPagamento.getSelectionModel().select(receitaCriada.getFormaPagamento() - 1);
for (CategoriaConta categoria : this.cbCategoria.getItems()) {
if (categoria.getCategoriaContaID() == receitaCriada.getSubCategoria().getCategoriaConta().getCategoriaContaID()) {
this.cbCategoria.getSelectionModel().select(categoria);
}
}
for (SubCategoria subcategoria : this.cbSubCategoria.getItems()) {
if (subcategoria.getSubCategoriaID() == receitaCriada.getSubCategoria().getSubCategoriaID()) {
this.cbSubCategoria.getSelectionModel().select(subcategoria);
}
}
//this.calendario.setValue(LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(receitaCriada.getDataOcorrencia()) ));
}
return pane;
}
public Receita getReceitaCriada() {
return receitaCriada;
}
}
| true |
ed5a886d5cb2e8d6fcbf4a8202f634d4a0fb4bda | Java | huntertran/soen6441-riskgame | /src/main/java/soen6441riskgame/models/ModelCommandsPair.java | UTF-8 | 1,439 | 3.375 | 3 | [] | no_license | package soen6441riskgame.models;
import java.util.ArrayList;
import java.util.List;
/**
* a pair of command and params
*
* <p>this model only accept a pair of params for each command, which is create a hard code into the
* source
*/
public class ModelCommandsPair {
public String param;
public String value1;
public String value2 = "";
/**
* constructor
*
* @param newParam command
* @param newValue1 value 1
* @param newValue2 value 2
*/
public ModelCommandsPair(String newParam, String newValue1, String newValue2) {
this.param = newParam.trim();
this.value1 = newValue1.trim();
this.value2 = newValue2.trim();
}
/**
* a second type with only 1 value
*
* @param newParam command
* @param newValue1 value 1
*/
public ModelCommandsPair(String newParam, String newValue1) {
this.param = newParam.trim();
this.value1 = newValue1.trim();
}
/**
* convert back to string
*
* @return the original string
*/
public String[] toStringArray() {
List<String> retList = new ArrayList<String>();
retList.add(this.param);
if (!this.value1.isEmpty()) {
retList.add(this.value1);
}
if (!this.value2.isEmpty()) {
retList.add(this.value2);
}
return retList.toArray(new String[retList.size()]);
}
}
| true |
2f1f91e3c10543c46289bfe2148b3778b7ef3d5e | Java | xy-platform/rfid | /rfid-bri/src/main/java/br/com/devsource/rfid/bri/GpiDispatcher.java | UTF-8 | 1,520 | 2.546875 | 3 | [] | no_license | package br.com.devsource.rfid.bri;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Consumer;
import com.intermec.datacollection.rfid.BasicReaderException;
import com.intermec.datacollection.rfid.GPITrigger;
import com.intermec.datacollection.rfid.TriggerEvent;
import br.com.devsource.rfid.api.gpio.GpiHandler;
import br.com.devsource.rfid.api.gpio.GpioStatus;
/**
* @author guilherme.pacheco
*/
public final class GpiDispatcher {
private final BriReaderBuilder builder;
private final Map<Integer, GpiHandler> handlers;
public GpiDispatcher(BriReaderBuilder builder) {
handlers = new HashMap<>();
this.builder = builder;
}
public void add(int number, GpiHandler handler, GpioStatus status) {
try {
GPITrigger trigger = GpiUtils.gpiTrigger(number, status);
builder.get().setGPITrigger(trigger);
handlers.put(number, handler);
} catch (BasicReaderException ex) {
throw new IllegalArgumentException("Não foi possível adicionar gatliho GPI: " + number);
}
}
public void remove(int number) {
handlers.remove(number);
}
public void call(TriggerEvent event) {
int number = Integer.valueOf(event.getTriggerName());
handlers.entrySet().stream().filter(e -> e.getKey() == number).forEach(callTrigger(event));
}
public Consumer<Entry<Integer, GpiHandler>> callTrigger(TriggerEvent event) {
return entry -> entry.getValue().onEvent(GpiUtils.gpiEvent(entry.getKey(), event));
}
}
| true |
724c9e681e321abb4e043e974e4fb5a6bf82d85c | Java | dzenya-7/electricalLearningApp | /app/src/main/java/net/vrgsoft/rollinglayoutmanager/CurrentActivity.java | UTF-8 | 3,401 | 2.328125 | 2 | [] | no_license | package net.vrgsoft.rollinglayoutmanager;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.util.Arrays;
public class CurrentActivity extends AppCompatActivity {
int wrap = LinearLayout.LayoutParams.WRAP_CONTENT;
LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current);
linearLayout = findViewById(R.id.linear_layout);
Intent intent = getIntent();
getSupportActionBar().setTitle(intent.getStringExtra("title"));
int string_res = intent.getIntExtra("strings",0);
int int_res = intent.getIntExtra("ints",0);
String[] ints = getResources().getStringArray(int_res);
String[] strings = getResources().getStringArray(string_res);
LinearLayout.LayoutParams layoutParams;
int[] before = getResources().getIntArray(intent.getIntExtra("before",0));
int j=0;
try{
for(int i=0;i<strings.length;i++){
if(found(before,i)){
if(j<before.length){
ImageView imageView = new ImageView(this);
Drawable drawable = getDrawable(getResources().getIdentifier(ints[j], "drawable", getPackageName()));
imageView.setImageDrawable(drawable);
imageView.setPadding(0, 0, 0, 0);
layoutParams = new LinearLayout.LayoutParams(600, 400);
layoutParams.topMargin = 0;
layoutParams.bottomMargin = 0;
layoutParams.gravity = Gravity.CENTER;
linearLayout.addView(imageView, layoutParams);
j++;
}
}
TextView textView = new TextView(this);
textView.setText(strings[i]);
textView.setPadding(50,10,50,10);
textView.setTextColor(Color.BLACK);
layoutParams = new LinearLayout.LayoutParams(wrap,wrap);
layoutParams.gravity = Gravity.CENTER;
Log.println(Log.ERROR,"Message",Integer.toString(i));
linearLayout.addView(textView,layoutParams);
}
}
catch (Exception e){
}
}
public boolean found(int[] array, int x){
int a= Arrays.binarySearch(array,x);
if(a==-1){
return false;
}
else{
return true;
}
}
} | true |
4d2aa674023f9947144febff53749368e6532554 | Java | fajarnugrohoid/filterisasi | /src/main/java/com/filterisasi/filterisasi/repository/PpdbRegistrationRepositoryImpl.java | UTF-8 | 3,275 | 2.0625 | 2 | [] | no_license | package com.filterisasi.filterisasi.repository;
import com.filterisasi.filterisasi.dto.PpdbOption;
import com.filterisasi.filterisasi.dto.PpdbRegistration;
import com.mongodb.bulk.BulkWriteResult;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import static org.springframework.data.mongodb.core.query.Criteria.where;
@Service
public class PpdbRegistrationRepositoryImpl implements PpdbRegistrationRepository {
private final MongoTemplate mongoTemplate;
@Autowired
public PpdbRegistrationRepositoryImpl(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
private MatchOperation getMatchOperation(float minPrice, float maxPrice) {
Criteria priceCriteria = where("price").gt(minPrice).andOperator(where("price").lt(maxPrice));
return match(priceCriteria);
}
public List<PpdbRegistration> getByFirstChoice(ObjectId firstChoice) {
System.out.println("getPpdbRegistrations");
Query query = new Query();
query.addCriteria(Criteria.where("jenjang_pendaftaran").is("vocational")
.andOperator(Criteria.where("first_choice").is(firstChoice))
//.andOperator(Criteria.where("first_choice").lt(upperBound))
).with(
Sort.by(Sort.Direction.DESC, "skor_peserta").
and(Sort.by(Sort.Direction.ASC, "score_jarak_1"))
);
return mongoTemplate.find(query, PpdbRegistration.class);
}
@Override
public int updateAcceptedStudent(List<PpdbOption> ppdbOptions, int optIdx) {
BulkOperations ops = mongoTemplate.bulkOps(BulkOperations.BulkMode.ORDERED, PpdbRegistration.class);
for (int stdIdx = 0; stdIdx <ppdbOptions.get(optIdx).getPpdbRegistrationList().size() ; stdIdx++) {
Update update = new Update();
update.set("accepted_choice_no", ppdbOptions.get(optIdx).getPpdbRegistrationList().get(stdIdx).getAcceptedOptionNo());
update.set("accepted_choice_id", ppdbOptions.get(optIdx).getPpdbRegistrationList().get(stdIdx).getAcceptedOptionId());
ops.updateOne(Query.query(where("_id").is(ppdbOptions.get(optIdx).getPpdbRegistrationList().get(stdIdx).get_id())), update);
}
BulkWriteResult x = ops.execute();
return x.getModifiedCount();
}
}
| true |
eb1a71d27d4a03f3d65f1a39b9bf3866dd40a32a | Java | rajeshtalreja/CSVGraphGenerator | /CSVGraphGenerator/src/com/csvgenerator/csvprocessor/CSVRecordCache.java | UTF-8 | 729 | 2.71875 | 3 | [] | no_license | package com.csvgenerator.csvprocessor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
*/
/**
* @author Rajesh
*
*/
public class CSVRecordCache {
private static Map<String,List<CSVRecord>> csvCache = new HashMap<>();
public static List<CSVRecord> getCSVRecordList(String ticker){
if(ticker != null){
return csvCache.get(ticker);
}
return null;
}
public static void put(String ticker , List<CSVRecord> csvRecords){
csvCache.put(ticker, csvRecords);
}
public static Set<String> getCacheKeys(){
return csvCache.keySet();
}
/**
*
*/
public static void clearCache(){
csvCache.clear();
}
}
| true |
5039ae432b8f8de31e2d419be9cba770e16d5b47 | Java | Kiddinglife/CRAPS-Kernel | /Utils/SHDL2VHDL/src/org/jcb/shdl/UnivGateLabel.java | UTF-8 | 1,960 | 2.484375 | 2 | [] | no_license |
package org.jcb.shdl;
import java.util.*;
import java.awt.*;
import java.awt.geom.*;
import org.jcb.shdl.*;
// equaation label associated to a universal gate
public class UnivGateLabel extends ModuleLabel {
private CompoundModule compModule;
private UniversalGate ug;
private String text = "S=/A+B";
public UnivGateLabel(CompoundModule compModule, UniversalGate ug, Point2D relLoc) {
super(relLoc);
this.compModule = compModule;
this.ug = ug;
}
public UniversalGate getUnivGate() {
return ug;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Color getTextColor() {
return Module.labelColor;
}
public Color getBackgroundColor() {
return Module.labelBackgroundColor;
}
public Color getFrameColor() {
return Module.labelFrameColor;
}
public Point2D getAnchorLocation() {
return compModule.getSubModuleLocation(ug.getId());
}
public RoundRectangle2D getRect(Point2D anchorLoc) {
float width = (float) Module.widthFontMetrics.stringWidth(getText()) + 6.f;
float height = (float) Module.widthFontMetrics.getHeight();
return new RoundRectangle2D.Double(anchorLoc.getX() + relLoc.getX(), anchorLoc.getY() + relLoc.getY() - height / 2.0, width, height, 4.0, 4.0);
}
public void paint(Graphics2D g2) {
String str = getText();
Point2D loc = getAnchorLocation();
// draw label line
RoundRectangle2D rect = getRect(loc);
g2.setStroke(Module.labelLineStroke);
g2.setPaint(Module.labelLineColor);
g2.draw(new Line2D.Double(loc.getX(), loc.getY(), rect.getX() + rect.getWidth() / 2., rect.getY() + rect.getHeight() / 2.0));
// draw name into background color rectangle
g2.setPaint(Module.backgroundColor);
g2.fill(rect);
g2.setPaint(Module.universalGateTextColor);
g2.setFont(Module.universalGateTextFont);
g2.drawString(str, (float) rect.getX(), (float) (rect.getY() + Module.universalGateTextFontMetrics.getAscent()));
}
}
| true |
f4e4373542b1cf44e370dcb918f9d8fc58b73dd9 | Java | RobertMoralesO/personas_material_2021_1 | /app/src/main/java/com/example/personas20211/DetallePersona.java | UTF-8 | 2,506 | 2.125 | 2 | [] | no_license | package com.example.personas20211;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
public class DetallePersona extends AppCompatActivity {
private ImageView foto;
private TextView cedula, nombre, apellido;
private Bundle bundle;
private Intent intent;
private StorageReference storageReference;
private Persona p;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detalle_persona);
String ced, nomb, apell, id;
foto = findViewById(R.id.imgFotoDetalle);
cedula = findViewById(R.id.lblCedulaDetalle);
nombre = findViewById(R.id.lblNombreDetalle);
apellido = findViewById(R.id.lblApellidoDetalle);
intent = getIntent();
bundle = intent.getBundleExtra("datos");
id = bundle.getString("id");
ced = bundle.getString("cedula");
nomb = bundle.getString("nombre");
apell = bundle.getString("apellido");
p = new Persona(ced, nomb, apell, id);
cedula.setText(ced);
nombre.setText(nomb);
apellido.setText(apell);
storageReference = FirebaseStorage.getInstance().getReference();
storageReference.child(id).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(foto);
}
});
}
public void Eliminar(View v){
String positivo, negativo;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.mensaje_eliminar);
builder.setMessage(R.string.pregunta_eliminar_persona);
positivo = getString(R.string.mensaje_si);
negativo = getString(R.string.mensaje_no);
builder.setPositiveButton(positivo, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
p.eliminar();
onBackPressed();
}
});
builder.setNegativeButton(negativo, null);
AlertDialog dialog = builder.create();
dialog.show();
}
public void onBackPressed(){
finish();
Intent intent = new Intent(DetallePersona.this, MainActivity.class);
}
}
| true |
6233cf4047e0536080d2df3d1cd9848238de0b15 | Java | ffs1985/MyBakingApp | /app/src/main/java/com/ffs1985/mybakingapp/MainActivity.java | UTF-8 | 2,783 | 2.046875 | 2 | [] | no_license | package com.ffs1985.mybakingapp;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.test.espresso.IdlingResource;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import com.ffs1985.mybakingapp.adapters.RecipesAdapter;
import com.ffs1985.mybakingapp.data.RecipesUtil;
import com.ffs1985.mybakingapp.model.Recipe;
import com.ffs1985.mybakingapp.model.RecipesViewModel;
import com.ffs1985.mybakingapp.util.BasicIdlingResource;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecipesAdapter.RecipesAdapterOnClickHandler{
private List<Recipe> recipeList;
private RecyclerView mRecyclerView;
private RecipesAdapter mRecipesAdapter;
private static final String recipeId = "recipe_id";
private RecipesViewModel recipesViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recyclerview_recipes);
boolean isTablet = getResources().getBoolean(R.bool.isTablet);
if (isTablet) {
GridLayoutManager listLayoutManager = new GridLayoutManager(this,3);
mRecyclerView.setLayoutManager(listLayoutManager);
} else {
LinearLayoutManager listLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(listLayoutManager);
}
mRecipesAdapter = new RecipesAdapter(this);
mRecyclerView.setAdapter(mRecipesAdapter);
recipesViewModel = RecipesViewModel.getInstance();
recipesViewModel.addObserver(mRecipesAdapter);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public void onClick(Recipe recipe) {
Context context = this;
Class destinationClass = RecipeActivity.class;
Intent intentToStartRecipeActivity = new Intent(context, destinationClass);
intentToStartRecipeActivity.putExtra(recipeId, recipe.getId());
recipesViewModel.loadRecipe(recipe.getId());
recipesViewModel.removeObserver(mRecipesAdapter);
startActivity(intentToStartRecipeActivity);
}
@VisibleForTesting
@NonNull
public IdlingResource getIdlingResource() {
return recipesViewModel.getIdlingResource();
}
}
| true |
1e471251e9d2e0f5b1f1554a95e63f97520bc3bb | Java | franplk/xtable | /src/main/java/com/emar/xreport/web/dao/DataDao.java | UTF-8 | 2,435 | 2.296875 | 2 | [] | no_license | package com.emar.xreport.web.dao;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import com.emar.xreport.web.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.emar.xreport.cache.DataCacheService;
import com.emar.xreport.util.crypt.MD5Encrypt;
import com.emar.xreport.exception.BusinessException;
import com.emar.xreport.util.log.LogUtil;
import com.emar.xreport.query.ModelUtil;
import com.emar.xreport.query.domain.SQLQuery;
import com.emar.xreport.web.domain.JTableData;
/**
* @author franplk 2016.07.11
*/
@Repository
public class DataDao extends BaseDao {
@Resource(name="dataTemplate")
private JdbcTemplate dataTemplate;
@Autowired
private DataCacheService dataCacheService;
/**
* Organize The Table Data
*/
public JTableData getTableData(SQLQuery query) {
// Total Records And Summary
Map<String, Object> sumAndCountData = getSumAndCount(query);
long records = (long) sumAndCountData.get("records");
// DataList
List<Map<String, Object>> dataList = getRowList(query);
JTableData tableData = new JTableData();
tableData.setTotal(records);
tableData.addSum(sumAndCountData);
tableData.setRows(dataList);
return tableData;
}
/**
* Get Sum And Count
*/
public Map<String, Object> getSumAndCount(SQLQuery query) {
String sql = ModelUtil.getSumAndCountSQL(query);
LogUtil.info("Sum And Count SQL:" + sql, LogUtil.TYPE_QUERY);
try {
String sqlKey = MD5Encrypt.encrypt(sql);
Map<String, Object> data = dataCacheService.getDataMap(sqlKey);
if (null == data) {
data = dataTemplate.queryForMap(sql);
dataCacheService.put(sqlKey, data);
}
return data;
} catch (Exception e) {
throw new BusinessException("QueryFailed[sql=" + sql + "]");
}
}
/**
* Get Data
*/
public List<Map<String, Object>> getRowList(SQLQuery query) {
String sql = ModelUtil.getListSql(query);
LogUtil.info("List SQL:" + sql, LogUtil.TYPE_QUERY);
try {
String sqlKey = MD5Encrypt.encrypt(sql);
List<Map<String, Object>> datas = dataCacheService.getDataList(sqlKey);
if (null == datas) {
datas = dataTemplate.queryForList(sql);
dataCacheService.put(sqlKey, datas);
}
return datas;
} catch (Exception e) {
throw new BusinessException("QueryFailed[sql=" + sql + "]");
}
}
}
| true |
0d6770acf22e6912b2af177412a4efd9e76e6854 | Java | danilproger/LabsJava | /Lab2/src/main/java/calculator/operator/Push.java | UTF-8 | 738 | 2.984375 | 3 | [] | no_license | package calculator.operator;
import context.Context;
import java.util.List;
import java.util.logging.Logger;
public class Push implements Operator {
@Override
public void execute(Context context, List<String> args) {
if(args.size() < 1) throw new IllegalArgumentException();
double value;
try {
value = Double.parseDouble(args.get(0));
} catch (NumberFormatException e) {
try {
value = context.get(args.get(0));
} catch (NullPointerException ex) {
throw new IllegalArgumentException();
}
}
context.push(value);
Logger.getLogger("CalculatorLogger").info("pushed value = " + value);
}
} | true |
012e0034566ab7c415b31d57f953ccf003eba537 | Java | Gideon-1999/Hal-QPay-Android | /app/src/main/java/com/haltechbd/app/android/qpay/utils/GetResponse.java | UTF-8 | 4,962 | 2.1875 | 2 | [] | no_license | package com.haltechbd.app.android.qpay.utils;
import android.util.Log;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class GetResponse {
// Method retrieving MYCash Server Response
// Method retrieving MYCash Server Response
// Method retrieving MYCash Server Response
public static String getResponse(String strEncryptMitUserName, String strEncryptMitPin, String strEncryptReferenceId, String strMasterKey) {
String METHOD_NAME = "QPAY_GetResponse";
String SOAP_ACTION = "http://www.bdmitech.com/m2b/QPAY_GetResponse";
SoapObject request = new SoapObject(GlobalData.getStrNamespace().replaceAll(" ","%20"), METHOD_NAME);
// AccountNo:
// PIN:
// RefID:
// strMasterKey:
// Declare the version of the SOAP request
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
PropertyInfo encryptMitUserName = new PropertyInfo();
encryptMitUserName.setName("AccountNo");
encryptMitUserName.setValue(strEncryptMitUserName);
encryptMitUserName.setType(String.class);
request.addProperty(encryptMitUserName);
PropertyInfo encryptMitPin = new PropertyInfo();
encryptMitPin.setName("PIN");
encryptMitPin.setValue(strEncryptMitPin);
encryptMitPin.setType(String.class);
request.addProperty(encryptMitPin);
PropertyInfo encryptReferenceId = new PropertyInfo();
encryptReferenceId.setName("RefID");
encryptReferenceId.setValue(strEncryptReferenceId);
encryptReferenceId.setType(String.class);
request.addProperty(encryptReferenceId);
PropertyInfo masterKey = new PropertyInfo();
masterKey.setName("strMasterKey");
masterKey.setValue(strMasterKey);
masterKey.setType(String.class);
request.addProperty(masterKey);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
Log.v("myApp:", request.toString());
envelope.implicitTypes = true;
Object objMyCashResponse = null;
String strMyCashResponse = "";
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(GlobalData.getStrUrl().replaceAll(" ","%20"), 1000);
androidHttpTransport.call(SOAP_ACTION, envelope);
objMyCashResponse = envelope.getResponse();
strMyCashResponse = objMyCashResponse.toString();
Log.v("MyCashResponse: ", strMyCashResponse);
if (strMyCashResponse.equalsIgnoreCase("0001")) {
strMyCashResponse = "Request Submit successfully";
} else if (strMyCashResponse.equalsIgnoreCase("0002")) {
strMyCashResponse = "Transaction failed";
} else if (strMyCashResponse.equalsIgnoreCase("0003")) {
strMyCashResponse = "Wallet Id is not correct format";
} else if (strMyCashResponse.equalsIgnoreCase("0004")) {
strMyCashResponse = "Not a Customer Wallet";
} else if (strMyCashResponse.equalsIgnoreCase("0005")) {
strMyCashResponse = "If user name and password is incorrect";
} else if (strMyCashResponse.equalsIgnoreCase("0006")) {
strMyCashResponse = "Customer Wallet/PIN No. Not Correct";
} else if (strMyCashResponse.equalsIgnoreCase("0007")) {
strMyCashResponse = "OTP is expired";
} else if (strMyCashResponse.equalsIgnoreCase("0008")) {
strMyCashResponse = "Merchant is not correct";
} else if (strMyCashResponse.equalsIgnoreCase("0009")) {
strMyCashResponse = "Not enough balance";
} else if (strMyCashResponse.equalsIgnoreCase("0010")) {
strMyCashResponse = "Unauthorized Domain";
} else if (strMyCashResponse.equalsIgnoreCase("0011")) {
strMyCashResponse = "Technical Error";
} else if (strMyCashResponse.equalsIgnoreCase("0012")) {
strMyCashResponse = "Request ID is not correct";
} else if (strMyCashResponse.equalsIgnoreCase("0013")) {
strMyCashResponse = "Unauthorized terminal";
} else if (strMyCashResponse.equalsIgnoreCase("0024")) {
strMyCashResponse = "Excceds Funds Available";
} else if (strMyCashResponse.equalsIgnoreCase("0050")) {
strMyCashResponse = "Request Time out";
} else {
strMyCashResponse = objMyCashResponse.toString();
}
} catch (Exception exception) {
Log.e("MyCashResponse: ", "Error!!!");
strMyCashResponse = "Error!!!";
}
return strMyCashResponse;
}
}
| true |
a1a6de25224073ccd1ae0484db6bad1d8e7e4b4e | Java | programmerr47/vk-mobile-challenge | /app/src/main/java/com/github/programmerr47/vkgroups/adapter/item/FriendsCommunityItem.java | UTF-8 | 1,055 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | package com.github.programmerr47.vkgroups.adapter.item;
import com.github.programmerr47.vkgroups.R;
import com.vk.sdk.api.model.VKApiCommunityFull;
import static com.github.programmerr47.vkgroups.utils.AndroidUtils.res;
/**
* @author Michael Spitsin
* @since 2016-01-20
*/
public final class FriendsCommunityItem extends CommunityItem {
private int friendsCount;
private String cachedFriendCountString;
public FriendsCommunityItem(VKApiCommunityFull community) {
this(community, 1);
}
public FriendsCommunityItem(VKApiCommunityFull community, int friendsCount) {
super(community);
setFriendsCount(friendsCount);
}
public void addFriend() {
setFriendsCount(friendsCount + 1);
}
@Override
protected String getTextForSubInfoView() {
return cachedFriendCountString;
}
private void setFriendsCount(int friendsCount) {
this.friendsCount = friendsCount;
this.cachedFriendCountString = res().plural(R.plurals.friends, friendsCount, friendsCount);
}
}
| true |
fac75104c8529a4efa845ea477978ae7427e6f3e | Java | ivilqna/Shop | /TestMyProcect.java | UTF-8 | 225 | 2.109375 | 2 | [] | no_license | import java.io.IOException;
public class TestMyProcect {
public static void main(String[] args) throws IOException, InterruptedException
{
MyFrame frame = new MyFrame();
frame.construct();
}
}
| true |
2e2f5ffc88feefe32c05b8d99fcf526b06795300 | Java | weixinkeji/JWebPower | /src/main/java/weixinkeji/vip/jweb/power/model/JWPType.java | UTF-8 | 551 | 1.789063 | 2 | [] | no_license | package weixinkeji.vip.jweb.power.model;
/**
* 控制路径 的权限类型
*/
public enum JWPType {
/**
* 放行区
*/
common
/**
* 会话区
*/
,session
/**
* 等级区(提交锁定是会话区之后)
*/
,grades
/**
* 编号区(提交锁定是会话区之后)
*/
,code
/**
* 等级区+编号区(提交锁定是会话区之后)
*/
,gradesAndCode
/**
* 仅仅有监听(提交锁定是会话区之后)
*/
,onlyListen
/**
* 未知
*/
,unknow
;
}
| true |
6e422f2a7bbd193b8c5dd16ea9e8a78da9a350de | Java | Muthu2093/Algorithms-practice | /445. Add Two Numbers II.Java | UTF-8 | 2,360 | 3.90625 | 4 | [
"MIT"
] | permissive | /**
* You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
* You may assume the two numbers do not contain any leading zero, except the number 0 itself.
* Follow up:
* What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
* Example:
* Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 8 -> 0 -> 7
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int len1 = findListLength(l1);
int len2 = findListLength(l2);
ListNode result = addTwoNumbersRec(l1, l2, len1, len2);
return result.val == 0 ? result.next : result;
}
public int findListLength(ListNode head){
ListNode fast = head;
int count = 0;
while (fast != null && fast.next != null){
head = head.next;
fast = fast.next.next;
count++;
}
count = count*2;
if(fast != null){
count += 1;
}
return count;
}
public ListNode addTwoNumbersRec (ListNode l1, ListNode l2, int len1, int len2) {
ListNode res = new ListNode(0);
if (l1 == null && l2 == null){
return res;
}
int a = l1.val, b = l2.val;
if (len1 > len2){
res.next = addTwoNumbersRec (l1.next, l2, --len1, len2);
res.next.val += l1.val;
if (res.next.val > 9){
res.next.val %= 10;
res.val += 1;
}
}
else if (len1 < len2){
res.next = addTwoNumbersRec (l1, l2.next, len1 , --len2);
res.next.val += l2.val;
if (res.next.val > 9){
res.next.val %= 10;
res.val += 1;
}
}
else{
res.next = addTwoNumbersRec (l1.next, l2.next, --len1, --len2);
res.next.val += l1.val + l2.val;
if (res.next.val > 9){
res.next.val %= 10;
res.val += 1;
}
}
return res;
}
}
| true |
c54bfee9008563732bf9b62e9412b7793437b2d0 | Java | MayanTiwari/hrankproblems | /src/main/java/hrank/TimeConversion.java | UTF-8 | 760 | 3.0625 | 3 | [] | no_license | package hrank;
import java.util.Scanner;
public class TimeConversion {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// String time = in.next();
String time = "07:05:45PM";
StringBuilder out = new StringBuilder(time);
if (!time.isEmpty()) {
Integer temp = 0;
if (time.substring(8, 10).equals("PM")) {
temp = Integer.parseInt(time.substring(0, 2));
if (temp != 12)
temp = Integer.parseInt(time.substring(0, 2)) + 12;
out.replace(0, 2, Integer.toString(temp));
} else if (time.substring(8, 10).equals("AM")) {
temp = Integer.parseInt(time.substring(0, 2));
if (temp == 12)
out.replace(0, 2, "00");
}
out.setLength(out.length() - 2);
System.out.println(out);
}
}
}
| true |
3b4a330a00d5b04668f44ffe0a420e6112ef4be2 | Java | meteor12138/ssmDemo | /main/java/com/met/dao/SuccessKilledDao.java | UTF-8 | 723 | 2.265625 | 2 | [] | no_license | package com.met.dao;
import com.met.entity.SuccessKilled;
import com.met.enums.SeckillStateEnum;
import org.apache.ibatis.annotations.Param;
public interface SuccessKilledDao {
/**
* 插入购买明细,可以过滤重复
*
* @param seckillId
* @param userPhone
* @return 插入的行数
*/
int insertSuccessKilled(@Param("seckillId") long seckillId, @Param("userPhone")long userPhone, @Param("state") int state);
/**
* 根据id查询successKilled并携带秒杀产品对象实体
*
* @param seckillId
* @return 成功秒杀的记录
*/
SuccessKilled queryByIdWithSeckill(@Param("seckillId") long seckillId, @Param("userPhone")long userPhone);
}
| true |
025ea574850c57eba280e662a8b7b822062eea0e | Java | mayank98108/DataStructureJava | /02.Arrays/HotelBooking.java | UTF-8 | 841 | 3.375 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.Collections;
public class HotelBooking {
public static void main(String[] args) {
ArrayList<Integer> arrive = new ArrayList<>();
ArrayList<Integer> depart = new ArrayList<>();
arrive.add(1);
arrive.add(3);
arrive.add(5);
depart.add(2);
depart.add(6);
depart.add(8);
int K = 3;
boolean r = hotel(arrive,depart, K);
System.out.println(r);
}
public static boolean hotel(ArrayList<Integer> arrive, ArrayList<Integer> depart, int K) {
Collections.sort(arrive);
Collections.sort(depart);
for(int i = 0 ; i < arrive.size() ; i++) {
if (i + K < arrive.size() && arrive.get(i + K) < depart.get(i))
return false;
}
return true;
}
}
| true |
622184c10eb65db6783b7491a5195c4e1251e859 | Java | greenomsk/codingtest | /src/main/java/com/green/codingtest/srp/service/strategy/GameStrategyFactory.java | UTF-8 | 398 | 2.28125 | 2 | [] | no_license | package com.green.codingtest.srp.service.strategy;
/**
* <h2>class GameStrategyFactory</h2>
*
* Factory pattern providing with {@link GameStrategy}
*
* @author <a href="mailto:greenomsk@gmail.com">Andrey Grinenko</a>
* @since 25.07.2019
*/
public interface GameStrategyFactory {
/**
* Provides with {@link GameStrategy}
* @return {@link GameStrategy}
*/
GameStrategy getGameStrategy();
}
| true |
91752e156ccc246815fc8058462206fd72ce95e4 | Java | RJaco1/Supermercado | /app/src/main/java/dao/UsuarioDAO.java | UTF-8 | 123 | 1.882813 | 2 | [] | no_license | package dao;
import modelo.Usuario;
public interface UsuarioDAO extends CRUD<Usuario> {
Usuario login(Usuario us);
}
| true |
e128ec2ee31fdc172f453456fb4d39cb44f028b0 | Java | answes/SmartLights | /app/src/main/java/com/bigshark/smartlight/pro/mine/view/MyOrderFragment.java | UTF-8 | 9,278 | 1.78125 | 2 | [] | no_license | package com.bigshark.smartlight.pro.mine.view;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.bigshark.smartlight.R;
import com.bigshark.smartlight.SmartLightsApplication;
import com.bigshark.smartlight.bean.OrderResult;
import com.bigshark.smartlight.mvp.presenter.impl.MVPBasePresenter;
import com.bigshark.smartlight.pro.base.presenter.BasePresenter;
import com.bigshark.smartlight.pro.base.view.BaseFragment;
import com.bigshark.smartlight.pro.market.view.PayActivity;
import com.bigshark.smartlight.pro.mine.presenter.MinePresenter;
import com.bigshark.smartlight.pro.mine.view.adapter.BaseOrderAdapter;
import com.bigshark.smartlight.utils.JSONUtil;
import com.bigshark.smartlight.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import static android.app.Activity.RESULT_OK;
/**
* Created by jlbs1 on 2017/5/16.
*/
public class MyOrderFragment extends BaseFragment {
private final int QRSH = 0;
private final int QRQX = 1;
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@BindView(R.id.rv_content)
RecyclerView rvContent;
@BindView(R.id.xrefreshview)
XRefreshView xrefreshview;
private BaseOrderAdapter adapter;
private MinePresenter presenter;
private List<OrderResult.Order> orderDatas = new ArrayList<>();
@Override
public int getContentView() {
return R.layout.fragment_mine_order;
}
@Override
public void initContentView(View viewContent) {
ButterKnife.bind(this, viewContent);
initView();
}
private void initView() {
loadDatas(true, getType());
xrefreshview.setPullRefreshEnable(true);
// 设置是否可以上拉加载
xrefreshview.setPullLoadEnable(true);
// 设置刷新完成以后,headerview固定的时间
xrefreshview.setPinnedTime(1000);
// 静默加载模式不能设置footerview
// 设置支持自动刷新
xrefreshview.setAutoLoadMore(true);
//设置静默加载时提前加载的item个数
// xRefreshView.setPreLoadCount(2);
rvContent.setHasFixedSize(true);
rvContent.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new BaseOrderAdapter(getActivity(), orderDatas);
rvContent.setAdapter(adapter);
adapter.setCustomLoadMoreView(new XRefreshViewFooter(getContext()));
xrefreshview.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
@Override
public void onRefresh() {
loadDatas(true, getType());
}
@Override
public void onLoadMore(boolean isSlience) {
loadDatas(false, getType());
}
});
adapter.setItemOnClickListener(new BaseOrderAdapter.ItemOnClickListener() {
@Override
public void onItemClick(View view, int postion) {
OrderResult orderResult = new OrderResult();
OrderResult.Order order = orderDatas.get(postion);
List<OrderResult.Order> orders = new ArrayList<>();
orders.add(order);
switch (view.getId()) {
case R.id.bt_logistics:
if ("0".equals(order.getStatus())) {
showDialog("是否取消该订单", QRQX,order);
} else if ("1".equals(order.getStatus()) || "2".equals(order.getStatus())) {
//查看物流。
ToastUtil.showToast(getContext(), "暂时无法查看物流");
}
return;
case R.id.bt_receipt:
if ("0".equals(order.getStatus())) {
orderResult.setData(orders);
PayActivity.openPayActivity(getActivity(), orderResult);
} else if ("1".equals(order.getStatus()) || "2".equals(order.getStatus())) {
showDialog("是否确认收到货", QRSH,order);
}
return;
}
OrderDetailActivity.openOrderDetailActivityForResult(getActivity(), Integer.parseInt(orderDatas.get(postion).getId()));
}
});
}
private void showDialog(String message, final int type, final OrderResult.Order order) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity()).setMessage(message)
.setPositiveButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).setNegativeButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (type == QRQX) {
upOrderStatu(order.getId(), -1, 1);
} else if (type == QRSH) {
upOrderStatu(order.getId(), 3, 1);
}
}
});
alertDialog.show();
}
/**
* @param statu 1:款之后,-1:取消订单,3:确认收货
* @param payType 1:支付宝,2:微信
*/
private void upOrderStatu(String orderid, int statu, int payType) {
presenter.upOrderStatu(Integer.parseInt(orderid), statu, payType, new BasePresenter.OnUIThreadListener<Integer>() {
@Override
public void onResult(Integer result) {
if (result == 1) {
loadDatas(true, getType());
ToastUtil.showToast(getActivity(), "修改成功");
} else {
ToastUtil.showToast(getActivity(), "修改失败");
}
}
@Override
public void onErro(String string) {
}
});
}
int page = 1;
private void loadDatas(final boolean isDownRefresh, final String type) {
if(isDownRefresh){
page = 1;
}else{
page++;
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://pybike.idc.zhonxing.com/Order/orderlist",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
OrderResult orderResult = JSONUtil.getObject(response, OrderResult.class);
if (isDownRefresh) {
xrefreshview.stopRefresh();
} else {
xrefreshview.stopLoadMore();
}
if (null != orderResult) {
if (null != orderResult.getData() && orderResult.getData().size() != 0) {
if(isDownRefresh){
orderDatas.clear();
}
orderDatas.addAll(orderResult.getData());
adapter.notifyDataSetChanged();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("user_id", SmartLightsApplication.USER.getId());
map.put("p", String.valueOf(page));
if(!"-1".equals(type)){
map.put("status", type);
}
return map;
}
};
SmartLightsApplication.queue.add(stringRequest);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
loadDatas(true, getType());
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
public MVPBasePresenter bindPresenter() {
presenter = new MinePresenter(getActivity());
return presenter;
}
}
| true |
a2edd4ec03f12239c01a3e478421706e4a424c0b | Java | skroutz/elasticsearch-skroutz-greekstemmer | /src/main/java/org/elasticsearch/index/analysis/SkroutzGreekStemmerTokenFilterFactory.java | UTF-8 | 830 | 1.851563 | 2 | [] | no_license | package org.elasticsearch.index.analysis;
import java.io.IOException;
import org.apache.lucene.analysis.TokenStream;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.assistedinject.Assisted;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.IndexSettings;
public class SkroutzGreekStemmerTokenFilterFactory extends
AbstractTokenFilterFactory {
@Inject
public SkroutzGreekStemmerTokenFilterFactory(IndexSettings indexSettings,
Environment env, @Assisted String name,
@Assisted Settings settings) throws IOException {
super(indexSettings, name, settings);
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new SkroutzGreekStemTokenFilter(tokenStream);
}
} | true |
4db8ae0c4f1f3adf09444f66a30ae60cdef6bc25 | Java | bullship/BullSheepFood-android | /app/src/main/java/com/bullsheep/bullsheepfood_android/model/FoodResponse.java | UTF-8 | 336 | 1.984375 | 2 | [] | no_license | package com.bullsheep.bullsheepfood_android.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class FoodResponse {
@SerializedName("food")
private Food food;
public Food getFood() {
return food;
}
public void setFood(Food food) {
this.food = food;
}
}
| true |
6b6d956964bba222bb5ed8bc849ea7c3e7160653 | Java | utkarshyadavin/Wireless-Net | /SocioCellular/src/SourceCode/Residual.java | UTF-8 | 2,905 | 2.25 | 2 | [] | no_license | package SourceCode;
public class Residual{
public static int RUNS;
public static void main(String [] args){
args = "./UE.txt ./BS.txt 500".split(" ");
RUNS = Integer.parseInt(args[2]);
String outPath = "./outPut/";
CdfHelper sinrZeroOperatorCollaborationCDF = new CdfHelper(2,-1, Params.CDF_STEP, outPath+"sinrZeroOperatorCollaboration");
CdfHelper sinrFullOperatorCollaborationCDF = new CdfHelper(2,-1, Params.CDF_STEP, outPath+"sinrFullOperatorCollaboration");
CdfHelper sinrPartialOperatorCollaborationCDF = new CdfHelper(2,-1, Params.CDF_STEP, outPath+"sinrPartialOperatorCollaboration");
CdfHelper sinrSocialOperatorCollaborationCDF = new CdfHelper(2,-1, Params.CDF_STEP, outPath+"sinrSocialOperatorCollaboration");
CdfHelper bitrateZeroOperatorCollaborationCDF = new CdfHelper(5, 0, Params.CDF_STEP, outPath+"bitrateZeroOperatorCollaboration");
CdfHelper bitrateFullOperatorCollaborationCDF = new CdfHelper(5, 0, Params.CDF_STEP, outPath+"bitrateFullOperatorCollaboration");
CdfHelper bitratePartialOperatorCollaborationCDF = new CdfHelper(5, 0, Params.CDF_STEP, outPath+"bitratePartialOperatorCollaboration");
CdfHelper bitrateSocialOperatorCollaborationCDF = new CdfHelper(5, 0, Params.CDF_STEP, outPath+"bitrateSocialOperatorCollaboration");
for(int i=1; i<=1; i++){
Simulation scenario = new Simulation();
scenario.init(args[0], args[1]);
scenario.associationRSRP();
scenario.printAllInfo(1);
sinrZeroOperatorCollaborationCDF.addCDFList(scenario.sinrZeroOperatorCollaboration);
bitrateZeroOperatorCollaborationCDF.addCDFList(scenario.bitrateZeroOperatorCollaboration);
sinrZeroOperatorCollaborationCDF.saveToFile();
bitrateZeroOperatorCollaborationCDF.saveToFile();
scenario.associationRSRPSocialPartialOperatorCollaboration();
scenario.printAllInfo(1);
sinrSocialOperatorCollaborationCDF.addCDFList(scenario.sinrSocialOperatorCollaboration);
bitrateSocialOperatorCollaborationCDF.addCDFList(scenario.bitrateSocialOperatorCollaboration);
sinrSocialOperatorCollaborationCDF.saveToFile();
bitrateSocialOperatorCollaborationCDF.saveToFile();
scenario.associationRSRPPartialOperatorCollaboration();
scenario.printAllInfo(1);
sinrPartialOperatorCollaborationCDF.addCDFList(scenario.sinrPartialOperatorCollaboration);
bitratePartialOperatorCollaborationCDF.addCDFList(scenario.bitratePartialOperatorCollaboration);
sinrPartialOperatorCollaborationCDF.saveToFile();
bitratePartialOperatorCollaborationCDF.saveToFile();
scenario.associationRSRPCollaboration();
scenario.printAllInfo(1);
sinrFullOperatorCollaborationCDF.addCDFList(scenario.sinrFullOperatorCollaboration);
bitrateFullOperatorCollaborationCDF.addCDFList(scenario.bitrateFullOperatorCollaboration);
sinrFullOperatorCollaborationCDF.saveToFile();
bitrateFullOperatorCollaborationCDF.saveToFile();
}
}
} | true |
25b4d1f542661477569ec01ca20eb602c491d717 | Java | XTGF49/javaLearning | /Java/java基础进阶代码/day4_1_shape/ShapeTest.java | UTF-8 | 1,179 | 3.28125 | 3 | [] | no_license | package day4_1_shape;
import java.util.*;
/**
* @Auther:sommer1111
* @date 2020/4/1 10:32
*/
public class ShapeTest {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(23);
arrayList.add(34);
arrayList.add("terry");
for(Object b:arrayList){
System.out.println(b);
}
HashMap<String, Integer> hashMap = new HashMap<String,Integer>();
hashMap.put("tom",32);
hashMap.put("jerry",22);
hashMap.put("xiaomi",12);
Set<Map.Entry<String, Integer>> set = hashMap.entrySet();
Iterator<Map.Entry<String, Integer>> iterator = set.iterator();
while(iterator.hasNext()){
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
int value = entry.getValue();
System.out.println(key+value);
}
ArrayList<String> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
ArrayList<?> list3 = new ArrayList<>();
list3=list1;
list3 = list1;
}
}
| true |
639768219d0a4f7da026885e30a58e2116783c4a | Java | nvthao-math/auc.server-monitor | /server-monitor/src/main/java/org/auc/core/utils/TimeUtils.java | UTF-8 | 2,304 | 2.625 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.auc.core.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.auc.core.file.utils.Logger;
/**
*
* @author thaonguyen
*/
public class TimeUtils {
private static final String TAG = TimeUtils.class.getSimpleName();
public static final SimpleDateFormat yyyy_MM_dd_HH = new SimpleDateFormat("yyyy-MM-dd-HH");
public static final SimpleDateFormat yyyy_MM_dd = new SimpleDateFormat("yyyy-MM-dd");
public static final SimpleDateFormat yyyyMMddHH = new SimpleDateFormat("yyyy/MM/dd/HH");
public static final SimpleDateFormat yyyyMMdd_HHmmss = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
public static final SimpleDateFormat yyyy_MM_dd_HHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String toString(Date date, SimpleDateFormat formatter) {
return formatter.format(date);
}
public static String toString(Date date) {
return yyyy_MM_dd_HH.format(date);
}
public static Date toTime(String str, SimpleDateFormat formatter) throws ParseException {
return formatter.parse(str);
}
public static Date toTime(String str) throws ParseException {
return yyyy_MM_dd_HH.parse(str);
}
public static String getHour(Date date) {
String hour = null;
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
hour = NumberUtils.leadingZeroFill(calendar.get(Calendar.HOUR_OF_DAY), 2);
} catch (Exception ex) {
Logger.error(TAG, ex);
}
return hour;
}
public static String asPath(String time) {
String path = null;
try {
Date date = TimeUtils.toTime(time);
path = new StringBuilder("day=")
.append(TimeUtils.toString(date, TimeUtils.yyyy_MM_dd))
.append("/hour=").append(TimeUtils.getHour(date))
.toString();
} catch (Exception ex) {
Logger.error(TAG, ex);
}
return path;
}
}
| true |
3d864c566ebdd747228841d987c7826d4aae1798 | Java | ngando59/gk-spring-mycatalog | /src/main/java/gk/ngando/mycatalog/produit/controller/ProduitController.java | WINDOWS-1252 | 2,307 | 2.109375 | 2 | [] | no_license | package gk.ngando.mycatalog.produit.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import gk.ngando.mycatalog.produit.business.IProduitBusiness;
import gk.ngando.mycatalog.produit.domain.Produit;
@Controller
public class ProduitController {
@Autowired
private IProduitBusiness business;
@RequestMapping(value = "/produit/produits")
private String produits(Model model) {
model.addAttribute("produit", new Produit());
model.addAttribute("produits", business.findAll());
return "produit/produits";
}
@RequestMapping(value = "/produit/edit/{id}")
public String edit(@PathVariable(value = "id") Long id, Model model) {
model.addAttribute("produit", business.findOneById(id));
model.addAttribute("produits", business.findAll());
return "produit/edit";
}
@RequestMapping(value = "/produit/save")
private String save(@Valid Produit produit, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors())
return "produit/produits";
if (produit.getIdProduit() == null) {
business.add(produit);
} else {
business.update(produit);
model.addAttribute("messageSuccess", "produit mis jour!");
return "produit/edit";
}
model.addAttribute("produit", new Produit());
model.addAttribute("produits", business.findAll());
return "redirect:/produit/produits";
}
@RequestMapping(value = "/produit/delete")
public String delete(@RequestParam(value = "id") Long id, Model model) {
business.delete(id);
model.addAttribute("produit", new Produit());
model.addAttribute("produits", business.findAll());
return "redirect:/produit/produits";
}
@RequestMapping(value = "/produit/{search}")
@ResponseBody
public List<Produit> listProduits(@PathVariable(value = "search") String search) {
return business.findByName(search);
}
}
| true |
a9901abc6e0c43173451cc882e7fc9aaff28d67a | Java | rishugupta87/CrackingTheCodingInterview | /src/main/java/sortingandsearching/Q10_05_Sparse_Search/SparseSearch.java | UTF-8 | 2,145 | 4.34375 | 4 | [] | no_license | package sortingandsearching.Q10_05_Sparse_Search;
/**
Sparse Search: Given a sorted array of strings that is interspersed with empty strings, write a method to find
the location of a given string.
Inout: ball, {"at", "", "", "", "ball", "", "", "car, " ", " ", "dad", "", ""}
Output: 4
*/
public class SparseSearch {
public static int sparseSearch(String[] strings, String lookString) {
return search(strings, 0, strings.length - 1, lookString);
}
private static int search(final String[] strings, final int first, final int last, String lookString) {
if (first > last) {
return -1;
}
int mid = (first + last)/2;
//if mid point is "", go left and right to find first not empty string, that will be the new mid
if(strings[mid].isEmpty()) {
int left = mid - 1;
int right = mid + 1;
while(true) {
if (left < first && right > last) {
return -1;
}
if(left >= first && !strings[left].isEmpty()) {
mid = left;
break;
}
if(right <= last && !strings[right].isEmpty()) {
mid = right;
break;
}
left--;
right++;
}
}
if(strings[mid].equals(lookString)) {
return mid;
} else if(strings[mid].compareTo(lookString) < 0) { //since strings are sorted compare lexicographically, search right
return search(strings, mid+1, last, lookString);
} else { //search left
return search(strings, first, mid - 1, lookString);
}
}
public static void main(String[] args) {
String[] stringList1 = {"apple", "", "", "banana", "", "", "", "carrot", "duck", "", "", "eel", "", "flower"};
String[] stringList2 = {"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""};
//System.out.println(sparseSearch(stringList1, "banana"));
System.out.println(sparseSearch(stringList2, "ball"));
}
}
| true |
14c126e739eefdca11d8a5395f48e81e8ef81e11 | Java | YanniD/Dominion | /Dominion/src/dominion/Models/CardType.java | UTF-8 | 358 | 1.6875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dominion.Models;
/**
*
* @author Yanni
*/
public enum CardType {
Action,
ActionAttack,
Treasure,
Victory,
ActionReaction
}
| true |
6beec1aec8f4bddf2960960fdab951da827f1b5b | Java | Lulocu/4B-ETSINF | /CDM/pract3/P1/sources/com/google/android/gms/tagmanager/InstallReferrerReceiver.java | UTF-8 | 686 | 1.65625 | 2 | [] | no_license | package com.google.android.gms.tagmanager;
import com.google.android.gms.analytics.CampaignTrackingReceiver;
import com.google.android.gms.analytics.CampaignTrackingService;
public final class InstallReferrerReceiver extends CampaignTrackingReceiver {
/* access modifiers changed from: protected */
@Override // com.google.android.gms.analytics.CampaignTrackingReceiver
public void zzaL(String str) {
zzax.zzex(str);
}
/* access modifiers changed from: protected */
@Override // com.google.android.gms.analytics.CampaignTrackingReceiver
public Class<? extends CampaignTrackingService> zzhf() {
return InstallReferrerService.class;
}
}
| true |
d36ee2ae519eb51fa533f4925bcb53e91af89bee | Java | Eugen-commits/studyProject_masterProject | /src/main/java/com/example/master_study/persistance/entity/Master.java | UTF-8 | 1,211 | 2.703125 | 3 | [] | no_license | package com.example.master_study.persistance.entity;
import com.example.master_study.persistance.enums.Districts;
import lombok.Data;
import javax.persistence.*;
import java.util.Objects;
import java.util.Set;
@Data
@Entity
public class Master {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String name;
@ManyToMany (fetch = FetchType.LAZY)
@JoinTable(
name = "master_skill",
joinColumns = {@JoinColumn(name = "master_id")},
inverseJoinColumns = {@JoinColumn (name = "skill_id")}
)
private Set <Skill> skills;
@Column(nullable = false)
@Enumerated (EnumType.STRING)
private Districts district;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Master)) return false;
Master master = (Master) o;
return
Objects.equals(name, master.name) &&
Objects.equals(skills, master.skills) &&
Objects.equals(district, master.district);
}
@Override
public int hashCode() {
return Objects.hash(name, skills, district);
}
}
| true |
f3a889d25548973b725f5f26ecb7539a59eb6543 | Java | BuiThanh02/java | /java2/CustomerList/Customers.java | UTF-8 | 452 | 3.0625 | 3 | [] | no_license | package CustomerList;
public class Customers {
private String name;
private String phone;
public Customers(String name, String phone) {
this.name = name;
this.phone = phone;
}
public String getPhone() {
return phone;
}
public String getName() {
return name;
}
public static Customers createCustomer(String name, String phone){
return new Customers(name, phone);
}
}
| true |
49308a695f8b08dc9fdb386f072a3335fca09f7e | Java | akira2nd/FATEC-TG | /SGAS-1/src/main/java/com/fatec/tg/model/DadosDoServico.java | UTF-8 | 533 | 1.640625 | 2 | [] | no_license | package com.fatec.tg.model;
import javax.persistence.*;
import lombok.Data;
@Data
@Entity
@Table(name="dados_do_servico")
public class DadosDoServico {
// TODO arrumar ??
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id_dados_servico")
private Integer id;
@OneToOne
private CadastroServico cadastroServico;
@OneToOne
private Socioeconomico socioeconomico;
@OneToOne
private MembroFamiliar membroFamiliar;
private Integer fonecontato;
private boolean temLaptop;
}
| true |
3dc9b2b1f3a7aef0f8605fefa9f8d83162a2b660 | Java | fanitriastowo/appb | /src/main/java/com/skripsi/appb/repository/SPKRepository.java | UTF-8 | 586 | 1.867188 | 2 | [] | no_license | package com.skripsi.apsb.repository;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import com.skripsi.apsb.entity.News;
import com.skripsi.apsb.entity.Spk;
import com.skripsi.apsb.entity.User;
public interface SPKRepository extends JpaRepository<Spk, Long> {
Spk findOneByUser(User user);
Spk findOneByUserAndNews(User user, News one);
List<Spk> findAllByNews(News one);
List<Spk> findAllByNews(News one, Pageable pageable);
List<Spk> findAllByNewsOrderByVectorVDesc(News one);
}
| true |
effe388dd169826e7cd3467d5620d3f6c91fe72a | Java | amandoabreu/5x5Assistant | /app/src/main/java/hitro/a5x5assistant/LoginActivity.java | UTF-8 | 4,612 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | package hitro.a5x5assistant;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginAcivity";
private static final int RC_SIGN_IN = 123;
private String uid;
private DatabaseReference dbProfiles;
List<AuthUI.IdpConfig> providers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Choose authentication providers
providers = Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build()
);
// Create and launch sign-in intent
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setLogo(R.mipmap.text_logo)
.setTheme(R.style.AppTheme_NoActionBar)
.setIsSmartLockEnabled(false)
.build(),
RC_SIGN_IN);
}
@Override
public void onStart() {
super.onStart();
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
Intent intent = new Intent(this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN && resultCode == RESULT_OK) {
try {
uid = FirebaseAuth.getInstance().getUid();
} catch (NullPointerException e) {
Toast.makeText(getApplicationContext(), "Problem signing in",
Toast.LENGTH_LONG).show();
}
dbProfiles = FirebaseDatabase.getInstance().getReference("profiles/" + uid);
dbProfiles.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
finish();
} else {
Intent intent = new Intent(LoginActivity.this, StatsActivity.class);
intent.putExtra("IS_REGISTERED", false);
startActivity(intent);
finish();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.v(TAG, "error reading profile");
}
});
}
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(LoginActivity.this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
System.exit(0);
}
})
.setNegativeButton("No", null)
.show();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
} | true |
d4c10235e3ff17ffc06d782e2a9ab8993e079314 | Java | shanjock46/propcluster10 | /Common/test/com/prop/cluster10/common/test/app/controller/ctrlestadistiquesgenerals/TestCtrlEstadistiquesGenerals.java | UTF-8 | 2,638 | 3.0625 | 3 | [] | no_license | package com.prop.cluster10.common.test.app.controller.ctrlestadistiquesgenerals;
import java.util.HashMap;
import java.util.Iterator;
import com.prop.cluster10.common.test.app.model.baralla.inout;
public class TestCtrlEstadistiquesGenerals {
public static void main(String[] args) {
try {
int operacio = -1;
inout io = new inout();
CtrlEstadistiquesGeneralsStub ctrlEstadistiquesGeneralsStub = new CtrlEstadistiquesGeneralsStub();
io.writeln("1- Crear Controlador d'estadistiques");
io.writeln("2- Carregar estadistiques generals");
io.writeln("3- Guardar estadistiques generals");
io.writeln("4- Crear noves estadistiques generals");
io.writeln("5- Obtenir estadistiques generals");
io.writeln("0- Sortir");
while (operacio != 0) {
operacio = io.readint();
switch (operacio) {
case 1:
ctrlEstadistiquesGeneralsStub = new CtrlEstadistiquesGeneralsStub();
io.writeln("Creat controlador d'estadistiques generals");
break;
case 2:
io.writeln("Estadistiques generals:");
HashMap<String, Object> estadistiques = ctrlEstadistiquesGeneralsStub.carregaEstadistiquesGenerals();
Iterator<String> keys = estadistiques.keySet().iterator();
String key;
while(keys.hasNext()) {
key = keys.next();
System.out.println(key + " : " + estadistiques.get(key));
}
break;
case 3:
ctrlEstadistiquesGeneralsStub.guardaEstadistiquesGenerals();
break;
case 4:
io.writeln("Crear estadistiques generals");
SBEstadistiquesGenerals sbEstadistiquesGenerals = new SBEstadistiquesGenerals();
io.writeln("Introdueix total de partides jugades");
sbEstadistiquesGenerals.setTotalPartidesJugades(io.readint());
io.writeln("Introdueix total de jugadors participants");
sbEstadistiquesGenerals.setTotalJugadorsParticipants(io.readint());
io.writeln("Introdueix total de rondes jugades");
sbEstadistiquesGenerals.setTotalRondesJugades(io.readint());
ctrlEstadistiquesGeneralsStub.setEstadistiquesGenerals(sbEstadistiquesGenerals);
break;
case 5:
sbEstadistiquesGenerals = (SBEstadistiquesGenerals) ctrlEstadistiquesGeneralsStub.getEstadistiquesGenerals();
io.writeln("Estadistiques generals:");
io.writeln("Total partides jugades: " + sbEstadistiquesGenerals.getTotalPartidesJugades());
io.writeln("Total rondes jugades: " + sbEstadistiquesGenerals.getTotalRondesJugades());
io.writeln("Total jugadors participants: " + sbEstadistiquesGenerals.getTotalJugadorsParticipants());
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
0dea3f39a26ffffe26f3aeb901e059887faf2b6b | Java | serg-ksv/test-task-nta | /src/main/java/com/ksv/springboottask/controller/OrderController.java | UTF-8 | 2,590 | 2.0625 | 2 | [] | no_license | package com.ksv.springboottask.controller;
import com.ksv.springboottask.model.dto.OrderCreateDto;
import com.ksv.springboottask.model.dto.OrderResponseDto;
import com.ksv.springboottask.model.dto.OrderUpdateDto;
import com.ksv.springboottask.model.mapper.OrderMapper;
import com.ksv.springboottask.service.OrderService;
import com.ksv.springboottask.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
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
@AllArgsConstructor
@RequestMapping("/orders")
public class OrderController {
private final OrderService orderService;
private final OrderMapper orderMapper;
private final UserService userService;
@GetMapping("/{id}")
public OrderResponseDto get(@PathVariable Long id,
Authentication authentication) {
var order = orderService.findByIdAndUserLogin(id, authentication.getName());
return orderMapper.getDtoFromOrder(order);
}
@PostMapping
public OrderResponseDto create(@RequestBody OrderCreateDto dto,
Authentication authentication) {
var user = userService.getByLogin(authentication.getName());
var order = orderMapper.getOrderFromDto(dto);
order.setUser(user);
return orderMapper.getDtoFromOrder(orderService.create(order));
}
@PutMapping
public OrderResponseDto update(@RequestBody OrderUpdateDto dto,
Authentication authentication) {
var order = orderService.findByIdAndUserLogin(dto.getId(), authentication.getName());
order.setAmount(dto.getAmount())
.setProductName(dto.getProductName());
return orderMapper.getDtoFromOrder(orderService.update(order));
}
@DeleteMapping("/{id}")
public OrderResponseDto delete(@PathVariable Long id,
Authentication authentication) {
var order = orderService.findByIdAndUserLogin(id, authentication.getName());
return orderMapper.getDtoFromOrder(orderService.delete(order));
}
}
| true |
fb6c054235cb67982d2823443fea37520b3aaf9c | Java | Alexandr1907/java4Android | /src/main/java/lesson8/lesson/interfaces/Test.java | UTF-8 | 213 | 2.296875 | 2 | [] | no_license | package lesson8.lesson.interfaces;
public interface Test {
void swim(int length, String s);
default void testMethod() {
System.out.println("Реализация поумолчанию");
}
}
| true |
80c559aac0c34b3b86b3da10398d1aa3d7375ab7 | Java | srkajal/assignments | /11_RestFulAPI_Assignment2/src/main/java/org/kajal/mallick/repositories/BookRepository.java | UTF-8 | 411 | 2.171875 | 2 | [] | no_license | package org.kajal.mallick.repositories;
import org.kajal.mallick.entities.Book;
import org.springframework.data.repository.Repository;
import java.util.List;
public interface BookRepository extends Repository<Book,Long> {
List<Book> findAll();
List<Book> findByTitleIgnoreCaseContaining(String title);
Book findById(Long bookId);
Book save(Book book);
void deleteByBookId(Long bookId);
}
| true |
92168afed904d654a7386cacbcf93d03487a6985 | Java | dapporcellis/Livraria | /src/java/modelo/Livro.java | UTF-8 | 3,853 | 1.882813 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modelo;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Temporal;
/**
*
* @author dappo
*/
@Entity
@NamedQueries({
@NamedQuery(name="Livro.findAll", query="SELECT a FROM Livro a"),
@NamedQuery(name="Livro.findFilter", query="SELECT a FROM Livro a WHERE a.nome LIKE :filtro"),
@NamedQuery(name="Livro.findGenero", query="SELECT a FROM Livro a WHERE a.genero.id = :genero"),
@NamedQuery(name="Livro.findAutor", query="SELECT a FROM Livro a JOIN a.autores l WHERE l.id = :autor"),
@NamedQuery(name="Livro.findEditora", query="SELECT a FROM Livro a WHERE a.editora.id = :editora")
})
public class Livro implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String nome;
private Integer paginas;
private String isbn;
private String idioma;
@Temporal(javax.persistence.TemporalType.DATE)
private Date lancamento;
@Lob
private String sinopse;
private String foto1;
private String foto2;
private String foto3;
//private List<String> fotos;
@ManyToOne
private Genero genero;
@ManyToOne
private Editora editora;
@ManyToMany
private List<Autor> autores;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Integer getPaginas() {
return paginas;
}
public void setPaginas(Integer paginas) {
this.paginas = paginas;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getIdioma() {
return idioma;
}
public void setIdioma(String idioma) {
this.idioma = idioma;
}
public Date getLancamento() {
return lancamento;
}
public void setLancamento(Date lancamento) {
this.lancamento = lancamento;
}
public String getSinopse() {
return sinopse;
}
public void setSinopse(String sinopse) {
this.sinopse = sinopse;
}
public String getFoto1() {
return foto1;
}
public void setFoto1(String foto1) {
this.foto1 = foto1;
}
public String getFoto2() {
return foto2;
}
public void setFoto2(String foto2) {
this.foto2 = foto2;
}
public String getFoto3() {
return foto3;
}
public void setFoto3(String foto3) {
this.foto3 = foto3;
}
public Genero getGenero() {
return genero;
}
public void setGenero(Genero genero) {
this.genero = genero;
}
public Editora getEditora() {
return editora;
}
public void setEditora(Editora editora) {
this.editora = editora;
}
public List<Autor> getAutores() {
return autores;
}
public void setAutores(List<Autor> autores) {
this.autores = autores;
}
}
| true |
798cbf6b254b0deb3cb038b6f2d8c6c3ebef0b4a | Java | dwifdji/real-project | /366pai/zeus-core/core-dubbo-api/src/main/java/com/_360pai/core/facade/finance/req/AdjustedRecordReq.java | UTF-8 | 390 | 1.53125 | 2 | [] | no_license | package com._360pai.core.facade.finance.req;
import com._360pai.arch.common.RequestModel;
import lombok.Data;
/**
* @author xiaolei
* @create 2018-10-03 14:58
*/
public class AdjustedRecordReq {
@Data
public static class GetAdjustedRecord extends RequestModel {
private Integer partyId;
private int adjustedStatus;
private String withdrawNo;
}
}
| true |
6291a35d48f4f119bc538f5447727001a8ebdb2a | Java | MornSunShine/AliPay | /app/src/main/java/morn/xposed/alipay/AntCooperate.java | UTF-8 | 5,525 | 1.992188 | 2 | [] | no_license | package morn.xposed.alipay;
import android.os.PowerManager;
import org.json.JSONArray;
import org.json.JSONObject;
import morn.xposed.alipay.hook.AntCooperateRpcCall;
import morn.xposed.alipay.hook.XposedHook;
import morn.xposed.alipay.util.Config;
import morn.xposed.alipay.util.CooperationIdMap;
import morn.xposed.alipay.util.FriendIdMap;
import morn.xposed.alipay.util.Log;
import morn.xposed.alipay.util.RandomUtils;
import morn.xposed.alipay.util.Statistics;
public class AntCooperate {
private static final String TAG = "pansong291.xposed.quickenergy.ࠁ";
private static Runnable task;
public static void start(ClassLoader loader, int times) {
if (Config.getCooperateWater() && times == 0) {
if (task == null) {
task = new Runnable() {
ClassLoader loader;
public Runnable setData(ClassLoader loader) {
this.loader = loader;
return this;
}
@Override
public void run() {
PowerManager.WakeLock wakeLock = XposedHook.getWakeLock();
try {
while (FriendIdMap.currentUid == null || FriendIdMap.currentUid.isEmpty()) {
Thread.sleep(100L);
}
String s = AntCooperateRpcCall.rpcCall_queryUserCooperatePlantList(loader);
if (s == null) {
Thread.sleep(RandomUtils.delay());
s = AntCooperateRpcCall.rpcCall_queryUserCooperatePlantList(loader);
}
JSONObject jo = new JSONObject(s);
if (jo.getString("resultCode").equals("SUCCESS")) {
int userCurrentEnergy = jo.getInt("userCurrentEnergy");
JSONArray ja = jo.getJSONArray("cooperatePlants");
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
String cooperationId = jo.getString("cooperationId");
if (!jo.has("name")) {
s = AntCooperateRpcCall.rpcCall_queryCooperatePlant(loader, cooperationId);
jo = new JSONObject(s).getJSONObject("cooperatePlant");
}
String name = jo.getString("name");
int waterDayLimit = jo.getInt("waterDayLimit");
CooperationIdMap.putIdMap(cooperationId, name);
if (!Statistics.canCooperateWaterToday(FriendIdMap.currentUid, cooperationId))
continue;
int index = -1;
for (int j = 0; j < Config.getCooperateWaterList().size(); j++) {
if (Config.getCooperateWaterList().get(j).equals(cooperationId)) {
index = j;
break;
}
}
if (index >= 0) {
int num = Config.getCooperateWaterNumList().get(index);
if (num > waterDayLimit)
num = waterDayLimit;
if (num > userCurrentEnergy)
num = userCurrentEnergy;
if (num > 0)
cooperateWater(loader, FriendIdMap.currentUid, cooperationId, num, name);
}
}
} else {
Log.i(TAG, jo.getString("resultDesc"));
}
} catch (Throwable t) {
Log.i(TAG, "start.run err:");
Log.printStackTrace(TAG, t);
}
CooperationIdMap.saveIdMap();
XposedHook.setWakeLock(wakeLock);
}
}.setData(loader);
}
if (Config.getOriginalMode()) {
new Thread(task).start();
} else {
AntBroadcastReceiver.triggerTask(task, RandomUtils.nextInt(1000, 2000));
}
}
}
private static void cooperateWater(ClassLoader loader, String uid, String coopId, int count, String name) {
try {
JSONObject jo = new JSONObject(AntCooperateRpcCall.rpcCall_cooperateWater(loader, uid, coopId, count));
if (jo.getString("resultCode").equals("SUCCESS")) {
Log.forest("合种【" + name + "】" + jo.getString("barrageText"));
Statistics.cooperateWaterToday(FriendIdMap.currentUid, coopId);
} else {
Log.i(TAG, jo.getString("resultDesc"));
}
} catch (Throwable t) {
Log.i(TAG, "cooperateWater err:");
Log.printStackTrace(TAG, t);
}
}
} | true |
509a945722ff1ce99ae7d271ebdd72c1c4814ee8 | Java | wprogLK/Ursuppe | /P2 Ursuppe/src/helpClasses/SaveAndLoad.java | UTF-8 | 1,106 | 3.25 | 3 | [] | no_license | package helpClasses;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public abstract class SaveAndLoad {
public static void saveObject(Object obj, String filename)
{
try
{
FileOutputStream file = new FileOutputStream( filename );
ObjectOutputStream o = new ObjectOutputStream( file );
System.out.println("Save object "+ obj.toString());
o.writeObject(obj);
o.close();
}
catch ( IOException e ) { System.err.println( e + " Error in saveObject " + filename); }
}
public static Object loadObject(String filename)
{
Object obj=null;
try
{
FileInputStream file = new FileInputStream( filename );
ObjectInputStream o = new ObjectInputStream( file );
obj =o.readObject();
o.close();
}
catch ( IOException e ) { System.err.println( e ); }
catch ( ClassNotFoundException e ) { System.err.println( e + " Error in loadObject"); }
return obj;
}
}
| true |
26bc8587ee4796bef0d095cde950febd90083875 | Java | rjewsbury/MutexVisual | /src/mutex/display/elements/ThreadBall.java | UTF-8 | 3,038 | 3.078125 | 3 | [] | no_license | package mutex.display.elements;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
public class ThreadBall extends ViewElement
{
//default radius
public static final int RADIUS = 20;
private int myRadius;
private Color myColor;
private int myID;
private ElementContainer myContainer;
private boolean myLight;
public ThreadBall(int ID, Color color)
{
this(ID, color, RADIUS);
}
public ThreadBall(int ID, Color color, int radius)
{
myRadius = radius;
myID = ID;
myColor = color;
myLight = false;
myContainer = null;
}
public void setCenterX(int x){
setX(x-myRadius);
}
public void setCenterY(int y){
setY(y-myRadius);
}
public int getCenterX(){
return getX()+myRadius;
}
public int getCenterY(){
return getY()+myRadius;
}
/**
* The container controls the threadball's position, so having
* multiple controllers can cause problems
*/
public void setContainer(ElementContainer container, int index)
{
setContainer(container);
container.addElement(this, index);
}
public void setContainer(ElementContainer container)
{
if(myContainer != container)
leaveContainer();
myContainer = container;
}
public boolean inContainer(ElementContainer container)
{
return myContainer == container;
}
public void leaveContainer()
{
if(myContainer != null)
myContainer.removeElement(this);
myContainer = null;
}
public void setRadius(int radius)
{
int centerX = getCenterX();
int centerY = getCenterY();
myRadius = radius;
//by default this would cause the circle to expand from the top left corner,
//so we reposition it to stay centered
setCenterX(centerX);
setCenterY(centerY);
}
public void setLight(boolean light)
{
if(myLight != light)
{
if(myLight)
myColor = myColor.darker();
else
myColor = myColor.brighter();
}
myLight = light;
}
public int getID()
{
return myID;
}
public int getWidth()
{
return myRadius*2;
}
public void setWidth(int width)
{
myRadius = width/2;
}
public int getHeight()
{
return myRadius*2;
}
public void setHeight(int height)
{
myRadius = height/2;
}
public void draw(Graphics2D g)
{
g.setColor(myColor);
g.setStroke(new BasicStroke(myRadius/10f));
g.fillOval(getX(), getY(), getWidth(), getHeight());
g.setColor(Color.BLACK);
g.drawOval(getX(), getY(), getWidth(), getHeight());
g.setFont(g.getFont().deriveFont((float)myRadius));
//center the ID
String idString = myID+"";
int xOffset = (int)(myRadius*(1-idString.length()*0.3));
int yOffset = (int)(myRadius*1.4);
g.drawString(idString, getX()+xOffset, getY()+yOffset);
}
@Override
public ThreadBall clone()
{
ThreadBall copy = (ThreadBall) super.clone();
//if the threadball is being copied, wont it have a different container??
copy.myContainer = null;
return copy;
}
}
| true |
1b583059e58a0ceed9e001c52883d82cc92a3ea6 | Java | HWendless/hw | /wuxian/src/main/java/com/mao/spider/ElePC.java | UTF-8 | 6,164 | 1.921875 | 2 | [] | no_license | package com.mao.spider;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
public class ElePC {
public static void main(String[] args) throws IOException {
ReadExcel readExcel = new ReadExcel();
InputStream is = new FileInputStream("C:\\Users\\yraka\\Desktop\\coco\\七分甜\\苏州.xlsx");
List<List<String>> excelInfo = readExcel.getExcelInfo(is, "苏州.xlsx");
for(List<String> strings : excelInfo){
for(String string : strings){
}
}
List<Map> rest = sendUrl("https://www.ele.me/restapi/bgs/poi/search_poi_nearby?geohash=wttdpcwn012n"+"&keyword="+"常熟万达"+"&latitude=31.29834&limit=20&longitude=120.583191&type=nearby");
BigDecimal latitude = (BigDecimal) rest.get(0).get("latitude");
BigDecimal longitude = (BigDecimal)rest.get(0).get("longitude");
Map foodDatas = sendUrlMap("https://www.ele.me/restapi/shopping/restaurants/search?extras%5B%5D=activity&keyword=7分甜&latitude="+latitude+"&limit=100&longitude="+longitude+"&offset=0&terminal=web");
List<Map<String, Object>> restaurant_with_foods = (List<Map<String, Object>>) foodDatas.get("restaurant_with_foods");
for(Map<String, Object>restaurant_with_food : restaurant_with_foods){
System.out.println(restaurant_with_food);
}
}
public static List<Map> sendUrl(String rul) throws IOException {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(rul);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader(":authority", "www.ele.me");
httpGet.setHeader(":method","GET");
httpGet.setHeader(":path", "/restapi/bgs/poi/search_poi_nearby?geohash=wttdpcwn012n&keyword=d&latitude=31.29834&limit=20&longitude=120.583191&type=nearby");
httpGet.setHeader(":scheme", "https");
httpGet.setHeader("accept-language", "zh-CN,zh;q=0.9");
httpGet.setHeader("cookie: ubt_ssid=dkhx932mn1zbdatylm3k1fbxr3445c5k_2019-07-09", "_utrace=190164111b3ca1b1db2269e6b8168e72_2019-07-09; ut_ubt_ssid=wudotui7v29l1icqbi77iyy56o6i7en2_2019-07-09; cna=U9mNFZYkCiQCAbfRbF8Cx1F8; track_id=1562643997|31c5af8e606267e956c0d9c3e4bed758f6f6f6b71985ad23d1|1aefbd8b32dc70a7ed696fd948826d07; USERID=136129407; UTUSER=136129407; SID=9mvBo8VJEruIPKpXvJJcr226kTTxahTq9Pqg; ZDS=1.0|1562643997|ZUYvGae+rxyD0HFe9ptYlP9Vsnoqt/u4wtaODFAosFtbopaY+UNSWURsCtEgXPrb; tzyy=f206005981683f074299152d85123341; isg=BEZGLRKoZ3WxdTORbSeWdM5GlzxkuY3ZqsC2jzBvH2lEM-ZNmDRzcSzCDy9am4J5; pizza73686f7070696e67=CPuz42fVoxnRVcVQ1x33fbTsKeCbvg_FV4YzWx_TbJgbwOF4BR7gpWFHGwiGdsEj");
httpGet.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36");
httpGet.setHeader("x-shard: loc","120.587876,31.313376");
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
//System.out.println("网页内容:"+result);
List<Map> maps = FastJsonUtils.toList(result, Map.class);
return maps;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
response.close();
client.close();
}
}
public static Map sendUrlMap(String rul) throws IOException {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(rul);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader(":authority", "www.ele.me");
httpGet.setHeader(":method","GET");
httpGet.setHeader(":path", "/restapi/bgs/poi/search_poi_nearby?geohash=wttdpcwn012n&keyword=d&latitude=31.29834&limit=20&longitude=120.583191&type=nearby");
httpGet.setHeader(":scheme", "https");
httpGet.setHeader("accept-language", "zh-CN,zh;q=0.9");
httpGet.setHeader("cookie: ubt_ssid=dkhx932mn1zbdatylm3k1fbxr3445c5k_2019-07-09", "_utrace=190164111b3ca1b1db2269e6b8168e72_2019-07-09; ut_ubt_ssid=wudotui7v29l1icqbi77iyy56o6i7en2_2019-07-09; cna=U9mNFZYkCiQCAbfRbF8Cx1F8; track_id=1562643997|31c5af8e606267e956c0d9c3e4bed758f6f6f6b71985ad23d1|1aefbd8b32dc70a7ed696fd948826d07; USERID=136129407; UTUSER=136129407; SID=9mvBo8VJEruIPKpXvJJcr226kTTxahTq9Pqg; ZDS=1.0|1562643997|ZUYvGae+rxyD0HFe9ptYlP9Vsnoqt/u4wtaODFAosFtbopaY+UNSWURsCtEgXPrb; tzyy=f206005981683f074299152d85123341; isg=BEZGLRKoZ3WxdTORbSeWdM5GlzxkuY3ZqsC2jzBvH2lEM-ZNmDRzcSzCDy9am4J5; pizza73686f7070696e67=CPuz42fVoxnRVcVQ1x33fbTsKeCbvg_FV4YzWx_TbJgbwOF4BR7gpWFHGwiGdsEj");
httpGet.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36");
httpGet.setHeader("x-shard: loc","120.587876,31.313376");
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
//System.out.println("网页内容:"+result);
Map map = (Map)FastJsonUtils.convertJsonToObject(result,Map.class);
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
response.close();
client.close();
}
}
}
| true |
f17f71a891baaa1e1e1cf94454af9cd3c15b4865 | Java | rabp99/sgh-web-rabp | /src/java/org/sghweb/beans/RegistrarCitaBean.java | UTF-8 | 16,099 | 1.640625 | 2 | [] | no_license |
package org.sghweb.beans;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Color;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.sghweb.controllers.CitaJpaController;
import org.sghweb.controllers.DetallehistoriaclinicaJpaController;
import org.sghweb.controllers.HistoriaclinicaJpaController;
import org.sghweb.controllers.ReferenciaJpaController;
import org.sghweb.controllers.ServicioJpaController;
import org.sghweb.controllers.VwCitaJpaController;
import org.sghweb.controllers.VwMedicoJpaController;
import org.sghweb.controllers.VwReportepacienteJpaController;
import org.sghweb.controllers.exceptions.IllegalOrphanException;
import org.sghweb.controllers.exceptions.NonexistentEntityException;
import org.sghweb.controllers.exceptions.RollbackFailureException;
import org.sghweb.jpa.Cita;
import org.sghweb.jpa.CitaPK;
import org.sghweb.jpa.Detallehistoriaclinica;
import org.sghweb.jpa.DetallehistoriaclinicaPK;
import org.sghweb.jpa.Historiaclinica;
import org.sghweb.jpa.HistoriaclinicaPK;
import org.sghweb.jpa.Referencia;
import org.sghweb.jpa.Servicio;
import org.sghweb.jpa.VwCita;
import org.sghweb.jpa.VwMedico;
import org.sghweb.jpa.VwReportepaciente;
import org.sghweb.jpa.VwReportereceta;
/**
*
* @author essalud
*/
@ManagedBean
@ViewScoped
public class RegistrarCitaBean implements Serializable {
// Paciente
private List<VwReportepaciente> listaReportePacientes;
private VwReportepacienteJpaController vrjc;
private VwReportepaciente selectedReportePaciente;
private VwReportepaciente vwReportepaciente;
private String dni;
// Servicio
private List<Servicio> listaServicios;
private ServicioJpaController vsjc;
private Servicio selectedServicio;
private Servicio servicio;
private String codigoServicio;
// Médico
private List<VwMedico> listaMedicos;
private VwMedicoJpaController vmjc;
private VwMedico selectedMedico;
private VwMedico vwMedico;
private String cmp;
// Cita
private List<VwCita> listaCitas;
private VwCitaJpaController vcjc;
private VwCita selectedCita;
private StreamedContent reporteCita;
public RegistrarCitaBean() {
// Paciente
vrjc = new VwReportepacienteJpaController(null, null);
listaReportePacientes = vrjc.findVwReportepacienteEntities();
vwReportepaciente = new VwReportepaciente();
// Servicio
vsjc = new ServicioJpaController(null, null);
listaServicios = vsjc.findServicioEntities();
servicio = new Servicio();
// Médico
vmjc = new VwMedicoJpaController(null, null);
listaMedicos = vmjc.findVwMedicoEntities();
vwMedico = new VwMedico();
// Cita
vcjc = new VwCitaJpaController(null, null);
listaCitas = vcjc.findVwCitaDisponibles();
// Logueado como paciente
FacesContext context = javax.faces.context.FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
LoginBean loginBean = (LoginBean) session.getAttribute("loginBean");
dni = loginBean.getLoginPaciente().getDni();
vwReportepaciente = vrjc.findVwReportepaciente(loginBean.getLoginPaciente().getDni());
}
public void onRowSelectPaciente(SelectEvent event) {
setVwReportepaciente((VwReportepaciente) event.getObject());
RequestContext.getCurrentInstance().reset("frmRegistrarCita_atcDni");
dni = vwReportepaciente.getDni();
}
public List<String> listaDni(String query) {
List<String> results = new ArrayList();
for(VwReportepaciente vwReportepaciente : getListaReportePacientes()) {
if(vwReportepaciente.getDni().startsWith(query))
results.add(vwReportepaciente.getDni());
}
return results;
}
public void verificarPaciente() {
VwReportepaciente auxVwReportepaciente = vrjc.findVwReportepaciente(dni);
if(auxVwReportepaciente != null)
setVwReportepaciente(auxVwReportepaciente);
}
public List<String> listaCodigoServicio(String query) {
List<String> results = new ArrayList();
for(Servicio servicio : getListaServicios()) {
if(servicio.getCodigo().startsWith(query))
results.add(servicio.getCodigo());
}
return results;
}
public void onRowSelectServicio(SelectEvent event) {
setServicio((Servicio) event.getObject());
RequestContext.getCurrentInstance().reset("frmRegistrarCita_atcCodigoServicio");
codigoServicio = servicio.getCodigo();
listaMedicos = vmjc.findVwMedicoByServicio(servicio.getDescripcion());
}
public void verificarServicio() {
Servicio auxServicio = vsjc.findServicio(codigoServicio);
if(auxServicio != null) {
servicio = auxServicio;
listaMedicos = vmjc.findVwMedicoByServicio(servicio.getDescripcion());
}
}
public void onRowSelectMedico(SelectEvent event) {
setVwMedico((VwMedico) event.getObject());
RequestContext.getCurrentInstance().reset("frmRegistrarCita_atcCMP");
cmp = vwMedico.getCmp();
listaCitas = vcjc.findVwCitaDisponibles(cmp);
}
public List<String> listaCmp(String query) {
List<String> results = new ArrayList();
for(VwMedico vwMedico : getListaMedicos()) {
if(vwMedico.getCmp().startsWith(query))
results.add(vwMedico.getCmp());
}
return results;
}
public void verificarMedico() {
VwMedico auxVwMedico = vmjc.findVwMedico(cmp);
if(auxVwMedico != null) {
setVwMedico(auxVwMedico);
listaCitas = vcjc.findVwCitaDisponibles(cmp);
}
}
public void registrar() throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
if(dni == null) {
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Debe seleccionar un paciente", null);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
return;
}
if(getSelectedCita() == null) {
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Debe seleccionar una Cita", null);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
return;
}
ReferenciaJpaController rjc = new ReferenciaJpaController(null, null);
List<Referencia> referencias = rjc.findReferenciabyDni(dni);
if(referencias.isEmpty()) {
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "El paciente tiene una referencia vencida", null);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
return;
}
// Cita
CitaJpaController cjc = new CitaJpaController(null, null);
CitaPK cpk = new CitaPK(getSelectedCita().getActoMedico(), getSelectedCita().getCmp(), getSelectedCita().getMedicoDni());
Cita cita = cjc.findCita(cpk);
cita.setEstado('3');
cjc.edit(cita);
// Detalle Historia Clínica
DetallehistoriaclinicaJpaController djc = new DetallehistoriaclinicaJpaController(null, null);
Detallehistoriaclinica d = new Detallehistoriaclinica();
DetallehistoriaclinicaPK dpk = new DetallehistoriaclinicaPK();
dpk.setCitaMedicocmp(getSelectedCita().getCmp());
dpk.setCitaMedicodni(getSelectedCita().getMedicoDni());
dpk.setCitaactoMedico(getSelectedCita().getActoMedico());
dpk.setHistoriaClinicaPacientedni(vwReportepaciente.getDni());
dpk.setHistoriaClinicaautogenerado(vwReportepaciente.getAutogenerado());
dpk.setHistoriaClinicanumeroRegistro(vwReportepaciente.getNumeroRegistro());
d.setDetallehistoriaclinicaPK(dpk);
d.setFecha(cita.getFecha());
HistoriaclinicaJpaController hjc = new HistoriaclinicaJpaController(null, null);
HistoriaclinicaPK hcpk = new HistoriaclinicaPK();
hcpk.setAutogenerado(vwReportepaciente.getAutogenerado());
hcpk.setNumeroRegistro(vwReportepaciente.getNumeroRegistro());
hcpk.setPacientedni(vwReportepaciente.getDni());
Historiaclinica h = hjc.findHistoriaclinica(hcpk);
d.setHistoriaclinica(h);
d.setCita(cita);
djc.create(d);
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, "La cita fue registrada correctamente", null);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
Document pdf = new Document();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PdfWriter.getInstance(pdf, os);
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
pdf.open();
// INICIO Escritura de Reporte
// Cabecera
Paragraph cabecera = new Paragraph();
String logo = servletContext.getRealPath("") + File.separator + "resources"+ File.separator + "img" + File.separator + "logo - header.png";
cabecera.add(Image.getInstance(logo));
pdf.setHeader(new HeaderFooter(cabecera, false));
// Título
pdf.add(cabecera);
Paragraph titulo = new Paragraph("Cita Registrada", FontFactory.getFont(FontFactory.HELVETICA, 22, Font.BOLD, new Color(0, 0, 0)));
titulo.setAlignment(Element.ALIGN_CENTER);
pdf.add(titulo);
//Mostrar información de la Receta
pdf.add(Chunk.NEWLINE);
PdfPTable table = new PdfPTable(2);
table.getDefaultCell().setBorder(0);
table.addCell("Acto Médico:");
table.addCell(getSelectedCita().getActoMedico());
table.addCell("Médico:");
table.addCell(selectedMedico.getNombreCompleto());
table.addCell("CMP Médico:");
table.addCell(selectedMedico.getCmp());
table.addCell("Servicio:");
table.addCell(selectedServicio.getDescripcion());
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
table.addCell("Fecha y Hora:");
table.addCell(sdf.format(getSelectedCita().getFechaHora()));
table.addCell("Paciente:");
table.addCell(selectedReportePaciente.getNombreCompleto());
table.addCell("DNI Paciente:");
table.addCell(selectedReportePaciente.getDni());
table.addCell("H/C:");
table.addCell(selectedReportePaciente.getNumeroRegistro());
pdf.add(table);
pdf.close(); // no need to close PDFwriter?
InputStream is = new ByteArrayInputStream(os.toByteArray());
setReporteCita(new DefaultStreamedContent(is, "application/pdf", "Reporte Cita.pdf"));
}
public List<VwReportepaciente> getListaReportePacientes() {
return listaReportePacientes;
}
public void setListaReportePacientes(List<VwReportepaciente> listaReportePacientes) {
this.listaReportePacientes = listaReportePacientes;
}
public VwReportepacienteJpaController getVrjc() {
return vrjc;
}
public void setVrjc(VwReportepacienteJpaController vrjc) {
this.vrjc = vrjc;
}
public VwReportepaciente getSelectedReportePaciente() {
return selectedReportePaciente;
}
public void setSelectedReportePaciente(VwReportepaciente selectedReportePaciente) {
this.selectedReportePaciente = selectedReportePaciente;
}
public VwReportepaciente getVwReportepaciente() {
return vwReportepaciente;
}
public void setVwReportepaciente(VwReportepaciente vwReportepaciente) {
this.vwReportepaciente = vwReportepaciente;
}
public String getDni() {
return dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public List<Servicio> getListaServicios() {
return listaServicios;
}
public void setListaServicios(List<Servicio> listaServicios) {
this.listaServicios = listaServicios;
}
public ServicioJpaController getVsjc() {
return vsjc;
}
public void setVsjc(ServicioJpaController vsjc) {
this.vsjc = vsjc;
}
public Servicio getSelectedServicio() {
return selectedServicio;
}
public void setSelectedServicio(Servicio selectedServicio) {
this.selectedServicio = selectedServicio;
}
public Servicio getServicio() {
return servicio;
}
public void setServicio(Servicio servicio) {
this.servicio = servicio;
}
public String getCodigoServicio() {
return codigoServicio;
}
public void setCodigoServicio(String codigoServicio) {
this.codigoServicio = codigoServicio;
}
public List<VwMedico> getListaMedicos() {
return listaMedicos;
}
public void setListaMedicos(List<VwMedico> listaMedicos) {
this.listaMedicos = listaMedicos;
}
public VwMedicoJpaController getVmjc() {
return vmjc;
}
public void setVmjc(VwMedicoJpaController vmjc) {
this.vmjc = vmjc;
}
public VwMedico getSelectedMedico() {
return selectedMedico;
}
public void setSelectedMedico(VwMedico selectedMedico) {
this.selectedMedico = selectedMedico;
}
public VwMedico getVwMedico() {
return vwMedico;
}
public void setVwMedico(VwMedico vwMedico) {
this.vwMedico = vwMedico;
}
public String getCmp() {
return cmp;
}
public void setCmp(String cmp) {
this.cmp = cmp;
}
public List<VwCita> getListaCitas() {
return listaCitas;
}
public void setListaCitas(List<VwCita> listaCitas) {
this.listaCitas = listaCitas;
}
public VwCitaJpaController getVcjc() {
return vcjc;
}
public void setVcjc(VwCitaJpaController vcjc) {
this.vcjc = vcjc;
}
public VwCita getSelectedCita() {
return selectedCita;
}
public void setSelectedCita(VwCita selectedCita) {
this.selectedCita = selectedCita;
}
public StreamedContent getReporteCita() {
return reporteCita;
}
public void setReporteCita(StreamedContent reporteCita) {
this.reporteCita = reporteCita;
}
}
| true |
9a778b49ddd02610f516229dd989635a954cd581 | Java | zggg/dew | /components/appexample/src/main/java/com/ecfront/dew/appexample/controller/WSController.java | UTF-8 | 1,608 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | package com.ecfront.dew.appexample.controller;
import com.ecfront.dew.appexample.entity.TestEntity;
import com.ecfront.dew.appexample.repository.TestRepository;
import com.ecfront.dew.common.Resp;
import com.ecfront.dew.core.Dew;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping(value = "/ws")
public class WSController {
private static final Logger logger = LoggerFactory.getLogger(WSController.class);
@Autowired
private RestTemplate restTemplate;
@Autowired
private TestRepository testRepository;
@PostMapping(value = "")
@ResponseBody
public Resp<String> ws(@RequestBody String message) throws Exception {
if (Dew.context().getToken() == null || Dew.context().getToken().isEmpty()) {
throw new Exception("");
}
TestEntity entity = new TestEntity();
entity.setToken(Dew.context().getToken());
entity.setMessage(message);
logger.info("info test");
logger.trace("trace test");
logger.debug("debug test");
testRepository.save(entity);
Dew.Timer.periodic(10L, () ->
testRepository.findAll().forEach(
i ->
restTemplate.postForEntity(Dew.EB.buildUrl("wsgateway", "push", i.getToken()), "push>>" + i.getMessage(), String.class)
)
);
return Resp.success(message);
}
}
| true |
792872c579b57a9f45b5123ccc5c08188d02eca6 | Java | havrikov/mexcounter | /src/test/java/de/cispa/se/mexcounter/AgentTests.java | UTF-8 | 1,456 | 2.25 | 2 | [
"MIT"
] | permissive | package de.cispa.se.mexcounter;
import com.example.Foo;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.agent.builder.ResettableClassFileTransformer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.instrument.Instrumentation;
public class AgentTests {
private Instrumentation instrumentation;
private ResettableClassFileTransformer transformer;
@Before
public void setUp() {
CounterState.METHOD_COUNTERS.clear();
instrumentation = ByteBuddyAgent.install();
}
@After
public void tearDown() {
if (transformer != null) {
transformer.reset(instrumentation, AgentBuilder.RedefinitionStrategy.REDEFINITION);
}
}
@Test
public void hitCountingInterceptor_seesLocalClasses() {
String prefix = "com.example";
transformer = MEXCountingAgent.buildAgent(prefix)
.with(AgentBuilder.Listener.StreamWriting.toSystemOut().withTransformationsOnly())
.installOnByteBuddyAgent();
new Foo().foo();
Assert.assertFalse(CounterState.METHOD_COUNTERS.isEmpty());
Assert.assertEquals(2, CounterState.METHOD_COUNTERS.getOrDefault("com.example.Foo::bar()", 0).intValue());
Assert.assertEquals(1, CounterState.METHOD_COUNTERS.getOrDefault("com.example.Qux::qux()", 0).intValue());
}
}
| true |
bc8771e5b84da2ded24aee8eec368860d0be6e86 | Java | Alektas/Stroymat | /app/src/main/java/alektas/stroymat/di/AppComponent.java | UTF-8 | 1,120 | 1.867188 | 2 | [
"Apache-2.0"
] | permissive | package alektas.stroymat.di;
import android.content.Context;
import android.content.res.Resources;
import javax.inject.Singleton;
import alektas.stroymat.data.Repository;
import alektas.stroymat.ui.MainActivity;
import alektas.stroymat.ui.calculators.profnastil.ProfnastilViewModel;
import alektas.stroymat.ui.calculators.stove.StoveViewModel;
import alektas.stroymat.ui.calculators.trotuar.TrotuarViewModel;
import alektas.stroymat.ui.cart.CartViewModel;
import alektas.stroymat.ui.gallery.GalleryViewModel;
import alektas.stroymat.ui.pricelist.PricelistViewModel;
import alektas.stroymat.ui.server.AdminViewModel;
import dagger.Component;
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
Context getContext();
Resources getResources();
Repository getRepository();
void inject(MainActivity activity);
void inject(CartViewModel vm);
void inject(AdminViewModel vm);
void inject(GalleryViewModel vm);
void inject(PricelistViewModel vm);
void inject(ProfnastilViewModel vm);
void inject(StoveViewModel vm);
void inject(TrotuarViewModel vm);
}
| true |
c86df3c72b7f652167be96375643794e592c7a9a | Java | APF2019Project/ap_4 | /src/gamecenter/ZombieGameMode.java | UTF-8 | 9,551 | 2.5 | 2 | [] | no_license | package gamecenter;
import controller.Viewcontroller;
import gamecenter.plants.*;
import gamecenter.zombies.Zombies;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class ZombieGameMode extends GameMode {
int turn = 0;
Random generator = new Random();
private int coin = 50000;
private int ladder = 3;
Zombies current;
ArrayList<Zombies> zombies_hand;
ArrayList<Integer> zombies_health = new ArrayList<>();
ArrayList<Plants> plants = new ArrayList<>();
Zombies[][] zombies = new Zombies[6][2];
int[] lanes = new int[6];
ArrayList<String> showLanes = new ArrayList<>();
ArrayList<Integer> showlanesNumbers = new ArrayList<>();
public ZombieGameMode() {
zombies_hand = Viewcontroller.collection.zombies_hand;
for (int i = 0; i < 6; i++) {
for (int k = 0; k < 19; k++) {
GameGround[i][k].groundX = i;
GameGround[i][k].groundY = k;
GameGround[i][k].type = true;
}
}
for (int i = 0; i < 6; i++) {
lanes[i] = 0;
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 2; j++) {
if (zombies[i][j] == null)
zombies[i][j] = new Zombies();
}
}
}
public void setDefaults() {
GameGround = new Ground[6][19];
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 19; j++) {
GameGround[i][j] = new Ground();
GameGround[i][j].settledPlant = new Plants();
}
}
PlantsinGame = new ArrayList<>();
ZombiesinGame = new ArrayList<>();
peas = new ArrayList<>();
rockets = new ArrayList<>();
showLawnX = new ArrayList<>();
showLawnY = new ArrayList<>();
showLawnHealth = new ArrayList<>();
zombies_dead = new ArrayList<>();
plants_dead = new ArrayList<>();
turn = 0;
coin = 50;
ladder = 3;
zombies_hand = Viewcontroller.collection.zombies_hand;
zombies_health = new ArrayList<>();
plants = new ArrayList<>();
zombies = new Zombies[6][2];
showLanes = new ArrayList<>();
showlanesNumbers = new ArrayList<>();
for (int i = 0; i < 6; i++) {
for (int k = 0; k < 19; k++) {
GameGround[i][k].groundX = i;
GameGround[i][k].groundY = k;
GameGround[i][k].type = true;
}
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 2; j++) {
if (zombies[i][j] == null)
zombies[i][j] = new Zombies();
}
}
}
public int endTurn() {
turn++;
for (Plants plant : PlantsinGame) {
plant.setXY(this);
plant.operation(this);
}
for (int i = 0; i < peas.size(); i++) {
peas.get(i).setXY(this);
int x = peas.get(i).getGroundX();
if (peas.get(i).operation(GameGround[x])) {
peas.remove(i);
}
}
for (int i = 0; i < rockets.size(); i++) {
rockets.get(i).setXY(this);
int x = rockets.get(i).getGroundX();
if (rockets.get(i).operation(GameGround[x])) {
rockets.remove(i);
}
}
for (Zombies zombie : ZombiesinGame) {
zombie.setXY(this);
int i = zombie.getGroundX();
zombie.operation(GameGround[i]);
}
deathSets();
for (int i = 0; i < plants_dead.size(); i++) {
coin += plants_dead.get(i).getHealth() * 10;
}
Viewcontroller.shop.setCoin(plants_dead.size() * 10);
if (!plantsCheck()) {
return 2;
}
if (!zombiesCheck() && coin < 20) {
return 0;
}
if (!zombiesCheck()) {
return 1;
}
return -1;
}
public void randomPlanting() {
Ground e = null;
int a;
ArrayList<Integer> random = new ArrayList<>();
ArrayList<Plants> plants = new ArrayList<>(
Arrays.asList(
new Damage("Potato Mine", e), new Damage("Potato Mine", e), new Damage("Potato Mine", e),
new Damage("Explode-o-nut", e), new Damage("Explode-o-nut", e), new Damage("Explode-o-nut", e),
new Pea("Gatling Pea", e), new Pea("Threepeater", e),
new Pea("Scaredy-shroom", e), new Pea("Scaredy-shroom", e), new Pea("Scaredy-shroom", e),
new Pea("Scaredy-shroom", e), new Pea("Scaredy-shroom", e), new Pea("Scaredy-shroom", e),
new Pea("Snow Pea", e), new Pea("Snow Pea", e),
new Shooter("Cabbage-pult", e), new Shooter("Cabbage-pult", e)
));
while (true) {
int flag = 1;
a = generator.nextInt(18);
for (int j = 0; j < random.size(); j++) {
if (random.get(j) == a) {
flag = 0;
break;
}
}
if (flag == 1)
random.add(a);
if (random.size() == 18)
break;
}
for (int i = 0; i < 18; i++) {
int x = random.get(i) / 3;
int y = random.get(i) % 3;
Ground ground = GameGround[x][y];
ground.settledPlant = plants.get(i);
plants.get(i).setGround(ground);
PlantsinGame.add(plants.get(i));
}
}
boolean plantsCheck() {
boolean check = false;
for (int i = 0; i < 6; i++) {
for (int k = 0; k < 19; k++) {
if (GameGround[i][k].settledPlant == null)
continue;
if (!GameGround[i][k].settledPlant.isDead())
check = true;
}
}
return check;
}
boolean zombiesCheck() {
boolean check = false;
for (int i = 0; i < 6; i++) {
for (int k = 0; k < 19; k++) {
for (int w = 0; w < GameGround[i][k].settledZombie.size(); w++)
if (!GameGround[i][k].settledZombie.get(w).isDead())
check = true;
}
}
return check;
}
public int put(String name, int number, int line) {
if (line > 5)
return -2;
if (lanes[line] + number > 2)
return 1;
for (Zombies zombie : zombies_hand) {
if (name.equals(zombie.getName())) {
if (coin >= 10 * zombie.getHealth() * number) {
coin -= zombie.getHealth() * 10 * number;
current = cardFinder(zombie, name);
if (number == 1) {
if (lanes[line] == 0) {
zombies[line][0] = current;
current.setGround(GameGround[line][17]);
GameGround[line][17].settledZombie.add(current);
}
if (lanes[line] == 1) {
zombies[line][1] = current;
GameGround[line][18].settledZombie.add(current);
current.setGround(GameGround[line][18]);
}
lanes[line]++;
ZombiesinGame.add(current);
}
if (number == 2) {
zombies[line][0] = current;
current.setGround(GameGround[line][17]);
GameGround[line][17].settledZombie.add(current);
ZombiesinGame.add(current);
current = cardFinder(zombie, name);
zombies[line][1] = current;
GameGround[line][18].settledZombie.add(current);
current.setGround(GameGround[line][18]);
ZombiesinGame.add(current);
lanes[line] += 2;
}
return 2;
} else return 0;
}
}
return -1;
}
public int putLadder(int line) {
if (line > 5)
return -1;
if (ladder <= 0)
return 0;
for (int i = 2; i <= 0; i++) {
if (GameGround[line][i].settledPlant.type.equals("withoutaction")) {
GameGround[line][i].settledPlant.suddenDeath();
break;
}
}
return 1;
}
public ArrayList<String> showLanes() {
for (int i = 0; i < 6; i++) {
showlanesNumbers.add(i);
for (int j = 0; j < 2; j++) {
showLanes.add(zombies[i][j].getName());
}
}
return showLanes;
}
public ArrayList<Integer> showlanesNumbers() {
return showlanesNumbers;
}
public ArrayList<String> showHand() {
ArrayList<String> all = new ArrayList<String>();
for (int i = 0; i < zombies_hand.size(); i++) {
all.add(zombies_hand.get(i).getName());
zombies_health.add(zombies_hand.get(i).getHealth());
}
return all;
}
public ArrayList<Integer> showHandHealth() {
return zombies_health;
}
public void setLadder() {
this.ladder = 3;
}
}
| true |
7bf3151e5c3295cac2c344c3f03044037f1c067b | Java | yosafatrend/MovieCatalogueFinal | /app/src/test/java/com/yorren/moviecatalogue/data/source/CatalogueRepositoryTest.java | UTF-8 | 5,664 | 2.046875 | 2 | [] | no_license | package com.yorren.moviecatalogue.data.source;
import android.graphics.Movie;
import androidx.arch.core.executor.testing.InstantTaskExecutorRule;
import androidx.lifecycle.MutableLiveData;
import androidx.paging.DataSource;
import androidx.paging.PagedList;
import com.yorren.moviecatalogue.BuildConfig;
import com.yorren.moviecatalogue.data.source.local.LocalDataSource;
import com.yorren.moviecatalogue.data.source.local.entity.MovieEntity;
import com.yorren.moviecatalogue.data.source.local.entity.TvShowsEntity;
import com.yorren.moviecatalogue.data.source.remote.RemoteDataSource;
import com.yorren.moviecatalogue.utils.AppExecutors;
import com.yorren.moviecatalogue.utils.DataDummy;
import com.yorren.moviecatalogue.utils.LiveDataTestUtil;
import com.yorren.moviecatalogue.utils.PagedListUtil;
import com.yorren.moviecatalogue.vo.Resource;
import org.junit.Rule;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CatalogueRepositoryTest {
@Rule
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();
private RemoteDataSource remote = mock(RemoteDataSource.class);
private LocalDataSource local = mock(LocalDataSource.class);
private AppExecutors appExecutors = mock(AppExecutors.class);
private FakeCatalogueRepository catalogueRepository = new FakeCatalogueRepository(remote, local, appExecutors);
private ArrayList<MovieEntity> movieResponse = DataDummy.generateDummyMovies();
private ArrayList<TvShowsEntity> tvResponse = DataDummy.generateDummyTvShows();
private String movieId = movieResponse.get(0).getMovieId();
private String tvId = tvResponse.get(0).getTvId();
@Test
public void getAllMovies() {
DataSource.Factory<Integer, MovieEntity> dataSourceFactory = mock(DataSource.Factory.class);
when(local.getAllMovies()).thenReturn(dataSourceFactory);
catalogueRepository.getAllMovies(BuildConfig.API_KEY, BuildConfig.LANGUAGE, BuildConfig.PAGE);
Resource<PagedList<MovieEntity>> courseEntities = Resource.success(PagedListUtil.mockPagedList(DataDummy.generateDummyMovies()));
verify(local).getAllMovies();
assertNotNull(courseEntities.data);
assertEquals(movieResponse.size(), courseEntities.data.size());
}
@Test
public void getDetailMovie() {
MutableLiveData<MovieEntity> dummyEntity = new MutableLiveData<>();
dummyEntity.setValue(DataDummy.generateDummyMovies().get(0));
when(local.getMovieById(movieId)).thenReturn(dummyEntity);
Resource<MovieEntity> movieEntities = LiveDataTestUtil.getValue(catalogueRepository.getDetailMovie(movieId, BuildConfig.API_KEY, BuildConfig.LANGUAGE));
verify(local).getMovieById(movieId);
assertNotNull(movieEntities.data);
assertNotNull(movieEntities.data.getTitle());
assertEquals(movieResponse.get(0).getTitle(), movieEntities.data.getTitle());
}
@Test
public void getFavoritedMovies() {
DataSource.Factory<Integer, MovieEntity> dataSourceFactory = mock(DataSource.Factory.class);
when(local.getFavoriteMovies()).thenReturn(dataSourceFactory);
catalogueRepository.getFavoriteMovie();
Resource<PagedList<MovieEntity>> courseEntities = Resource.success(PagedListUtil.mockPagedList(DataDummy.generateDummyMovies()));
verify(local).getFavoriteMovies();
assertNotNull(courseEntities);
assertEquals(movieResponse.size(), courseEntities.data.size());
}
@Test
public void getAllTvShows() {
DataSource.Factory<Integer, TvShowsEntity> dataSourceFactory = mock(DataSource.Factory.class);
when(local.getAllTvShows()).thenReturn(dataSourceFactory);
catalogueRepository.getAllTvShows(BuildConfig.API_KEY, BuildConfig.LANGUAGE, BuildConfig.PAGE);
Resource<PagedList<TvShowsEntity>> tvShowsEntities = Resource.success(PagedListUtil.mockPagedList(DataDummy.generateDummyTvShows()));
verify(local).getAllTvShows();
assertNotNull(tvShowsEntities.data);
assertEquals(tvResponse.size(), tvShowsEntities.data.size());
}
@Test
public void getDetailTvShows() {
MutableLiveData<TvShowsEntity> dummyEntity = new MutableLiveData<>();
dummyEntity.setValue(DataDummy.generateDummyTvShows().get(0));
when(local.getTvShowsById(tvId)).thenReturn(dummyEntity);
Resource<TvShowsEntity> tvShowEntities = LiveDataTestUtil.getValue(catalogueRepository.getDetailTvShow(tvId, BuildConfig.API_KEY, BuildConfig.LANGUAGE));
verify(local).getTvShowsById(tvId);
assertNotNull(tvShowEntities.data);
assertNotNull(tvShowEntities.data.getTitle());
assertEquals(tvResponse.get(0).getTitle(), tvShowEntities.data.getTitle());
}
@Test
public void getFavoritedTvShows() {
DataSource.Factory<Integer, TvShowsEntity> dataSourceFactory = mock(DataSource.Factory.class);
when(local.getFavoriteTvShows()).thenReturn(dataSourceFactory);
catalogueRepository.getFavoriteTv();
Resource<PagedList<TvShowsEntity>> tvShowsEntities = Resource.success(PagedListUtil.mockPagedList(DataDummy.generateDummyTvShows()));
verify(local).getFavoriteTvShows();
assertNotNull(tvShowsEntities);
assertEquals(tvResponse.size(), tvShowsEntities.data.size());
}
} | true |
6e0e532f1ac3bfce8bb2d6b7b8365ea563019a3d | Java | ZePing01/mybatis_Query | /test/cn/lzp/mapper/ScoreMapperCustomTest.java | UTF-8 | 1,807 | 2.234375 | 2 | [] | no_license | package cn.lzp.mapper;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import cn.lizeping.po.Score;
import cn.lizeping.po.ScoreCustom;
public class ScoreMapperCustomTest {
public SqlSessionFactory sqlSessionFactory;
@Before
public void setUp() throws Exception {
//创建sqlSessionFactory
// mybatis配置文件
String resource="SqlMapConfig.xml";
// 得到配置文件流
InputStream inputStream=Resources.getResourceAsStream(resource);
// 创建会话工厂,传入mybatis的配置文件信息
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
}
//查询成绩关联学生表
@Test
public void testFindScoreStudent() throws Exception {
//打开会话
SqlSession sqlSession=sqlSessionFactory.openSession();
//创建StudentMapper的对象
ScoreMapperCustom scoreMapperCustom=sqlSession.getMapper(ScoreMapperCustom.class);
//调用mapper方法
List<ScoreCustom> list=scoreMapperCustom.findScoreStudent();
System.out.println(list);
sqlSession.close();
}
//查询成绩表关联学生表,用resultMapper
@Test
public void testFindScoreStudentResultMapper() throws Exception {
//打开会话
SqlSession sqlSession=sqlSessionFactory.openSession();
//创建StudentMapper的对象
ScoreMapperCustom scoreMapperCustom=sqlSession.getMapper(ScoreMapperCustom.class);
//调用mapper方法
List<Score> list=scoreMapperCustom.findScoreStudentResultMapper();
System.out.println(list);
sqlSession.close();
}
}
| true |
ca85cd1ba7f7a022eef2fad4755346aa7393d10d | Java | JohnMG/COMP9024 | /assn2/net/datastructures/TreePosition.java | UTF-8 | 559 | 2.984375 | 3 | [] | no_license | package net.datastructures;
//begin#fragment TPos
/**
* Interface for a node of a binary tree. It maintains an element, a
* parent node, a left node, and a right node.
//end#fragment TPos
*
* @author Michael Goodrich
//begin#fragment TPos
*/
public interface TreePosition<E> extends Position<E> { // inherits element()
public void setElement(E o);
public PositionList<Position<E>> getChildren();
public void setChildren(PositionList<Position<E>> c);
public TreePosition<E> getParent();
public void setParent(TreePosition<E> v);
}
//end#fragment TPos
| true |
ff1ec9c675b1f8ea33d1f227fa49f016eba7d6c5 | Java | elenaborisova/SoftUni-Java-Web-Developer-Path | /08 - Spring Advanced/04 - Workshop/tabula/src/main/java/bg/softuni/tabula/registration/RegistrationController.java | UTF-8 | 1,495 | 2.171875 | 2 | [] | no_license | package bg.softuni.tabula.registration;
import bg.softuni.tabula.announcement.dto.AnnouncementDTO;
import bg.softuni.tabula.registration.dto.RegistrationDTO;
import bg.softuni.tabula.user.UserService;
import javax.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@AllArgsConstructor
@Controller
public class RegistrationController {
private final UserService userService;
@GetMapping("/registration")
public String showRegister(Model model) {
model.addAttribute("formData", new RegistrationDTO());
return "registration/registration";
}
@PostMapping("/registration")
public String register(@Valid @ModelAttribute("formData") RegistrationDTO registrationDTO,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "registration/registration";
}
if (userService.exists(registrationDTO.getEmail())) {
bindingResult.rejectValue("email",
"error.email",
"An account already exists for this email.");
return "registration/registration";
}
userService.registerAndLoginUser(registrationDTO.getEmail(), registrationDTO.getPassword());
return "redirect:/home";
}
}
| true |
bcd4911b28cc1c3f95bd2cf772283ea77a253017 | Java | guehel/JavaIV | /QuizJavaIV/src/TaxProcessor.java | UTF-8 | 81 | 2.328125 | 2 | [] | no_license |
public abstract class TaxProcessor {
public abstract double calculateTaxes();
}
| true |
cf2a7d985e8515f598ab53f5688e58c88b67f1c9 | Java | DiegoHerreraf/ResolucionPrueba3 | /src/java/shop/dao/DbConnection.java | UTF-8 | 1,629 | 2.8125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package shop.dao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Diego
*/
public class DbConnection {
public DbConnection() {
}
public static Connection getConnection(){
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/prueba3db?zeroDateTimeBehavior=convertToNull";
String user = "root";
String pass = "";
Connection con = null;
try {
Class.forName(driver);
con = (Connection)DriverManager.getConnection(url, user, pass);
System.out.println("Conexion satisfactoria");
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
}
public static void deshacerCambios(Connection cn) {
try{cn.rollback();}catch (Exception e){}
}
//Metodo utilizado para cerrar el callablestatemente
public static void cerrarCall(CallableStatement cl) {
try{cl.close();}catch(Exception e){}
}
//Metodo utilizado para cerrar la conexion
public static void cerrarConnection(Connection cn) {
try{cn.close();} catch (Exception e) {}
}
}
| true |
deb14b8511dd9545f8cc04d461585413e1f94ef3 | Java | awesomeleo/LoopTube | /Loop/src/com/kskkbys/loop/ui/fragments/PlayerListFragment.java | UTF-8 | 6,175 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package com.kskkbys.loop.ui.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.kskkbys.loop.R;
import com.kskkbys.loop.logger.KLog;
import com.kskkbys.loop.model.BlackList;
import com.kskkbys.loop.model.Playlist;
import com.kskkbys.loop.model.Video;
import com.kskkbys.loop.service.PlayerCommand;
import com.kskkbys.loop.ui.VideoPlayerActivity;
/**
* This class is a fragment of playlist.
* @author keisuke.kobayashi
*
*/
public class PlayerListFragment extends Fragment {
private static final String TAG = PlayerListFragment.class.getSimpleName();
private ListView mPlayListView;
private VideoAdapter mAdapter;
private ActionMode mActionMode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_player_list, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// PlayListView
mPlayListView = (ListView)getView().findViewById(R.id.playListView);
mPlayListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
KLog.v(TAG, "onItemClick " + position);
Video touchedVideo = Playlist.getInstance().getVideoAtIndex(position);
BlackList bl = BlackList.getInstance(getActivity());
if (bl.containsByUser(touchedVideo.getId()) || bl.containsByApp(touchedVideo.getId())) {
// In blacklist: can not play it.
KLog.v(TAG, "This video can not be played.");
Toast.makeText(getActivity(), R.string.loop_video_player_ignored_already, Toast.LENGTH_SHORT).show();
} else {
Playlist.getInstance().setPlayingIndex(position);
PlayerCommand.play(getActivity(), true);
}
}
});
mPlayListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
if (mActionMode != null) {
return false;
}
mPlayListView.setItemChecked(position, true);
startContextualActionBar(position);
return true;
}
});
// Set adapter
mAdapter = new VideoAdapter(getActivity());
mPlayListView.setAdapter(mAdapter);
}
/**
* Update video info
*/
public void updateVideoInfo() {
mAdapter.notifyDataSetChanged();
}
/**
* Start contextual action bar by long click of play list.
* @param position
*/
public void startContextualActionBar(final int position) {
final VideoPlayerActivity activity = (VideoPlayerActivity)getActivity();
mActionMode = activity.startSupportActionMode(new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.activity_player_cab, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode,
Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode,
MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_ignore:
ignoreVideo(position);
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
@Override
public void onDestroyActionMode(ActionMode mode) {
updateVideoInfo();
mActionMode = null;
}
});
}
/**
* Add the selected video to blacklist
* @param position
*/
private void ignoreVideo(int position) {
KLog.v(TAG, "ignoreVideo");
Video video = Playlist.getInstance().getVideoAtIndex(position);
if (video != null) {
String videoId = video.getId();
BlackList.getInstance(getActivity()).addUserBlackList(videoId);
// update list view
updateVideoInfo();
// Show toast
Toast.makeText(getActivity(), R.string.loop_video_player_ignored, Toast.LENGTH_SHORT).show();
}
}
/**
* Adapter for playlist view
* @author keisuke.kobayashi
*/
private static class VideoAdapter extends ArrayAdapter<Video> {
private Activity mActivity;
public VideoAdapter(Activity activity) {
super(activity, R.layout.row_video_player_playlist, R.id.videoTitleViewInList, Playlist.getInstance().getVideos());
mActivity = activity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater)mActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.row_video_player_playlist, null);
}
Video video = getItem(position);
if (video != null) {
// video title
TextView textView = (TextView)v.findViewById(R.id.videoTitleViewInList);
textView.setText(video.getTitle());
// now playing or blacklist or nothing
ImageView imageView = (ImageView)v.findViewById(R.id.nowPlayingImageInList);
if (Playlist.getInstance().getPlayingIndex() == position) {
imageView.setImageResource(R.drawable.volume_plus2);
} else if (BlackList.getInstance(mActivity).containsByUser(video.getId())) {
imageView.setImageResource(R.drawable.prohibited);
} else if (BlackList.getInstance(mActivity).containsByApp(video.getId())) {
imageView.setImageResource(R.drawable.circle_exclamation);
} else {
imageView.setImageBitmap(null);
}
}
return v;
}
}
}
| true |
65035d8b48d87da050da4471110ed13a6bf8a2f0 | Java | LolitaComplex/VM-BiliBili | /app/src/main/java/com/doing/bilibili/ui/fragment/recycleritem/BangumiCommonItem.java | UTF-8 | 3,546 | 2.171875 | 2 | [] | no_license | package com.doing.bilibili.ui.fragment.recycleritem;
import android.content.Context;
import android.view.View;
import com.doing.bilibili.R;
import com.doing.bilibili.ui.adapter.CardViewAndTitleBangumiAdapter;
import com.doing.bilibili.baselib.adapter.recyclerview.BaseViewHolder;
import com.doing.bilibili.baselib.utils.ToastUtil;
import com.doing.bilibili.baselib.utils.UIUtils;
import com.doing.bilibili.data.entity.bangumi.BangumiItemBean;
import com.doing.bilibili.ui.widget.GridViewFactoryView;
/**
* Created by Doing on 2016/9/23.
*
*/
public class BangumiCommonItem extends ItemViewDelegateImp<BangumiItemBean> implements View.OnClickListener {
private int[] iconBox;
private int[] seasonIconBox;
private String[] titleBox;
private String[] titleMoreBox;
public BangumiCommonItem(Context context) {
super(context);
iconBox = new int[]{R.mipmap.ic_category_t33,
R.mipmap.ic_category_t153, 0,
R.mipmap.ic_category_t22};
seasonIconBox = new int[]{R.drawable.bangumi_home_ic_season_1,
R.drawable.bangumi_home_ic_season_2,
R.drawable.bangumi_home_ic_season_3,
R.drawable.bangumi_home_ic_season_4};
titleBox = UIUtils.getStringArray(R.array.array_home_bangumi_title);
titleMoreBox = UIUtils.getStringArray(R.array.array_home_bangumi_title_more);
}
@Override
public int getItemViewLayoutId() {
return R.layout.item_bangumi_common;
}
@Override
public boolean isForViewType(BangumiItemBean item, int position) {
if (position < 4 ) {
return true;
}else{
return false;
}
}
@Override
public void convert(BaseViewHolder holder, BangumiItemBean data, int position) {
initTitleAndLogo(holder, data, position);
holder.setOnClickListener(R.id.BangumiCommonItem_header_tv_more, this);
holder.getView(R.id.BangumiCommonItem_header_tv_more).setTag(position);
GridViewFactoryView gridViewFratory = holder.getView(R.id.BangumiCommonItem_body_cvf);
if(position == 0) {
gridViewFratory.setRowCount(2, true);
}
if(position == 3){
gridViewFratory.setVisibility(View.GONE);
holder.getView(R.id.BangumiCommonItem_header_tv_more).setVisibility(View.GONE);
}else{
gridViewFratory.setAdapter(new CardViewAndTitleBangumiAdapter(mContext,
R.layout.layout_cardview_and_title, data.getList(), position));
}
}
private void initTitleAndLogo(BaseViewHolder holder, BangumiItemBean data, int position) {
String title;
int iconId;
if (position == 2) {
title = 1 + (data.getSeason()-1)*3 + titleBox[position];
iconId = seasonIconBox[data.getSeason()-1];
} else {
title = titleBox[position];
iconId = iconBox[position];
}
holder.setText(R.id.BangumiCommonItem_header_tv_title, title);
holder.setImageBitmapRes(R.id.BangumiCommonItem_header_iv_logo, iconId);
if (position < 3) {
holder.setText(R.id.BangumiCommonItem_header_tv_more, titleMoreBox[position]);
}
}
@Override
public void onClick(View v) {
int currentPostion = (int) v.getTag();
switch (v.getId()) {
case R.id.BangumiCommonItem_header_tv_more:
ToastUtil.show(titleMoreBox[currentPostion]);
break;
}
}
}
| true |
d58819a7978a79634e3c62c8ce664ffa67860ef3 | Java | shq-0103/app | /app/src/main/java/com/shq/movies/http/request/MessageApi.java | UTF-8 | 575 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | package com.shq.movies.http.request;
import com.hjq.http.config.IRequestApi;
public final class MessageApi implements IRequestApi {
public String getApi() {
return "notice/my";
}
private int page;
private int pageSize;
public int getPage() {
return page;
}
public int getPageSize() {
return pageSize;
}
public MessageApi setPage(int page) {
this.page = page;
return this;
}
public MessageApi setPageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
}
| true |
22d574f5278af24d3193243b4025d26192a45abd | Java | SjoerdvanderHeijden/endless-ql | /piotr/org.uva.sc.piotr.ql/src/main/java/ql/logic/collectors/CollectQuestionModelsVisitor.java | UTF-8 | 3,183 | 2.453125 | 2 | [] | no_license | package ql.logic.collectors;
import ql.ast.model.Form;
import ql.ast.model.expressions.Expression;
import ql.ast.model.expressions.binary.logical.LogicalAnd;
import ql.ast.model.expressions.unary.logical.Negation;
import ql.ast.model.statements.IfStatement;
import ql.ast.model.statements.Question;
import ql.ast.model.statements.Statement;
import ql.ast.visitors.AbstractASTTraverse;
import ql.gui.model.QuestionModel;
import ql.logic.type.QLDataTypeWrapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
public class CollectQuestionModelsVisitor extends AbstractASTTraverse<Void> {
private List<QuestionModel> questionModels = new ArrayList<>();
private Stack<Expression> conditionsStack = new Stack<>();
public List<QuestionModel> getQuestionModels(Form form) {
this.questionModels = new ArrayList<>();
this.conditionsStack = new Stack<>();
form.accept(this);
return questionModels;
}
@Override
public Void visit(Form form) {
for (Statement statement : form.getStatementList()) {
statement.accept(this);
}
return null;
}
@Override
public Void visit(Question question) {
Expression aggregatedVisibilityCondition = this.aggregateConditionsStack();
// strips question and flattens visibility condition (for ql.gui rendering ease)
QuestionModel questionModel = new QuestionModel(
question,
aggregatedVisibilityCondition
);
this.questionModels.add(questionModel);
question.getVariableType().accept(this);
if (question.getAssignedExpression() != null) {
question.getAssignedExpression().accept(this);
}
return null;
}
@Override
public Void visit(IfStatement ifStatement) {
ifStatement.getCondition().accept(this);
// if block
this.conditionsStack.push(ifStatement.getCondition());
for (Statement statement : ifStatement.getStatementList()) {
statement.accept(this);
}
// else block
this.conditionsStack.push(new Negation(this.conditionsStack.pop()));
for (Statement statement : ifStatement.getElseStatementList()) {
statement.accept(this);
}
this.conditionsStack.pop();
return null;
}
private Expression aggregateConditionsStack() {
Expression finalExpression = null;
for (Expression expression : this.conditionsStack) {
if (finalExpression == null) {
finalExpression = expression;
} else {
finalExpression = new LogicalAnd(finalExpression, expression);
}
}
return finalExpression;
}
public HashMap<String, QLDataTypeWrapper> getVariablesValues() {
HashMap<String, QLDataTypeWrapper> variablesValues = new HashMap<>();
for (QuestionModel questionModel : this.questionModels) {
variablesValues.put(questionModel.getVariableName(), questionModel.getQLDataTypeValue());
}
return variablesValues;
}
}
| true |
8614998a7dd1771692d992038ba19a9691daf070 | Java | Laugic/theVacant | /src/main/java/theVacant/cards/Skills/TheAnvil.java | UTF-8 | 3,024 | 2.171875 | 2 | [] | no_license | package theVacant.cards.Skills;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.actions.animations.VFXAction;
import com.megacrit.cardcrawl.actions.common.DamageAllEnemiesAction;
import com.megacrit.cardcrawl.actions.utility.SFXAction;
import com.megacrit.cardcrawl.cards.DamageInfo;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import com.megacrit.cardcrawl.vfx.combat.CleaveEffect;
import theVacant.VacantMod;
import theVacant.cards.AbstractDynamicCard;
import theVacant.characters.TheVacant;
import static theVacant.VacantMod.makeCardPath;
public class TheAnvil extends AbstractDynamicCard {
public static final String ID = VacantMod.makeID(TheAnvil.class.getSimpleName());
public static final String IMG = makeCardPath("TheAnvil.png");
private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID);
private static final CardRarity RARITY = CardRarity.RARE;
private static final CardTarget TARGET = CardTarget.ALL_ENEMY;
private static final CardType TYPE = CardType.SKILL;
public static final CardColor COLOR = TheVacant.Enums.COLOR_GOLD;
private static final int COST = -2;
private static final int DAMAGE = 24;
private static final int UPGRADE_PLUS_DMG = 8;
public TheAnvil()
{
super(ID, IMG, COST, TYPE, COLOR, RARITY, TARGET);
magicNumber = baseMagicNumber = DAMAGE;
isUnnate = true;
isHeavy = true;
postMillAction = true;
isMultiDamage = true;
}
@Override
public boolean canUse(AbstractPlayer p, AbstractMonster m)
{
this.cantUseMessage = cardStrings.UPGRADE_DESCRIPTION;
return false;
}
@Override
public void use(AbstractPlayer p, AbstractMonster m)
{
//AbstractDungeon.actionManager.addToBottom( new DamageAction(m, new DamageInfo(p, damage, damageTypeForTurn), AbstractGameAction.AttackEffect.BLUNT_LIGHT));
}
@Override
public void PostMillAction()
{
AbstractPlayer player = AbstractDungeon.player;
AbstractDungeon.actionManager.addToBottom(new SFXAction("ATTACK_HEAVY"));
AbstractDungeon.actionManager.addToBottom(new VFXAction(player, new CleaveEffect(), 0.1F));
//addToBot(new DamageAllEnemiesAction(player, multiDamage, damageTypeForTurn, AbstractGameAction.AttackEffect.NONE));
AbstractDungeon.actionManager.addToBottom(new DamageAllEnemiesAction(player, DamageInfo.createDamageMatrix(magicNumber, true), DamageInfo.DamageType.THORNS, AbstractGameAction.AttackEffect.NONE));
}
@Override
public void upgrade()
{
if (!upgraded)
{
upgradeName();
upgradeMagicNumber(UPGRADE_PLUS_DMG);
initializeDescription();
}
}
} | true |
f4d2416a30380fde4b04afcd282f1371bc83c72f | Java | vitorbg/trabalho-sd | /Trabalho-1/Cliente/src/cliente/Cliente.java | UTF-8 | 1,093 | 3.015625 | 3 | [] | no_license | package cliente;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
/* Passe dois argumentos: url + porta
* Exemplos:
* localhost 80
* www.uol.com.br 80
* localhost 8089
*/
public class Cliente {
public static void main(String[] args) throws IOException {
Socket server;
if(args[0].equals("localhost") || args[0].equals("127.0.0.1"))
{
server = new Socket(InetAddress.getLocalHost(), Integer.parseInt(args[1]));
}
else{
server = new Socket(InetAddress.getByName(args[0]), Integer.parseInt(args[1]));
}
PrintWriter pw = new PrintWriter(server.getOutputStream());
pw.println("GET / HTTP/1.1");
pw.println("Host: "+args[0]);
pw.println("");
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(server.getInputStream()));
String t;
while((t = br.readLine()) != null)
System.out.println(t);
br.close();
}
}
| true |
76f8198874b708a3b56ef6dc6a14ffcc9d7bdab6 | Java | li-ch/enforcer | /core/src/main/java/netlink/TcObject.java | UTF-8 | 1,968 | 1.984375 | 2 | [] | no_license | package netlink;
import netlink.swig.SWIGTYPE_p_rtnl_tc;
import netlink.swig.capi;
import java.io.IOException;
public class TcObject {
final SWIGTYPE_p_rtnl_tc ptr;
protected TcObject(SWIGTYPE_p_rtnl_tc ptr) {
this.ptr = ptr;
}
public String getKind() {
return capi.rtnl_tc_get_kind(ptr);
}
public TcObject setKind(String kind) throws IOException {
int ret = capi.rtnl_tc_set_kind(ptr, kind);
if (ret < 0) {
throw new IOException(capi.nl_geterror(ret));
}
return this;
}
public int getIfindex() {
return capi.rtnl_tc_get_ifindex(ptr);
}
public TcObject setIfindex(int ifindex) {
capi.rtnl_tc_set_ifindex(ptr, ifindex);
return this;
}
public long getMtu() {
return capi.rtnl_tc_get_mtu(ptr);
}
public TcObject setMtu(long mtu) {
capi.rtnl_tc_set_mtu(ptr, mtu);
return this;
}
public long getMpu() {
return capi.rtnl_tc_get_mpu(ptr);
}
public TcObject setMpu(long mpu) {
capi.rtnl_tc_set_mpu(ptr, mpu);
return this;
}
public long getOverhead() {
return capi.rtnl_tc_get_overhead(ptr);
}
public TcObject setOverhead(long overhead) {
capi.rtnl_tc_set_overhead(ptr, overhead);
return this;
}
public long getLinkType() {
return capi.rtnl_tc_get_linktype(ptr);
}
public TcObject setLinkType(long linkType) {
capi.rtnl_tc_set_linktype(ptr, linkType);
return this;
}
public long getHandle() {
return capi.rtnl_tc_get_handle(ptr);
}
public TcObject setHandle(long handle) {
capi.rtnl_tc_set_handle(ptr, handle);
return this;
}
public long getParent() {
return capi.rtnl_tc_get_parent(ptr);
}
public TcObject setParent(long parent) {
capi.rtnl_tc_set_parent(ptr, parent);
return this;
}
}
| true |
e9fecb6214c1b3467cf4c885eac97496615522e2 | Java | harinathk/medileads-appointments | /src/main/java/com/medileads/spring/cloud/ms/appointments/AppointmentWithQueues.java | UTF-8 | 449 | 2.421875 | 2 | [] | no_license | package com.medileads.spring.cloud.ms.appointments;
import java.util.List;
public class AppointmentWithQueues extends Appointment {
private List<Queue> queues;
public AppointmentWithQueues(Appointment r, List<Queue> queues) {
super(r.getName(), r.getId(), r.getState(), r.getCity());
this.queues = queues;
}
public List<Queue> getQueues(){
return queues;
}
public void setQueues(List<Queue> queues){
this.queues = queues;
}
}
| true |
f44268b18207f15aec8378669b47c6f64d97cc4e | Java | nidichaoge/bms-trade | /bms-trade-common/src/main/java/com/mouse/bms/trade/common/response/MapResult.java | UTF-8 | 392 | 1.859375 | 2 | [] | no_license | package com.mouse.bms.trade.common.response;
import java.util.Map;
import lombok.Data;
/**
* CopyRight(C),mouse
*
* @author : mouse
* @fileName : MapResult
* @date : 2019/3/2 13:49
* @description : 接口返回的是map
*/
@Data
public class MapResult<K, V> extends BaseResult {
private static final long serialVersionUID = 3322979975143941046L;
private Map<K, V> data;
}
| true |
861d775d235b3b962143bc13ef2394b4197f5d44 | Java | RioSif/Java-HackerRank_Challenges | /ProjectEuler/$2_Even_Fibonacci_numbers/Solution.java | UTF-8 | 816 | 3.40625 | 3 | [] | no_license | package $2_Even_Fibonacci_numbers;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static long sumeven(long n) {
// your code
long result = 0;
long fSum = Long.MAX_VALUE;
long fibN0 = 0;
long fibN = 1;
long fibN1;
while (n >= (fibN1 = fibN + fibN0 )) {
result = fibN1 % 2 == 0 ? result + fibN1 : result;
fibN0 = fibN;
fibN = fibN1;
}
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long n = in.nextLong();
System.out.println(sumeven(n));
}
}
} | true |
385e64ec61dcc4ee4e1bda95638a832214a88ba9 | Java | xiaoyamer/my_wx | /src/main/java/com/my/demo1/common/ResultResponse.java | UTF-8 | 1,479 | 2.65625 | 3 | [] | no_license | package com.my.demo1.common;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.my.demo1.common.enums.ResultEnums;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResultResponse<T> {
private int code;
private String msg;
//返回json时忽略null的属性
@JsonInclude(JsonInclude.Include.NON_NULL)
private T data;
//失败或成功,不返回数据时
public ResultResponse(int code,String msg){
this.code=code;
this.msg=msg;
}
//失败后不带数据只带信息
public static ResultResponse fail(String msg){
return new ResultResponse(ResultEnums.FAIL.getCode(),msg);
}
//失败后带数据和信息
public static <T>ResultResponse fail(String msg,T t){
return new ResultResponse<>(ResultEnums.FAIL.getCode(),msg,t);
}
//失败后只携带数据,不带信息
public static <T>ResultResponse fail(T t){
return new ResultResponse<>(ResultEnums.FAIL.getCode(),ResultEnums.FAIL.getMsg(),t);
}
//成功后携带数据
public static <T>ResultResponse success(T t){
return new ResultResponse<>(ResultEnums.SUCCESS.getCode(),ResultEnums.SUCCESS.getMsg(),t);
}
//成功后不带数据
public static <T>ResultResponse success(){
return new ResultResponse(ResultEnums.SUCCESS.getCode(),ResultEnums.SUCCESS.getMsg());
}
}
| true |
82cd588a879b982e3dd9122d0f95df8fee356c33 | Java | Aadirn/DAOTxt | /src/dao/RAMPersonaDAO.java | UTF-8 | 1,459 | 2.796875 | 3 | [] | no_license | package dao;
import java.util.ArrayList;
import java.util.List;
import modelo.Persona;
import modelo.Tipo;
public class RAMPersonaDAO implements PersonaDAO {
private ArrayList<Persona> personas;
public RAMPersonaDAO() {
personas = new ArrayList<>();
personas.add(new Persona("11111111X", "Eva Rey", 69, Tipo.CLIENTE));
personas.add(new Persona("22222222H", "Rosa Meltroso", 31, Tipo.EMPLEADO));
personas.add(new Persona("33333333F", "Ricardo Nardo", 24, Tipo.PROVEEDOR));
personas.add(new Persona("44444444R", "Luis Pitis", 44, Tipo.CLIENTE));
}
@Override
public List<Persona> getAllPersona() {
return personas;
}
@Override
public Persona getPersonaByNIF(String NIF) {
for (Persona p : personas) {
if (p.getNIF().equals(NIF)) {
return p;
}
}
return null;
}
@Override
public boolean addPersona(Persona p) {
if (personas.contains(p)) {
return false;
} else {
personas.add(p);
return true;
}
}
@Override
public boolean removePersona(Persona p) {
return personas.remove(p);
}
@Override
public boolean updatePersona(Persona p) {
int indice;
if ((indice = personas.indexOf(p)) == -1) {
return false;
} else {
personas.set(indice, p);
return true;
}
}
}
| true |
ddea5bba3d79eb55ecc64957c534aab0ace39d39 | Java | LaoLiulaoliu/hbasedemo | /src/main/java/com/hbase/hbasedemo/structure/Address.java | UTF-8 | 1,005 | 2.484375 | 2 | [] | no_license | package com.hbase.hbasedemo.structure;
public class Address {
public String ctryCde;
public String line3;
public String line2;
public String line1;
public String getCtryCde() {
return ctryCde;
}
public void setCtryCde(String ctryCde) {
this.ctryCde = ctryCde;
}
public String getLine3() {
return line3;
}
public void setLine3(String line3) {
this.line3 = line3;
}
public String getLine2() {
return line2;
}
public void setLine2(String line2) {
this.line2 = line2;
}
public String getLine1() {
return line1;
}
public void setLine1(String line1) {
this.line1 = line1;
}
@Override
public String toString() {
return "Address{" +
"ctryCde='" + ctryCde + '\'' +
", line3='" + line3 + '\'' +
", line2='" + line2 + '\'' +
", line1='" + line1 + '\'' +
'}';
}
} | true |
7a2bca74b0c8f2f1bd33db8375eb29a770e918aa | Java | haneyeyedea/Terrarium | /Project4/TextStatistics.java | UTF-8 | 759 | 2.609375 | 3 | [] | no_license | import java.io.File;
public class TextStatistics implements TextStatisticsInterface
{
public TextStatistics(String string) {
File file = new File(string);
}
@Override
public int getCharCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getWordCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getLineCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int[] getLetterCount() {
// TODO Auto-generated method stub
return null;
}
@Override
public int[] getWordLengthCount() {
// TODO Auto-generated method stub
return null;
}
@Override
public double getAverageWordLength() {
// TODO Auto-generated method stub
return 0;
}
}
| true |
104f2c70d22ae47101b9c11011dc7dd3a6570777 | Java | 805058027/wanandroid-mvp | /app/src/main/java/com/example/administrator/wanandroid/bean/LoginBean.java | UTF-8 | 608 | 1.757813 | 2 | [] | no_license | package com.example.administrator.wanandroid.bean;
import java.util.List;
/**
* Created by Administrator on 2019/3/1.
*/
public class LoginBean {
/**
* chapterTops : []
* collectIds : [3146,3218,3386,5638,3648,7619]
* email :
* icon :
* id : 5475
* password :
* token :
* type : 0
* username : 805058027
*/
public String email;
public String icon;
public int id;
public String password;
public String token;
public int type;
public String username;
public List<?> chapterTops;
public List<Integer> collectIds;
}
| true |
d11308fbf70fbe71826dc543abba5658a4d859d2 | Java | ddo009/HelloAndroid4 | /app/src/main/java/com/choinisae/nisaechoi/myapplication/last/LastFragmentExam.java | UTF-8 | 425 | 1.53125 | 2 | [] | no_license | package com.choinisae.nisaechoi.myapplication.last;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.choinisae.nisaechoi.myapplication.R;
public class LastFragmentExam extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last_fragment_exam);
}
}
| true |
2a1a484e4a7ccaa700730473364198ed65cf9791 | Java | jkk84/Bookstore-Spring-Boot-API-Project | /src/main/java/pl/bookstore/restapi/model/ReviewEntity.java | UTF-8 | 936 | 2.171875 | 2 | [
"MIT"
] | permissive | package pl.bookstore.restapi.model;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Getter
@Setter
@Table(name = "reviews")
public class ReviewEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long reviewId;
private long rating;
private String comment;
@CreationTimestamp
@Column(updatable = false)
private LocalDateTime createdAt;
@ManyToOne
@JoinTable(name="reviews_users", joinColumns = @JoinColumn(name = "reviews_reviewId"),
inverseJoinColumns = @JoinColumn(name = "users_userId"))
private UserEntity userEntity;
@ManyToOne
@JoinTable(name="reviews_books", joinColumns = @JoinColumn(name = "reviews_reviewId"),
inverseJoinColumns = @JoinColumn(name = "books_bookId"))
private BookEntity bookEntity;
}
| true |
1fac37fc3712992cf691943ed2847fae9b054bf5 | Java | zhuyf03516/ares-studio | /core/com.hundsun.ares.studio.procedure.ui/src/com/hundsun/ares/studio/procedure/ui/support/ProcedureRelatedInfoColumnLabelProvider.java | GB18030 | 3,573 | 1.984375 | 2 | [
"MIT"
] | permissive | /**
* <p>Copyright: Copyright (c) 2013</p>
* <p>Company: ӹɷ˾</p>
*/
package com.hundsun.ares.studio.procedure.ui.support;
import org.apache.commons.lang.StringUtils;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import com.hundsun.ares.studio.core.IARESProject;
import com.hundsun.ares.studio.core.IARESResource;
import com.hundsun.ares.studio.jres.basicdata.constant.IBasicDataRestypes;
import com.hundsun.ares.studio.jres.basicdata.core.basicdata.BasicDataBaseModel;
import com.hundsun.ares.studio.jres.database.constant.IDatabaseRefType;
import com.hundsun.ares.studio.jres.metadata.constant.IMetadataRefType;
import com.hundsun.ares.studio.jres.model.database.TableResourceData;
import com.hundsun.ares.studio.model.reference.ReferenceInfo;
import com.hundsun.ares.studio.procdure.ProcdurePackage;
import com.hundsun.ares.studio.procdure.RelatedInfo;
import com.hundsun.ares.studio.procedure.ui.assistant.ProcedurePageHelper;
import com.hundsun.ares.studio.reference.ReferenceManager;
import com.hundsun.ares.studio.ui.editor.blocks.DisplayItem;
import com.hundsun.ares.studio.ui.editor.viewers.EObjectColumnLabelProvider;
/**
* @author qinyuan
*
*/
public class ProcedureRelatedInfoColumnLabelProvider extends EObjectColumnLabelProvider {
private IARESProject project;
protected EReference reference;
public ProcedureRelatedInfoColumnLabelProvider(IARESResource resource, EReference reference, EStructuralFeature attribute) {
super(attribute);
this.project = resource.getARESProject();
this.reference = reference;
}
/* (non-Javadoc)
* @see com.hundsun.ares.studio.ui.editor.viewers.BaseEObjectColumnLabelProvider#getText(java.lang.Object)
*/
@Override
public String getText(Object element) {
if(element instanceof RelatedInfo) {
RelatedInfo relatedInfo = (RelatedInfo)element;
EStructuralFeature feature = getEStructuralFeature(element);
if(ProcdurePackage.Literals.PROCEDURE__RELATED_TABLE_INFO.equals(reference)){//
ReferenceInfo referenceInfo = ReferenceManager.getInstance().getFirstReferenceInfo(project,IDatabaseRefType.Table,relatedInfo.getId(),true);
if(null != referenceInfo) {
TableResourceData table = (TableResourceData)referenceInfo.getObject();
if(ProcdurePackage.Literals.RELATED_INFO__ID.equals(feature)){
return relatedInfo.getId();
}else if(ProcdurePackage.Literals.RELATED_INFO__COMMENT.equals(feature)) {
return table.getChineseName();
}else if(ProcdurePackage.Literals.RELATED_INFO__PATH.equals(feature)) {
return referenceInfo.getResource().getResource().getProjectRelativePath().toOSString();
}
}
}else if(ProcdurePackage.Literals.PROCEDURE__RELATED_BASIC_DATA_INFO.equals(reference)) {//
ReferenceInfo referenceInfo = ReferenceManager.getInstance().getFirstReferenceInfo(project,IBasicDataRestypes.singleTable,relatedInfo.getId(),true);
if(null != referenceInfo) {
BasicDataBaseModel table = (BasicDataBaseModel)referenceInfo.getObject();
if(ProcdurePackage.Literals.RELATED_INFO__ID.equals(feature)){
return relatedInfo.getId();
}else if(ProcdurePackage.Literals.RELATED_INFO__COMMENT.equals(feature)) {
return table.getChineseName();
}else if(ProcdurePackage.Literals.RELATED_INFO__PATH.equals(feature)) {
return referenceInfo.getResource().getResource().getProjectRelativePath().toOSString();
}
}
}
}
return StringUtils.EMPTY;
}
}
| true |
ea88838df23ec9b4882c8571d4a89b0f6503c137 | Java | yangkklt/Algorythms | /src/org/mechaevil/algos/misc/SudokuSolver.java | UTF-8 | 988 | 3.125 | 3 | [] | no_license | package org.mechaevil.algos.misc;
import java.util.Arrays;
public class SudokuSolver {
private SudokuSolver() {
}
public static boolean solve(int[][] mtx) {
int l = mtx.length;
int x = -1, y = -1;
for (int i = 0; x < 0 && y < 0 && i < l; i++) {
for (int j = 0; j < l; j++) {
if (mtx[i][j] == 0) {
x = i;
y = j;
break;
}
}
}
if (x < 0 && y < 0)
return true;
boolean[] digits = new boolean[l + 1];
int sq = (int) Math.sqrt(l);
for (int i = 0; i < l; i++) {
digits[mtx[i][y]] = digits[mtx[x][i]] = true;
if (sq * sq == l) {
digits[mtx[(x / sq) * sq + (i / sq)][(y / sq) * sq + (i % sq)]] = true;
}
}
for (int i = 9; i > 0; i--) {
if (!digits[i]) {
mtx[x][y] = i;
if (solve(mtx))
return true;
mtx[x][y] = 0;
}
}
return false;
}
public static void main(String[] args) {
int[][] mtx = new int[9][9];
solve(mtx);
for (int[] row : mtx)
System.out.println(Arrays.toString(row));
}
}
| true |
5a6b7716d70c33b4583e89b222b3bc6994308ef2 | Java | ma-c-kik/java-food-deliver-app-volados-user | /app/src/main/java/gofereats/adapters/main/ReceiptOrderAdapter.java | UTF-8 | 2,744 | 2.28125 | 2 | [] | no_license | package gofereats.adapters.main;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.obs.CustomTextView;
import java.util.List;
import javax.inject.Inject;
import gofereats.R;
import gofereats.configs.AppController;
import gofereats.configs.SessionManager;
import gofereats.datamodels.order.MenuListModel;
/**
* @author Trioangle Product Team
* @version 1.0
* @package com.gofereats
* @subpackage adapter.main
* @category Adapter
*/
/* ************************************************************
Receipt Order adapter of an upcoming order
*********************************************************** */
public class ReceiptOrderAdapter extends RecyclerView.Adapter<ReceiptOrderAdapter.ViewHolder> {
public @Inject
SessionManager sessionManager;
private List<MenuListModel> menuListModels;
/**
* ReceiptOrderAdapter Constructor
*
* @param menuListModels menuListModels list
*/
public ReceiptOrderAdapter(List<MenuListModel> menuListModels) {
AppController.getAppComponent().inject(this);
this.menuListModels = menuListModels;
}
@NonNull
@Override
public ReceiptOrderAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.receipt_orders, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ReceiptOrderAdapter.ViewHolder holder, int position) {
holder.item_count.setText(String.valueOf(menuListModels.get(position).getQuantity()));
holder.item_name.setText(menuListModels.get(position).getMenuName());
//holder.addtional_charge.setText(menuListModels.get(position).getQuantity());
int count = menuListModels.get(position).getQuantity();
double eachPrice = Double.valueOf(menuListModels.get(position).getPrice());
holder.item_price.setText(sessionManager.getCurrencySymbol() + String.valueOf(eachPrice));
}
@Override
public int getItemCount() {
return menuListModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private CustomTextView item_count;
private CustomTextView item_name;
private CustomTextView item_price;
public ViewHolder(View itemView) {
super(itemView);
item_count = itemView.findViewById(R.id.item_count);
item_name = itemView.findViewById(R.id.item_name);
item_price = itemView.findViewById(R.id.item_price);
}
}
}
| true |
1693b7efdf76b5fe8fb9a36e3b7ffc04386be337 | Java | Nedelosk/Modular-Machines | /src/main/java/modularmachines/common/utils/content/IColoredItem.java | UTF-8 | 180 | 1.867188 | 2 | [
"MIT"
] | permissive | package modularmachines.common.utils.content;
import net.minecraft.item.ItemStack;
public interface IColoredItem {
int getColorFromItemstack(ItemStack stack, int tintIndex);
}
| true |
6776a67fe1c78b86987f8b9b53c83e5ba92b471f | Java | songyahuix2/cx | /src/java04/day12_framework/work/Test_2_ArrayListToReserveString.java | UTF-8 | 781 | 3.265625 | 3 | [] | no_license | package java04.day12_framework.work;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @author shkstart
* @date 7/30/2019 - 5:48 PM
*/
public class Test_2_ArrayListToReserveString {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("test_1");
list.add("test_2");
list.add("test_3");
list.add("test_4");
list.add("test_5");
System.out.println(list.get(2));
list.remove(1);
list.set(2,"run");
Iterator<String> it = list.iterator();
while (it.hasNext()){
System.out.print(it.next()+'\t');
}
for (String str:list
) {
System.out.print(str+" ");
}
}
}
| true |