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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
04efa481a710e1df139b4d83cea9899f8796f5f9 | Java | ping2ravi/gae-data-viewer | /GWTCommon/src/com/next/common/client/panels/generic/MyDatePicker.java | UTF-8 | 2,044 | 2.515625 | 3 | [] | no_license | package com.next.common.client.panels.generic;
import java.util.Date;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.datepicker.client.DatePicker;
public class MyDatePicker extends HorizontalPanel implements ClickHandler{
private TextBox dateField;
private Button datePickerButton;
public MyDatePicker()
{
dateField = new TextBox();
dateField.setEnabled(false);
datePickerButton = new Button("..");
datePickerButton.addClickHandler(this);
this.add(dateField);
this.add(datePickerButton);
}
@Override
public void onClick(ClickEvent event) {
if(event.getSource().equals(datePickerButton))
{
final PopupPanel pp = new PopupPanel();
DatePicker datePicker = new DatePicker();
datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {
@Override
public void onValueChange(ValueChangeEvent<Date> event) {
Date date = event.getValue();
String dateString = DateTimeFormat.getMediumDateFormat().format(date);
dateField.setText(dateString);
pp.hide();
}
});
pp.setWidget(datePicker);
pp.setAutoHideEnabled(true);
pp.showRelativeTo((UIObject)event.getSource());
}
}
public String getDate()
{
return dateField.getText();
}
public void setDate(String dateValue)
{
dateField.setText(dateValue);
}
public void clear()
{
dateField.setText("");
}
public void setEnabled(boolean enabled)
{
datePickerButton.setEnabled(enabled);
}
}
| true |
fc59cacb18489fdedb3b9f1b520839953150f073 | Java | cenkatahan/Recipe-List | /app/src/main/java/com/example/recipeslist/RecipeActivity.java | UTF-8 | 2,344 | 2.140625 | 2 | [] | no_license | package com.example.recipeslist;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class RecipeActivity extends AppCompatActivity {
private Recipe recipe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
Toolbar toolbarRecipe = findViewById(R.id.toolbar_recipe);
setSupportActionBar(toolbarRecipe);
toolbarRecipe.setLogo(R.drawable.ic_action_app);
TextView recipeName = findViewById(R.id.recipe_name);
TextView ingredientsName = findViewById(R.id.ingredient_view);
TextView preparation = findViewById(R.id.preparation_view);
int recipeId = (Integer) getIntent().getExtras().get("position");
recipe = Recipe.recipes[recipeId];
recipeName.setText(recipe.getName());
ingredientsName.setText(recipe.getIngredients());
preparation.setText(recipe.getPreparation());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.help_menu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.action_help:
openHelpDialog();
return true;
case R.id.action_share:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, recipe.getName());
intent.putExtra(Intent.EXTRA_TEXT, recipe.getIngredients());
intent.putExtra(Intent.EXTRA_TEXT, recipe.getPreparation());
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openHelpDialog(){
HelpDialog helpDialog = new HelpDialog();
helpDialog.show(getSupportFragmentManager(),"help dialog");
}
} | true |
bba694f3230a4027f9949c0457072aaeec9c6835 | Java | chenz123/AI | /AI1/src/BaseGraph.java | UTF-8 | 3,562 | 3.125 | 3 | [] | no_license | import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.HashMap;
public abstract class BaseGraph<V extends Vertex, E extends Edge<V>>
implements Graph<V, E> {
private AbstractCollection<E> edges;
private AbstractCollection<V> vertices;
public BaseGraph(AbstractCollection<V> vertices, AbstractCollection<E> edges) {
this.edges = edges;
this.vertices = vertices;
}
@Override
public E addEdge(E e) throws EdgeAlreadyInGraphException {
if (!this.edges.contains(e)) {
this.edges.add(e);
return e;
}
throw new EdgeAlreadyInGraphException("Edge " + e.getNumber()
+ " is already in the graph");
}
@Override
public V addVertex(V v) throws VertexAlreadyInGraphException {
if (!this.vertices.contains(v)) {
this.vertices.add(v);
return v;
}
throw new VertexAlreadyInGraphException("Vertex " + v.getNumber()
+ " is already in the graph");
}
@Override
public AbstractCollection<E> getAllEdgesForVertex(V v) {
AbstractCollection<E> result = new ArrayList<E>();
for (E e : this.edges) {
if (e.hasVertex(v)) {
result.add(e);
}
}
return result;
}
@Override
public V getVertexByNumber(int number) {
for (V v : this.getVertices()) {
if (v.getNumber() == number) {
return v;
}
}
return null;
}
public AbstractCollection<E> getEdges() {
return this.edges;
}
public AbstractCollection<V> getVertices() {
return this.vertices;
}
public HashMap<String, HashMap<Integer,Integer>> shortestPathsForEdges(V src, AbstractCollection<E> edges) {
// an implementation of Dijkstra's shortest path algorithm
HashMap<Integer, Integer> distances = new HashMap<Integer, Integer>();
HashMap<Integer, Boolean> visited = new HashMap<Integer, Boolean>();
HashMap<Integer, Integer> previous = new HashMap<Integer, Integer>();
HashMap<String, HashMap<Integer,Integer>> res = new HashMap<String, HashMap<Integer,Integer>>();
for (V v : this.getVertices()) {
distances.put(v.getNumber(), Integer.MAX_VALUE);
visited.put(v.getNumber(), false);
previous.put(v.getNumber(), null);
}
ArrayList<V> notVisited = new ArrayList<V>();
// start from source, distance to itself = 0
distances.put(src.getNumber(), 0);
notVisited.add(src);
while (!notVisited.isEmpty()) {
// find closest vertex that WASN'T visited...
V current = notVisited.get(0);
for (V v : notVisited) {
if (distances.get(v.getNumber()) < distances.get(current.getNumber())
|| (distances.get(v.getNumber()) == distances.get(current.getNumber()) && v
.getNumber() < current.getNumber())) {
}
}
notVisited.remove(current);
// closest vertex is now in "current"
visited.put(current.getNumber(), true);
for (E e : edges) {
// neighbour node is the other vertex on this edge
if (e.hasVertex(current)){
V neighbour = e.getOther(current);
int alternatePath = distances.get(current.getNumber()) + e.getWeight();
if (alternatePath < distances.get(neighbour.getNumber())
&& !visited.get(neighbour.getNumber())) {
distances.put(neighbour.getNumber(), alternatePath);
previous.put(neighbour.getNumber(), current.getNumber());
notVisited.add(neighbour);
}
}
}
}
res.put("distances", distances);
res.put("previous", previous);
return res;
}
public AbstractCollection<E> getEdgesFor(V v1, V v2){
AbstractCollection<E> result = new ArrayList<E>();
for (E e : this.getEdges()){
if (e.hasVertex(v1) && e.hasVertex(v2)){
result.add(e);
}
}
return result;
}
}
| true |
d4745243bdb926cfdf1c2bb9eb6c13f942287351 | Java | xmw9160/base-code | /mybatis/src/main/java/com/xmw/bean/User.java | UTF-8 | 683 | 2.1875 | 2 | [] | no_license | package com.xmw.bean;
import java.util.List;
import com.xmw.enums.UserType;
import lombok.Data;
@Data
public class User {
private String id;
private String username;
/**
* 用户号码
*/
private String svcnum;
private String password;
/**
* 一个用户只能对应一个客户
*/
private Cust cust;
/**
* 一个用户对应多个账户
*/
private List<Acct> accts;
/**
* 用户类型: 普通用户和重要用户
*/
private String type;
public User(String id, String username) {
super();
this.id = id;
this.username = username;
}
public User(){}
}
| true |
d723af110f4b65c08ffe6d94ccc59d9abc9946c9 | Java | shuoshuo70/DesignPattern | /src/Factory/Operation.java | UTF-8 | 475 | 2.6875 | 3 | [] | no_license | package Factory;
/**
* Created by shuoshu on 2017/10/25.
*/
public class Operation {
private double numA;
private double numB;
public double getResult() throws Exception{
return 0.0;
}
public double getNumA() {
return numA;
}
public void setNumA(double numA) {
this.numA = numA;
}
public double getNumB() {
return numB;
}
public void setNumB(double numB) {
this.numB = numB;
}
}
| true |
9230eb7b4652bd1d769fe002c03cca8f5baa2db8 | Java | samucadutra/teste-generic-dao-again | /Evento/src/exemplo/jpa/modelo/EntidadeBase.java | UTF-8 | 452 | 1.820313 | 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 exemplo.jpa.modelo;
/**
*
* Interface apenas com o intuito de ter o método getId que será usado no DAO Genérico
*
* @author samuel
*/
public interface EntidadeBase {
public Long getId();
// public Serializable getId();
}
| true |
d24627f3ae57796bea3fcbf06c79ad17d070ce95 | Java | PauloFS01/DesignPatterns | /DesignPatterns2/src/strategy/Imposto.java | UTF-8 | 101 | 1.898438 | 2 | [] | no_license | package strategy;
public interface Imposto {
public double getValor(Orcamento orcamento);
}
| true |
2ffecd5efeef94dacc7644d614a39410af9b6df8 | Java | PIONteam/SEP | /app/src/main/java/com/example/android/sep/homeActivity.java | UTF-8 | 5,101 | 1.78125 | 2 | [] | no_license | package com.example.android.sep;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import java.io.IOException;
import java.util.HashMap;
import static com.example.android.sep.loginActivity.TAG_KATA_SANDI;
import static com.example.android.sep.loginActivity.TAG_NAMA_PENGGUNA;
public class homeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
SharedPreferences sharedpreferences;
private SliderLayout sliderLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sliderLayout = (SliderLayout) findViewById(R.id.slider);
HashMap<String,Integer> file_maps = new HashMap<String, Integer>();
file_maps.put("Jilid biasa",R.drawable.lakban);
file_maps.put("Jilid Spiral",R.drawable.spiral1);
file_maps.put("Hardcover",R.drawable.hard);
for(String name : file_maps.keySet()){
TextSliderView textSliderView = new TextSliderView(this);
// initialize a SliderLayout
textSliderView
.description(name)
.image(file_maps.get(name))
.setScaleType(BaseSliderView.ScaleType.Fit);
//add your extra information
textSliderView.bundle(new Bundle());
textSliderView.getBundle()
.putString("extra",name);
sliderLayout.addSlider(textSliderView);}
sliderLayout.setPresetTransformer(SliderLayout.Transformer.Accordion);
sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
sliderLayout.setCustomAnimation(new DescriptionAnimation());
sliderLayout.setDuration(4000);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profil) {
Intent intent = new Intent(getApplicationContext(), profilActivity.class );
startActivity(intent);
}
if (id == R.id.nav_cetak) {
Intent intent = new Intent(getApplicationContext(), cetakActivity.class );
startActivity(intent);
}
if (id == R.id.nav_status) {
Intent intent = new Intent(getApplicationContext(), berkasActivity.class );
startActivity(intent);
}
if (id == R.id.nav_tentang) {
Intent intent = new Intent(getApplicationContext(), tentangActivity.class );
startActivity(intent);
}
if (id == R.id.nav_keluar) {
sharedpreferences = getSharedPreferences(loginActivity.my_shared_preferences, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(loginActivity.session_status, false);
editor.putString(TAG_KATA_SANDI, null);
editor.putString(TAG_NAMA_PENGGUNA, null);
editor.commit();
Intent intent = new Intent(getApplicationContext(), homesebelumActivity.class );
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| true |
147db70ec8d16a6de666509b6a669d11ad8eb9d1 | Java | 101guptaji/SRIP-exp-6 | /jcommon-1.0.16_source_from_jdcore/org/jfree/base/modules/PackageState.java | UTF-8 | 3,299 | 2.421875 | 2 | [] | no_license | package org.jfree.base.modules;
import org.jfree.util.Log;
import org.jfree.util.Log.SimpleMessage;
public class PackageState
{
public static final int STATE_NEW = 0;
public static final int STATE_CONFIGURED = 1;
public static final int STATE_INITIALIZED = 2;
public static final int STATE_ERROR = -2;
private final Module module;
private int state;
public PackageState(Module module)
{
this(module, 0);
}
public PackageState(Module module, int state)
{
if (module == null)
{
throw new NullPointerException("Module must not be null.");
}
if ((state != 1) && (state != -2) && (state != 2) && (state != 0))
{
throw new IllegalArgumentException("State is not valid");
}
this.module = module;
this.state = state;
}
public boolean configure(SubSystem subSystem)
{
if (state == 0)
{
try
{
module.configure(subSystem);
state = 1;
return true;
}
catch (NoClassDefFoundError noClassDef)
{
Log.warn(new Log.SimpleMessage("Unable to load module classes for ", module.getName(), ":", noClassDef.getMessage()));
state = -2;
}
catch (Exception e)
{
if (Log.isDebugEnabled())
{
Log.warn("Unable to configure the module " + module.getName(), e);
}
else if (Log.isWarningEnabled())
{
Log.warn("Unable to configure the module " + module.getName());
}
state = -2;
}
}
return false;
}
public Module getModule()
{
return module;
}
public int getState()
{
return state;
}
public boolean initialize(SubSystem subSystem)
{
if (state == 1)
{
try
{
module.initialize(subSystem);
state = 2;
return true;
}
catch (NoClassDefFoundError noClassDef)
{
Log.warn(new Log.SimpleMessage("Unable to load module classes for ", module.getName(), ":", noClassDef.getMessage()));
state = -2;
}
catch (ModuleInitializeException me)
{
if (Log.isDebugEnabled())
{
Log.warn("Unable to initialize the module " + module.getName(), me);
}
else if (Log.isWarningEnabled())
{
Log.warn("Unable to initialize the module " + module.getName());
}
state = -2;
}
catch (Exception e)
{
if (Log.isDebugEnabled())
{
Log.warn("Unable to initialize the module " + module.getName(), e);
}
else if (Log.isWarningEnabled())
{
Log.warn("Unable to initialize the module " + module.getName());
}
state = -2;
}
}
return false;
}
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (!(o instanceof PackageState))
{
return false;
}
PackageState packageState = (PackageState)o;
if (!module.getModuleClass().equals(module.getModuleClass()))
{
return false;
}
return true;
}
public int hashCode()
{
return module.hashCode();
}
}
| true |
a0b9eb8ee5b26a289166594256a2b9438dd98423 | Java | marcellinamichie291/coinPorter | /admin/src/main/java/com/qidiancamp/modules/sys/controller/SysConfigController.java | UTF-8 | 2,745 | 1.9375 | 2 | [] | no_license | /**
* Copyright 2018 人人开源 http://www.renren.io
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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.qidiancamp.modules.sys.controller;
import com.qidiancamp.common.annotation.SysLog;
import com.qidiancamp.common.utils.PageUtils;
import com.qidiancamp.common.utils.R;
import com.qidiancamp.common.validator.ValidatorUtils;
import com.qidiancamp.modules.sys.entity.SysConfigEntity;
import com.qidiancamp.modules.sys.service.SysConfigService;
import java.util.Map;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 系统配置信息
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2016年12月4日 下午6:55:53
*/
@RestController
@RequestMapping("/sys/config")
public class SysConfigController extends AbstractController {
@Autowired private SysConfigService sysConfigService;
/** 所有配置列表 */
@RequestMapping("/list")
@RequiresPermissions("sys:config:list")
public R list(@RequestParam Map<String, Object> params) {
PageUtils page = sysConfigService.queryPage(params);
return R.ok().put("page", page);
}
/** 配置信息 */
@RequestMapping("/info/{id}")
@RequiresPermissions("sys:config:info")
public R info(@PathVariable("id") Long id) {
SysConfigEntity config = sysConfigService.selectById(id);
return R.ok().put("config", config);
}
/** 保存配置 */
@SysLog("保存配置")
@RequestMapping("/save")
@RequiresPermissions("sys:config:save")
public R save(@RequestBody SysConfigEntity config) {
ValidatorUtils.validateEntity(config);
sysConfigService.save(config);
return R.ok();
}
/** 修改配置 */
@SysLog("修改配置")
@RequestMapping("/update")
@RequiresPermissions("sys:config:update")
public R update(@RequestBody SysConfigEntity config) {
ValidatorUtils.validateEntity(config);
sysConfigService.update(config);
return R.ok();
}
/** 删除配置 */
@SysLog("删除配置")
@RequestMapping("/delete")
@RequiresPermissions("sys:config:delete")
public R delete(@RequestBody Long[] ids) {
sysConfigService.deleteBatch(ids);
return R.ok();
}
}
| true |
ad3b436162409bfdea00dd6d8bd984fcfd6b0e15 | Java | iantal/AndroidPermissions | /apks/malware/app81/source/com/tencent/android/tpush/XGPushTextMessage.java | UTF-8 | 644 | 2.21875 | 2 | [
"Apache-2.0"
] | permissive | package com.tencent.android.tpush;
public class XGPushTextMessage
{
String a = "";
String b = "";
String c = "";
public XGPushTextMessage() {}
public String getContent()
{
return this.b;
}
public String getCustomContent()
{
return this.c;
}
public String getTitle()
{
return this.a;
}
public String toString()
{
StringBuilder localStringBuilder = new StringBuilder();
localStringBuilder.append("XGPushShowedResult [title=").append(this.a).append(", content=").append(this.b).append(", customContent=").append(this.c).append("]");
return localStringBuilder.toString();
}
}
| true |
36eb79c239db43084ba79c0dda7f4e0b029654a7 | Java | seastar-ss/gt_code | /db-common/src/main/java/com/shawn/ss/lib/tools/sql_code_gen/api/impl/SQLDeleteImpl.java | UTF-8 | 1,071 | 2.28125 | 2 | [] | no_license | package com.shawn.ss.lib.tools.sql_code_gen.api.impl;
import com.shawn.ss.lib.tools.sql_code_gen.api.SQLDelete;
import net.sf.jsqlparser.statement.common.*;
import net.sf.jsqlparser.statement.delete.Delete;
public class SQLDeleteImpl extends SQLImpl<SQLDelete> implements SQLDelete{
Delete delete;
public SQLDeleteImpl() {
super(SqlType.delete);
delete=new Delete();
}
public SQLDeleteImpl(Delete statement) {
super(SqlType.delete);
delete=statement;
}
@Override
protected HasWhere getWhereHandler() {
return delete;
}
@Override
protected HasMainTable getMainTableHandler() {
return delete;
}
@Override
protected HasColumnExpression getColumnExpressionHandler() {
return delete;
}
@Override
protected HasLimit getLimitHandler() {
return delete;
}
@Override
protected HasOrderBy getOrderByHandler() {
return delete;
}
@Override
public String getSql(String type) {
return delete.toString();
}
}
| true |
2eaec07b1312763830423e09c1d34d9bf3580af0 | Java | ExplorersTeam/jmemadmin | /jmemadmin-common/src/main/java/org/exp/jmemadmin/entity/TenantRequest.java | UTF-8 | 549 | 2.046875 | 2 | [] | no_license | package org.exp.jmemadmin.entity;
public class TenantRequest {
// TODO:attributions wait to expand
private String tenant;
public TenantRequest() {
// Do nothing
}
public TenantRequest(String tenant) {
this.tenant = tenant;
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
@Override
public String toString() {
return "TenantRequest [tenant=" + tenant + "]";
}
}
| true |
9c64f561409c81e249092ea2c87933efd1044970 | Java | kmille/android-pwning | /apks/aldi/src/com/google/android/gms/gcm/zzl.java | UTF-8 | 2,018 | 2.140625 | 2 | [] | no_license | package com.google.android.gms.gcm;
import android.os.Bundle;
public final class zzl
{
public static final zzl zzao = new zzl(0, 30, 3600);
private static final zzl zzap = new zzl(1, 30, 3600);
private final int zzaq;
private final int zzar;
private final int zzas;
private zzl(int paramInt1, int paramInt2, int paramInt3)
{
this.zzaq = paramInt1;
this.zzar = 30;
this.zzas = 3600;
}
public final boolean equals(Object paramObject)
{
if (paramObject == this) {
return true;
}
if (!(paramObject instanceof zzl)) {
return false;
}
paramObject = (zzl)paramObject;
return (((zzl)paramObject).zzaq == this.zzaq) && (((zzl)paramObject).zzar == this.zzar) && (((zzl)paramObject).zzas == this.zzas);
}
public final int hashCode()
{
return ((this.zzaq + 1 ^ 0xF4243) * 1000003 ^ this.zzar) * 1000003 ^ this.zzas;
}
public final String toString()
{
int i = this.zzaq;
int j = this.zzar;
int k = this.zzas;
StringBuilder localStringBuilder = new StringBuilder(74);
localStringBuilder.append("policy=");
localStringBuilder.append(i);
localStringBuilder.append(" initial_backoff=");
localStringBuilder.append(j);
localStringBuilder.append(" maximum_backoff=");
localStringBuilder.append(k);
return localStringBuilder.toString();
}
public final Bundle zzf(Bundle paramBundle)
{
paramBundle.putInt("retry_policy", this.zzaq);
paramBundle.putInt("initial_backoff_seconds", this.zzar);
paramBundle.putInt("maximum_backoff_seconds", this.zzas);
return paramBundle;
}
public final int zzh()
{
return this.zzaq;
}
public final int zzi()
{
return this.zzar;
}
public final int zzj()
{
return this.zzas;
}
}
/* Location: /home/kmille/projects/android-pwning/apks/aldi/ALDI TALK_v6.2.1_apkpure.com-dex2jar.jar!/com/google/android/gms/gcm/zzl.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
2de0b7272f39d0091c5180896a0429663b109729 | Java | narusas/jeaseungkimandroid | /MyFavoriteAndroid/src/org/asky78/android/favorite/ResourceManagement.java | UTF-8 | 4,137 | 2.359375 | 2 | [] | no_license | package org.asky78.android.favorite;
import java.util.*;
import org.asky78.android.favorite.resources.*;
import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.*;
public class ResourceManagement extends Activity {
private ListView list;
private List<String> menuText;
private List<String> menuSummary;
private String menuKey = "menukey";
private String summaryKey = "summarykey";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.common_sample);
menuText = new ArrayList<String>();
menuText.add("저장소 갱신");//0
menuText.add("display 정보");//1
// menuText.add("프로그레시브바 새창");//2
// menuText.add("Radio 버튼 새창");//3
// menuText.add("Simple Dialog");//4
// menuText.add("Time Picker");//5
// menuText.add("Date Picker");//6
// menuText.add("다중선택 새창");//7
// menuText.add("프로그레시브바 가로 막대 진행상태");//8
// menuText.add("커스텀 프로그레시브(회전자)");//9
// menuText.add("투명 Dialog");//10
menuSummary = new ArrayList<String>();
menuSummary.add("현재 저장소를 갱신합니다.");//0
menuSummary.add("기기의 Display 정보를 화면에 보여줍니다.");
// menuSummary.add("진행중을 나타내는 프로그레시브바 Alert 예제구현다.");
// menuSummary.add("Radio 버튼이 들어간 새창 이며 선택하면 창이 닫힌다. ");
// menuSummary.add("선택에 따른 로직구현을 위한 다이얼로그 창 구현");
// menuSummary.add("Time Picker 시간선택 컨트롤을 다이얼로그에 구현");
// menuSummary.add("Date Picker 날짜선택 컨트롤을 다이얼로그에 구현");
// menuSummary.add("다중선택을 할수 있는 Alert 예제구현이다.");
// menuSummary.add("진행상태를 수치상으로 알수 있게 가로막대 프로그레시브바로 표현한예제");
// menuSummary.add("회전자를 커스텀 이미지로 바꾼 프로그레시브바 예제");
// menuSummary.add("배경이 아무것도 없는 대화상자. 아이콘만 보이도록 세팅");//10
((TextView)findViewById(R.id.txt_common_sample_subject)).setText("자원 관리 예제들");
list = (ListView) findViewById(R.id.list_common_samples);
SimpleAdapter listDialogSampleAdapter = new SimpleAdapter(this//
, getMenuDataList()//
, android.R.layout.simple_list_item_2//
, new String[] { menuKey, summaryKey }//
, new int[] { android.R.id.text1, android.R.id.text2 });
list.setAdapter(listDialogSampleAdapter);
list.setOnItemClickListener(listItemClickListener);
}
/**
* List의 Item 클릭 이벤트 처리
*/
private OnItemClickListener listItemClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
switch (position) {
case 0:
startActivity(RefreshStorage.class);//파일다운로드
break;
case 1:
startActivity(DeviceDisplayInfo.class);//디스플레이 정보 보기
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
case 9:
break;
case 10:
break;
default:
break;
}
}
};
/** @param name 구동할 activity class 이름 */
private void startActivity(Class<?> name){
Intent intent = new Intent(this, name);
startActivity(intent);
}
/**
* SimpleAdapter에 사용할 리스트를 생성해 반환합니다.
*
* @return
*/
private ArrayList<Map<String, String>> getMenuDataList() {
ArrayList<Map<String, String>> arrlist = new ArrayList<Map<String, String>>();
for (int i = 0; i < menuText.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(menuKey, menuText.get(i));
map.put(summaryKey, menuSummary.get(i));
arrlist.add(map);
}
return arrlist;
}
}
| true |
bd2cb0d9871156e30dca32e928c551cbfcf5a63a | Java | proliuxz/RemoteVideoOnDemandSystem | /SourceCode/Client/player/src/org/videolan/vlc/gui/NetClass2Fragment.java | GB18030 | 3,349 | 1.78125 | 2 | [] | no_license | package org.videolan.vlc.gui;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.LibVlcException;
import org.videolan.vlc.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import org.videolan.vlc.gui.MainActivity;
import org.videolan.vlc.gui.SidebarAdapter.SidebarEntry;
public class NetClass2Fragment extends Fragment {
private LibVLC mLibVLC;
public static int vidnum;
public final static String TAG = "VLC/VideoWebIndexViewFragment";
public NetClass2Fragment() {
try {
mLibVLC = LibVLC.getInstance();
} catch (LibVlcException e) {
Log.d(TAG, "LibVlcException encountered in VideoWebIndexViewFragment", e);
return;
}
}
@JavascriptInterface
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Log.e(TAG, "go to video web!");
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.videowebindex, container, false);
WebView web01 = (WebView)v.findViewById(R.id.webview1);
// t.loadData(Util.readAsset("videowebindex.htm", ""), "textml", "UTF8");
WebSettings webSettings = null;
webSettings = web01.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
web01.addJavascriptInterface(this,"android");
int screenDensity = getResources().getDisplayMetrics(). densityDpi ;
WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity. MEDIUM ;
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
web01.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}});
String url= MainActivity.serverip+"/index.aspx";
web01.loadUrl(url);
return v;
}
public void downloadingvideomark()
{
// MainActivity.downloadingmark=1;//ʾļҪ
}
public void opennetclass(String btn,int num)//@JavascriptInterface ҳӿں
{
vidnum=num;
((MainActivity) MainActivity.mContext).sendHandleMessage(btn);
}
public String getFileName(String pathandname){
int start=pathandname.lastIndexOf("/");
int end=pathandname.lastIndexOf("."); //
end=pathandname.length();//
Log.d("count", "end="+end);
if(start!=-1 && end!=-1){
return pathandname.substring(start+1,end);
}else{
return null;
}
}
}
| true |
2ea5af19b83355f6dde2405b3aa18295db3ea108 | Java | SysVentas/SysVentas | /Java/src/GUI/login.java | UTF-8 | 1,870 | 2.5625 | 3 | [] | no_license | package GUI;
import javax.swing.*;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class login extends JFrame {
JTextField tex1;
JPasswordField tex2;
JButton ingresar;
JButton salir;
JLabel imagen;
static int flag;
public login(){
/////////////////////////777
setTitle("login");
setBounds(0,0,367,374);
setIconImage(Toolkit.getDefaultToolkit().getImage(login.class.getResource("/sysVentasJava/ico-venta-equipo.png")));
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(null);
tex1 = new JTextField("usuario");
tex1.setBounds(67,195,212,30);
getContentPane().add(tex1);
tex2 = new JPasswordField("");
tex2.setBounds(67,236,212,30);
getContentPane().add(tex2);
ingresar=new JButton("Ingresar");
ingresar.setFont(new Font("Comic Sans MS", Font.PLAIN, 10));
ingresar.setBounds(105,277,97,30);
getContentPane().add(ingresar);
ingresar.addActionListener(new listener());
salir =new JButton("Salir");
salir.setFont(new Font("Comic Sans MS", Font.PLAIN, 10));
salir.setBounds(216,277,63,30);
getContentPane().add(salir);
salir.addActionListener(new listener());
imagen=new JLabel();
imagen.setIcon(new ImageIcon(login.class.getResource("/sysVentasJava/ico-venta-equipo.png")));
getContentPane().add(imagen);
imagen.setBounds(95,8,165,176);
}
public class listener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if (e.getSource()==salir) {
System.exit(0);
}
if(e.getSource()==ingresar){
empleado vent2=new empleado();
vent2.setVisible(true);
Admin vent3=new Admin();
vent3.setVisible(true);
setVisible(false);
}
}
}
}
| true |
26e2c5f7ab40fc0f184e39a7b16bb205f24b0a05 | Java | 871041532/Design | /HeadFirstDesign_Java/src/Strategy/ModelDuck.java | UTF-8 | 391 | 2.546875 | 3 | [] | no_license | package Strategy;
import Strategy.behaviorImpl.FlyNoWay;
import Strategy.behaviorImpl.MuteQuack;
/**
* Created by zhoukb on 2017/8/24.
*/
public class ModelDuck extends Duck
{
public ModelDuck()
{
flyBehavior=new FlyNoWay();
quackBehavior=new MuteQuack();
}
@Override
public void display()
{
System.out.println("一只模型鸭");
}
}
| true |
9ea6721b3c005a262cf5ff6044b629a37ec10efd | Java | Srilekhanarahari/Design_Patterns | /ChatRoom/src/main/java/strategy/ISocMed.java | UTF-8 | 91 | 1.898438 | 2 | [] | no_license | package strategy;
public interface ISocMed {
public void connectTo(String friendName);
}
| true |
17a60a3cc9d890bc9beacc515a1adb9c36d36cf1 | Java | jpain01/DressingApp | /app/src/main/java/dressing/asi/insarouen/fr/dressing/activity/notice/NoticeActivity.java | UTF-8 | 1,702 | 2.046875 | 2 | [] | no_license | package dressing.asi.insarouen.fr.dressing.activity.notice;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.MenuItem;
import android.widget.TextView;
import dressing.asi.insarouen.fr.dressing.R;
/**
* Created by julie on 23/12/16.
*/
public class NoticeActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.notice);
TextView myTextView = (TextView) findViewById(R.id.textNotice);
myTextView.setText(Html.fromHtml(getString(R.string.notice_text)));
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.dressingToolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close_white_24dp);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle(R.string.notice);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
overridePendingTransition(R.anim.stay, R.anim.slide_down); //Animation transition slide down
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.stay, R.anim.slide_down); //Animation transition slide down
}
}
| true |
63a0d259a8ae06eeecef2f48496f1cba9080c9b2 | Java | njmube/MiHabitatPortal | /mihabitat-contabilidad/src/main/java/com/bstmexico/mihabitat/proveedores/service/ProveedorService.java | UTF-8 | 483 | 1.984375 | 2 | [] | no_license | package com.bstmexico.mihabitat.proveedores.service;
import com.bstmexico.mihabitat.proveedores.model.Proveedor;
import java.util.Collection;
import java.util.Map;
/**
* @author JPC
* @version 1.0
* @since 2015
*/
public interface ProveedorService {
void save(Proveedor departamento);
Proveedor get(Long id);
void update(Proveedor proveedor);
@SuppressWarnings("rawtypes")
Collection<Proveedor> search(Map map);
Proveedor existeProveedor(Proveedor proveedor);
}
| true |
0e92afafb7a3bc78f56d714283954ab8d51b9217 | Java | Kawser-nerd/CLCDSA | /Source Codes/CodeJamData/08/52/12.java | UTF-8 | 6,074 | 2.859375 | 3 | [] | no_license | package googlecodejam;
import java.io.*;
import java.util.*;
public class ProblemB {
static final int INF = 123456789;
static int[] dr = new int[] { 0, 1, 0, -1 };
static int[] dc = new int[] { 1, 0, -1, 0 };
public static void main(String[] args) {
try {
Scanner s = new Scanner(new File("B-small-attempt0.in"));
PrintWriter p = new PrintWriter(new File("B-small-out.txt"));
int nCases = Integer.parseInt(s.nextLine());
for (int i=1; i<=nCases; i++) {
int[] data = parseIntArray(s.nextLine());
int nRows = data[0];
int nCols = data[1];
char[][] map = new char[nRows][nCols];
int posR=-1, posC=-1;
for (int r=0; r<nRows; r++) {
String row = s.nextLine();
for (int c=0; c<nCols; c++) {
map[r][c] = row.charAt(c);
if (map[r][c]=='O') {
posR = r;
posC = c;
}
}
}
GooglyPriorityQueue q = new GooglyPriorityQueue(nRows*nCols*nRows*nCols*4);
// the state is: where you are, where the output portal is
int[][][][] best = new int[nRows][nCols][nRows][nCols];
// shoot gun west to create a blue portal
int gr = posR;
int gc = posC;
while (gc>=0 && (map[gr][gc]=='.' || map[gr][gc]=='O')) gc--;
gc++;
for (int a=0; a<nRows; a++) {
for (int b=0; b<nCols; b++) {
for (int c=0; c<nRows; c++) {
for (int d=0; d<nCols; d++) {
best[a][b][c][d] = INF;
}
}
}
}
best[posR][posC][gr][gc] = 0;
q.insert(0, new int[] { posR, posC, gr, gc });
int ans = INF;
while (!q.isEmpty()) {
data = (int[])q.removeMin();
int r = data[0];
int c = data[1];
int pr = data[2];
int pc = data[3];
int val = best[r][c][pr][pc];
if (map[r][c]=='X') {
ans = val;
break;
}
// Move
for (int dir=0; dir<4; dir++) {
int rr = r+dr[dir];
int cc = c+dc[dir];
if (rr>=0 && rr<nRows && cc>=0 && cc<nCols && map[rr][cc]!='#') {
if (1+val < best[rr][cc][pr][pc]) {
best[rr][cc][pr][pc] = 1+val;
q.insert(1+val, new int[] { rr, cc, pr, pc });
}
} else {
// walk through portal
if (1+val < best[pr][pc][pr][pc]) {
best[pr][pc][pr][pc] = 1+val;
q.insert(1+val, new int[] { pr, pc, pr, pc });
}
}
}
// Shoot a output portal
for (int dir=0; dir<4; dir++) {
gr = r;
gc = c;
while (gr>=0 && gr<nRows && gc>=0 && gc<nCols && (map[gr][gc]!='#')) {
gr += dr[dir];
gc += dc[dir];
}
gr -= dr[dir];
gc -= dc[dir];
if (val < best[r][c][gr][gc]) {
best[r][c][gr][gc] = val;
q.insert(val, new int[] { r, c, gr, gc });
}
}
}
//String line = s.nextLine();
if (ans==INF) {
p.println("Case #" + (i) + ": THE CAKE IS A LIE");
} else {
p.println("Case #" + (i) + ": " + ans);
}
}
p.flush();
p.close();
} catch (Exception e) {
e.printStackTrace();
}
}
static int[] parseIntArray(String s) {
StringTokenizer st = new StringTokenizer(s, " ");
int[] ret = new int[st.countTokens()];
for (int i=0; i<ret.length; i++) {
ret[i] = Integer.parseInt(st.nextToken());
}
return ret;
}
static class GooglyPriorityQueue {
int N;
int size;
Object[] data;
int[] keys;
public GooglyPriorityQueue(int n) {
N = n;
size = 0;
data = new Object[N+1];
keys = new int[N+1];
keys[0] = Integer.MIN_VALUE;
}
public void insert(int key, Object o) {
if (size == N) {
System.out.println("Resizing heap to " + (2*N) + " !");
Object[] data2 = new Object[2*N+1];
int[] keys2 = new int[2*N+1];
System.arraycopy(data, 0, data2, 0, N+1);
System.arraycopy(keys, 0, keys2, 0, N+1);
N = 2*N;
data = data2;
keys = keys2;
}
int k = ++size;
while (keys[k/2] > key) {
data[k] = data[k/2];
keys[k] = keys[k/2];
k /= 2;
}
data[k] = o;
keys[k] = key;
}
public boolean isEmpty() {
return (size==0);
}
public Object removeMin() {
if (isEmpty()) {
throw new RuntimeException("Heap is empty!");
}
Object ret = data[1];
Object lastObj = data[size];
int lastKey = keys[size];
size--;
int k = 1;
while ((2*k<=size && lastKey > keys[2*k]) || (2*k+1<=size && lastKey > keys[2*k+1])) {
int j = 2*k;
if (j+1<=size && keys[j+1] < keys[j]) j++;
keys[k] = keys[j];
data[k] = data[j];
k = j;
}
keys[k] = lastKey;
data[k] = lastObj;
return ret;
}
}
}
| true |
e6be2cf826024c8b05a44a9b9fc39fe5064bc637 | Java | TSPeterson206/UW-JAVA-510 | /MavenScrap/src/main/java/scrapfile/main/Car.java | UTF-8 | 938 | 3.34375 | 3 | [] | no_license | package scrapfile.main;
public class Car {
private int id;
private String make;
private int price;
private int mileage;
boolean available;
Car(int id, String make, int mileage, boolean available) {
this.id = id;
this.make = make;
this.price = price;
setAvailable(false);
setMileage(mileage);
}
/**
* @return the mileage
*/
public int getMileage() {
return mileage;
}
/**
* @param mileage the mileage to set
*/
public void setMileage(int mileage) {
this.mileage = mileage;
}
/**
* @return the available
*/
public boolean isAvailable() {
return available;
}
/**
* @param available the available to set
*/
public void setAvailable(boolean available) {
this.available = available;
}
public int getPrice() {
return this.price;
}
}
| true |
c753ff87493ad5725275eee63ac47e426f08a3d7 | Java | daltokki/conference-schedule | /src/test/java/com/schedule/services/domain/schedule/InitialConferenceScheduleMakerTest.java | UTF-8 | 1,344 | 2.0625 | 2 | [] | no_license | package com.schedule.services.domain.schedule;
import com.google.common.collect.Iterables;
import com.schedule.repository.entity.ConferenceRoom;
import com.schedule.repository.entity.ConferenceSchedule;
import com.schedule.repository.entity.ScheduleTime;
import com.schedule.services.application.conference.ConferenceService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class InitialConferenceScheduleMakerTest {
private ConferenceSchedule conferenceSchedule;
@Before
public void init() {
conferenceSchedule = Mockito.any(ConferenceSchedule.class);
}
@Test
public void generateConferenceRoom() {
List<ConferenceRoom> conferenceRooms = InitialConferenceScheduleMaker.generateConferenceRoom(conferenceSchedule);
Assert.assertEquals(conferenceRooms.size(), DefaultConferenceRoom.values().length);
}
@Test
public void generateScheduleTime() {
List<ScheduleTime> scheduleTimes = InitialConferenceScheduleMaker.generateScheduleTime(conferenceSchedule);
Assert.assertEquals(Iterables.getLast(scheduleTimes).getScheduleTime(), "1730");
}
} | true |
f8a7dcce3f30b4e51b9a4fa2ddae6909d031e6a8 | Java | Uniandes-ISIS2603-backup/201720-s3_gimnasio | /gimnasio-backend/src/main/java/co/edu/uniandes/baco/gimnasio/persistence/EstadoPersistence.java | UTF-8 | 523 | 1.710938 | 2 | [
"MIT"
] | permissive | /*
* 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 co.edu.uniandes.baco.gimnasio.persistence;
import co.edu.uniandes.baco.gimnasio.entities.EstadoEntity;
import javax.ejb.Stateless;
/**
*
* @author js.palacios437
*/
@Stateless
public class EstadoPersistence extends BasePersistence<EstadoEntity>{
public EstadoPersistence() {
super(EstadoEntity.class);
}
}
| true |
4b33086149c39a6dbbd3ee2e1cd1e1a50bafc1b6 | Java | eeecodernik/Truyum-web-UI | /DesignPrinciples/handson/handson4/leaveApproval/Supervisor.java | UTF-8 | 454 | 2.5 | 2 | [] | no_license | package leaveApproval;
public class Supervisor implements ILeaveRequestHandler {
ILeaveRequestHandler nextHandler=new ProjectManager();
@Override
public void HandleRequest(LeaveRequest request) {
int leave=request.getLeaveDays();
if(leave>=1 && leave<3) {
System.out.println("Supervisor : Leave Request by "+request.getEmployee()+" approved [Days: "+leave+" ]");
}
else {
nextHandler.HandleRequest(request);
}
}
}
| true |
4391e2c1af6bc3b7f39743b9441ea0ea2a6dd77b | Java | RVRhub/IntelligentTopicSearchWeb | /src/main/java/com/intelligent/topic/search/domain/Documents.java | UTF-8 | 461 | 2.046875 | 2 | [] | no_license | package com.intelligent.topic.search.domain;
import java.io.Serializable;
import java.util.List;
public class Documents implements Serializable {
private List<DocumentImpl> documents;
public Documents() {
}
public Documents(List<DocumentImpl> documents) {
this.documents = documents;
}
public List<DocumentImpl> getDocuments() {
return documents;
}
public void setDocuments(List<DocumentImpl> documents) {
this.documents = documents;
}
}
| true |
fc602e206819a7c71a79b783908726f051327eed | Java | JakobGeiger/ClusterSets | /src/mapViewer/PointMapObject.java | UTF-8 | 1,534 | 2.8125 | 3 | [] | no_license | package mapViewer;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Point;
public class PointMapObject implements MapObject, Comparable<PointMapObject> {
private Point myPoint;
public String fclass;
public Color myColor;
private int strokeWidth = 1;
/**
* @return the myPoint
*/
public Point getMyPoint() {
return myPoint;
}
public PointMapObject(Point p) {
myPoint = p;
}
@Override
public void draw(Graphics2D g, Transformation t) {
g.setStroke(new BasicStroke(strokeWidth));
Color c = g.getColor();
g.fillOval(t.getColumn(myPoint.getX()) - 6, t.getRow(myPoint.getY()) - 6, 13, 13);
if (myColor != null) g.setColor(myColor);
g.fillOval(t.getColumn(myPoint.getX()) - 4, t.getRow(myPoint.getY()) - 4, 9, 9);
g.setColor(c);
}
@Override
public Envelope getBoundingBox() {
return new Envelope(myPoint.getX(),myPoint.getX(),myPoint.getY(),myPoint.getY());
}
public int compareTo(PointMapObject p2) {
if (this.myPoint.getX() < p2.myPoint.getX()) {
return -1;
} else if (this.myPoint.getX() > p2.myPoint.getX()) {
return 1;
} else {
if (this.myPoint.getY() < p2.myPoint.getY()) {
return -1;
} else if (this.myPoint.getY() > p2.myPoint.getY()) {
return 1;
} else {
return 0;
}
}
}
public void setStrokeWidth(int i) {
strokeWidth = i;
}
}
| true |
c4b61cb8b39c6c533a593a7287b7d576487d5a8c | Java | omarmercado8/ProyectoCom1 | /src/controller/InformacionController.java | UTF-8 | 1,362 | 2.015625 | 2 | [] | no_license | package controller;
import hibernate.Blog;
import hibernate.Categoria;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import dao.BlogDAO;
import dao.CategoriasDAO;
import dao.PaginaDAO;
@Controller
public class InformacionController {
@Autowired
PaginaDAO paginaDAO;
@Autowired
CategoriasDAO categoriasDAO;
@Autowired
BlogDAO blogDAO;
@RequestMapping(value="/Informacion.htm", method=RequestMethod.GET)
public ModelAndView getCategoriaForm(HttpServletRequest request){
Map<String, String> VersionInfo = paginaDAO.getVersion(request, "Informacion");
List<Categoria> ListCategorias = categoriasDAO.getCategoriasInfo();
List<Blog> ListaBlogs = blogDAO.getUltimos10();
ModelAndView mv = new ModelAndView(VersionInfo.get("View"));
mv.addObject("ListaBlogs", ListaBlogs);
mv.addObject("Pagina",paginaDAO.getPagina());
mv.addObject("ListCategorias",ListCategorias);
String tipo = VersionInfo.get("Tipo");
paginaDAO.pageView("Portada", "", tipo);
return mv;
}
}
| true |
b2098828109ad63c872281f0c7779b7d9d93d606 | Java | Wiktor89/directoryTest | /src/main/java/net/directory/utilits/ConnectingDataBase.java | UTF-8 | 702 | 2.359375 | 2 | [] | no_license | package net.directory.utilits;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
*
*/
public class ConnectingDataBase {
public ConnectingDataBase(){
}
public static Connection getConnection() {
InitialContext initialContext = null;
DataSource dataSource = null;
Connection connection = null;
try {
initialContext = new InitialContext();
dataSource = (DataSource) initialContext.lookup("java:/comp/env/jdbc/postgres");
connection = dataSource.getConnection();
} catch (NamingException | SQLException e) {
e.printStackTrace();
}
return connection;
}
}
| true |
7fcc313879d556bc46d334635863808f91ca460c | Java | Blackdread/alias | /type-alias-axon-serializer-integration-test/src/test/java/org/alias/axon/serializer/example/query/model/member/account/AccountEntityTest.java | UTF-8 | 570 | 1.851563 | 2 | [
"Apache-2.0"
] | permissive | package org.alias.axon.serializer.example.query.model.member.account;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.EqualsVerifierReport;
import nl.jqno.equalsverifier.Warning;
public class AccountEntityTest {
@Test
public void equalsAndHashcodeTechnicallyCorrect() {
EqualsVerifierReport report = EqualsVerifier.forClass(AccountEntity.class).usingGetClass().suppress(Warning.SURROGATE_KEY).report();
assertTrue(report.getMessage(), report.isSuccessful());
}
}
| true |
4dd109dc10bc12c2a9a7978a5ed094f9b8a2dd87 | Java | peggypan0411/KalypsoBase | /KalypsoZmlCore/src/org/kalypso/zml/core/diagram/base/ZmlLayerProviders.java | UTF-8 | 3,861 | 1.640625 | 2 | [] | no_license | /*---------------- FILE HEADER KALYPSO ------------------------------------------
*
* This file is part of kalypso.
* Copyright (C) 2004 by:
*
* Technical University Hamburg-Harburg (TUHH)
* Institute of River and coastal engineering
* Denickestra�e 22
* 21073 Hamburg, Germany
* http://www.tuhh.de/wb
*
* and
*
* Bjoernsen Consulting Engineers (BCE)
* Maria Trost 3
* 56070 Koblenz, Germany
* http://www.bjoernsen.de
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact:
*
* E-Mail:
* belger@bjoernsen.de
* schlienger@bjoernsen.de
* v.doemming@tuhh.de
*
* ---------------------------------------------------------------------------*/
package org.kalypso.zml.core.diagram.base;
import java.util.Calendar;
import java.util.Date;
import javax.xml.bind.DatatypeConverter;
import jregex.Pattern;
import jregex.RETokenizer;
import org.apache.commons.lang3.StringUtils;
import org.kalypso.ogc.sensor.IAxis;
import org.kalypso.ogc.sensor.IObservation;
import org.kalypso.ogc.sensor.metadata.MetadataList;
import org.kalypso.ogc.sensor.provider.IObsProvider;
import org.kalypso.ogc.sensor.timeseries.AxisUtils;
import org.kalypso.zml.core.KalypsoZmlCoreExtensions;
import org.kalypso.zml.core.base.request.IRequestStrategy;
import de.openali.odysseus.chart.framework.model.layer.IParameterContainer;
/**
* @author Dirk Kuch
*/
public final class ZmlLayerProviders
{
private ZmlLayerProviders( )
{
}
public static IAxis getValueAxis( final IObsProvider provider, final String type )
{
if( provider == null )
return null;
final IObservation observation = provider.getObservation();
if( observation == null )
return null;
final IAxis[] axes = observation.getAxes();
return AxisUtils.findAxis( axes, type );
}
public static Date getMetadataDate( final IParameterContainer parameters, final String key, final MetadataList metadata )
{
final String parameter = parameters.getParameterValue( key, "" ); //$NON-NLS-1$
return getMetadataDate( parameter, metadata );
}
private static final Pattern PATTERN_METADATE_DATE = new Pattern( "^metadata\\:" ); //$NON-NLS-1$
public static Date getMetadataDate( final String key, final MetadataList metadata )
{
final RETokenizer tokenizer = new RETokenizer( PATTERN_METADATE_DATE, key );
final String mdKey = tokenizer.nextToken();
// FIXME: error handling if property is missing
final String property = metadata.getProperty( mdKey );
if( StringUtils.isBlank( property ) )
return null;
final Calendar calendar = DatatypeConverter.parseDate( property );
return calendar.getTime();
}
public static IRequestStrategy getRequestStrategy( final IZmlLayer layer, final IParameterContainer container )
{
final String id = container.getParameterValue( "request.strategy", "request.strategy.prognose" ); //$NON-NLS-1$ //$NON-NLS-2$
final IRequestStrategy strategy = KalypsoZmlCoreExtensions.getInstance().findStrategy( id );
strategy.init( layer, container );
return strategy;
}
}
| true |
6e2f676d00b5b017660d7d53e5a96fd30d65c3ee | Java | YangChengTeam/headstyle | /app/src/main/java/com/feiyou/headstyle/common/Constant.java | UTF-8 | 3,337 | 1.578125 | 2 | [] | no_license | package com.feiyou.headstyle.common;
import android.os.Environment;
import com.feiyou.headstyle.App;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
/**
* Created by admin on 2016/9/6.
*/
public class Constant {
public final static int RESULT_SUCCESS = 0;
public final static int RESULT_FAIL = -1;
public final static int OPERATION_CODE = -2;
public final static Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").disableHtmlEscaping()
.create();
public final static String USER_INFO = "user_info";
public final static String LAST_UPDATE_TIME = "last_update_time";
public static String SD_DIR = App.sdPath;
public static final String BASE_SD_DIR = SD_DIR + File.separator + "GXTX";
public static final String BASE_NORMAL_FILE_DIR = BASE_SD_DIR + File.separator + "files";
//public static final String BASE_NORMAL_IMAGE_DIR = BASE_SD_DIR + File.separator + "images";
public static final String BASE_NORMAL_IMAGE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "gxtx_images";
public static final String BASE_NORMAL_SAVE_IMAGE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final int NOTIFICATION_ID_UPDATE = 0x0;
public static final int NOTIFICATION_LSDD_ID = 0x1;
//修改用户头像
public static String USER_IMAGE_UPDATE_ACTION = "com.feiyou.headstyle.userImg";
public static final String userHeadName = "gxtx_user_head.jpg";
public static String FIGHT_DOWN_URL = "http://zs.qqtn.com/zbsq/Apk/tnzbsq_QQTN.apk";
public static String FIGHT_SOURCE_FILE_PATH = BASE_NORMAL_FILE_DIR +File.separator +"fight.apk";
public static String FIGHT_DOWN_FILE_PATH = BASE_NORMAL_FILE_DIR +File.separator +"fight_down.apk";
public static String LSDD_DOWN_URL = "http://vip.cr173.com/Apk/sound_gxtx.apk";
public static String LSDD_SOURCE_FILE_PATH = BASE_NORMAL_FILE_DIR +File.separator +"lsdd_from_gxtx.apk";
public static String LSDD_DOWN_FILE_PATH = BASE_NORMAL_FILE_DIR +File.separator +"lsdd_from_gxtx_down.apk";
public final static String IS_SHOW_TIP = "is_show_tip";
public static final String GAME_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "feiyousdk";// 用隐藏文件,不让看见;
public static String GAME_INSTALL_URL = "http://apk.6071.com/diguoshidai/diguoshidai_zbsq.apk";
public static String GAME_DOWN_FILE_PATH = GAME_DIR +File.separator +"game.apk";
public static final String GAME_PACKAGE_NAME = "com.regin.dgsd.leqi6071";
public final static String ALL_ARTICLE = "0";
public final static String TAKE_PHOTO_ARTICLE = "1";
public final static String CHAT_ARTICLE = "2";
public final static String COMMENT_COUNT = "comment_count";
public final static String LOGIN_SUCCESS = "user_login_success";
public final static String MESSAGE = "message_hint";
public final static String PRAISE_SUCCESS = "praise_success";
public static final String APPID = "1107873400";
public static final String SPA_POSID = "6050141079184468";
public static final String AD_LIST_FIRENDS = "1010445089780509";
public static final String AD_LIST_TEST = "9090342150260042";
}
| true |
32e313edc82f18e8e1c1ab898fce4941162499c8 | Java | teggr/news-crud-app | /src/main/java/com/robintegg/news/journalist/NewsStoryUpdatedEvent.java | UTF-8 | 337 | 1.953125 | 2 | [] | no_license | package com.robintegg.news.journalist;
import org.springframework.context.ApplicationEvent;
@SuppressWarnings("serial")
public class NewsStoryUpdatedEvent extends ApplicationEvent {
public NewsStoryUpdatedEvent(NewsStory newsStory) {
super(newsStory);
}
public NewsStory getNewsStory() {
return (NewsStory) getSource();
}
}
| true |
eee7c5c01cee0e090735be3f7d5817b3f87d4b57 | Java | imithlesh/PhoneAuth | /src/main/java/com/example/fragmentlogin/ui/login/LoginFragment.java | UTF-8 | 3,377 | 2 | 2 | [] | no_license | package com.example.fragmentlogin.ui.login;
import android.os.Bundle;
import androidx.appcompat.widget.AppCompatButton;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.fragmentlogin.MainActivity;
import com.example.fragmentlogin.R;
import com.example.fragmentlogin.base.BaseActivity;
import com.example.fragmentlogin.ui.home.HomeFragment;
import com.example.fragmentlogin.ui.register.RegisterFragment;
import com.example.fragmentlogin.ui.verifyOtp.VerifyOTP;
public class LoginFragment extends Fragment {
EditText RegisteredNumber;
AppCompatButton loginBtn;
TextView newUser;
public LoginFragment() {
}
public static LoginFragment newInstance() {
return new LoginFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, container, false);
RegisteredNumber = view.findViewById(R.id.phoneLoginET);
loginBtn = view.findViewById(R.id.LoginBtn);
newUser = view.findViewById(R.id.newUser);
String text = "<font color=#FF000000>New User? </font> <font color=#EC6940>click here to register</font>";
newUser.setText(Html.fromHtml(text));
newUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new RegisterFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_id, fragment);
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
// getActivity().getFragmentManager().popBackStack();
}
});
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String phoneNumberLogin = RegisteredNumber.getText().toString().trim();
if (phoneNumberLogin.length() != 10)
{
Toast.makeText(getActivity(), "enter valid number", Toast.LENGTH_SHORT).show();
}
else {
Fragment fragment = new HomeFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_id, fragment);
Bundle args = new Bundle();
args.putString("phoneNumber", phoneNumberLogin);
fragment.setArguments(args);
fragmentTransaction.commit();
getActivity().getFragmentManager().popBackStack();
}
}
});
return view;
}
} | true |
02851866cb6f6d6dccd23ce2c0d083d5d1d7ea65 | Java | mike841211/HomShop2 | /src/com/homlin/module/shop/dao/impl/TbShopMemberGradeDaoImpl.java | UTF-8 | 1,519 | 2.140625 | 2 | [] | no_license | package com.homlin.module.shop.dao.impl;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.homlin.app.dao.impl.BaseDaoImpl;
import com.homlin.module.shop.dao.TbShopMemberGradeDao;
import com.homlin.module.shop.model.TbShopMemberGrade;
import com.homlin.utils.HqlHelper;
@Repository
public class TbShopMemberGradeDaoImpl extends BaseDaoImpl<TbShopMemberGrade, String> implements TbShopMemberGradeDao {
@SuppressWarnings("unchecked")
@Override
public List<Map<String, Object>> getAll() {
String hql = "select new map(";
hql += HqlHelper.mapping("createDate,discount,id,isSpecial,lever,modifyDate,name,remark,score");
hql += ") from TbShopMemberGrade order by lever asc";
return (List<Map<String, Object>>) find(hql);
}
@Override
public TbShopMemberGrade getFirstLeverGrade() {
String hql = "from TbShopMemberGrade order by lever asc";
return (TbShopMemberGrade) findOne(hql);
}
@SuppressWarnings("unchecked")
@Override
public List<Map<String, Object>> getAllForSelect() {
String hql = "select new map(id as id,name as name) from TbShopMemberGrade order by lever";
return (List<Map<String, Object>>) find(hql);
}
@Override
public TbShopMemberGrade findByScore(BigDecimal score) {
String hqlString = "from TbShopMemberGrade where isnull(isSpecial,'0')<>'1' and score<=? order by lever desc";
return (TbShopMemberGrade) findOne(hqlString, score);
}
}
| true |
85213085a73f4f42d659c18d96d6913593878c24 | Java | mareknovotny/pnc | /datastore/src/main/java/org/jboss/pnc/datastore/predicates/rsql/AbstractTransformer.java | UTF-8 | 1,166 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package org.jboss.pnc.datastore.predicates.rsql;
import org.jboss.pnc.model.GenericEntity;
import javax.persistence.criteria.*;
import java.util.List;
abstract class AbstractTransformer<Entity extends GenericEntity<? extends Number>> implements Transformer<Entity> {
private final ArgumentHelper argumentHelper = new ArgumentHelper();
@Override
public Predicate transform(Root<Entity> r, CriteriaBuilder cb, Class<?> selectingClass, String operand, List<String> arguments) {
return transform(r, selectWithOperand(r, operand), cb, operand, argumentHelper.getConvertedType(selectingClass, operand, arguments));
}
public Path<Entity> selectWithOperand(Root<Entity> r, String operand) {
String [] splittedFields = operand.split("\\.");
Path<Entity> currentPath = r;
for(int i = 0; i < splittedFields.length - 1; ++i) {
currentPath = r.join(splittedFields[i]);
}
return currentPath.get(splittedFields[splittedFields.length - 1]);
}
abstract Predicate transform(Root<Entity> r, Path<Entity> selectedPath, CriteriaBuilder cb, String operand, List<Object> convertedArguments);
}
| true |
b214a16a01077ef01050266fbcfb055c549b1790 | Java | Fall2019COMP401-001/a1-charliet10 | /src/a1/A1Adept.java | UTF-8 | 4,331 | 3.921875 | 4 | [] | no_license | package a1;
import java.util.Scanner;
public class A1Adept {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Your code follows here.
// takes in an integer to show the number of items in the store.
int itemCount = scan.nextInt();
// an array to take in the name of each item in the store
String[] itemName = new String[itemCount];
// an array to take in the prices of each item in the store
double[] itemPrice = new double[itemCount];
// a for loop to assign price values into the price array
for(int i=0; i<itemPrice.length; i++) {
itemName[i] = scan.next();
itemPrice[i] = scan.nextDouble();
}
// takes in an integer to show the number of customers
int totalCust = scan.nextInt();
// an array to take in the first names of customers
String[] firstNames = new String[totalCust];
// an array to take in the last names of customers
String [] lastNames = new String[totalCust];
// an array to take in the total number of items bought by the customer
int[] totalItems = new int[totalCust];
// an array to take in the total amount spent by the customer
double[]amountSpent = new double[totalCust];
// a for loop to read and input values into each array listed above
for(int i=0; i<firstNames.length; i++) {
firstNames[i] = scan.next();
lastNames[i] = scan.next();
totalItems[i] = scan.nextInt();
// a nested for loop for each item to store the quantity and price of each item into an array
for (int k=0; k<totalItems[i]; k++) {
int[] itemQuant = new int[totalItems[i]];
itemQuant[k] = scan.nextInt();
String[] shoppingList = new String [totalItems[i]];
shoppingList[k] = scan.next();
amountSpent[i] += itemQuant[k] * priceCheck(shoppingList[k], itemName, itemPrice);
}
} scan.close();
System.out.println("Biggest: " + firstNames[(biggestIndex(amountSpent))] + " " + lastNames[(biggestIndex(amountSpent))] + " (" + String.format("%.2f", biggest(amountSpent)) + ")");
System.out.println("Smallest: " + firstNames[(smallestIndex(amountSpent))]+ " " + lastNames[(smallestIndex(amountSpent))] + " (" + String.format("%.2f", smallest(amountSpent)) + ")");
System.out.println("Average: " + String.format("%.2f", average(amountSpent, totalCust)));
}
// a method that checks the price of the customer's items and returns that price
static double priceCheck(String shoppingList, String [] itemName, double [] itemPrice) {
double price = 0;
for (int k=0; k<itemName.length; k++) {
if (shoppingList.equals(itemName[k])) {
price = itemPrice[k];
}
}
return price;
}
// a method that returns the smallest amount spent from all customers
static double smallest(double[] amountSpent) {
double currentMin = amountSpent[0];
for (int i=1; i<amountSpent.length; i++) {
if (amountSpent[i] < currentMin) {
currentMin = amountSpent[i];
}
}
return currentMin;
}
// a method that returns an integer that represents the index of the smallest spender name
static int smallestIndex(double[] amountSpent) {
double currentMin = amountSpent[0];
int index = 0;
for (int i=1; i<amountSpent.length; i++) {
if (amountSpent[i] < currentMin) {
currentMin = amountSpent[i];
index = i;
}
}
return index;
}
// a method that returns the biggest amount spent from all customers
static double biggest(double[] amountSpent) {
double currentMax = amountSpent[0];
for (int i=1; i<amountSpent.length; i++) {
if (amountSpent[i] > currentMax) {
currentMax = amountSpent[i];
}
}
return currentMax;
}
// a method that returns an integer that represents the index of the biggest spender name
static int biggestIndex(double[] amountSpent) {
double currentMax = amountSpent[0];
int index = 0;
for (int i=1; i<amountSpent.length; i++) {
if (amountSpent[i] > currentMax) {
currentMax = amountSpent[i];
index = i;
}
}
return index;
}
// a method that returns the average amount spent from all customers
static double average(double[] amountSpent, int totalCust) {
double average = 0;
double total = 0;
for(int i=0; i<amountSpent.length; i++) {
total += amountSpent [i];
}
average = total / totalCust;
return average;
}
}
| true |
801102b885f98b1780b4d79484a90f112ac07f73 | Java | SpongePowered/Mixin | /src/ap/java/org/spongepowered/tools/obfuscation/service/ObfuscationTypeDescriptor.java | UTF-8 | 3,921 | 1.953125 | 2 | [
"MIT"
] | permissive | /*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation.service;
import org.spongepowered.tools.obfuscation.ObfuscationEnvironment;
import org.spongepowered.tools.obfuscation.ObfuscationType;
/**
* Describes the arguments for a particular obfuscation type, used as an args
* object for creating {@link ObfuscationType}s
*/
public class ObfuscationTypeDescriptor {
/**
* Refmap key for this mapping type
*/
private final String key;
/**
* The name of the Annotation Processor argument which contains the file
* name to read the mappings for this obfuscation type from
*/
private final String inputFileArgName;
/**
* The name of the Annotation Processor argument which contains the file
* name to read the extra mappings for this obfuscation type from
*/
private final String extraInputFilesArgName;
/**
* The name of the Annotation Processor argument which contains the file
* name to write generated mappings to
*/
private final String outFileArgName;
private final Class<? extends ObfuscationEnvironment> environmentType;
public ObfuscationTypeDescriptor(String key, String inputFileArgName, String outFileArgName,
Class<? extends ObfuscationEnvironment> environmentType) {
this(key, inputFileArgName, null, outFileArgName, environmentType);
}
public ObfuscationTypeDescriptor(String key, String inputFileArgName, String extraInputFilesArgName, String outFileArgName,
Class<? extends ObfuscationEnvironment> environmentType) {
this.key = key;
this.inputFileArgName = inputFileArgName;
this.extraInputFilesArgName = extraInputFilesArgName;
this.outFileArgName = outFileArgName;
this.environmentType = environmentType;
}
/**
* Get the key for this type, must be unique
*/
public final String getKey() {
return this.key;
}
/**
* Get the name of the AP argument used to specify the input file
*/
public String getInputFileOption() {
return this.inputFileArgName;
}
/**
* Get the name of the AP argument used to specify extra input files
*/
public String getExtraInputFilesOption() {
return this.extraInputFilesArgName;
}
/**
* Get the name of the AP argument used to specify the output file
*/
public String getOutputFileOption() {
return this.outFileArgName;
}
/**
* Get the environment class
*/
public Class<? extends ObfuscationEnvironment> getEnvironmentType() {
return this.environmentType;
}
}
| true |
9e555e39b7da993fee44c39629c2493f04dea64d | Java | shwetaodel/Java-Programs | /DeleteFolder.java | UTF-8 | 330 | 2.890625 | 3 | [] | no_license | package core;
import java.io.File;
public class DeleteFolder {
public static void main(String[] args) {
File obj = new File("C:\\Users\\odel\\Desktop");
if(obj.delete()) {
System.out.println("folder deleted="+obj.getName());
}else {
System.out.println("failed to delete the folder");
}
}
}
| true |
f7ef890fe1e253df65c97c9a580ada28ada1b843 | Java | rezafd23/android-mobile-banking | /app/src/main/java/com/example/android_mobile_banking/ui/adapter/MutasiAdapter.java | UTF-8 | 4,002 | 2.09375 | 2 | [] | no_license | package com.example.android_mobile_banking.ui.adapter;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.example.android_mobile_banking.R;
import com.example.android_mobile_banking.model.Mutasi;
import com.example.android_mobile_banking.ui.activity.DetailTransactionActivity;
import com.example.android_mobile_banking.util.Util;
import java.util.ArrayList;
public class MutasiAdapter extends RecyclerView.Adapter<MutasiAdapter.MutasiViewHolder> {
private Context context;
private ArrayList<Mutasi> listMutasi;
private Activity activity;
public MutasiAdapter(Activity activity,Context context, ArrayList<Mutasi> listMutasi) {
this.activity = activity;
this.context = context;
this.listMutasi = listMutasi;
}
@NonNull
@Override
public MutasiAdapter.MutasiViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_mutasi, parent, false);
return new MutasiAdapter.MutasiViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MutasiAdapter.MutasiViewHolder holder, int position) {
// Log.v("isiNAMATRANSAKSI: ",listMutasi.get(position).getNama_transaksi());
String[] dateParts = listMutasi.get(position).getTgl_transaksi().split(" ");
String dayMonthYear = dateParts[0];
String[] dateMonth = dayMonthYear.split("-");
String nominal = "Rp." + Util.round(String.valueOf(listMutasi.get(position).getNominal()));
holder.tv_nama_transaksi.setText(listMutasi.get(position).getNama_transaksi());
if (listMutasi.get(position).getStatus_transaksi().equals("kredit")) {
holder.tv_nilai_transaksi.setText("+" + nominal);
holder.tv_nilai_transaksi.setTextColor(context.getColor(R.color.green));
} else {
holder.tv_nilai_transaksi.setText("-" + nominal);
holder.tv_nilai_transaksi.setTextColor(context.getColor(R.color.colorTextError));
}
holder.tv_tgl_transaksi.setText(dateMonth[2] + "/" + dateMonth[1]);
if (listMutasi.get(position).getNama_transaksi().contains("Pembelian Token")){
holder.layout_item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// public static void navigate(Activity activity,String tgl_trx,String nama_trx,String no_token,
// String payment,String card_no){
DetailTransactionActivity.navigate(activity,listMutasi.get(position).getTgl_transaksi(),
listMutasi.get(position).getNama_transaksi(),listMutasi.get(position).getDesc_transaksi(),
nominal,listMutasi.get(position).getCard_no());
}
});
}
}
@Override
public int getItemCount() {
return listMutasi.size();
}
public class MutasiViewHolder extends RecyclerView.ViewHolder {
AppCompatTextView tv_nama_transaksi, tv_tgl_transaksi, tv_nilai_transaksi, tv_status_transaksi;
LinearLayoutCompat layout_item;
public MutasiViewHolder(@NonNull View itemView) {
super(itemView);
tv_nama_transaksi = itemView.findViewById(R.id.tv_nama_transaksi);
tv_tgl_transaksi = itemView.findViewById(R.id.tv_tgl_transaksi);
tv_nilai_transaksi = itemView.findViewById(R.id.tv_nilai_transaksi);
tv_status_transaksi = itemView.findViewById(R.id.tv_status_transaksi);
layout_item = itemView.findViewById(R.id.layout_item);
}
}
}
| true |
72827dcfc64e8a4228fdfe817336e361314fedd8 | Java | wuguosong/riskcontrol | /BECE/rcm-rest_gf/src/main/java/com/yk/rcm/report/service/impl/ReportInfoService.java | UTF-8 | 1,786 | 1.742188 | 2 | [] | no_license | package com.yk.rcm.report.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.yk.power.service.IOrgService;
import com.yk.rcm.report.dao.IReportInfoMapper;
import com.yk.rcm.report.service.IReportInfoService;
import common.PageAssistant;
@Service
public class ReportInfoService implements IReportInfoService {
@Resource
private IReportInfoMapper reportInfoMapper;
@Resource
private IOrgService orgService;
@Override
public void saveReport(Map<String, Object> params) {
this.reportInfoMapper.saveReport(params);
}
@Override
public void updateReportByBusinessId(Map<String, Object> params) {
this.reportInfoMapper.updateReportByBusinessId(params);
}
@Override
public List<Map<String, Object>> queryPertainAreaAchievement() {
return this.reportInfoMapper.queryPertainAreaAchievement();
}
@Override
public List<Map<String, Object>> queryProjectsByPertainareaid(PageAssistant page) {
Map<String, Object> paramMap = new HashMap<String,Object>();
paramMap.put("page", page);
if(page.getParamMap() != null){
if(page.getParamMap().get("state").equals("all")){
page.getParamMap().remove("state");
}
paramMap.putAll(page.getParamMap());
}
List<Map<String, Object>> queryProjectsByPertainareaid = this.reportInfoMapper.queryProjectsByPertainareaid(paramMap);
page.setList(queryProjectsByPertainareaid);
Map<String, Object> queryByPkvalue = orgService.queryByPkvalue((String)page.getParamMap().get("pertainareaId"));
Map<String, Object> data = new HashMap<String,Object>();
data.put("name", (String)queryByPkvalue.get("NAME"));
page.setParamMap(data);
return queryProjectsByPertainareaid;
}
}
| true |
ebbbb04f7924c549fb489db576720222fa11b44e | Java | mamunhtd/SeleniumProject | /SeleniumProject/src/main/java/learnInterface/A.java | UTF-8 | 105 | 1.773438 | 2 | [] | no_license | package learnInterface;
public interface A {
void play();
void football();
void baseball();
}
| true |
b76ecdcf3fe0c8b3b58d582e1100ec8eb70490fe | Java | roman1pr/itmo-lab3-Multytreads | /FibonacciManager/src/main/java/com/example/Fibonacci/domain/FNumber.java | UTF-8 | 1,040 | 2.6875 | 3 | [] | no_license | package com.example.Fibonacci.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.math.BigInteger;
@Entity
@Table(name="FNumber")
public class FNumber {
@Id
private int id;
private int number;
private BigInteger value;
private BigInteger value2;
public FNumber() {
}
public FNumber(int id, int number, BigInteger value, BigInteger value2) {
this.id = id;
this.number = number;
this.value = value;
this.value2 = value2;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public BigInteger getValue() {
return value;
}
public BigInteger getValue2() { return value2; }
public void setValue(BigInteger value) {
this.value = value;
}
}
| true |
2a49deca33b66d567b62cd9a7b32c1688640f589 | Java | wy19840708/facs-agriculture | /facs-agriculture-service/src/main/java/com/facs/agriculture/service/impl/DeptResourceServiceImpl.java | UTF-8 | 2,741 | 2.09375 | 2 | [] | no_license | package com.facs.agriculture.service.impl;
import com.facs.agriculture.dao.DeptResourceMapper;
import com.facs.agriculture.iservice.IDeptResourceService;
import com.facs.agriculture.support.model.bo.DeptResourceQuery;
import com.facs.agriculture.support.model.dto.DeptResourceQueryRequest;
import com.facs.agriculture.support.model.dto.DeptResourceRequest;
import com.facs.agriculture.support.model.dto.DeptResourceResponse;
import com.facs.agriculture.support.model.po.DeptResource;
import com.facs.basic.framework.common.util.FacsBeanUtils;
import com.facs.basic.framework.model.bo.BoPageRequest;
import com.facs.basic.framework.model.dto.PageRequest;
import com.facs.basic.framework.model.rest.MutiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("deptResourceService")
public class DeptResourceServiceImpl implements IDeptResourceService {
@Autowired
private DeptResourceMapper deptResourceMapper;
@Override
public MutiResponse<DeptResourceResponse> loadPage(PageRequest<DeptResourceQueryRequest> paramData) {
//转换查询条件的格式
BoPageRequest<DeptResourceQuery> daoRequest = new BoPageRequest<>();
daoRequest.setPageNum(paramData.getPageNo());
daoRequest.setPageSize(paramData.getLimit());
daoRequest.setStart((paramData.getPageNo()-1)*paramData.getLimit());
daoRequest.setParamData(FacsBeanUtils.copy(paramData.getParam(), DeptResourceQuery.class));
//获取数据
List<DeptResource> list = deptResourceMapper.loadPage(daoRequest);
Long total = deptResourceMapper.total(daoRequest.getParamData());
//转换回传数据的格式
MutiResponse<DeptResourceResponse> pageResponse = new MutiResponse<>();
pageResponse.setItems(FacsBeanUtils.copyList(list, DeptResourceResponse.class));
pageResponse.setTotal(total);
pageResponse.setLimit(paramData.getLimit());
pageResponse.setPageNo(paramData.getPageNo());
return pageResponse;
}
@Override
public DeptResourceResponse load(DeptResourceRequest paramData) {
DeptResource object = deptResourceMapper.load(paramData.getId());
return FacsBeanUtils.copy(object,DeptResourceResponse.class);
}
@Override
public DeptResourceResponse create(DeptResourceRequest paramData) {
DeptResource newObj = FacsBeanUtils.copy(paramData, DeptResource.class);
deptResourceMapper.insert(newObj);
return FacsBeanUtils.copy(newObj,DeptResourceResponse.class);
}
@Override
public DeptResourceResponse update(DeptResourceRequest paramData) {
DeptResource updateObj = FacsBeanUtils.copy(paramData, DeptResource.class);
deptResourceMapper.update(updateObj);
return FacsBeanUtils.copy(updateObj,DeptResourceResponse.class);
}
}
| true |
2fc92eafe26bf560fd767c96c7feb6635239b0c6 | Java | mmoayyed/java-identity-provider | /idp-saml-api/src/main/java/net/shibboleth/idp/saml/session/SAML2SPSession.java | UTF-8 | 5,953 | 1.734375 | 2 | [] | no_license | /*
* Licensed to the University Corporation for Advanced Internet Development,
* Inc. (UCAID) under one or more contributor license agreements. See the
* NOTICE file distributed with this work for additional information regarding
* copyright ownership. The UCAID 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 net.shibboleth.idp.saml.session;
import java.time.Instant;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.opensaml.core.xml.io.MarshallingException;
import org.opensaml.core.xml.util.XMLObjectSupport;
import org.opensaml.saml.common.xml.SAMLConstants;
import org.opensaml.saml.saml2.core.NameID;
import org.opensaml.saml.saml2.profile.SAML2ObjectSupport;
import com.google.common.base.MoreObjects;
import net.shibboleth.idp.session.BasicSPSession;
import net.shibboleth.shared.annotation.constraint.NotEmpty;
import net.shibboleth.shared.logic.Constraint;
import net.shibboleth.shared.primitive.StringSupport;
import net.shibboleth.shared.xml.SerializeSupport;
/**
* Extends a {@link BasicSPSession} with SAML 2.0 information required for
* reverse lookup in the case of a logout.
*/
public class SAML2SPSession extends BasicSPSession {
/** The NameID asserted to the SP. */
@Nonnull private final NameID nameID;
/** The SessionIndex asserted to the SP. */
@Nonnull @NotEmpty private final String sessionIndex;
/** The ACS location used for the associated response. */
@Nullable @NotEmpty private final String acsLocation;
/** Whether logout propagation is possible. */
private final boolean supportsLogoutPropagation;
// Checkstyle: ParameterNumber OFF
/**
* Constructor.
*
* @param id the identifier of the service associated with this session
* @param creation creation time of session
* @param expiration expiration time of session
* @param assertedNameID the NameID asserted to the SP
* @param assertedIndex the SessionIndex asserted to the SP
* @param acsLoc the response endpoint used
* @param supportsLogoutProp whether the session supports logout propagation
*/
public SAML2SPSession(@Nonnull @NotEmpty final String id, @Nonnull final Instant creation,
@Nonnull final Instant expiration, @Nonnull final NameID assertedNameID,
@Nonnull @NotEmpty final String assertedIndex, @Nullable @NotEmpty final String acsLoc,
final boolean supportsLogoutProp) {
super(id, creation, expiration);
nameID = Constraint.isNotNull(assertedNameID, "NameID cannot be null");
sessionIndex = Constraint.isNotNull(StringSupport.trimOrNull(assertedIndex),
"SessionIndex cannot be null or empty");
acsLocation = StringSupport.trimOrNull(acsLoc);
supportsLogoutPropagation = supportsLogoutProp;
}
// Checkstyle: ParameterNumber ON
/**
* Get the {@link NameID} asserted to the SP.
*
* @return the asserted {@link NameID}
*/
@Nonnull public NameID getNameID() {
return nameID;
}
/**
* Get the {@link org.opensaml.saml.saml2.core.SessionIndex} value asserted to the SP.
*
* @return the SessionIndex value
*/
@Nonnull @NotEmpty public String getSessionIndex() {
return sessionIndex;
}
/** {@inheritDoc} */
@Override
@Nullable public String getSPSessionKey() {
return nameID.getValue();
}
/** {@inheritDoc} */
@Override
@Nullable @NotEmpty public String getProtocol() {
return SAMLConstants.SAML20P_NS;
}
/**
* Get the ACS location used for the response that produced this session.
*
* @return ACS location
*/
@Nullable @NotEmpty public String getACSLocation() {
return acsLocation;
}
/** {@inheritDoc} */
@Override
public boolean supportsLogoutPropagation() {
return supportsLogoutPropagation;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return (getId() + '!' + nameID.getValue() + '!' + sessionIndex).hashCode();
}
/** {@inheritDoc} */
@Override
public boolean equals(final Object obj) {
if (!super.equals(obj)) {
return false;
}
if (obj instanceof SAML2SPSession) {
final NameID n1 = ((SAML2SPSession) obj).getNameID();
final NameID n2 = nameID;
if (n1 != null && n2 != null && Objects.equals(n1.getValue(), n2.getValue())
&& SAML2ObjectSupport.areNameIDFormatsEquivalent(n1.getFormat(), n2.getFormat())
&& Objects.equals(n1.getNameQualifier(), n2.getNameQualifier())
&& Objects.equals(n1.getSPNameQualifier(), n2.getSPNameQualifier())) {
return Objects.equals(getSessionIndex(), ((SAML2SPSession) obj).getSessionIndex());
}
}
return false;
}
/** {@inheritDoc} */
@Override
public String toString() {
try {
return MoreObjects.toStringHelper(this)
.add("NameID", SerializeSupport.nodeToString(XMLObjectSupport.marshall(nameID)))
.add("SessionIndex", sessionIndex).toString();
} catch (final MarshallingException e) {
throw new IllegalArgumentException("Error marshalling NameID", e);
}
}
} | true |
18e37286fd04c5e06bd76585d37a577ea9749027 | Java | Theembers/RKES | /src/com/wke/webapp/comm/utility/ClassCaster.java | UTF-8 | 4,632 | 2.84375 | 3 | [] | no_license | package com.wke.webapp.comm.utility;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
/**
* Title: 系统组件 类造型器
* Description: 中国税务税收征管信息系统
* Copyright: Copyright (c) 2006
* Company: 中国软件与技术服务股份有限公司
* @author 康水明
* @version 1.0
*/
public class ClassCaster {
public static final Logger logger = LoggerFactory.getLogger(ClassCaster.class);
/**
* 根据对象类型造型
* @param Class 造型结果类型
* @param obj 要造型的对象
* @return Object 造型结果
*/
public static Object classCast(Class clas, Object obj) {
return classCast(clas.getName(),obj);
}
/**
* 根据对象类型造型
* @param classType 造型结果类型
* @param obj 要造型的对象
* @return Object 造型结果
*/
public static Object classCast(String classType, Object obj) {
Object result = null; // 造型结果
try {
if (classType != null && obj != null && !"".equals(obj)) {
String temp = String.valueOf(obj);
String classname = obj.getClass().getName();
if (classType.endsWith("String")) {
if (classname.startsWith("[L")) {
String[] str = (String[]) obj;
result = str[0];
} else {
result = temp;
}
} else if (classType.endsWith("Double")) {
if ("java.lang.Double".equals(classname)) {
result = (Double) obj;
} else {
result = new Double(temp);
}
} else if (classType.endsWith("Long")) {
if ("java.lang.Long".equals(classname)) {
result = (Long) obj;
} else {
result = new Long(temp);
}
} else if (classType.endsWith("Integer")) {
if ("java.lang.Integer".equals(classname)) {
result = (Integer) obj;
} else {
result = new Integer(temp);
}
} else if (classType.endsWith("double")) {
if ("java.lang.Double".equals(classname)) {
result = (Double) obj;
} else {
result = new Double(temp);
}
} else if (classType.endsWith("int")) {
if ("java.lang.Integer".equals(classname)) {
result = (Integer) obj;
} else {
result = new Integer(temp);
}
} else if (classType.endsWith("long")) {
if ("java.lang.Long".equals(classname)) {
result = (Long) obj;
} else {
result = new Long(temp);
}
} else if (classType.endsWith("BigDecimal")) {
if ("java.math.BigDecimal".equals(classname)) {
result = (BigDecimal) obj;
} else {
result = new BigDecimal(temp);
}
} else if (classType.endsWith("Calendar")) {
result = toCalendar(obj);
} else if (classType.endsWith("Date")) {
result = toDate(obj);
}
}
} catch (ClassCastException ex) {
logger.error("class造型失败:", ex);
}
return result;
}
/**
* 造型为Calendar
* @param obj
* @return Calendar
*/
private static Calendar toCalendar(Object obj) {
Calendar cal = Calendar.getInstance();
try {
String classname = obj.getClass().getName();
if ("java.lang.String".equals(classname)) {
cal = DateUtils.parseDate((String) obj);
} else if ("java.sql.Date".equals(classname)) {
cal.setTime((java.util.Date) obj);
} else if ("java.sql.Timestamp".equals(classname)) {
cal = DateUtils.convSqlTimestampToUtilCalendar((Timestamp) obj);
} else if ("java.util.Date".equals(classname)) {
cal.setTime((java.util.Date) obj);
} else {
cal = (Calendar) obj;
}
} catch (ClassCastException ex) {
logger.error("Calendar造型失败:", ex);
}
return cal;
}
/**
* 造型为Date
* @param obj
* @return Date
*/
private static Date toDate(Object obj) {
Date date = new Date();
try {
String classname = obj.getClass().getName();
if ("java.lang.String".equals(classname)) {
date = DateUtils.StringToDate((String) obj);
} else if ("java.sql.Timestamp".equals(classname)) {
date.setTime(((java.sql.Timestamp) obj).getTime());
} else if ("java.util.Calendar".equals(classname)) {
date = ((java.util.Calendar) obj).getTime();
} else if ("java.util.GregorianCalendar".equals(classname)) {
date = ((java.util.Calendar) obj).getTime();
} else {
date = (Date) obj;
}
} catch (ClassCastException ex) {
logger.error("Date造型失败:", ex);
}
return date;
}
}
| true |
a02853f5e24a7636b6affb13af6e4a5659ab26e6 | Java | TOTALLY-JOHN/CSCI366_Assg1_Image_Contrast_Enhancement_App | /app/src/main/java/com/csci366_2020/jihwanjeong/contrastenhancement/MainActivity.java | UTF-8 | 8,787 | 2.3125 | 2 | [] | no_license | package com.csci366_2020.jihwanjeong.contrastenhancement;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
// DECLARE REQUEST VARIABLE
final int PICK_IMAGE_REQUEST = 111;
// DECLARE VARIABLES
boolean imageLoadStatus = false;
TextView textViewOriginalImage;
ImageView imageViewPart1, imageViewPart2;
FloatingActionButton loadButton;
Bitmap inputBM, outputBM;
Button backButton, processButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// TO CONNECT USING ID
imageViewPart1 = findViewById(R.id.imageViewPart1);
imageViewPart2 = findViewById(R.id.imageViewPart2);
loadButton = findViewById(R.id.floatingActionButtonLoad);
backButton = findViewById(R.id.backButton);
processButton = findViewById(R.id.processButton);
textViewOriginalImage = findViewById(R.id.textView1);
}
public void updateImage(View v) {
// IF THE IMAGE IS SUCCESSFULLY LOADED
if (imageLoadStatus) {
// TO GET THE WIDTH AND HEIGHT FROM THE IMAGE
int width = inputBM.getWidth();
int height = inputBM.getHeight();
// TO DECLARE TWO RGB ARRAYS TO BE STORED
int[] rgb = new int[3];
int[] rgb1 = new int[3];
// TO DECLARE THE COLOR VALUE FOR YUV
float Y, U, V;
// TO CREATE OUTPUT BITMAP IMAGE USING THE LOADED CONFIGURATION
outputBM = Bitmap.createBitmap(width, height, inputBM.getConfig());
// TO DECLARE ARRAYS FOR THE NUMBER OF GRAY VALUE BASED ON RGB COLORS
double count0[] = new double[256];
double count1[] = new double[256];
double count2[] = new double[256];
for (int j = 0; j < height; j++) {
for(int i = 0; i < width; i++) {
// TO GET THE COLOR FROM EACH PIXEL
int color = inputBM.getPixel(i, j);
rgb[0] = Color.red(color);
rgb[1] = Color.green(color);
rgb[2] = Color.blue(color);
// TO COUNT THE NUMBER OF GRAY VALUES THAT APPEAR IN THE ENTIRE PICTURE
if (count0[rgb[0]]==0){
count0[rgb[0]]=1;
}
else {
count0[rgb[0]]+=1;
}
if (count1[rgb[1]]==0){
count1[rgb[1]]=1;
}
else {
count1[rgb[1]]+=1;
}
if (count2[rgb[2]]==0){
count2[rgb[2]]=1;
}
else {
count2[rgb[2]]+=1;
}
}
}
// TO COUNT THE PROPORTION OF THE GRAY VALUE TO THE WHOLE
double gl0[] = new double[256];
for (int i=0;i<256;i++){
gl0[i]=count0[i]/(width*height);
}
double gl1[] = new double[256];
for (int i=0;i<256;i++){
gl1[i]=count1[i]/(width*height);
}
double gl2[] = new double[256];
for (int i=0;i<256;i++){
gl2[i]=count2[i]/(width*height);
}
// TO SET UP STATISTICS CUMULATIVE HISTOGRAM (CUMULATIVE PERCENTAGE)
double sk0[]=new double[256];
for (int i=0;i<256;i++){
for (int j=0;j<=i;j++){
sk0[i]+=gl0[j];
}
}
double sk1[]=new double[256];
for (int i=0;i<256;i++){
for (int j=0;j<=i;j++){
sk1[i]+=gl1[j];
}
}
double sk2[]=new double[256];
for (int i=0;i<256;i++){
for (int j=0;j<=i;j++){
sk2[i]+=gl2[j];
}
}
// TO MULTIPLY THE CALCULATED ACCUMULATION RATIO BY THE MAXIMUM PIXEL VALUE (255)
// TO RECORD THE NEW PIXEL VALUE
double Sk0[]=new double[256];
for (int i=0;i<256;i++){
Sk0[i]=((255)*sk0[i]+0.5);
}
double Sk1[]=new double[256];
for (int i=0;i<256;i++){
Sk1[i]=((255)*sk1[i]+0.5);
}
double Sk2[]=new double[256];
for (int i=0;i<256;i++){
Sk2[i]=((255)*sk2[i]+0.5);
}
for (int j=0;j<height;j++){
for(int i=0;i<width;i++){
int color = inputBM.getPixel(i, j);
int alpha = Color.alpha(color);
rgb[0] = Color.red(color);
rgb[1] = Color.green(color);
rgb[2] = Color.blue(color);
// TO ASSIGN THE NEW PIXEL VALUE TO THE ORIGINAL PIXEL VALUE
rgb1[0]=(int)Sk0[rgb[0]];
rgb1[1]=(int)Sk1[rgb[1]];
rgb1[2]=(int)Sk2[rgb[2]];
// TO CONVERT INTO YUV COLOR VALUE
Y = (float) (0.299*rgb1[0] + 0.587*rgb1[1] + 0.114*rgb1[2]);
U = (float) (-0.147*rgb1[0] - 0.289*rgb1[1] + 0.436*rgb1[2]);
V = (float) (0.615*rgb1[0] - 0.515*rgb1[1] - 0.100*rgb1[2]);
// TO CONVERT INTO RGB VALUE AGAIN
rgb1[0] = (int) (Y + 1.140*V);
rgb1[1] = (int) (Y - 0.395*U - 0.581*V);
rgb1[2] = (int) (Y + 2.032*U);
// IF THE COLOR VALUE IS OUT OF BOUNDS
if (rgb1[0] > 255)
rgb1[0] = 255;
else if (rgb1[0] < 0)
rgb1[0] = 0;
if (rgb1[1] > 255)
rgb1[1] = 255;
else if (rgb1[1] < 0)
rgb1[1] = 0;
if (rgb1[2] > 255)
rgb1[2] = 255;
else if (rgb1[2] < 0)
rgb1[2] = 0;
// TO SET EACH PIXEL WITH COLOR
outputBM.setPixel(i, j, Color.argb(alpha, rgb1[0], rgb1[1], rgb1[2]));
}
}
imageViewPart2.setImageBitmap(outputBM);
}
}
// WHEN THE IMAGE LOAD BUTTON IS CLICKED, IT RUNS
public void loadImage(View view) {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "Select Picture"), PICK_IMAGE_REQUEST);
}
// IF THE USER CLICKS THE BACK BUTTON
public void backButtonClick(View view) {
imageViewPart1.setImageBitmap(null);
imageViewPart2.setImageBitmap(null);
backButton.setVisibility(View.INVISIBLE);
loadButton.setVisibility(View.VISIBLE);
textViewOriginalImage.setVisibility(View.INVISIBLE);
processButton.setVisibility(View.INVISIBLE);
}
// WHEN RETURNING, IT RUNS FROM CHOOSER ACTIVITY
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
inputBM = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageViewPart1.setImageBitmap(inputBM);
imageLoadStatus = true;
textViewOriginalImage.setVisibility(View.VISIBLE);
backButton.setVisibility(View.VISIBLE);
processButton.setVisibility(View.VISIBLE);
loadButton.setVisibility(View.GONE);
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | true |
f4986ec919682c71bca37261854cb935bd43b650 | Java | LiangGuiPing/FamousTeacherStation | /ftw/ftw-station/station-dao/src/main/java/com/ftw/dao/adm/AdmModulesDAO.java | UTF-8 | 996 | 1.921875 | 2 | [] | no_license | package com.ftw.dao.adm;
import com.ftw.entity.adm.AdmModules;
import com.ftw.entity.adm.AdmModulesExample;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface AdmModulesDAO {
long countByExample(AdmModulesExample example);
int deleteByExample(AdmModulesExample example);
int deleteByPrimaryKey(Integer id);
int insert(AdmModules record);
int insertSelective(AdmModules record);
List<AdmModules> selectByExample(AdmModulesExample example);
AdmModules selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") AdmModules record, @Param("example") AdmModulesExample example);
int updateByExample(@Param("record") AdmModules record, @Param("example") AdmModulesExample example);
int updateByPrimaryKeySelective(AdmModules record);
int updateByPrimaryKey(AdmModules record);
} | true |
815345fecd46d7b6e2b8347626eaf0689c88f164 | Java | ylxb23/springboot | /src/main/java/org/zero/boot/web/init/conf/security/CustomSuccessHandler.java | UTF-8 | 6,787 | 2.1875 | 2 | [
"MIT"
] | permissive | package org.zero.boot.web.init.conf.security;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.zero.boot.dao.first.entity.SysUser;
import org.zero.boot.dao.first.entity.SysUserExample;
import org.zero.boot.dao.first.repository.SysUserMapper;
import org.zero.boot.domain.response.LoginResponse;
import org.zero.boot.domain.vo.UserPlus;
import org.zero.boot.domain.vo.UserVo;
import org.zero.boot.util.ResponseUtil;
/**
* 登录成功handler
* @date 2017年11月17日 下午4:37:05
* @author zero
*/
@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private final Logger logger = LoggerFactory.getLogger(CustomSuccessHandler.class);
@Autowired
private SysUserMapper userMapper;
public CustomSuccessHandler() {
super();
custom();
}
private void custom() {
// 如果登陆时参数中没有找到 fromUrl,则从高 Header中的 "Referer"中找登录成功后跳转的 url
setUseReferer(true);
// 登陆时将登录成功要跳转的路径传入的参数名,譬如 /login?fromUrl=/user/home
setTargetUrlParameter("fromUrl");
}
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
// store user info into sesssion
sessionUserInfo(request, authentication);
doWriteResponse(request, response, authentication);
}
/**
* In use
* @param request
* @param response
* @param authentication
*/
@SuppressWarnings("unchecked")
protected void doWriteResponse(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
// get from url
String fromUrl = determineTargetUrl(request, response);
List<SimpleGrantedAuthority> simpleauthorities = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
UserVo<UserPlus> vo = new UserVo<>();
User user = (User) authentication.getPrincipal();
vo.setUsername(user.getUsername());
vo.setIsAccountNonExpired(user.isAccountNonExpired());
vo.setIsAccountNonLocked(user.isAccountNonLocked());
vo.setIsCredentialsNonExpired(user.isCredentialsNonExpired());
vo.setIsEnabled(user.isEnabled());
Set<String> authorities = simpleauthorities.stream().map(s -> s.getAuthority()).collect(Collectors.toSet());
vo.setAuthorities(authorities);
LoginResponse resObj = LoginResponse.builder()
.fromUrl(fromUrl)
.code(LoginResponse.CODE_SUCCESS)
.msg(LoginResponse.MSG_SUCCESS)
.user(vo).build();
vo.setPlus(getPlusByUsername(vo.getUsername()));
ResponseUtil.writeResponse(response, resObj);
}
/**
* 获取用户附加信息
* @param username
* @return
*/
private UserPlus getPlusByUsername(String username) {
SysUserExample example = new SysUserExample();
example.createCriteria().andUsernameEqualTo(username);
List<SysUser> list = userMapper.selectByExample(example);
if(list.isEmpty()) {
// could not happen
throw new AuthenticationCredentialsNotFoundException("用户信息不存在");
}
SysUser user = list.get(0);
UserPlus plus = new UserPlus();
plus.setEmail(user.getEmail());
plus.setGendar(user.getGendar());
plus.setMark(user.getMark());
plus.setPhone(user.getPhone());
plus.setRealname(user.getRealname());
return plus;
}
/**
* 登录成功,根据角色跳转页面
* @deprecated 前后端分离,舍弃页面跳转方式返回
* @param request
* @param response
* @param authentication
* @throws IOException
* @throws ServletException
*/
@Deprecated
protected void doSendRedirect(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
String fromUrl = request.getParameter("fromUrl");
if(StringUtils.isEmpty(fromUrl)) {
// 如果参数中没有 fromUrl,则通过权限中获取的角色跳转到对应的 HOME路径下
// 从 handle中获取 request,response,authentication对象
// SimpleGrantedAuthority
@SuppressWarnings("unchecked")
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) authentication.getAuthorities(); // 只有一个角色
if(authorities.isEmpty()) {
// 嘿嘿,这是不可能的,因为我会写死他
User user = (User) authentication.getPrincipal();
logger.warn("用户[{}]权限有问题,他没角色!", user.getUsername());
throw new IllegalArgumentException("用户权限有问题");
}
// 第一个角色为主要角色
SimpleGrantedAuthority authority = (SimpleGrantedAuthority) Arrays.asList(authorities.toArray()).get(0);
String toUrl = null;
// 使用 Builder创建的GrantedAuthority 会有 "ROLE_"这个前缀,是因为在 SimpleGrantedAuthority对象创建的时候 UserBuilder会给它加上去.
// 当前 UserDetails对象是通过自定义的 UserDetailsService装配的,其中的 authorities也是自定义的,并没有 ROLE_ 前缀
switch (authority.getAuthority()) {
case "USER":
toUrl = "/user/home";
break;
case "ADMIN":
toUrl = "/admin/home";
break;
default:
toUrl = "/";
break;
}
toUrl = response.encodeRedirectURL(toUrl);
response.sendRedirect(toUrl);
return;
} else {
// 否则使用框架中的 handle
super.handle(request, response, authentication);
}
}
private void sessionUserInfo(HttpServletRequest request, Authentication authentication) {
HttpSession session = request.getSession(true);
Map<String, Object> map = new HashMap<>(4);
map.put("username", authentication.getPrincipal());
map.put("authorities", authentication.getAuthorities());
session.setAttribute("authentication", map);
}
}
| true |
c0ad77e8976a5208a81f9f40b7eaac6c7f514a23 | Java | tungmk97/bookstore-backend | /BookStore/src/main/java/com/mk/repository/GenresRepository.java | UTF-8 | 202 | 1.679688 | 2 | [] | no_license | package com.mk.repository;
import com.mk.data.entities.Genres;
import org.springframework.data.jpa.repository.JpaRepository;
public interface GenresRepository extends JpaRepository<Genres, Long> {
} | true |
b96135ae4d12b2f8e43b46287fb1c7e9d6db5234 | Java | Azure/azure-libraries-for-java | /azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/RoleDefinitionInner.java | UTF-8 | 4,428 | 1.992188 | 2 | [
"MIT"
] | permissive | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.graphrbac.implementation;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
/**
* Role definition.
*/
@JsonFlatten
public class RoleDefinitionInner {
/**
* The role definition ID.
*/
@JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY)
private String id;
/**
* The role definition name.
*/
@JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY)
private String name;
/**
* The role definition type.
*/
@JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY)
private String type;
/**
* The role name.
*/
@JsonProperty(value = "properties.roleName")
private String roleName;
/**
* The role definition description.
*/
@JsonProperty(value = "properties.description")
private String description;
/**
* The role type.
*/
@JsonProperty(value = "properties.type")
private String roleType;
/**
* Role definition permissions.
*/
@JsonProperty(value = "properties.permissions")
private List<PermissionInner> permissions;
/**
* Role definition assignable scopes.
*/
@JsonProperty(value = "properties.assignableScopes")
private List<String> assignableScopes;
/**
* Get the id value.
*
* @return the id value
*/
public String id() {
return this.id;
}
/**
* Get the name value.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Get the type value.
*
* @return the type value
*/
public String type() {
return this.type;
}
/**
* Get the roleName value.
*
* @return the roleName value
*/
public String roleName() {
return this.roleName;
}
/**
* Set the roleName value.
*
* @param roleName the roleName value to set
* @return the RoleDefinitionInner object itself.
*/
public RoleDefinitionInner withRoleName(String roleName) {
this.roleName = roleName;
return this;
}
/**
* Get the description value.
*
* @return the description value
*/
public String description() {
return this.description;
}
/**
* Set the description value.
*
* @param description the description value to set
* @return the RoleDefinitionInner object itself.
*/
public RoleDefinitionInner withDescription(String description) {
this.description = description;
return this;
}
/**
* Get the roleType value.
*
* @return the roleType value
*/
public String roleType() {
return this.roleType;
}
/**
* Set the roleType value.
*
* @param roleType the roleType value to set
* @return the RoleDefinitionInner object itself.
*/
public RoleDefinitionInner withRoleType(String roleType) {
this.roleType = roleType;
return this;
}
/**
* Get the permissions value.
*
* @return the permissions value
*/
public List<PermissionInner> permissions() {
return this.permissions;
}
/**
* Set the permissions value.
*
* @param permissions the permissions value to set
* @return the RoleDefinitionInner object itself.
*/
public RoleDefinitionInner withPermissions(List<PermissionInner> permissions) {
this.permissions = permissions;
return this;
}
/**
* Get the assignableScopes value.
*
* @return the assignableScopes value
*/
public List<String> assignableScopes() {
return this.assignableScopes;
}
/**
* Set the assignableScopes value.
*
* @param assignableScopes the assignableScopes value to set
* @return the RoleDefinitionInner object itself.
*/
public RoleDefinitionInner withAssignableScopes(List<String> assignableScopes) {
this.assignableScopes = assignableScopes;
return this;
}
}
| true |
298f18687406fe00b5034fdcf469d14fe477f85a | Java | dujunqi/springTest | /src/com/springTest/test/AspectJTest.java | UTF-8 | 572 | 1.984375 | 2 | [] | no_license | package com.springTest.test;
import com.springTest.aop.anno.AspectJAnnoTest;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @desciption:用途
* @author: 杜俊圻
* @date: 2020/10/24 16:15
*/
public class AspectJTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("annoConfig.xml");
AspectJAnnoTest anno = context.getBean("anno", AspectJAnnoTest.class);
anno.after();
}
}
| true |
b5bec5ba261ec564718f6526e13357b906601691 | Java | apache/hbase | /hbase-client/src/main/java/org/apache/hadoop/hbase/client/MultiResponse.java | UTF-8 | 3,392 | 1.96875 | 2 | [
"CC-BY-3.0",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-protobuf",
"MIT"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.client;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos;
/**
* A container for Result objects, grouped by regionName.
*/
@InterfaceAudience.Private
public class MultiResponse extends AbstractResponse {
// map of regionName to map of Results by the original index for that Result
private Map<byte[], RegionResult> results = new TreeMap<>(Bytes.BYTES_COMPARATOR);
/**
* The server can send us a failure for the region itself, instead of individual failure. It's a
* part of the protobuf definition.
*/
private Map<byte[], Throwable> exceptions = new TreeMap<>(Bytes.BYTES_COMPARATOR);
public MultiResponse() {
super();
}
/** Returns Number of pairs in this container */
public int size() {
int size = 0;
for (RegionResult result : results.values()) {
size += result.size();
}
return size;
}
/** Add the pair to the container, grouped by the regionName. */
public void add(byte[] regionName, int originalIndex, Object resOrEx) {
getResult(regionName).addResult(originalIndex, resOrEx);
}
public void addException(byte[] regionName, Throwable ie) {
exceptions.put(regionName, ie);
}
/** Returns the exception for the region, if any. Null otherwise. */
public Throwable getException(byte[] regionName) {
return exceptions.get(regionName);
}
public Map<byte[], Throwable> getExceptions() {
return exceptions;
}
public void addStatistic(byte[] regionName, ClientProtos.RegionLoadStats stat) {
getResult(regionName).setStat(stat);
}
private RegionResult getResult(byte[] region) {
RegionResult rs = results.get(region);
if (rs == null) {
rs = new RegionResult();
results.put(region, rs);
}
return rs;
}
public Map<byte[], RegionResult> getResults() {
return this.results;
}
@Override
public ResponseType type() {
return ResponseType.MULTI;
}
static class RegionResult {
Map<Integer, Object> result = new HashMap<>();
ClientProtos.RegionLoadStats stat;
public void addResult(int index, Object result) {
this.result.put(index, result);
}
public void setStat(ClientProtos.RegionLoadStats stat) {
this.stat = stat;
}
public int size() {
return this.result.size();
}
public ClientProtos.RegionLoadStats getStat() {
return this.stat;
}
}
}
| true |
10c15080c6addf3e5367c46d77449e22bbbaaf2d | Java | sapna2206/Assignment-Core-Java | /training/oopDesign/abcShop/ProdMain.java | UTF-8 | 1,914 | 3.140625 | 3 | [] | no_license | package com.psl.training.oopDesign.abcShop;
public class ProdMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
SoftwareProd microsoftOffice = new SoftwareProd();
microsoftOffice.setOs("Windows");
microsoftOffice.setProdID(100);
microsoftOffice.setProdName("Microsoft Office");
microsoftOffice.setMemory(1000);
microsoftOffice.setLicenseKey(100100);
SoftwareProd tally = new SoftwareProd();
tally.setOs("Linux");
tally.setProdID(101);
tally.setProdName("Tally");
tally.setMemory(64);
tally.setLicenseKey(101101);
HardwareProd computers = new HardwareProd();
computers.setProdID(102);
computers.setProdName("Computer");
computers.setBrand("Dell");
computers.setCapacity(500);
computers.setDimension(1920*1080);
computers.setPowerSupply(3);
HardwareProd laptops = new HardwareProd();
laptops.setProdID(103);
laptops.setProdName("Laptop");
laptops.setBrand("HP");
laptops.setCapacity(500);
laptops.setDimension(1440*900);
laptops.setPowerSupply(3);
HardwareProd carDeck = new HardwareProd();
carDeck.setProdID(103);
carDeck.setProdName("CarDeck");
carDeck.setBrand("Hi-Tech");
carDeck.setCapacity(30);
carDeck.setDimension(50*180);
carDeck.setPowerSupply(2);
HardwareProd homeTheater = new HardwareProd();
homeTheater.setProdID(103);
homeTheater.setProdName("HomeTheater");
homeTheater.setBrand("JBL");
homeTheater.setCapacity(6000);
homeTheater.setDimension(48.2*40.2*39);
homeTheater.setPowerSupply(1000);
Product[] prodArray = new Product[] {microsoftOffice, tally, computers, laptops, carDeck, homeTheater };
/*for(int i =0;i<prodArray.length;i++)
{
if(prodArray[i] instanceOf SoftwareProd) {
(SoftwarePro
}
}*/
for(Product p: prodArray) {
/*if(p.getClass().getName() == "Assignment2.com.training.shop.SoftwareProd") {
p.display();
}*/
p.display();
}
}
}
| true |
372660ed2de4031618e9e68ac7543c02f86cdafb | Java | skiskon/Maven | /src/main/java/Sem2/ClassWork/Server2/Main.java | UTF-8 | 1,520 | 2.796875 | 3 | [] | no_license | package Sem2.ClassWork.Server2;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Executors;
/**
* Created by admin on 07.04.2017.
*/
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(10));
AsynchronousServerSocketChannel ass = AsynchronousServerSocketChannel.open(group);
ass.bind(new InetSocketAddress(80));
ass.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
@Override
public void completed(AsynchronousSocketChannel result, Void attachment) {
ass.accept(null,this);
Request.readRequest(result);
}
@Override
public void failed(Throwable exc, Void attachment) {
exc.printStackTrace();
}
});
//Thread.sleep(60000); если засунуть эту строчку в бесконечный цикл, то сервер будет спать
//таким образом он ухадит в сон на вечно
Object x = new Object();
synchronized (x){
x.wait();
}
}
}
| true |
198ec8ce0e70f93c62d3c5bfa330325340decc8a | Java | zKaveriZencon/VeelsPlusFuelDelaerApp | /app/src/main/java/com/veelsplusfueldealerapp/managers/DatabaseHelper.java | UTF-8 | 31,788 | 1.757813 | 2 | [] | no_license | package com.veelsplusfueldealerapp.managers;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.veelsplusfueldealerapp.models.DailySalesInfoModel;
import com.veelsplusfueldealerapp.models.FuelTerminalModel;
import com.veelsplusfueldealerapp.models.InfraMappingDbModel;
import com.veelsplusfueldealerapp.models.OperatorDailyWorkListModel;
import com.veelsplusfueldealerapp.models.OperatorInfoFragModel;
import com.veelsplusfueldealerapp.models.PaymentModelLocal;
import com.veelsplusfueldealerapp.models.SalesInfoCardModel;
import com.veelsplusfueldealerapp.models.ShiftWiseCreditModel;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "FuelDealer";
private static final String TABLE_FUEL_INFRA_MAPPING = "fuelInfraMapping";
private static final String KEY_PK = "tankDuNzMap";
private static final String KEY_TANK_NO = "tankNo";
private static final String KEY_DU = "duNo";
private static final String KEY_NOZZLE = "nozzleNo";
private static final String KEY_PRODUCT_ID = "productId";
private static final String KEY_BRAND_NAME = "prodBrandName";
private static final String KEY_PROD_CATEGORY = "prodCategory";
private static final String KEY_PROD_NAME = "prodName";
private static final String KEY_PROD_CODE = "prodCode";
private static final String KEY_MAP_STATUS = "mappingStatus";
private static final String KEY_FUEL_DEALER_ID = "fuelDealerId";
private static final String KEY_FUELINFRAMAP_ID = "fuelInfraMapId";
//for fuel terminal
private static final String TABLE_FUEL_TERMINAL = "fuelTerminal";
private static final String fuelTerminalsId = "fuelTerminalsId";
private static final String terminalName = "terminalName";
private static final String attachedBankName = "attachedBankName";
private static final String terminalType = "terminalType";
//for daily sales
private static final String TABLE_SALES = "dailysales";
private static final String sales_pk = "sales_pk";
private static final String batchId = "batchId";
private static final String paymentType = "paymentType";
private static final String amount = "amount";
private static final String transId = "transId";
//for fuel infocardsales
private static final String TABLE_INFO_CARD = "infocardsales";
private static final String infocard_pk = "infocard_pk";
private static final String product = "product";
private static final String meter_sale = "meter_sale";
private static final String total_amt = "total_amt";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_FUEL_INFRA_TABLE = "CREATE TABLE " + TABLE_FUEL_INFRA_MAPPING +
" (" + KEY_PK + " TEXT PRIMARY KEY, " + KEY_TANK_NO + " TEXT, " + KEY_DU +
" TEXT, " + KEY_NOZZLE + " TEXT, " + KEY_PRODUCT_ID + " TEXT, " +
KEY_BRAND_NAME + " TEXT, " + KEY_PROD_CATEGORY + " TEXT, " + KEY_PROD_NAME
+ " TEXT, " + KEY_PROD_CODE + " TEXT, " + KEY_MAP_STATUS + " TEXT," + KEY_FUEL_DEALER_ID + " TEXT, " + KEY_FUELINFRAMAP_ID + " TEXT)";
sqLiteDatabase.execSQL(CREATE_FUEL_INFRA_TABLE);
String CREATE_FUEL_TERMINAL = "CREATE TABLE " + TABLE_FUEL_TERMINAL +
" (" + fuelTerminalsId + " TEXT PRIMARY KEY, " + terminalName
+ " TEXT, " + attachedBankName +
" TEXT, " + terminalType + " TEXT)";
sqLiteDatabase.execSQL(CREATE_FUEL_TERMINAL);
String CREATE_DAILY_SALES = "CREATE TABLE " + TABLE_SALES +
" (" + sales_pk + " INTEGER PRIMARY KEY AUTOINCREMENT, " + batchId + " TEXT, " + paymentType
+ " TEXT, " + amount +
" TEXT, " + transId + " TEXT)";
sqLiteDatabase.execSQL(CREATE_DAILY_SALES);
String CREATE_INFO_CARD = "CREATE TABLE " + TABLE_INFO_CARD +
" (" + infocard_pk + " INTEGER PRIMARY KEY AUTOINCREMENT, " + product +
" TEXT, " + meter_sale
+ " TEXT, " + total_amt +
" TEXT)";
sqLiteDatabase.execSQL(CREATE_INFO_CARD);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_FUEL_INFRA_MAPPING);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_FUEL_TERMINAL);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_SALES);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_INFO_CARD);
onCreate(sqLiteDatabase);
}
public long addInfraMappingDetails(List<InfraMappingDbModel> infraMappingDbModelList) {
SQLiteDatabase db = this.getWritableDatabase();
long result = 0;
try {
for (int i = 0; i < infraMappingDbModelList.size(); i++) {
InfraMappingDbModel infraMappingDbModel = infraMappingDbModelList.get(i);
ContentValues values = new ContentValues();
values.put(KEY_PK, infraMappingDbModel.getTankDuNzMap());
values.put(KEY_TANK_NO, infraMappingDbModel.getTankNo());
values.put(KEY_DU, infraMappingDbModel.getDuNo());
values.put(KEY_NOZZLE, infraMappingDbModel.getNozzleNo());
values.put(KEY_PRODUCT_ID, infraMappingDbModel.getProductId());
values.put(KEY_BRAND_NAME, infraMappingDbModel.getProdBrandName());
values.put(KEY_PROD_CATEGORY, infraMappingDbModel.getProdCategory());
values.put(KEY_PROD_NAME, infraMappingDbModel.getProdName());
values.put(KEY_PROD_CODE, infraMappingDbModel.getProdCode());
values.put(KEY_MAP_STATUS, infraMappingDbModel.getMappingStatus());
values.put(KEY_FUEL_DEALER_ID, infraMappingDbModel.getFuelDealerId());
values.put(KEY_FUELINFRAMAP_ID, infraMappingDbModel.getFuelInfraMapId());
result = db.insert(TABLE_FUEL_INFRA_MAPPING, null, values);
Log.d(TAG, "addInfraMappingDetails: insert result : " + result);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
return result;
}
public List<String> getAllPumpsFromInfraMapping() {
SQLiteDatabase db = null;
Cursor cursor = null;
List<String> allTanks = new ArrayList<>();
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT DISTINCT duNo FROM fuelInfraMapping";
cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
allTanks.add(cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return allTanks;
}
public List<String> getAllNozzlesFromInfraMapping(String duNo) {
SQLiteDatabase db = null;
Cursor cursor = null;
List<String> allNozzles = new ArrayList<>();
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM fuelInfraMapping where duNo = ?";
cursor = db.rawQuery(selectQuery, new String[]{duNo});
if (cursor.moveToFirst()) {
do {
allNozzles.add(cursor.getString(3));
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return allNozzles;
}
public List<String> getAllTanksFromInfraMapping() {
SQLiteDatabase db = null;
Cursor cursor = null;
List<String> allTanks = new ArrayList<>();
allTanks.add("Select Tank");
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT DISTINCT tankNo FROM fuelInfraMapping";
cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
allTanks.add(cursor.getString(0));
} while (cursor.moveToNext());
}
for (int i = 0; i < allTanks.size(); i++) {
}
db.close();
cursor.close();
} catch (Exception e) {
}
return allTanks;
}
public String getProductNameByTankId(String tankNo) {
SQLiteDatabase db = null;
Cursor cursor = null;
String productName = "";
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM fuelInfraMapping where tankNo = ?";
cursor = db.rawQuery(selectQuery, new String[]{tankNo});
if (cursor.moveToFirst()) {
do {
productName = (cursor.getString(6));
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return productName;
}
public List<String> getProductNameAndInfraIdByTankId(String tankNo) {
SQLiteDatabase db = null;
Cursor cursor = null;
String productName = "";
String infraMapId = "";
List<String> detailsList = new ArrayList<>();
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT fuelInfraMapId,prodCategory FROM fuelInfraMapping where tankNo = ?";
cursor = db.rawQuery(selectQuery, new String[]{tankNo});
if (cursor.moveToFirst()) {
do {
infraMapId = (cursor.getString(0));
productName = (cursor.getString(1));
detailsList.add(infraMapId);
detailsList.add(productName);
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return detailsList;
}
public List<String> getNozzleTankAndPkByDuNo(String duNo) {
SQLiteDatabase db = null;
Cursor cursor = null;
List<String> detailsList = new ArrayList<>();
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM fuelInfraMapping where duNo = ?";
cursor = db.rawQuery(selectQuery, new String[]{duNo});
if (cursor.moveToFirst()) {
do {
String dunzmap = (cursor.getString(0));
String tankNo = (cursor.getString(1));
String nozzleNo = (cursor.getString(3));
String prodCategory = (cursor.getString(6));
String dealerId = (cursor.getString(10));
String inframapId = (cursor.getString(11));
detailsList.add(dunzmap);
detailsList.add(tankNo);
detailsList.add(nozzleNo);
detailsList.add(prodCategory);
detailsList.add(dealerId);
detailsList.add(inframapId);
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return detailsList;
}
public String getTankByPumpAndNozzle(String duNo, String nozNo) {
Log.d(TAG, "getTankByPumpAndNozzle:duNo : " + duNo);
Log.d(TAG, "getTankByPumpAndNozzle:nozNo : " + nozNo);
SQLiteDatabase db = null;
Cursor cursor = null;
String tankNo = "";
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT tankNo FROM fuelInfraMapping where duNo = ? and nozzleNo = ?";
cursor = db.rawQuery(selectQuery, new String[]{duNo, nozNo});
if (cursor.moveToFirst()) {
do {
tankNo = (cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return tankNo;
}
public String getProductByTank(String tankNo) {
Log.d(TAG, "getProductByTank:tankNo : " + tankNo);
SQLiteDatabase db = null;
Cursor cursor = null;
String prodCategory = "";
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT prodCategory FROM fuelInfraMapping where tankNo = ?";
cursor = db.rawQuery(selectQuery, new String[]{tankNo});
if (cursor.moveToFirst()) {
do {
prodCategory = (cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return prodCategory;
}
public String getInfraMapIdByTankNo(String tankNo) {
SQLiteDatabase db = null;
Cursor cursor = null;
String infraMapId = "";
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM fuelInfraMapping where tankNo = ? limit 1";
cursor = db.rawQuery(selectQuery, new String[]{tankNo});
if (cursor.moveToFirst()) {
do {
infraMapId = (cursor.getString(11));
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return infraMapId;
}
public long saveFuelTerminals(List<FuelTerminalModel> fuelTerminalsList) {
SQLiteDatabase db = this.getWritableDatabase();
long result = 0;
try {
for (int i = 0; i < fuelTerminalsList.size(); i++) {
FuelTerminalModel fuelTerminalModel = fuelTerminalsList.get(i);
ContentValues values = new ContentValues();
values.put(fuelTerminalsId, fuelTerminalModel.getFuelTerminalsId());
values.put(terminalName, fuelTerminalModel.getTerminalName());
values.put(attachedBankName, fuelTerminalModel.getAttachedBankName());
values.put(terminalType, fuelTerminalModel.getTerminalType());
result = db.insert(TABLE_FUEL_TERMINAL, null, values);
Log.d(TAG, "saveFuelTerminals: insert result : " + result);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
return result;
}
public List<FuelTerminalModel> getAllTerminals() {
SQLiteDatabase db = null;
Cursor cursor = null;
List<FuelTerminalModel> terminalsList = new ArrayList<>();
FuelTerminalModel fuelTerminalModel1 = new FuelTerminalModel("",
"Select Device", "", "");
terminalsList.add(fuelTerminalModel1);
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM fuelTerminal where terminalName is not null AND TRIM(terminalName,' ') != ''";
cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
FuelTerminalModel fuelTerminalModel = new FuelTerminalModel();
fuelTerminalModel.setFuelTerminalsId(cursor.getString(0));
fuelTerminalModel.setTerminalName(cursor.getString(1));
fuelTerminalModel.setAttachedBankName(cursor.getString(2));
fuelTerminalModel.setTerminalType(cursor.getString(3));
terminalsList.add(fuelTerminalModel);
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return terminalsList;
}
public List<String> getAllTerminalsType(String selctedTerminal) {
SQLiteDatabase db = null;
Cursor cursor = null;
String terminalType = "";
String transId = "";
List<String> details = new ArrayList<>();
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM fuelTerminal where terminalName = ?";
cursor = db.rawQuery(selectQuery, new String[]{selctedTerminal});
if (cursor.moveToFirst()) {
do {
transId = cursor.getString(0);
terminalType = (cursor.getString(3));
details.add(transId);
details.add(terminalType);
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return details;
}
public long addPaymentDetails(PaymentModelLocal paymentModelLocal) {
SQLiteDatabase db = this.getWritableDatabase();
long result = 0;
try {
ContentValues values = new ContentValues();
values.put(batchId, paymentModelLocal.getBatchId());
values.put(paymentType, paymentModelLocal.getPaymentType());
values.put(amount, paymentModelLocal.getAmount());
values.put(transId, paymentModelLocal.getTransId());
result = db.insert(TABLE_SALES, null, values);
Log.d(TAG, "addPaymentDetails: insert result : " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
return result;
}
public String getPaymentDetails(String batchId) {
SQLiteDatabase db = null;
Cursor cursor = null;
String tallyAmount = "";
try {
db = this.getWritableDatabase();
String selectQuery = "select sum(amount) from dailysales where batchId = '" + batchId + "' group by batchId;";
Log.d(TAG, "getPaymentDetails:selectQuery : " + selectQuery);
cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
tallyAmount = cursor.getString(0);
} while (cursor.moveToNext());
}
Log.d(TAG, "getPaymentDetails:tallyAmount : " + tallyAmount);
db.close();
cursor.close();
} catch (Exception e) {
}
return tallyAmount;
}
public void deleteDailySales() {
Log.d(TAG, "deleteDailySales: ");
SQLiteDatabase db = null;
try {
db = this.getWritableDatabase();
db.execSQL("DELETE FROM dailysales");
db.execSQL("VACUUM");
db.close();
} catch (Exception e) {
}
}
public String getDetails() {
SQLiteDatabase db = null;
Cursor cursor = null;
String tallyAmount = "";
try {
db = this.getWritableDatabase();
String selectQuery = "select * from dailysales";
Log.d(TAG, "getPaymentDetails:selectQuery : " + selectQuery);
cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
tallyAmount = cursor.getString(0);
} while (cursor.moveToNext());
}
Log.d(TAG, "getPaymentDetails:tallyAmount : " + tallyAmount);
db.close();
cursor.close();
} catch (Exception e) {
}
return tallyAmount;
}
public List<String> getFuelType() {
SQLiteDatabase db = null;
Cursor cursor = null;
String fuelType = "";
List<String> details = new ArrayList<>();
details.add("Select Fuel Type");
// String[] deatilsArr = new String[10];
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT DISTINCT prodCategory FROM fuelInfraMapping";
cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
fuelType = (cursor.getString(0));
details.add(fuelType);
/* deatilsArr[i] = fuelType;
i = i + 1;*/
} while (cursor.moveToNext());
}
cursor.close();
Log.d(TAG, "getFuelType: fuel type : " + fuelType);
db.close();
} catch (Exception e) {
}
return details;
}
public List<ShiftWiseCreditModel> getWholeProductName() {
SQLiteDatabase db = null;
Cursor cursor = null;
String fuelType = "";
String prodName = "";
List<ShiftWiseCreditModel> details = new ArrayList<>();
ShiftWiseCreditModel shiftWiseCreditModel = new ShiftWiseCreditModel("", "", "Select Product");
details.add(shiftWiseCreditModel);
// String[] deatilsArr = new String[10];
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT DISTINCT prodCategory,prodName FROM fuelInfraMapping";
cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
fuelType = (cursor.getString(0));
prodName = (cursor.getString(1));
String product = fuelType + "-" + prodName;
shiftWiseCreditModel = new ShiftWiseCreditModel(fuelType, prodName, product);
details.add(shiftWiseCreditModel);
/* deatilsArr[i] = fuelType;
i = i + 1;*/
} while (cursor.moveToNext());
}
cursor.close();
Log.d(TAG, "getFuelType: fuel type : " + fuelType);
db.close();
} catch (Exception e) {
}
return details;
}
public List<String> getProductNameByFuelType(String fuelType) {
Log.d(TAG, "getProductNameByFuelType:fuel type: " + fuelType);
SQLiteDatabase db = null;
Cursor cursor1 = null;
String productName = "";
List<String> details = new ArrayList<>();
details.add("Select Product");
db = this.getWritableDatabase();
String selectQuery1 = "SELECT DISTINCT prodName FROM fuelInfraMapping where prodCategory = ?";
Log.d(TAG, "getProductNameByFuelType: selectQuery1 : " + selectQuery1);
cursor1 = db.rawQuery(selectQuery1, new String[]{fuelType});
if (cursor1.moveToFirst()) {
do {
productName = (cursor1.getString(0));
details.add(productName);
} while (cursor1.moveToNext());
}
Log.d(TAG, "getProductNameByFuelType: prodname :" + productName);
return details;
}
public String getProductId(String prodname, String subProdName) {
Log.d(TAG, "getProductId:prodname : " + prodname);
Log.d(TAG, "getProductId: subProdName : " + subProdName);
SQLiteDatabase db = null;
Cursor cursor1 = null;
String productId = "";
db = this.getWritableDatabase();
String selectQuery1 = "SELECT DISTINCT productId FROM fuelInfraMapping where prodCategory = ? AND prodName = ?";
Log.d(TAG, "getProductId: selectQuery1 : " + selectQuery1);
cursor1 = db.rawQuery(selectQuery1, new String[]{prodname, subProdName});
if (cursor1.moveToFirst()) {
do {
productId = (cursor1.getString(0));
} while (cursor1.moveToNext());
}
Log.d(TAG, "getProductId: productId :" + productId);
cursor1.close();
return productId;
}
public String getPaymentType() {
Log.d(TAG, "getPaymentType:");
SQLiteDatabase db = null;
Cursor cursor1 = null;
String payType = "";
db = this.getWritableDatabase();
String selectQuery1 = "SELECT paymentType FROM dailysales ORDER BY sales_pk DESC LIMIT 1;";
Log.d(TAG, "getPaymentType: selectQuery1 : " + selectQuery1);
cursor1 = db.rawQuery(selectQuery1, null);
if (cursor1.moveToFirst()) {
do {
payType = (cursor1.getString(0));
} while (cursor1.moveToNext());
}
Log.d(TAG, "getPaymentType: productId :" + payType);
return payType;
}
public List<PaymentModelLocal> getDonePaymentDetails() {
SQLiteDatabase db = null;
Cursor cursor = null;
List<PaymentModelLocal> detailsList = new ArrayList<>();
try {
db = this.getWritableDatabase();
String selectQuery = "select * from dailysales where paymentType not in ('cash', 'submit')";
cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
String batchId = cursor.getString(1);
String paymentType = (cursor.getString(2));
String amount = (cursor.getString(3));
String transId = (cursor.getString(4));
PaymentModelLocal paymentModelLocal = new PaymentModelLocal(batchId, paymentType, amount, transId);
detailsList.add(paymentModelLocal);
Log.d(TAG, "getDonePaymentDetails: detailsList size :" + detailsList);
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return detailsList;
}
//save info card details
public long saveInfoCardDetails(List<OperatorDailyWorkListModel> infoModelsList) {
SQLiteDatabase db = this.getWritableDatabase();
long result = 0;
try {
for (int i = 0; i < infoModelsList.size(); i++) {
OperatorDailyWorkListModel dailySalesInfoModel = infoModelsList.get(i);
ContentValues values = new ContentValues();
values.put(product, dailySalesInfoModel.getProduct());
values.put(meter_sale, dailySalesInfoModel.getMeterSaleLiters());
values.put(total_amt, dailySalesInfoModel.getTotalAmount());
result = db.insert(TABLE_INFO_CARD, null, values);
Log.d(TAG, "saveInfoCardDetails: insert result : " + result);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
return result;
}
public List<OperatorInfoFragModel> getInfoCardsForDailySales() {
SQLiteDatabase db = null;
Cursor cursor = null;
List<OperatorInfoFragModel> detailsList = new ArrayList<>();
try {
db = this.getWritableDatabase();
String selectQuery = "select * from infocardsales";
cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
String product = cursor.getString(1);
String meterSale = (cursor.getString(2));
String amount = (cursor.getString(3));
OperatorInfoFragModel salesInfoCardModel = new OperatorInfoFragModel(product, meterSale, amount);
detailsList.add(salesInfoCardModel);
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return detailsList;
}
public void deleteSalesInfoCardTable() {
Log.d(TAG, "deleteSalesInfoCardTable: ");
SQLiteDatabase db = null;
try {
db = this.getWritableDatabase();
db.execSQL("DELETE FROM infocardsales");
db.execSQL("VACUUM");
db.close();
} catch (Exception e) {
}
}
public List<String> getTankAndPKByDuNozzle(String duNo, String nozzleNo) {
SQLiteDatabase db = null;
Cursor cursor = null;
List<String> detailsList = new ArrayList<>();
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM fuelInfraMapping where duNo = ? and nozzleNo = ?";
cursor = db.rawQuery(selectQuery, new String[]{duNo, nozzleNo});
if (cursor.moveToFirst()) {
do {
String dunzmap = (cursor.getString(0));
String tankNo = (cursor.getString(1));
String prodCategory = (cursor.getString(6));
String dealerId = (cursor.getString(10));
String inframapId = (cursor.getString(11));
detailsList.add(dunzmap);
detailsList.add(tankNo);
detailsList.add(prodCategory);
detailsList.add(dealerId);
detailsList.add(inframapId);
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return detailsList;
}
public String getFuelInfraMapIdForShiftCheck(String tankNo, String duNo, String nozzleNo) {
SQLiteDatabase db = null;
Cursor cursor = null;
String inframapId = "";
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT fuelInfraMapId FROM fuelInfraMapping where tankNo = ? and duNo = ? and nozzleNo = ?";
cursor = db.rawQuery(selectQuery, new String[]{tankNo, duNo, nozzleNo});
if (cursor.moveToFirst()) {
do {
inframapId = (cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return inframapId;
}
public List<String> getInfraMapIdByProdCategoryAndProdName(String prodCat, String prodName) {
SQLiteDatabase db = null;
Cursor cursor = null;
List<String> detailsList = new ArrayList<>();
String inframapId = "";
try {
db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM fuelInfraMapping where prodCategory = ? and prodName = ?";
cursor = db.rawQuery(selectQuery, new String[]{prodCat, prodName});
if (cursor.moveToFirst()) {
do {
/*String dunzmap = (cursor.getString(0));
String tankNo = (cursor.getString(1));
String prodCategory = (cursor.getString(6));
String dealerId = (cursor.getString(10));*/
inframapId = (cursor.getString(11));
detailsList.add(inframapId);
/* detailsList.add(dunzmap);
detailsList.add(tankNo);
detailsList.add(prodCategory);
detailsList.add(dealerId);
detailsList.add(inframapId);*/
} while (cursor.moveToNext());
}
db.close();
cursor.close();
} catch (Exception e) {
}
return detailsList;
}
} | true |
60b41f2034e6f0fb36c7cc504b65dae162f30afc | Java | hikitani/sber-school | /patterns/design-patterns-impl-car/src/main/java/com/sbt/javaschool/rnd/lesson18/core/CarChassis.java | UTF-8 | 188 | 2.28125 | 2 | [] | no_license | package com.sbt.javaschool.rnd.lesson18.core;
public class CarChassis implements Chassis {
@Override
public String getChassisParts() {
return "Car Chassis Parts";
}
}
| true |
60d5ede5574e8b4b60d696442e40fae813544894 | Java | gabrielbsanches/PrimeITProject | /src/main/java/com/primeit/client/model/User.java | UTF-8 | 2,302 | 2.34375 | 2 | [] | no_license | package com.primeit.client.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long userid;
private String loginname;
private String password;
private String manager_name;
private boolean enable;
private String authority;
private String email;
private String phone;
public User(){}
public User (String loginName, String password, boolean enabled, String authority){
this.loginname = loginName;
this.password = password;
this.enable = enabled;
this.authority = authority;
}
@Column(name = "userid", unique = true, nullable = false)
public long getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
@Column(name = "loginname")
public String getLoginname() {
return loginname;
}
public void setLoginname(String loginname) {
this.loginname = loginname;
}
@Column(name = "manager_name")
public String getManager_name() {
return manager_name;
}
public void setManager_name(String manager_name) {
this.manager_name = manager_name;
}
@Column(name = "enable")
public boolean isEnabled() {
return enable;
}
public void setEnabled(boolean enabled) {
this.enable = enabled;
}
@Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "authority")
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
@Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "phone")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User [loginName=" + loginname +
", password=" + password +
" manager_name="+ manager_name +
" authority="+ authority +
" email="+ email +
" phone="+ phone +
"]";
}
} | true |
351ff3954efae57ab92bdb5352885ecae3eaa7b9 | Java | seodongju-bit/devFw | /devFw/src/main/java/project/A/P001/vo/A_P001VO.java | UTF-8 | 2,881 | 1.984375 | 2 | [] | no_license | package project.A.P001.vo;
import java.sql.Date;
import org.springframework.stereotype.Component;
@Component("A_P001VO")
public class A_P001VO {
private String mem_no = "";
private String mem_id = "";
private String mem_pw = "";
private String mem_nick = "";
private String mem_name = "";
private String mem_email1 = "";
private String mem_email2 = "";
private String mem_tel = "";
private String mem_zip = "";
private String mem_address1 = "";
private String mem_address2 = "";
private String mem_division = "";
private String mem_verify = "";
private int mem_point;
private int mem_point_test;
public A_P001VO() {
System.out.println("A_P001VO 호출");
}
public String getMem_no() {
return mem_no;
}
public void setMem_no(String mem_no) {
this.mem_no = mem_no;
}
public String getMem_id() {
return mem_id;
}
public void setMem_id(String mem_id) {
this.mem_id = mem_id;
}
public String getMem_pw() {
return mem_pw;
}
public void setMem_pw(String mem_pw) {
this.mem_pw = mem_pw;
}
public String getMem_nick() {
return mem_nick;
}
public void setMem_nick(String mem_nick) {
this.mem_nick = mem_nick;
}
public String getMem_name() {
return mem_name;
}
public void setMem_name(String mem_name) {
this.mem_name = mem_name;
}
public String getMem_email1() {
return mem_email1;
}
public void setMem_email1(String mem_email1) {
this.mem_email1 = mem_email1;
}
public String getMem_email2() {
return mem_email2;
}
public void setMem_email2(String mem_email2) {
this.mem_email2 = mem_email2;
}
public String getMem_tel() {
return mem_tel;
}
public void setMem_tel(String mem_tel) {
this.mem_tel = mem_tel;
}
public String getMem_zip() {
return mem_zip;
}
public void setMem_zip(String mem_zip) {
this.mem_zip = mem_zip;
}
public String getMem_address1() {
return mem_address1;
}
public void setMem_address1(String mem_address1) {
this.mem_address1 = mem_address1;
}
public String getMem_address2() {
return mem_address2;
}
public void setMem_address2(String mem_address2) {
this.mem_address2 = mem_address2;
}
public String getMem_division() {
return mem_division;
}
public void setMem_division(String mem_division) {
this.mem_division = mem_division;
}
public String getMem_verify() {
return mem_verify;
}
public void setMem_verify(String mem_verify) {
this.mem_verify = mem_verify;
}
public int getMem_point() {
return mem_point;
}
public void setMem_point(int mem_point) {
this.mem_point = mem_point;
}
public int getMem_point_test() {
return mem_point_test;
}
public void setMem_point_test(int mem_point_test) {
this.mem_point_test = mem_point_test;
}
} | true |
8f9f412a7c8ee4db83100e5b7b17a65ef4f34671 | Java | junaidAnwar/carParkingProblem | /com.exercise.carparking/src/test/java/TicketTest.java | UTF-8 | 1,226 | 2.9375 | 3 | [] | no_license | import org.junit.Test;
import java.util.Date;
import static org.junit.Assert.*;
public class TicketTest {
private Ticket ticket;
@Test
public void shouldCreateTicketWithGivenParkingLotNumber() throws Exception {
ticket = new Ticket(1, 2, "");
int parkingLotNumber = ticket.getParkingLotNumber();
assertEquals(1, parkingLotNumber);
}
@Test
public void shouldCreateTicketWithGivenTicketNumber() throws Exception {
ticket = new Ticket(1, 2, "");
int ticketNumber = ticket.getTicketNumber();
assertEquals(2,ticketNumber);
}
@Test
public void shouldCreateTicketWithGivenParkingTime() throws Exception {
String expectedParkingTime = new Date().toString();
ticket = new Ticket(1, 2, expectedParkingTime);
String actualParkingTime = ticket.getParkingTime();
assertEquals(expectedParkingTime,actualParkingTime);
}
@Test
public void shouldNotCreateTicketWithInvalidArguments() throws Exception {
try {
ticket = new Ticket(-1, 2, null);
} catch (Exception e) {
assertEquals("Ticket Cannot be Created For Invalid Input", e.getMessage());
}
}
} | true |
27a481a8ca0ef4415be02f3fef27a086ac166439 | Java | gallalf/JDND | /projects/P02-VehiclesAPI/pricing-service/src/main/java/com/udacity/pricing/PricingServiceApplication.java | UTF-8 | 1,406 | 2.53125 | 3 | [
"MIT"
] | permissive | package com.udacity.pricing;
import com.udacity.pricing.domain.price.Price;
import com.udacity.pricing.domain.price.PriceRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import java.math.BigDecimal;
/**
* Creates a Spring Boot Application to run the Pricing Service.
*/
@SpringBootApplication
@EnableEurekaClient
public class PricingServiceApplication {
public static void main(String[] args) {
SpringApplication.run(PricingServiceApplication.class, args);
}
/**
* Initializes the prices available to the Pricing API.
* @param repository where the price information persists.
* @return the prices to add to the related repository
*/
@Bean
CommandLineRunner initDatabase(PriceRepository repository) {
return args -> {
repository.save(new Price("US$", new BigDecimal(50000)));
repository.save(new Price("US$", new BigDecimal(150000)));
repository.save(new Price("US$", new BigDecimal(20000)));
repository.save(new Price("US$", new BigDecimal(350000)));
repository.save(new Price("US$", new BigDecimal(120000)));
};
}
}
| true |
9e16aa72c95a6aa6aab3a1316f896617cfd9e7fe | Java | lockielyKIM/lockiely-parent | /lockiely-core/src/main/java/org/lockiely/datasource/support/DynamicDataSourceProperties.java | UTF-8 | 1,148 | 2.109375 | 2 | [] | no_license | package org.lockiely.datasource.support;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
@ConfigurationProperties(prefix = "spring.datasource.dynamic")
public class DynamicDataSourceProperties {
@NestedConfigurationProperty
private DynamicItemDataSourceProperties master = new DynamicItemDataSourceProperties();
@NestedConfigurationProperty
private Map<String, DynamicItemDataSourceProperties> slaves = new HashMap<>();
public DynamicItemDataSourceProperties getMaster() {
return master;
}
public void setMaster(DynamicItemDataSourceProperties master) {
this.master = master;
}
public Map<String, DynamicItemDataSourceProperties> getSlaves() {
return slaves;
}
public void setSlaves(Map<String, DynamicItemDataSourceProperties> slaves) {
this.slaves = slaves;
}
public static final String DYNAMIC_DATA_SOURCE_MASTER = "master";
public static final String DYNAMIC_DATA_SOURCE_SLAVE = "slave";
}
| true |
fa498e4d7f06b8c64cad2a3f92c54c7c78ee7c21 | Java | 13811787801/JSONInterface | /app/src/androidTest/java/me/keroxp/lib/jsoninterface/DataScheme.java | UTF-8 | 1,348 | 2.6875 | 3 | [] | no_license | package me.keroxp.lib.jsoninterface;
import java.util.ArrayList;
/**
* Created by keroxp on 2014/12/22.
*/
public class DataScheme extends JSONInterface {
protected String format;
protected ArrayList<User> data;
static class User extends JSONInterface{
protected String identifier;
protected String name;
protected Integer age;
protected Float tall;
protected String birth_of_date;
protected String sex;
public enum Sex { Unknown, Male, Female, Complex }
public Sex getSex() {
if (sex == null) return Sex.Unknown;
if (sex.equals("male")) {
return Sex.Male;
}else if (sex.equals("female")) {
return Sex.Female;
}else if (sex.equals("complex")) {
return Sex.Complex;
}
return Sex.Unknown;
}
@Override
public String getJavaFieldName(String attr) {
if (attr.equals("id")) {
return "identifier";
}
return super.getJavaFieldName(attr);
}
@Override
public String getJSONFieldName(String field) {
if (field.equals("identifier")) {
return "id";
}
return super.getJSONFieldName(field);
}
}
}
| true |
6fe43eeb6cd34b9a64955fd944ea9c7caa79e878 | Java | furdei/shopping_android | /shopping/src/main/java/com/furdey/shopping/utils/PreferencesManager.java | UTF-8 | 9,554 | 2 | 2 | [] | no_license | package com.furdey.shopping.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.furdey.shopping.contentproviders.PurchasesContentProvider;
public class PreferencesManager {
private static final String APP_PREFERENCES = "com.furdey.shopping";
private static final String PREF_LAST_RUN_DATE = "lastRunDate";
private static final String PREF_PURCHASES_SORT_ORDER = "purchasesSortOrder";
private static final String PREF_SHARE_STATE = "shareState";
private static final String PREF_SHARE_CHECK_DATE = "shareCheckDate";
private static final String PREF_SHARE_CHECK_PERIOD = "shareCheckPeriod";
private static final String PREF_LIKE_STATE = "likeState";
private static final String PREF_LIKE_CHECK_DATE = "likeCheckDate";
private static final String PREF_LIKE_CHECK_PERIOD = "likeCheckPeriod";
private static final String PREF_RUN_COUNT = "runCount";
private static final String PREF_ALARM_HOUR = "alarmHour";
private static final String PREF_ALARM_MINUTE = "alarmMinute";
private static final String PREF_ALARM_REPEAT = "alarmRepeat";
private static final String PREF_LANGUAGE = "language";
private static final String PREF_WIDGET_TRACKED = "widgetTracked";
private static final String PREF_ALARM_TRACKED = "alarmTracked";
private static final String PREF_SEND_LIST_TRACKED = "sendListTracked";
private static final String PREF_SHARE_TRACKED = "shareTracked";
public static final long SHARE_RUN_THRESHOLD = 5;
public static final long SHARE_DELAY = 1000 * 3600 * 24 * 7;
public static final long SHARE_LATER_DELAY = 1000 * 3600 * 24 * 2;
public static final long LIKE_RUN_THRESHOLD = 10;
public static final long LIKE_DELAY = 1000 * 3600 * 24 * 7;
public static final long LIKE_LATER_DELAY = 1000 * 3600 * 24 * 2;
public static final int ALARM_HOUR_UNSPECIFIED = -1;
public static final String DEF_LANGUAGE = "en";
public enum ShareState {
NOT_SHARED, SHARED
}
;
public enum LikeState {
NOT_LIKED, LIKED
}
;
public enum PurchasesSortOrder {
ORDER_BY_CATEGORY(PurchasesContentProvider.Columns.GOODSCATEGORY_NAME.getDbName() +
", " + PurchasesContentProvider.Columns.GOODS_NAME.getDbName()),
ORDER_BY_NAME(PurchasesContentProvider.Columns.GOODS_NAME.getDbName()),
ORDER_BY_ADD_TIME(PurchasesContentProvider.Columns.STRDATE.getDbName());
private String sortOrder;
private PurchasesSortOrder(String sortOrder) {
this.sortOrder = sortOrder;
}
public String getSortOrder() {
return sortOrder;
}
}
;
private static SharedPreferences loadPreferences(Context context) {
return context.getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
}
public static String getLastRunDate(Context context) {
return loadPreferences(context).getString(PREF_LAST_RUN_DATE, "");
}
public static void setLastRunDate(Context context, String lastRunDate) {
Editor e = loadPreferences(context).edit();
e.putString(PREF_LAST_RUN_DATE, lastRunDate);
e.commit();
}
public static PurchasesSortOrder getPurchasesSortOrder(Context context) {
return PurchasesSortOrder.valueOf(loadPreferences(context).getString(PREF_PURCHASES_SORT_ORDER,
PurchasesSortOrder.ORDER_BY_CATEGORY.toString()));
}
public static void setPurchasesSortOrder(Context context, PurchasesSortOrder purchasesSortOrder) {
Editor e = loadPreferences(context).edit();
e.putString(PREF_PURCHASES_SORT_ORDER, purchasesSortOrder.toString());
e.commit();
}
public static boolean isOkToShare(Context context) {
long date = loadPreferences(context).getLong(PREF_SHARE_CHECK_DATE, 0);
long period = loadPreferences(context).getLong(PREF_SHARE_CHECK_PERIOD, 0);
if (date == 0) {
// Первый запуск, установим интервал проверки
date = System.currentTimeMillis();
period = SHARE_DELAY;
setShareDelay(context, date, period);
return false;
}
return (System.currentTimeMillis() > (date + period))
&& (getRunCount(context) >= SHARE_RUN_THRESHOLD);
}
public static void setShareDelay(Context context, long date, long period) {
Editor e = loadPreferences(context).edit();
e.putLong(PREF_SHARE_CHECK_DATE, date);
e.putLong(PREF_SHARE_CHECK_PERIOD, period);
e.commit();
}
public static ShareState getShareState(Context context) {
String shareStateStr = loadPreferences(context).getString(PREF_SHARE_STATE, null);
ShareState shareState;
if (shareStateStr == null)
shareState = ShareState.NOT_SHARED;
else
shareState = ShareState.valueOf(shareStateStr);
return shareState;
}
public static void setShareState(Context context, ShareState shareState) {
Editor e = loadPreferences(context).edit();
e.putString(PREF_SHARE_STATE, shareState.toString());
e.commit();
}
public static boolean isOkToLike(Context context) {
long date = loadPreferences(context).getLong(PREF_LIKE_CHECK_DATE, 0);
long period = loadPreferences(context).getLong(PREF_LIKE_CHECK_PERIOD, 0);
if (date == 0) {
// Первый запуск, установим интервал проверки
date = System.currentTimeMillis();
period = LIKE_DELAY;
setLikeDelay(context, date, period);
return false;
}
return (System.currentTimeMillis() > (date + period))
&& (getRunCount(context) >= LIKE_RUN_THRESHOLD);
}
public static void setLikeDelay(Context context, long date, long period) {
Editor e = loadPreferences(context).edit();
e.putLong(PREF_LIKE_CHECK_DATE, date);
e.putLong(PREF_LIKE_CHECK_PERIOD, period);
e.commit();
}
public static LikeState getLikeState(Context context) {
String likeStateStr = loadPreferences(context).getString(PREF_LIKE_STATE, null);
LikeState likeState;
if (likeStateStr == null)
likeState = LikeState.NOT_LIKED;
else
likeState = LikeState.valueOf(likeStateStr);
return likeState;
}
public static void setLikeState(Context context, LikeState likeState) {
Editor e = loadPreferences(context).edit();
e.putString(PREF_LIKE_STATE, likeState.toString());
e.commit();
}
public static void setRunCount(Context context, long runCount) {
Editor e = loadPreferences(context).edit();
e.putLong(PREF_RUN_COUNT, runCount);
e.commit();
}
public static long getRunCount(Context context) {
return loadPreferences(context).getLong(PREF_RUN_COUNT, 0);
}
public static void setAlarmTime(Context context, int hour, int minute, int repeat) {
Editor e = loadPreferences(context).edit();
e.putInt(PREF_ALARM_HOUR, hour);
e.putInt(PREF_ALARM_MINUTE, minute);
e.putInt(PREF_ALARM_REPEAT, repeat);
e.commit();
}
public static int getAlarmHour(Context context) {
return loadPreferences(context).getInt(PREF_ALARM_HOUR, ALARM_HOUR_UNSPECIFIED);
}
public static int getAlarmMinute(Context context) {
return loadPreferences(context).getInt(PREF_ALARM_MINUTE, 0);
}
public static int getAlarmRepeat(Context context) {
return loadPreferences(context).getInt(PREF_ALARM_REPEAT, 0);
}
public static String getLanguage(Context context) {
return loadPreferences(context).getString(PREF_LANGUAGE, DEF_LANGUAGE);
}
public static void setLanguage(Context context, String language) {
Editor e = loadPreferences(context).edit();
e.putString(PREF_LANGUAGE, language);
e.commit();
}
public static boolean isWidgetTracked(Context context) {
return loadPreferences(context).getBoolean(PREF_WIDGET_TRACKED, false);
}
public static void setWidgetTracked(Context context, boolean tracked) {
Editor e = loadPreferences(context).edit();
e.putBoolean(PREF_WIDGET_TRACKED, tracked);
e.commit();
}
public static boolean isAlarmTracked(Context context) {
return loadPreferences(context).getBoolean(PREF_ALARM_TRACKED, false);
}
public static void setAlarmTracked(Context context, boolean tracked) {
Editor e = loadPreferences(context).edit();
e.putBoolean(PREF_ALARM_TRACKED, tracked);
e.commit();
}
public static boolean isSendListTracked(Context context) {
return loadPreferences(context).getBoolean(PREF_SEND_LIST_TRACKED, false);
}
public static void setSendListTracked(Context context, boolean tracked) {
Editor e = loadPreferences(context).edit();
e.putBoolean(PREF_SEND_LIST_TRACKED, tracked);
e.commit();
}
public static boolean isShareTracked(Context context) {
return loadPreferences(context).getBoolean(PREF_SHARE_TRACKED, false);
}
public static void setShareTracked(Context context, boolean tracked) {
Editor e = loadPreferences(context).edit();
e.putBoolean(PREF_SHARE_TRACKED, tracked);
e.commit();
}
}
| true |
387842dcef0907345f513621c06748df49fb026e | Java | adrien1212/Projet-Tuteure-S2 | /src/bataille/Coordonnee.java | ISO-8859-1 | 8,347 | 3.0625 | 3 | [] | no_license | /*
* Coordonnee.java 16 mai 2019
* IUT info1 2018-2019 groupe 1, aucun droits : ni copyright ni copyleft
*/
package bataille;
import java.util.ArrayList;
/**
* Une coordonne est dfinie par sa position en abscisse et en ordonne
* @author Groupe projet
*/
public class Coordonnee {
/** Abscisse de la coordonne */
private int x;
/** Ordonne de la coordonne */
private int y;
/** Indice de la coordonne dans la zone */
private int indiceCoord;
/** Indique si la coordonne est touche */
private boolean touche;
/** Indique si la coordonne contient un bateau */
private boolean contientBateau;
/** Indique si le bateau prsent sur la coordonne est coul */
private boolean bateauCoule;
/** Indice du bateau de la flotte */
private int indiceBateau;
/**
* Construit une coordonne dfini par un x et un y
* @param x abscisse de la coordonne
* @param y ordonne de la coordonne
*/
public Coordonnee(int x, int y) {
verifCoordonnee(x, y);
this.x = x;
this.y = y;
this.indiceCoord = y * Zone.tailleDefaut + x;
this.indiceBateau = -1;
}
/**
* Construit une coordonn avec l'indice du bateau et dfini par un x et un y
* @param x abscisse de la coordonne
* @param y ordonne de la coordonne
* @param indiceBateau indice du bateau dans la collection de flotte
* @param contientBateau indique si la coordonne contient un bateau
*/
public Coordonnee(int x, int y, int indiceBateau, boolean contientBateau) {
verifCoordonnee(x, y);
this.x = x;
this.y = y;
this.indiceCoord = y * Zone.tailleDefaut + x;
this.indiceBateau = indiceBateau;
this.contientBateau = contientBateau;
}
/**
* @return valeur de x
*/
public int getX() {
return x;
}
/**
* @return valeur de y
*/
public int getY() {
return y;
}
/**
* @return valeur de indiceCoord
*/
public int getIndiceCoord() {
return indiceCoord;
}
/**
* @return valeur de touche
*/
public boolean isTouche() {
return touche;
}
/**
* @param touche nouvelle valeur de touche
*/
public void setTouche(boolean touche) {
this.touche = touche;
}
/**
* @return valeur de contientBateau
*/
public boolean isContientBateau() {
return contientBateau;
}
/**
* @param contientBateau nouvelle valeur de contientBateau
*/
public void setContientBateau(boolean contientBateau) {
this.contientBateau = contientBateau;
}
/**
* @return valeur de bateauCoule
*/
public boolean isBateauCoule() {
return bateauCoule;
}
/**
* @param bateauCoule nouvelle valeur de bateauCoule
*/
public void setBateauCoule(boolean bateauCoule) {
this.bateauCoule = bateauCoule;
}
/**
* @return valeur de indiceBateau
*/
public int getIndiceBateau() {
return indiceBateau;
}
/**
* @param indiceBateau nouvelle valeur de indiceBateau
*/
public void setIndiceBateau(int indiceBateau) {
this.indiceBateau = indiceBateau;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
/**
* TODO commenter le rle de cette mthode
* @return la coordonne convertit en format A1
*/
public String convertit() {
char x;
int y;
x = (char) (this.getX() + 'A');
y = (this.getY() + 1);
return "" + x + y;
}
/**
* Vrifie si les abscisses et ordonne sont dans la zone
* @param x abscisse de la coordonne tester
* @param y ordonne de la coordonne tester
* @throws IllegalArgumentException si abscisse ou ordonne invalide
*/
private static void verifCoordonnee(int x, int y)
throws IllegalArgumentException {
if (x < 0 || y < 0) {
throw new IllegalArgumentException("Coordonne ngative");
} else if (Zone.tailleDefaut < x || Zone.tailleDefaut < y) {
throw new IllegalArgumentException("Coordonn en dehors");
}
}
/**
* Compare deux coordonnes
* @param aComparer coordonnes comparer
* @return vrai si coordonnes gales
*/
public boolean coordonneesEgales(Coordonnee aComparer) {
return this.getX() == aComparer.getX()
&& this.getY() == aComparer.getY();
}
/**
* Determine si un coup dj t jou partir de la liste des coups
* @param coupJoue collection contenant les coups jou
* @return vrai si le coup dj tait jou
*/
public boolean dejaJoue(ArrayList<Coordonnee> coupJoue) {
for (Coordonnee coup : coupJoue) {
if (this.coordonneesEgales(coup)) {
return true;
}
}
return false;
}
/**
* Mthode renvoyant une arraylist avec tout les bateau coul d'une arraylist
* spcifique
* @param coupJouer arraylist des coups jou
* @param flotte la flotte du jeux en cours
* @return une arraylist des bateau couls
*/
public ArrayList<Bateau> estCoule(ArrayList<Coordonnee> coupJouer, Flotte flotte) {
ArrayList<Bateau> bateauCoule = new ArrayList<Bateau>();
// on test tous les lments
// on compare les indice pour pas avoir 2 bateau identique
for (int index =0 ; index < coupJouer.size() ; index ++) {
if (coupJouer.get(index).isBateauCoule() &&
!bateauCoule.contains(flotte.getCollectionBateau().get(
coupJouer.get(index).getIndiceBateau()))) {
//on ajoute le bateau de la flotte correspondant l'indice
bateauCoule.add(flotte.getCollectionBateau().get(
coupJouer.get(index).getIndiceBateau()));
}
}
return bateauCoule;
}
/**
* Determine si 2 coordonne sont proches
* @param coordB coordonne comparer avec this
* @return vrai si les coordonnes sont cots
*/
public boolean estProche(Coordonnee coordB) {
int indiceA; // indice de this
int indiceB; // indice de coordB
/* rcupration des indices */
indiceA = this.getIndiceCoord();
indiceB = coordB.getIndiceCoord();
/* si la coordonne est proche */
if (indiceA + 1 == indiceB || indiceA - 1 == indiceB
|| indiceA - Zone.tailleDefaut == indiceB
|| indiceA + Zone.tailleDefaut == indiceB) {
return true;
}
return false;
}
/**
* Mthode determinant si un coup est pertinant ou pas en fonction des
* coup dja jou et de la flotte selectionn pour la partie
* @param coupDejaJoue arraylist des coups deja jou
* @param flotte
* @return si le coup est non pertinent ou pas
*/
public boolean coupNonPertinent(ArrayList<Coordonnee> coupDejaJoue, Flotte flotte) {
boolean coupNonPertinent = false;
ArrayList<Bateau> bateauCoule = estCoule( coupDejaJoue,flotte);
int xCoup,
yCoup;
xCoup= this.getX();
yCoup= this.getY();
// test d'un coup dj jou
if (dejaJoue(coupDejaJoue)){
return true;
}
//test d'un coup prsent dans la zone d'antiabordage
// //test de jeux sur la zone d'abordage d'un bateau coul
// for (int index=0 ; index< bateauCoule.size() ; index ++) {
// if (bateauCoule.get(index).getZoneContenu().get(0).collision(xCoup, yCoup)) {
// coupNonPertinent = true;
// }
// }
//test sur les bateau non coul contenant plus de 2 case touch (instable)
// non prise en charge dans un premier temps TODO : complter si possible
return coupNonPertinent;
}
}
| true |
5edad4e2f7b1298737def2fdd2b78db732517d5c | Java | emrcode/helloworld | /Sample.java | UTF-8 | 6,440 | 2.125 | 2 | [] | no_license | package sample_project;
import org.apache.hadoop.fs.FileSystem;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.hive.HiveContext;
//import com.dbs.ifrs.reportgeneration.*;
import scala.Tuple2;
//import ifrs.constants.ReportGeneratorConstants;
import java.util.*;
import java.io.*;
public class Sample {
final static SparkConf SPARKCONF = new SparkConf()
.setAppName("Hive Utility");
final static JavaSparkContext JAVACONTEXT = new JavaSparkContext(SPARKCONF);
final static HiveContext HIVECONTEXT = new HiveContext(JAVACONTEXT.sc());
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
String table_script = "";
String table_path = "../resources/tables/employee3.hql";
String sql_query = "";
try { Class.forName(driverName); } catch (ClassNotFoundException e) {
// TODO Auto-generated catch block e.printStackTrace();
System.exit(1); }
//FileSystem fs = FileSystem.get(JAVACONTEXT.hadoopConfiguration());
Connection con = DriverManager.getConnection(
"jdbc:hive2://10.92.139.143:10000/nrd_app_ecl;principal=hive/x01shdpeapp1a.sgp.dbs.com@REG1.UAT1BANK.DBS.COM");
Statement stmt = con.createStatement();
File dir = new File(table_path);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
FileInputStream fis = null;
try {
fis = new FileInputStream(child);
// System.out.println("Total file size to read (in bytes) : "+
// fis.available());
int content;
sql_query = "";
while ((content = fis.read()) != -1) {
// convert to char and display it
sql_query = sql_query + String.valueOf((char) content);
}
System.out.println(sql_query);
// stmt.executeQuery(sql_query);
HIVECONTEXT.sql(sql_query);
DataFrame df = HIVECONTEXT.sql(sql_query);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
} else {
System.out
.println("No Scripts are there for Hive Tables to be created");
}
stmt.close(); con.close();
/*
* End of Logic to handle Hive table creation when we the script in
* server under a given path
*/
/* try{
Process p = Runtime.getRuntime().exec((new
String[]{"/usr/bin/beeline ","-u","jdbc:hive2://10.92.139.143:10000/nrd_app_ecl;principal=hive/x01shdpeapp1a.sgp.dbs.com@REG1.UAT1BANK.DBS.COM -f /ECLDEV/app/scripts/hql/test_hive_table/ecl9_accounts_emr.hql"
})); } catch (IOException e) { e.printStackTrace(); }
/*
* try{ Process p = Runtime.getRuntime().exec((new
* String[]{"sh /ECLDEV/app/scripts/shell/run_hql.sh"
* ,"ecl9_accounts_emr"})); } catch (IOException e) {
* e.printStackTrace(); }
*/
/*
* HIVECONTEXT. try { String[] command={"/bin/bash",
* "run_hql.sh ecl9_accounts_emr","/ECLDEV/app/scripts/shell/"}; Process
* awk = new ProcessBuilder().start(); awk.waitFor(); } catch
* (IOException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } catch (InterruptedException e) {
* e.printStackTrace(); }
*/
/*
String[] command = { "/bin/bash", "run_hql.sh", "ecl9_accounts_emr" };
try {
ProcessBuilder p = new ProcessBuilder("sh", "run_hql.sh",
"ecl9_accounts_emr");
Process p2 = p.start();
BufferedReader br = new BufferedReader(new InputStreamReader(
p2.getInputStream()));
String line;
System.out.println("Output of running " + "/bin/bash"
+ "run_hql.sh" + "ecl9_accounts_emr" + " is: ");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
try {
String target = new String("/ECLDEV/app/scripts/shell/run_hql.sh");
// String target = new String("mkdir stackOver");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(target);
proc.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
System.out.println("### " + output);
} catch (Throwable t) {
t.printStackTrace();
}
// Call hive.
// System.out.println(String.format("Calling hive using %s.",
// HQL_PATH));
/*
* ProcessBuilder hiveProcessBuilder = new ProcessBuilder("hive", "-f",
* table_path); Process hiveProcess = hiveProcessBuilder.start();
*
* OutputRedirector outRedirect = new
* OutputRedirector(hiveProcess.getInputStream(), "HIVE_OUTPUT");
* OutputRedirector outToConsole = new
* OutputRedirector(hiveProcess.getErrorStream(), "HIVE_LOG");
*
* outRedirect.start(); outToConsole.start();
*
* hiveProcess.waitFor();
* System.out.println(String.format("Hive job call completed."));
* hiveProcess.destroy();
*
* } catch (ClassNotFoundException e) { e.printStackTrace(); } catch
* (IllegalArgumentException e) { e.printStackTrace(); } catch
* (FileNotFoundException e) { e.printStackTrace(); } catch (IOException
* e) { e.printStackTrace(); } catch (InterruptedException e) {
* e.printStackTrace(); }
*/
}
} | true |
7fa2658344e99b5da35eb7ddbb651a79cdf6696e | Java | SaoriKaku/LeetCode | /7. Reverse Integer.Java | UTF-8 | 1,937 | 4.0625 | 4 | [] | no_license |
/*
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
*/
// method 1: use an array to store the reversed number
// time complextiy: O(n), space complexity: O(n)
class Solution {
public int reverse(int x) {
boolean negative = false;
if(x < 0) {
negative = true;
}
x = Math.abs(x);
List<Integer> num = new ArrayList<>();
while(x > 0) {
num.add(x % 10);
x = x / 10;
}
// 123 -> 321
int result = 0;
for(int i = 0; i < num.size(); i++) {
// i = 0, 2 - 0 = 2
// i = 1, 2 - 1 = 1
// i = 2, 2 - 2 = 0
result += num.get(i) * Math.pow(10, num.size() - 1 - i);
if(result == Integer.MAX_VALUE) {
return 0;
}
}
if(negative) {
result *= -1;
}
return result;
}
}
// method 2: while % / already reverse the nunber, judge whether result > Integer.MAX_VALUE/10
// time complextiy: O(n), space complexity: O(1)
class Solution {
public int reverse(int x) {
boolean negative = false;
if(x < 0) {
negative = true;
}
x = Math.abs(x);
int result = 0;
// 123 -> 321
while(x > 0) {
if(result > Integer.MAX_VALUE/10) {
return 0;
}
int num = x % 10;
x = x / 10;
result = 10 * result + num;
}
if(negative) {
result *= -1;
}
return result;
}
}
| true |
90fbeacb66c9a84aa5095ca70df3277e1fcd8384 | Java | DomenicoVerde/Deliverable2 | /src/it/uniroma2/isw2/milestone1/model/MeasurableFile.java | UTF-8 | 3,350 | 2.59375 | 3 | [] | no_license | package it.uniroma2.isw2.milestone1.model;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
public class MeasurableFile {
private String name;
private String version;
//Metrics
private int loc;
private double age;
private int nr;
private int changeset;
private double averageChangeSet;
private int maxChangeSet;
private int nAuth;
private int locAdded;
private double avgLocAdded;
private boolean buggyness;
public MeasurableFile() {
this.loc = 0;
this.age = 0;
this.nr = 0;
this.changeset = 0;
this.averageChangeSet = 0;
this.maxChangeSet = 0;
this.nAuth = 0;
this.locAdded = 0;
this.avgLocAdded = 0;
this.buggyness = false;
}
public void print() {
Logger logger = LogManager.getLogger(MeasurableFile.class);
logger.info("Version: " + this.version);
logger.info("Filename: " + this.name);
logger.info("LOC: " + this.loc);
logger.info("Age: " + this.age);
logger.info("Number of Revisions: " + this.nr);
logger.info("Change Set: " + this.changeset);
logger.info("Average Change Set: " + this.averageChangeSet);
logger.info("Max Change Set: " + this.maxChangeSet);
logger.info("Number of Authors: " + this.nAuth);
logger.info("LOC Added Sum: " + this.locAdded);
logger.info("Average LOC Added: " + this.avgLocAdded);
logger.info("Buggy?: " + this.buggyness);
}
public void printonFile(FileWriter f) throws IOException {
f.append(this.version + ",");
f.append(this.name + ",");
f.append(this.loc + ",");
f.append(this.age + ",");
f.append(this.nr + ",");
f.append(this.changeset + ",");
f.append(this.averageChangeSet + ",");
f.append(this.maxChangeSet + ",");
f.append(this.nAuth + ",");
f.append(this.locAdded + ",");
f.append(this.avgLocAdded + ",");
f.append(this.buggyness + "\n");
}
public int getLoc() {
return loc;
}
public void setLoc(int loc) {
this.loc = loc;
}
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public int getNr() {
return nr;
}
public void setNr(int nr) {
this.nr = nr;
}
public int getChangeset() {
return changeset;
}
public void setChangeset(int changeset) {
this.changeset = changeset;
}
public double getAverageChangeSet() {
return averageChangeSet;
}
public void setAverageChangeSet(double averageChangeSet) {
this.averageChangeSet = averageChangeSet;
}
public int getMaxChangeSet() {
return maxChangeSet;
}
public void setMaxChangeSet(int maxChangeSet) {
this.maxChangeSet = maxChangeSet;
}
public int getnAuth() {
return nAuth;
}
public void setnAuth(int nAuth) {
this.nAuth = nAuth;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLocAdded() {
return locAdded;
}
public void setLocAdded(int locAdded) {
this.locAdded = locAdded;
}
public double getAvgLocAdded() {
return avgLocAdded;
}
public void setAvgLocAdded(double avgLocAdded) {
this.avgLocAdded = avgLocAdded;
}
public boolean isBuggy() {
return buggyness;
}
public void setBuggyness(boolean buggyness) {
this.buggyness = buggyness;
}
}
| true |
3ae7cd486c07174e8eca27b10fcebb9d72fd5e22 | Java | yk154/voogasalad_PrintStackTrace | /src/authoring_backend/src/groovy/graph/blocks/core/GroovyBlock.java | UTF-8 | 1,131 | 2.5 | 2 | [
"MIT"
] | permissive | package groovy.graph.blocks.core;
import authoringUtils.frontendUtils.Replicable;
import authoringUtils.frontendUtils.Try;
import graph.Node;
import groovy.api.BlockGraph;
import groovy.api.Ports;
import java.util.Map;
import java.util.Set;
/**
* Groovy Block is a composable block elements that represent piece of Groovy code.
* <p>
* The type signature GroovyBlock<T extends GroovyBlock> extends Replicable<T>
* Forces each subclass implementing GroovyBlock<T> to implement Replicable<T>;
*
* @author Inchan Hwang
*/
public interface GroovyBlock<T extends GroovyBlock<T>> extends Node, Replicable<T> {
/**
* Each GroovyBlock must be transformable into Groovy Code, although
* it might fail...
*
* @return Groovy code
*/
Try<String> toGroovy(BlockGraph graph);
/**
* Replicates this GroovyBlock
*
* @return Deep copy of this GroovyBlock
*/
T replicate();
/**
* @return Set of ports
*/
Set<Ports> ports();
/**
* @return Representative Name
*/
String name();
/**
* Params
*/
Map<String, Object> params();
}
| true |
84ef8ab2c6f296317cbb6bf366c5d10b0ecc8c16 | Java | jumpstreet13/MvpYandexTranslator | /app/src/main/java/com/smedialink/abakarmagomedov/mvpyandextranslator/managers/SharedPrefManager.java | UTF-8 | 1,257 | 2.25 | 2 | [] | no_license | package com.smedialink.abakarmagomedov.mvpyandextranslator.managers;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* Created by Abocha on 22.07.2017.
*/
public class SharedPrefManager {
private final static String TRANSLATE_LANG = "tranlate_lang";
private final static String DESCRIPTION_LANG = "description_lang";
private SharedPreferences sharedPreference;
public SharedPrefManager(Context context) {
sharedPreference = PreferenceManager.getDefaultSharedPreferences(context);
}
public void writeToPref(String lang){
SharedPreferences.Editor editor = sharedPreference.edit();
editor.putString(TRANSLATE_LANG, lang);
editor.apply();
}
public void writeDescriptionToPref(String lang){
SharedPreferences.Editor editor = sharedPreference.edit();
editor.putString(DESCRIPTION_LANG, lang);
editor.apply();
}
public String readDescriptionFromPref(){
return sharedPreference.getString(DESCRIPTION_LANG, "English");
}
public String readFromPref(){
return sharedPreference.getString(TRANSLATE_LANG, "en"); // TODO: 31/07/17 Put here GSONMANAGER
}
}
| true |
9334443b34212e7ac5a09af83dbfcb9c83bc30b4 | Java | andy2c/repositoryExolab | /melaCondominio/src/it/condominio/model/Delega.java | UTF-8 | 1,612 | 2.453125 | 2 | [] | no_license | package it.condominio.model;
import java.sql.Timestamp;
public class Delega {
private int id;
private String percorso_delega;
private int id_riunione;
private Timestamp data_creazione;
private Riunione riunione;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPercorso_delega() {
return percorso_delega;
}
public void setPercorso_delega(String percorso_delega) {
this.percorso_delega = percorso_delega;
}
public int getId_riunione() {
return id_riunione;
}
public void setId_riunione(int id_riunione) {
this.id_riunione = id_riunione;
}
public Timestamp getData_creazione() {
return data_creazione;
}
public void setData_creazione(Timestamp data_creazione) {
this.data_creazione = data_creazione;
}
public Riunione getRiunione() {
if(riunione==null)
riunione = new Riunione();
return riunione;
}
public void setRiunione(Riunione riunione) {
this.riunione = riunione;
}
public Delega(int id, String percorso_delega, int id_riunione) {
this.id = id;
this.percorso_delega = percorso_delega;
this.id_riunione = id_riunione;
}
public Delega(String percorso_delega, int id_riunione) {
this.percorso_delega = percorso_delega;
this.id_riunione = id_riunione;
}
@Override
public String toString() {
return "Delega [id=" + id + ", percorso_delega=" + percorso_delega + ", id_riunione=" + id_riunione
+ ", data_creazione=" + data_creazione + ", riunione=" + riunione + "]";
}
public Delega () {
}
}
| true |
f653822eab118c531b5c3ac30b9920796402d16b | Java | zddcyf/utils | /util/src/main/java/com/mul/utils/db/cache/CacheDatabase.java | UTF-8 | 3,780 | 2.265625 | 2 | [] | no_license | package com.mul.utils.db.cache;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.mul.utils.DataUtils;
import com.mul.utils.db.dao.CacheDao;
import com.mul.utils.db.dao.ListCacheDao;
import com.mul.utils.db.request.ApiCache;
import com.mul.utils.db.request.ApiListCache;
import com.mul.utils.log.LogUtil;
import com.mul.utils.manager.GlobalManager;
import java.util.ArrayList;
import java.util.List;
/**
* @ProjectName: utils
* @Package: com.mul.utils.db.cache
* @ClassName: CacheDatabase
* @Author: zdd
* @CreateDate: 2020/7/15 16:37
* @Description: java类作用描述
* @UpdateUser: 更新者
* @UpdateDate: 2020/7/15 16:37
* @UpdateRemark: 更新说明
* @Version: 1.0.0
* entities 数据库中有哪些表
* version 版本号
* exportSchema 默认为true。会导出一个json文件。会将所有的sql语句打印出一个文件
*/
@Database(entities = {ApiCache.class, ApiListCache.class}, version = 2)
public abstract class CacheDatabase extends RoomDatabase {
// public static String DB_NAME = "FaceIdentifyDb";
private static CacheDatabase database;
private static final List<Migration> mMigrations = new ArrayList<>();
/**
* @param startVersion 开始版本号
* @param endVersion 结束版本号
* @param updateSql 更新的数据库SQL语句 (alter table ApiCache ADD COLUMN createTime INTEGER NOT NULL DEFAULT 0)
*/
public static void setMigration(int startVersion, int endVersion, String... updateSql) {
Migration migration = new Migration(startVersion, endVersion) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
int mVersion = database.getVersion();
LogUtil.e("mVersion=" + mVersion);
// database.execSQL("alter table ApiCache ADD COLUMN createTime INTEGER NOT NULL DEFAULT 0");
// database.execSQL("alter table ListApiCache ADD COLUMN createTime INTEGER NOT NULL DEFAULT 0");
for (String mS : updateSql) {
database.execSQL(mS);
}
}
};
mMigrations.add(migration);
}
/**
* 初始化
*
* @param dbName 数据库表名
*/
public static void init(String dbName) {
// 创建一个内存数据库,这种创建方式只存在于内存中,也就是说一旦进程被杀死。数据随时丢失
// Room.inMemoryDatabaseBuilder()
LogUtil.saveI("数据库名:" + dbName);
Builder<CacheDatabase> mCacheDatabaseBuilder = Room.databaseBuilder(GlobalManager.INSTANCE.context, CacheDatabase.class, dbName);
mCacheDatabaseBuilder.allowMainThreadQueries(); // 是否允许在主线程进行查询
// mCacheDatabaseBuilder.addCallback(); // 数据库创建和打开后的回调
// mCacheDatabaseBuilder.setQueryExecutor(); // 设置查询的线程池
// mCacheDatabaseBuilder.openHelperFactory(); // 设置数据库工厂
// mCacheDatabaseBuilder.setJournalMode(); // room的日志模式
// mCacheDatabaseBuilder.fallbackToDestructiveMigration(); // 数据库升级异常后根据指定版本进行回滚
if (!DataUtils.isEmpty(mMigrations)) {
mCacheDatabaseBuilder.addMigrations(mMigrations.toArray(new Migration[]{})); // 是否允许在主线程进行查询
}
database = mCacheDatabaseBuilder.build();
}
public abstract CacheDao getCacheDao();
public abstract ListCacheDao getListCacheDao();
public static CacheDatabase get() {
return database;
}
} | true |
f52fa6b3449db38dc4cf212cdbe31f8eb43a24f9 | Java | zhou5827297/spider | /src/main/java/com/spider/config/ProxyConstant.java | UTF-8 | 3,449 | 2.09375 | 2 | [] | no_license | package com.spider.config;
import com.spider.util.PropertiesUtils;
import java.io.File;
import java.util.Properties;
/**
* 代理相关的配置
*/
public class ProxyConstant {
private final static Properties PROPERTIES = PropertiesUtils.loadProperties("conf/proxy.properties");
/**
* 是否使用代理
*/
public final static int PROXY_SWITCH = Integer.parseInt(PROPERTIES.getProperty("PROXY_SWITCH"));
/**
* 是否展示浏览器
*/
public final static int SHOW_BROWER = Integer.parseInt(PROPERTIES.getProperty("SHOW_BROWER"));
/**
* 读取超时时间
*/
public final static int TIMEOUT_READ = Integer.parseInt(PROPERTIES.getProperty("TIMEOUT_READ"));
/**
* JS执行超时时间
*/
public final static int JS_EXECUTE_TIMEOUT_READ = Integer.parseInt(PROPERTIES.getProperty("JS_EXECUTE_TIMEOUT_READ"));
/**
* 连接超时时间
*/
public final static int TIMEOUT_CONNECT = Integer.parseInt(PROPERTIES.getProperty("TIMEOUT_CONNECT"));
/**
* 代理服务器
*/
public final static String PROXY_URL = PROPERTIES.getProperty("PROXY_URL");
/**
* 获取ip的接口
*/
public final static String PROXY_GET = PROXY_URL + PROPERTIES.getProperty("PROXY_GET");
/**
* 通知成功接口
*/
public final static String PROXY_NOTICE_SUCCESS = PROXY_URL + PROPERTIES.getProperty("PROXY_NOTICE_SUCCESS");
/**
* 通知失败接口
*/
public final static String PROXY_NOTICE_FAILED = PROXY_URL + PROPERTIES.getProperty("PROXY_NOTICE_FAILED");
/**
* 代理ip重试最大次数
*/
public final static int PROXY_MAX_RETRY = Integer.parseInt(PROPERTIES.getProperty("PROXY_MAX_RETRY"));
/**
* 任务重试最大次数
*/
public final static int TASK_MAX_RETRY = Integer.parseInt(PROPERTIES.getProperty("TASK_MAX_RETRY"));
/**
* 浏览器池中借出的对象的最大数目
*/
public final static int POOL_MAXACTIVE = Integer.parseInt(PROPERTIES.getProperty("POOL_MAXACTIVE"));
/**
* 包执行超时时间(分钟)
*/
public final static int PACKAGE_EXECUTE_TIMEOUT = Integer.parseInt(PROPERTIES.getProperty("PACKAGE_EXECUTE_TIMEOUT"));
/**
* 池获取等待毫秒
*/
public final static int POOL_MAXWAIT = Integer.parseInt(PROPERTIES.getProperty("POOL_MAXWAIT"));
/**
* 执行最大线程数
*/
public final static int MAX_THREAD_COUNT = Integer.parseInt(PROPERTIES.getProperty("MAX_THREAD_COUNT"));
/**
* 配置文件目录
*/
public final static String CONFIG_ROOT = PROPERTIES.getProperty("CONFIG_ROOT");
/**
* 执行文件目录
*/
public final static String DATA_ROOT = PROPERTIES.getProperty("DATA_ROOT");
/**
* 抓取当前N小时以内的新闻
*/
public final static int FETCH_BEFORE_HOUR = Integer.parseInt(PROPERTIES.getProperty("FETCH_BEFORE_HOUR"));
/**
* 是否保存网页快照文件
*/
public final static int SNAPSHOT_WHETHER_SAVE = Integer.parseInt(PROPERTIES.getProperty("SNAPSHOT_WHETHER_SAVE"));
/**
* 快照文件路径
*/
public final static String SNAPSHOT_DATA_ROOT = PROPERTIES.getProperty("SNAPSHOT_DATA_ROOT");
/**
* json文件临时目录路径
*/
public final static String SPIDER_JSON_TMP_DIR = DATA_ROOT + File.separator + "spider-json-tmp";
}
| true |
241fc28521b603fe53dc5cf5194162d4720310f4 | Java | KuboSv/VAVA | /Server/ejbModule/com/server/ServerBean.java | WINDOWS-1250 | 5,041 | 2.59375 | 3 | [] | no_license | package com.server;
import java.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.naming.*;
import javax.sql.DataSource;
import java.io.IOException;
import javax.mail.*;
import javax.mail.internet.*;
import com.server.entity.*;
/**
* @author Jakub Juko, Ivan Petrov
*/
@Stateless
@LocalBean
@Remote(ServerBeanRemote.class)
public class ServerBean implements ServerBeanRemote {
/**
* Metoda ktora nacita z databazy otazky a odpovede podla kategoria
* @param kategoria_id predstavuje index kategorie
* @return zoznam otazok a odpovedi
* @see Question
*/
public List<Question> getOtazky(int kategoria_id) {
List<Question> otazky = new ArrayList<Question>();
Properties p = new Properties();
Connection conn = null;
String otazka = null;
String odpoved = null;
boolean spr = false;
try {
p.load(this.getClass().getResourceAsStream("/configuration.properties"));
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(p.getProperty("DATASOURCE"));
conn = (Connection) ds.getConnection();
PreparedStatement stmt = conn.prepareStatement("select o.text_otazky,o2.text_odpovede,o2.spravna from odpoved o2 "
+"join otazky o on o2.otazka_id = o.otazky_id "
+"join kategoria k on o.kategoria_id = k.kategoria_id "
+"where o.kategoria_id = ? order by otazky_id asc;");
stmt.setInt(1, kategoria_id);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Question o = new Question();
o.setQuestion(rs.getString(1));
o.setAnswer(rs.getString(2));
o.setCorrect(rs.getBoolean(3));
otazky.add(o);
}
stmt.close();
conn.close();
} catch (IOException | NamingException | SQLException e) {
e.printStackTrace();
}
return otazky;
}
/**
* Metoda ktora prida do databazy , tabulky rebricek noveho hraca
* @param meno predstavuje meno hraca
* @param body pocet ziskanych bodov
* @see TopPlayers
*/
public void pridaj(TopPlayers hrac) {
Properties p = new Properties();
Connection conn = null;
try {
Context ctx = new InitialContext();
p.load(this.getClass().getResourceAsStream("/configuration.properties"));
DataSource ds = (DataSource) ctx.lookup(p.getProperty("DATASOURCE"));
conn = (Connection) ds.getConnection();
PreparedStatement stmt = conn.prepareStatement("insert into rebricek (meno, body) values ('"+hrac.getName()+"',"+hrac.getScore()+");");
stmt.executeUpdate();
stmt.close();
conn.close();
} catch (IOException | NamingException | SQLException e) {
e.printStackTrace();
}
}
/**
* Metoda ktora vrati zoznam top hracov a ich body z databazy
* @return zoznam hracov nachadzajucich sa v rebricku
* @see TopPlayers
*/
public List<TopPlayers> getTopPlayers() {
List<TopPlayers> hraci = new ArrayList<TopPlayers>();
Connection conn = null;
Properties p = new Properties();
try {
Context ctx = new InitialContext();
p.load(this.getClass().getResourceAsStream("/configuration.properties"));
DataSource ds = (DataSource) ctx.lookup(p.getProperty("DATASOURCE"));
conn = (Connection) ds.getConnection();
PreparedStatement stmt = conn.prepareStatement(p.getProperty("SELECTHRACI"));
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
TopPlayers top = new TopPlayers();
top.setName(rs.getString(1));
top.setScore(rs.getInt(2));
hraci.add(top);
}
stmt.close();
conn.close();
} catch (IOException | NamingException | SQLException e) {
e.printStackTrace();
}
return hraci;
}
/**
*
* Metoda ktora posli na zadanu emailovu adresu email s menom hraca
* a poctom ziskanych bodov
* @param email cielova emailova adresa
* @param hrac aktualny hrac
*/
public void SentEmail(String email, TopPlayers hrac) {
try {
Properties props = new Properties();
Properties p = new Properties();
p.load(this.getClass().getResourceAsStream("/configuration.properties"));
props.load(this.getClass().getResourceAsStream("/mail.properties"));
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(p.getProperty("USERNAME"), p.getProperty("PASSWORD"));
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(p.getProperty("EMAIL")));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
message.setSubject(p.getProperty("SUBJECT"));
String text = "Dakujeme "+hrac.getName()+", ze ste si vyskusali svoje znalosti "
+ " pomocou nasej aplikacie Brain Challenge\nVase ziskane skore je "+hrac.getScore()+"\n\n\n\n"
+ "Brain Challenge Development Team,\nVasVa 2018 FIIT STU";
message.setText(text);
Transport.send(message);
} catch (IOException e) {
e.printStackTrace();
}
catch (MessagingException e) {
throw new RuntimeException(e);
}
}
} | true |
b1a31e9cd97c13df3334347760ea1ff8b384bccc | Java | azurewer/ArchStudio5 | /org.archstudio.xadl3.xadlcore/src/org/archstudio/xadl3/xadlcore_3_0/impl/SimpleLinkImpl.java | UTF-8 | 7,178 | 1.703125 | 2 | [] | no_license | /**
*/
package org.archstudio.xadl3.xadlcore_3_0.impl;
import org.archstudio.xadl3.xadlcore_3_0.SimpleLink;
import org.archstudio.xadl3.xadlcore_3_0.Xadlcore_3_0Package;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
/**
* <!-- begin-user-doc --> An implementation of the model object '<em><b>Simple Link</b></em>'. <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.archstudio.xadl3.xadlcore_3_0.impl.SimpleLinkImpl#getHref <em>Href</em>}</li>
* <li>{@link org.archstudio.xadl3.xadlcore_3_0.impl.SimpleLinkImpl#getId <em>Id</em>}</li>
* <li>{@link org.archstudio.xadl3.xadlcore_3_0.impl.SimpleLinkImpl#getType <em>Type</em>}</li>
* </ul>
*
* @generated
*/
public class SimpleLinkImpl extends MinimalEObjectImpl.Container implements SimpleLink {
/**
* The default value of the '{@link #getHref() <em>Href</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getHref()
* @generated
* @ordered
*/
protected static final String HREF_EDEFAULT = null;
/**
* The cached value of the '{@link #getHref() <em>Href</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getHref()
* @generated
* @ordered
*/
protected String href = HREF_EDEFAULT;
/**
* The default value of the '{@link #getId() <em>Id</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @see #getId()
* @generated
* @ordered
*/
protected static final String ID_EDEFAULT = null;
/**
* The cached value of the '{@link #getId() <em>Id</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @see #getId()
* @generated
* @ordered
*/
protected String id = ID_EDEFAULT;
/**
* The default value of the '{@link #getType() <em>Type</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getType()
* @generated
* @ordered
*/
protected static final String TYPE_EDEFAULT = "simple";
/**
* The cached value of the '{@link #getType() <em>Type</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getType()
* @generated
* @ordered
*/
protected String type = TYPE_EDEFAULT;
/**
* This is true if the Type attribute has been set. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
* @ordered
*/
protected boolean typeESet;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected SimpleLinkImpl() {
super();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
protected EClass eStaticClass() {
return Xadlcore_3_0Package.Literals.SIMPLE_LINK;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getHref() {
return href;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setHref(String newHref) {
String oldHref = href;
href = newHref;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, Xadlcore_3_0Package.SIMPLE_LINK__HREF, oldHref,
href));
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getId() {
return id;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setId(String newId) {
String oldId = id;
id = newId;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, Xadlcore_3_0Package.SIMPLE_LINK__ID, oldId, id));
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getType() {
return type;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setType(String newType) {
String oldType = type;
type = newType;
boolean oldTypeESet = typeESet;
typeESet = true;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, Xadlcore_3_0Package.SIMPLE_LINK__TYPE, oldType, type,
!oldTypeESet));
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void unsetType() {
String oldType = type;
boolean oldTypeESet = typeESet;
type = TYPE_EDEFAULT;
typeESet = false;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.UNSET, Xadlcore_3_0Package.SIMPLE_LINK__TYPE, oldType,
TYPE_EDEFAULT, oldTypeESet));
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isSetType() {
return typeESet;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Xadlcore_3_0Package.SIMPLE_LINK__HREF:
return getHref();
case Xadlcore_3_0Package.SIMPLE_LINK__ID:
return getId();
case Xadlcore_3_0Package.SIMPLE_LINK__TYPE:
return getType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Xadlcore_3_0Package.SIMPLE_LINK__HREF:
setHref((String) newValue);
return;
case Xadlcore_3_0Package.SIMPLE_LINK__ID:
setId((String) newValue);
return;
case Xadlcore_3_0Package.SIMPLE_LINK__TYPE:
setType((String) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Xadlcore_3_0Package.SIMPLE_LINK__HREF:
setHref(HREF_EDEFAULT);
return;
case Xadlcore_3_0Package.SIMPLE_LINK__ID:
setId(ID_EDEFAULT);
return;
case Xadlcore_3_0Package.SIMPLE_LINK__TYPE:
unsetType();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Xadlcore_3_0Package.SIMPLE_LINK__HREF:
return HREF_EDEFAULT == null ? href != null : !HREF_EDEFAULT.equals(href);
case Xadlcore_3_0Package.SIMPLE_LINK__ID:
return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id);
case Xadlcore_3_0Package.SIMPLE_LINK__TYPE:
return isSetType();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) {
return super.toString();
}
StringBuffer result = new StringBuffer(super.toString());
result.append(" (href: ");
result.append(href);
result.append(", id: ");
result.append(id);
result.append(", type: ");
if (typeESet) {
result.append(type);
}
else {
result.append("<unset>");
}
result.append(')');
return result.toString();
}
} // SimpleLinkImpl
| true |
4c2187c0dc974a733c94391072e1c9e434b40feb | Java | jakubszalaty/zut-api | /apk/android/support/v4/p003c/C0146a.java | UTF-8 | 1,139 | 1.953125 | 2 | [
"MIT"
] | permissive | package android.support.v4.p003c;
import android.graphics.Color;
/* renamed from: android.support.v4.c.a */
public final class C0146a {
private static final ThreadLocal<double[]> f408a;
static {
f408a = new ThreadLocal();
}
public static int m590a(int i, int i2) {
int alpha = Color.alpha(i2);
int alpha2 = Color.alpha(i);
int c = C0146a.m593c(alpha2, alpha);
return Color.argb(c, C0146a.m591a(Color.red(i), alpha2, Color.red(i2), alpha, c), C0146a.m591a(Color.green(i), alpha2, Color.green(i2), alpha, c), C0146a.m591a(Color.blue(i), alpha2, Color.blue(i2), alpha, c));
}
private static int m591a(int i, int i2, int i3, int i4, int i5) {
return i5 == 0 ? 0 : (((i * 255) * i2) + ((i3 * i4) * (255 - i2))) / (i5 * 255);
}
public static int m592b(int i, int i2) {
if (i2 >= 0 && i2 <= 255) {
return (16777215 & i) | (i2 << 24);
}
throw new IllegalArgumentException("alpha must be between 0 and 255.");
}
private static int m593c(int i, int i2) {
return 255 - (((255 - i2) * (255 - i)) / 255);
}
}
| true |
db255ad20cb6701eb120866b859375d61a07aa23 | Java | Duong4G/Movie_Web_Spring_Boot | /src/main/java/ptithcm/internship/movieapp/repository/RoleRepository.java | UTF-8 | 338 | 2.03125 | 2 | [] | no_license | package ptithcm.internship.movieapp.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import ptithcm.internship.movieapp.entrity.Role;
@Repository
public interface RoleRepository extends JpaRepository<Role, Integer>{
Role findByName(String name);
}
| true |
2ddc192871c3eb7ebb22bafdabadff1034a42127 | Java | cbpaul/DJMS | /src/main/java/com/paul/webapp/util/ObjectUtil.java | UTF-8 | 313 | 2.359375 | 2 | [] | no_license | package com.paul.webapp.util;
public class ObjectUtil {
public static boolean isPrimitive(Object obj) {
if (obj instanceof Integer || obj instanceof String
|| obj instanceof Long || obj instanceof Float
|| obj instanceof Double || obj instanceof Character) {
return true;
}
return false;
}
}
| true |
b4428c74ef1e7596b5c84375262611d879f6871b | Java | fshahy/modernisc | /ach/src/main/java/com/misc/ach/AchApplication.java | UTF-8 | 3,172 | 2.4375 | 2 | [] | no_license | package com.misc.ach;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
import com.misc.ach.model.DataFile;
import com.misc.ach.model.Line;
import com.misc.ach.service.AchService;
import com.misc.ach.service.CoreService;
import lombok.extern.slf4j.Slf4j;
@SpringBootApplication
@PropertySource("classpath:custom.properties")
@Slf4j
public class AchApplication {
@Value("${misc.watch.folder}")
private String watchfolder;
private static AchService achService;
private static CoreService coreService;
private static String staticWatchFolder;
public static void main(String[] args) {
SpringApplication.run(AchApplication.class, args);
log.info("Folder to Watch: " + staticWatchFolder);
watchForNewFile(staticWatchFolder);
}
@Value("${misc.watch.folder}")
public void setStaticWatchFolder(String value) {
AchApplication.staticWatchFolder = value;
}
@Autowired
public void setAchService(AchService service) {
AchApplication.achService = service;
}
@Autowired
public void setService(CoreService service) {
AchApplication.coreService = service;
}
private static void watchForNewFile(String folder) {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = FileSystems.getDefault().getPath(staticWatchFolder);
WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
while(true) {
key = watcher.take();
for(WatchEvent<?> event: key.pollEvents()) {
Object o = event.context();
if(o instanceof Path) {
Path path = (Path) o;
log.info("New File Detected: " + path);
processFile(path);
}
}
key.reset();
}
} catch(IOException e) {
e.printStackTrace();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
private static void processFile(Path path) {
try {
DataFile dataFile = DataFile.builder().name(path.toString()).build();
DataFile savedFile = achService.saveFile(dataFile);
File file = new File(staticWatchFolder, path.toString());
FileReader fileReader = new FileReader(file);
BufferedReader bufReader = new BufferedReader(fileReader);
String lineData;
while((lineData = bufReader.readLine()) != null) {
log.info("Processing Line: " + lineData);
Line line = Line.builder().data(lineData).file(savedFile).build();
Long coreId = coreService.submitLine(line);
line.setCoreId(coreId);
log.info("Got CoreID: " + coreId);
achService.saveLine(line);
}
fileReader.close();
bufReader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
| true |
a7be0e01e04fd672934dd62fb7f3170789622da5 | Java | zju-sclab/SchedulingPlatform | /common/src/main/java/com/skywilling/cn/common/model/Coordinate.java | UTF-8 | 279 | 1.78125 | 2 | [] | no_license | package com.skywilling.cn.common.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Coordinate extends AbstractPoint {
private double x;
private double y;
}
| true |
10ee8d403109e960469470de6b60ca9c7c26bfb9 | Java | grzegorzkurtyka/java-console-calculator | /src/test/java/calc/tokenizer/TokenizerTest.java | UTF-8 | 2,504 | 3.234375 | 3 | [] | no_license | package calc.tokenizer;
import calc.tokenizer.token.*;
import calc.tokenizer.token.type.TokenType;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class TokenizerTest {
@Test
void whiteSpacesAreIgnored() {
Tokenizer t1, t2;
t1 = new Tokenizer("1 + 1");
t2 = new Tokenizer("1+1");
try {
assertArrayEquals(t1.get().toArray(), t2.get().toArray());
} catch (Exception e) {
fail("Exception thrown from Tokenizer: " + e.getMessage());
}
t1 = new Tokenizer("(1+1*2/3^4)");
t2 = new Tokenizer(" ( 1 + 1 * 2 / 3^4 ) ");
try {
assertArrayEquals(t1.get().toArray(), t2.get().toArray());
} catch (Exception e) {
fail("Exception thrown from Tokenizer: " + e.getMessage());
}
}
@Test
void basicAddingOperation() {
Tokenizer t = new Tokenizer("1+2");
ArrayList<TokenType> expected = new ArrayList<>();
expected.add(new IntegerType(1));
expected.add(new OperatorADD());
expected.add(new IntegerType(2));
try {
assertArrayEquals(expected.toArray(), t.get().toArray());
} catch (Exception e) {
fail("Exception thrown from Tokenizer: " + e.getMessage());
}
}
@Test
void recognizeOperators() {
Tokenizer t = new Tokenizer("+-*/^");
ArrayList<TokenType> expected = new ArrayList<>();
expected.add(new OperatorADD());
expected.add(new OperatorSUB());
expected.add(new OperatorMUL());
expected.add(new OperatorDIV());
expected.add(new OperatorPOW());
try {
assertArrayEquals(expected.toArray(), t.get().toArray());
} catch (Exception e) {
fail("Exception thrown from Tokenizer: " + e.getMessage());
}
}
@Test
void recognizeNumbers() {
Tokenizer t = new Tokenizer("10 + 10000 + 0.3");
try {
ArrayList<TokenType> tokens = t.get();
assertEquals(new IntegerType(10), tokens.get(0));
assertEquals(new IntegerType(10000), tokens.get(2));
assertEquals(new DoubleType(0.3), tokens.get(4));
} catch (IndexOutOfBoundsException e) {
fail("Wrong number of tokens");
} catch (Exception e) {
fail("Exception thrown from Tokenizer: " + e.getMessage());
}
}
}
| true |
0bfbde1fbd42f212172b87a83e687b5018cc691c | Java | Yaseen549/StatusbarNotification | /src/com/saya/statusbarnotification/MainActivity.java | UTF-8 | 1,564 | 2.03125 | 2 | [] | no_license | package com.saya.statusbarnotification;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(android.R.drawable.stat_notify_more, "You have got an Email", System.currentTimeMillis());
Context context = MainActivity.this;
Intent i = new Intent(context, MainActivity.class);
PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, i, 0);
notification.setLatestEventInfo(context, "Email from facebook", "You have 4 friend request ", pending);
nm.notify(0, notification);
}
});
}
@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;
}
}
| true |
6f11c0b24a711ac439f49306a19520a1de0de7d5 | Java | AceArthur/Database-Query-Implementation | /src/source/tfile.java | UTF-8 | 1,623 | 3.203125 | 3 | [] | no_license | package source;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.*;
public class tfile {
private String filename;
private String filepath;
private String[] attributes;
private List<int[]> data;
public tfile(String filepath) {
this.filepath = filepath;
init();
}
private void init() {
try {
File file = new File(filepath);
filename = file.getName();
if (!file.exists()) {
file = new File(filepath);
if (!file.exists()) {
System.out.println("Error: " + filepath + " does not exist.");
System.exit(1);
}
}
BufferedReader reader = new BufferedReader(new FileReader(filepath));
String columnnames = reader.readLine();// Attribute names
attributes = columnnames.split(",");
data = new ArrayList<int[]>();
String line = null;
while ((line = reader.readLine()) != null) {
String tuple_str[] = line.split(",");
int tuple[] = new int[tuple_str.length];
for (int i = 0; i < tuple_str.length; i++) {
tuple[i] = Integer.parseInt(tuple_str[i]);
}
data.add(tuple);
}
reader.close();
} catch (Exception e) {
System.out.println("Error initializating " + filename + ".");
e.printStackTrace();
System.exit(1);
}
}
public int numAttributes() {
return attributes.length;
}
public int numTuples() {
return data.size();
}
public String[] getAttributes() {
return attributes;
}
public int[] getTuple(int index) {
return data.get(index);
}
public String getFilename() {
return filename;
}
}
| true |
de44fff30d2536da9579fd57ca307f9b0c5ae046 | Java | estera11/refactoring | /src/excercise/AccountType.java | UTF-8 | 83 | 1.757813 | 2 | [] | no_license | package excercise;
public enum AccountType {
CurrentAccount, DepositAccount
}
| true |
83d94544751e2532b0f84a85b6b89a3eec5879bc | Java | GeorgiyNaumenko/Java-Labs | /HW 5/src/task_4_3.java | WINDOWS-1251 | 808 | 3.34375 | 3 | [] | no_license | import java.util.Scanner;
/**
*
* @author . 26/10/2020. 4.3
*
*/
public class task_4_3 {
/**
* main 4.3
* @param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String r = "";
System.out.println(" :");
r = input.nextLine();
String[] rt = r.split(" ");
System.out.println(" , ");
int k = input.nextInt();
input.close();
Plane plane = new Plane(rt);
for(int i = 0; i < k; i ++) {
plane.fly();
}
System.out.println("Naumenko, task 4.3");
}
}
| true |
d9d8ea5537b1ce22517fc097935c7a9c954e796c | Java | fedor-malyshkin/story_line2_crawler | /src/test/java/ru/nlp_project/story_line2/crawler/ZooKeeperLocal.java | UTF-8 | 2,408 | 2.34375 | 2 | [] | no_license | package ru.nlp_project.story_line2.crawler;
import java.io.IOException;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import lombok.Getter;
import org.apache.zookeeper.server.ServerConfig;
import org.apache.zookeeper.server.ZooKeeperServerMain;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
public class ZooKeeperLocal {
private static final String ZOO_PROP_TICK_TIME = "tickTime";
private static final String ZOO_PROP_DATA_DIR = "dataDir";
private static final String ZOO_PROP_CLIENT_PORT = "clientPort";
private final Properties initialProps;
private final int initialPort;
private ZooKeeperServerMain zooKeeperServer;
private Thread zooKeeperServerThread;
@Getter
private int usedPort;
public ZooKeeperLocal(int port, Properties properties) {
this.initialProps = properties;
this.initialPort = port;
}
public void start() throws Exception {
this.usedPort = preparePort();
Properties props = prepareProps(usedPort);
QuorumPeerConfig quorumConfiguration = new QuorumPeerConfig();
quorumConfiguration.parseProperties(props);
zooKeeperServer = new ZooKeeperServerMain();
final ServerConfig configuration = new ServerConfig();
configuration.readFrom(quorumConfiguration);
zooKeeperServerThread = new Thread() {
public void run() {
try {
zooKeeperServer.runFromConfig(configuration);
} catch (IOException e) {
System.out.println("ZooKeeper Failed");
e.printStackTrace(System.err);
}
}
};
zooKeeperServerThread.start();
}
private Properties prepareProps(int port) throws IOException {
Properties properties = new Properties();
properties.setProperty(ZOO_PROP_TICK_TIME, String.valueOf(1000));
Path tempDirectory = Files.createTempDirectory("zoo");
properties.setProperty(ZOO_PROP_DATA_DIR, tempDirectory.toString());
if (initialProps != null) {
initialProps.forEach((k, v) -> properties.setProperty((String) k, (String) v));
}
properties.setProperty(ZOO_PROP_CLIENT_PORT, String.valueOf(port));
return properties;
}
private int preparePort() throws IOException {
if (initialPort != 0) {
return initialPort;
}
return TestUtils.getFreePort();
}
public void stop() {
zooKeeperServerThread.interrupt();
}
} | true |
0c99e3423c116e5009a0900a57471cef9b308ffb | Java | Kantheesh/OnlineMovieTicketBooking | /CRUD Task-13/src/controller/CostumerController.java | UTF-8 | 804 | 2.328125 | 2 | [] | no_license | package controller;
import java.sql.Date;
import java.util.List;
import dao.CostumerImpl;
import dao.ICostumer;
import model.Costumer;
public class CostumerController {
ICostumer eImpl = new CostumerImpl();
public int addCostumer(int id, String name, Date dos, String s) {
Costumer costumer = new Costumer(id, name, dos, s);
return eImpl.addCostumer(costumer);
}
public List<Costumer> viewCostumer() {
return eImpl.viewCostumer();
}
public int editCostumer(int id, String name, Date dos, String seatNo) {
Costumer costumer = new Costumer(id, name, dos, seatNo);
return eImpl.editCostumer(costumer);
}
public int removeCostumer(int id) {
Costumer costumer = new Costumer();
costumer.setId(id);
return eImpl.removeCostumer(costumer);
}
}
| true |
e8bf33cfb013525652a8dc7f1d511cefd49a859b | Java | tanlin1/sharepro | /src/com/example/moment/MainActivity.java | UTF-8 | 10,678 | 2.203125 | 2 | [] | no_license | package com.example.moment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import utils.android.Read;
import utils.android.Write;
import utils.android.judgment.Login;
import utils.internet.CheckInternetTool;
import utils.json.JSONObject;
import utils.json.JSONStringer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.*;
public class MainActivity extends Activity {
/**
* Called when the activity is first created.
*/
public static int screenWidth = 0;
public static int screenHeight = 0;
private EditText emailEdit;
private EditText passwordEdit;
private String password;
private String email;
//public static String url = "http://192.168.1.102";
public static String url = "http://192.168.191.1";
//public static String url = "http://10.10.117.120";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//全屏模式,无标题
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//得到屏幕的尺寸,方便后续使用
WindowManager vm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
screenWidth = vm.getDefaultDisplay().getWidth();
screenHeight = vm.getDefaultDisplay().getHeight();
//当前Activity 是哪一个布局文件,以何种方式显示
setContentView(R.layout.main);
//检查网络
//checkInternet(this);
//依次找到布局中的各个控件,并为之设置监听器,便于处理
ImageView imageView = (ImageView) findViewById(R.id.MainView);
imageView.setLayoutParams(new LinearLayout.LayoutParams(screenWidth,screenHeight*2/3));
imageView.setBackgroundDrawable(getWallpaper().getCurrent());
//登录(注册)按钮
Button login = (Button) findViewById(R.id.button_login);
Button register = (Button) findViewById(R.id.button_register);
//登录填写的邮箱,密码编辑框
emailEdit = (EditText) findViewById(R.id.set_name);
passwordEdit = (EditText) findViewById(R.id.set_password);
//记住密码
CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox);
TextView toFindPassword = (TextView) findViewById(R.id.find_password);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
try {
Write.write(MainActivity.this, "test.txt", "yes\r\n你好吗?");
} catch (IOException e) {
System.out.println("写入文件出错!");
e.printStackTrace();
}
}
}
});
toFindPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//连接到服务器找回密码
startActivity(new Intent().setClass(MainActivity.this, Index.class));
}
});
//获取昵称编辑框的数据(通过焦点转移)
emailEdit.setOnFocusChangeListener(new emailFocus());
passwordEdit.setOnFocusChangeListener(new passwordFocus());
//为编辑框设置回车键检测
passwordEdit.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
password = passwordEdit.getText().toString();
//自动以藏输入键盘
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
return true;
}
return false;
}
});
//点击注册,跳转到注册页面
//验证用户是否存在等信息在注册页面进行
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent().setClass(MainActivity.this, RegisterActivity.class));
}
});
//点击登录,进行验证用户名以及密码。
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (email == null || password == null) {
Toast.makeText(getApplication(), R.string.login_warning, Toast.LENGTH_SHORT).show();
} else {
new LoginThread().start();
}
}
});
}
/**
*
* @param context 上下文
* @return true: 已经接入网络,不管是Internet 还是移动网络
* false: 当前没有网络连接
*/
private boolean checkInternet(Context context) {
if(!CheckInternetTool.checkInternet(context)){
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle(R.string.login_dialog_title);
dialog.setMessage(R.string.net_warning);
dialog.setPositiveButton(R.string.login_dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startActivity(new Intent(Settings.ACTION_SETTINGS));
}
});
dialog.setNegativeButton(R.string.login_dialog_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
// dialog.setMultiChoiceItems(items,itemsCheck,new DialogInterface.OnMultiChoiceClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// System.out.println("null");
// }
// });
dialog.create().show();
return false;
}
return true;
}
//昵称编辑框焦点侦听
private class emailFocus implements View.OnFocusChangeListener {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
email = emailEdit.getText().toString();
if (!Login.isEmail(email)) {
Toast.makeText(getApplicationContext(), R.string.email_wrong, Toast.LENGTH_SHORT).show();
emailEdit.setText("");
email = null;
}
}
}
}
//密码编辑框焦点侦听
private class passwordFocus implements View.OnFocusChangeListener {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
password = passwordEdit.getText().toString();
}
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle data = msg.getData();
if ("true".equals(data.getString("password"))) {
//Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this, Index.class));
} else if ("false".equals(data.getString("password"))) {
Toast.makeText(MainActivity.this, R.string.login_error, Toast.LENGTH_SHORT).show();
} else if ("yes".equals(data.getString("timeout"))) {
Toast.makeText(MainActivity.this, R.string.timeout, Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(MainActivity.this, Index.class));
}
}
};
private class LoginThread extends Thread {
@Override
public void run() {
login();
}
}
/**
* @param url 具体的url
*
* @return 此URL的HttpURLConnection连接
*/
private HttpURLConnection getUrlConnect(String url) {
URL loginUrl;
HttpURLConnection connection = null;
try {
loginUrl = new URL(MainActivity.url + url);
connection = (HttpURLConnection) loginUrl.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setConnectTimeout(5000);
//设置请求头字段
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 这个属性将被用于大文件传输,有效的提高效率
// connection.setRequestProperty("Content-Type","multipart/form-data");
//有相同的属性则覆盖
connection.setRequestProperty("user-agent", "Android 4.0.1");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
private void login() {
String concreteUrl = ":8080/phone_login";
HttpURLConnection connection = getUrlConnect(concreteUrl);
//构造json字符串,并发送
JSONStringer jsonStringer = new JSONStringer();
String transfer;
transfer = jsonStringer.object().key("email").value(email).key("password").value(password)
.endObject().toString();
System.out.println(transfer);
try {
connection.connect();
OutputStream writeToServer = connection.getOutputStream();
writeToServer.write(transfer.getBytes());
writeToServer.flush();
writeToServer.close();
// 取得输入流,并使用Reader读取
JSONObject serverInformation = Read.read(connection.getInputStream());
if (serverInformation.getString("isPassed").equals("no")) {//|| serverInformation.getString("server").equals("error")) {
sendMessage("password", "false");
}
if (serverInformation.getString("isPassed").equals("yes")) {
sendMessage("password", "true");
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SocketTimeoutException e) {
sendMessage("timeout", "yes");
//startActivity(new Intent(this, HomeActivity.class));
} catch (SocketException e) {
System.out.println("服务器没有打开!");
} catch (IOException e) {
e.printStackTrace();
}
//显示的Intent(意图)
//startActivity(new Intent(this, HomeActivity.class));
//测试从子活动中接收数据
// Intent info = new Intent(MainActivity.this, HomeActivity.class);
// info.putExtra("key","test content");
// startActivityForResult(info, 0);
// Uri str = Uri.parse("file:///*/.*\\.mp3");
// startActivity(new Intent().setDataAndType(str,"audio/mp3"));
// startActivity(new Intent(this, UserCenterActivity.class));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == 0) {
Toast.makeText(this, data.getStringExtra("key"), Toast.LENGTH_LONG).show();
}
}
private void sendMessage(String key, String value) {
Bundle data = new Bundle();
Message msg = new Message();
data.putString(key, value);
msg.setData(data);
handler.sendMessage(msg);
}
} | true |
e7ff13a3040715c93fb975aa6d72e740f783186a | Java | GitQian/MyProject | /elevator_mobile/trunk/ElevatorGuard_Mobile/src/com/chinacnit/elevatorguard/mobile/util/DBUtil.java | UTF-8 | 858 | 2.0625 | 2 | [] | no_license | package com.chinacnit.elevatorguard.mobile.util;
import com.chinacnit.elevatorguard.mobile.application.ElevatorGuardApplication;
import com.chinacnit.elevatorguard.mobile.config.Constants;
import com.lidroid.xutils.DbUtils;
public class DBUtil {
private static DBUtil sInstance;
private DbUtils mDbUtils;
private static final String DB_NAME = "EG.dat";
private static String DB_PATH = Constants.DEFAULT_STORAGE_PATH + "/" + Constants.DEFAULT_PROJECT_PATH;
public DBUtil() {
if (null == mDbUtils) {
mDbUtils = DbUtils.create(ElevatorGuardApplication.getInstance(), DB_PATH, DB_NAME);
mDbUtils.configAllowTransaction(true);
mDbUtils.configDebug(true);
}
}
public static DBUtil getInstance() {
if (null == sInstance) {
sInstance = new DBUtil();
}
return sInstance;
}
public DbUtils getDbUtils() {
return mDbUtils;
}
}
| true |
fc200e5973a8a7760ded34b12d77a9b623201c91 | Java | seenuwisdom/blog | /ws-soap-consumer/src/main/java/com/brunozambiazi/ws/publisher/HelloWebService.java | UTF-8 | 1,214 | 2.015625 | 2 | [] | no_license |
package com.brunozambiazi.ws.publisher;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.8
* Generated source version: 2.2
*
*/
@WebService(name = "HelloWebService", targetNamespace = "http://publisher.ws.brunozambiazi.com/")
@XmlSeeAlso({
ObjectFactory.class
})
public interface HelloWebService {
/**
*
* @param arg0
*/
@WebMethod
@RequestWrapper(localName = "print", targetNamespace = "http://publisher.ws.brunozambiazi.com/", className = "com.brunozambiazi.ws.publisher.Print")
@ResponseWrapper(localName = "printResponse", targetNamespace = "http://publisher.ws.brunozambiazi.com/", className = "com.brunozambiazi.ws.publisher.PrintResponse")
@Action(input = "http://publisher.ws.brunozambiazi.com/HelloWebService/printRequest", output = "http://publisher.ws.brunozambiazi.com/HelloWebService/printResponse")
public void print(
@WebParam(name = "arg0", targetNamespace = "")
String arg0);
}
| true |
c1692de0b1b30ef3bc4dfb4b25c1f1b05b043a0c | Java | TryLuthfi/HEUROIX | /app/src/main/java/heuroix/myapps/com/heuroix/activity/Register3.java | UTF-8 | 1,782 | 1.96875 | 2 | [] | no_license | package heuroix.myapps.com.heuroix.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import heuroix.myapps.com.heuroix.R;
public class Register3 extends AppCompatActivity {
private EditText email, alamat,notelp;
private ImageView buttonNext;
private String mPostKeyNama = null;
private String mPostKeyUsername = null;
private String mPostKeyPassword = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register3);
email = findViewById(R.id.email);
alamat = findViewById(R.id.alamat);
notelp = findViewById(R.id.notelp);
buttonNext = findViewById(R.id.buttonnext);
mPostKeyNama = getIntent().getExtras().getString("nama");
mPostKeyUsername = getIntent().getExtras().getString("username");
mPostKeyPassword = getIntent().getExtras().getString("password");
buttonNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Register3.this, Register4.class);
intent.putExtra("nama", mPostKeyNama);
intent.putExtra("username",mPostKeyUsername);
intent.putExtra("password", mPostKeyPassword);
intent.putExtra("email", email.getText().toString());
intent.putExtra("alamat", alamat.getText().toString());
intent.putExtra("notelp", notelp.getText().toString());
startActivity(intent);
}
});
}
}
| true |
5a85f068e1100e7b740e164c91c8546ab0ec2f01 | Java | JuanMalaga/BrisasBack | /src/main/java/etable/infrastructure/mesa/jdbc/MesaRowMapper.java | UTF-8 | 2,090 | 2.375 | 2 | [] | no_license | package etable.infrastructure.mesa.jdbc;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.tree.RowMapper;
import javax.swing.tree.TreePath;
import org.springframework.stereotype.Component;
import etable.domain.mesa.model.Mesa;
import etable.domain.mesa.model.MesaDTO;
@Component
public class MesaRowMapper implements RowMapper {
public List<Mesa> mapRowMesa(List<Map<String, Object>> rows){
List<Mesa> mesas = new ArrayList<Mesa>();
for(Map<String, Object> row: rows) {
int cmesa = Integer.parseInt(row.get("CMESA").toString());
int cperfilmesa = Integer.parseInt(row.get("CPERFILMESA").toString());
int cestadomesa = Integer.parseInt(row.get("CESTADOMESA").toString());
String nombreMesa = row.get("NOMBREMESA").toString();
Mesa i = new Mesa(cmesa,cperfilmesa,cestadomesa, nombreMesa);
mesas.add(i);
}
return mesas;
}
public List<Mesa> getMesa(List<Map<String, Object>> rows){
List<Mesa> mesas = new ArrayList<Mesa>();
for(Map<String, Object> row: rows) {
int cmesa = Integer.parseInt(row.get("CMESA").toString());
int cperfilmesa = Integer.parseInt(row.get("CPERFILMESA").toString());
int cestadomesa = Integer.parseInt(row.get("CESTADOMESA").toString());
String nombreMesa = row.get("NOMBREMESA").toString();
Mesa i = new Mesa(cmesa,cperfilmesa,cestadomesa, nombreMesa);
mesas.add(i);
}
return mesas;
}
public List<MesaDTO> mapRowMesaDTO(List<Map<String, Object>> rows){
List<MesaDTO> mesas = new ArrayList<MesaDTO>();
for(Map<String, Object> row: rows) {
int cmesa = Integer.parseInt(row.get("CMESA").toString());
String nombremesa =row.get("NOMBREMESA").toString();
String emdescripcion =row.get("EMDESCRIPCION").toString();
String pmnombre = row.get("PMNOMBRE").toString();
int pmcapacidad = Integer.parseInt(row.get("PMCAPACIDAD").toString());
MesaDTO i = new MesaDTO(cmesa,nombremesa, emdescripcion,pmnombre, pmcapacidad);
mesas.add(i);
}
return mesas;
}
@Override
public int[] getRowsForPaths(TreePath[] path) {
return new int[0];
}
}
| true |
783eb0f68ac0fe8c8a13aeea0c8bf98e9360a40f | Java | HildaFlores/CheckMobile | /app/src/main/java/com/example/prueba/CheckMobile/VehiculoModelo/Modelo.java | UTF-8 | 3,065 | 2.0625 | 2 | [] | no_license | package com.example.prueba.CheckMobile.VehiculoModelo;
/**
* Created by Prueba on 22-may-17.
*/
public class Modelo extends ModeloResponse {
private String id;
private String idMarca;
private String id_empresa;
private String descripcion;
private String estado;
private String fechaInsercion;
private String usuarioInsercion;
private String fechaActualizacion;
private String usuarioActualizacion;
private String idTipoVehiculo;
public Modelo(String idMarca, String descripcion) {
this.idMarca = idMarca;
this.descripcion = descripcion;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIdMarca() {
return idMarca;
}
public void setIdMarca(String idMarca) {
this.idMarca = idMarca;
}
public String getId_empresa() {
return id_empresa;
}
public void setId_empresa(String id_empresa) {
this.id_empresa = id_empresa;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getFechaInsercion() {
return fechaInsercion;
}
public void setFechaInsercion(String fechaInsercion) {
this.fechaInsercion = fechaInsercion;
}
public String getUsuarioInsercion() {
return usuarioInsercion;
}
public void setUsuarioInsercion(String usuarioInsercion) {
this.usuarioInsercion = usuarioInsercion;
}
public String getFechaActualizacion() {
return fechaActualizacion;
}
public void setFechaActualizacion(String fechaActualizacion) {
this.fechaActualizacion = fechaActualizacion;
}
public String getUsuarioActualizacion() {
return usuarioActualizacion;
}
public void setUsuarioActualizacion(String usuarioActualizacion) {
this.usuarioActualizacion = usuarioActualizacion;
}
public String getIdTipoVehiculo() {
return idTipoVehiculo;
}
public void setIdTipoVehiculo(String idTipoVehiculo) {
this.idTipoVehiculo = idTipoVehiculo;
}
@Override
public String toString() {
return "Modelo{" +
"id='" + id + '\'' +
", idMarca='" + idMarca + '\'' +
", id_empresa='" + id_empresa + '\'' +
", descripcion='" + descripcion + '\'' +
", estado='" + estado + '\'' +
", fechaInsercion='" + fechaInsercion + '\'' +
", usuarioInsercion='" + usuarioInsercion + '\'' +
", fechaActualizacion='" + fechaActualizacion + '\'' +
", usuarioActualizacion='" + usuarioActualizacion + '\'' +
", idTipoVehiculo='" + idTipoVehiculo + '\'' +
'}';
}
}
| true |
f1cc6a4fe0ffb7362988d9207c82dc278819fe79 | Java | Barengific/Zazium | /J/src/main/java/TTest/TestConve.java | UTF-8 | 2,225 | 2.453125 | 2 | [] | no_license | package TTest;
import Misc.Checksums;
import Uses.Usermain;
import java.util.ArrayList;
import java.util.Random;
public class TestConve {
public static ArrayList generateEntropy(){
ArrayList<Integer> entropy1 = new ArrayList();
ArrayList<Integer> entropy2 = new ArrayList();
ArrayList<Integer> entropy3 = new ArrayList();
ArrayList<Integer> entropy4 = new ArrayList();
int min = 0;
int max = 1;
String entropyString = "";
String checksumVal = "";
for (int i = 0; i < 32; i++) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
entropy1.add(randomNum);
entropyString += Integer.toString(randomNum);
}
checksumVal += Integer.toString(Checksums.checksumz(entropy1));
for (int i = 0; i < 32; i++) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
entropy2.add(randomNum);
entropyString += Integer.toString(randomNum);
}
checksumVal += Integer.toString(Checksums.checksumz(entropy2));
for (int i = 0; i < 32; i++) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
entropy3.add(randomNum);
entropyString += Integer.toString(randomNum);
}
checksumVal += Integer.toString(Checksums.checksumz(entropy3));
for (int i = 0; i < 32; i++) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
entropy4.add(randomNum);
entropyString += Integer.toString(randomNum);
}
checksumVal += Integer.toString(Checksums.checksumz(entropy4));
String entropy = entropyString+checksumVal;
//b64Encode(entropy);
//String aa = Base64.encodeBase64String(entropy.getBytes());
//System.out.println("bas54: " + aa);
return Usermain.seed_phrase(entropy);
}
public static ArrayList<String> generateKeypair() throws Exception {
//System.out.println(generateEntropy());
return generateEntropy();
}
}
| true |
db9dfb40bae6bcdd26bd26c28ee24b3573d176ba | Java | lenka123123/jy | /commonlib/src/main/java/com/mcxtzhang/swipemenulib/customview/listdialog/MyAdapter.java | UTF-8 | 1,918 | 2.578125 | 3 | [] | no_license | package com.mcxtzhang.swipemenulib.customview.listdialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.mcxtzhang.swipemenulib.R;
import java.util.List;
public class MyAdapter extends BaseAdapter {
private List<String> fruitList;
Context context;
//从构造函数中获取fruitList和Context对象.
public MyAdapter(List<String> fruitList, Context context)
{
this.fruitList = fruitList;
this.context = context;
}
public int getCount()
{
return fruitList.size();
}
public Object getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return 0;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View v;
ViewHolder holder;
//滑入ListView中的item view没有缓存
if(convertView == null)
{
v = LayoutInflater.from(context).inflate(R.layout.activity_list_dialog_item, null);//动态加载滑入ListView的item的子布局文件,并绘制item view
/* 缓存子布局文件中的控件对象*/
holder = new ViewHolder();
holder.fruitName = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
}
//滑入ListView中的item view有缓存
else
{
v = convertView; //取出缓存的item View对象
holder = (ViewHolder)v.getTag(); //重新获取ViewHolder对象
}
holder.fruitName.setText(fruitList.get(position)); //设置fruitName
return v;
}
/* 定义ViewHolder用来缓存item view控件 */
class ViewHolder
{
TextView fruitName;
}
}
| true |
98c82559668f2305d785959bda0429273b77374a | Java | rhegishte27/dca | /backend/src/main/java/com/equisoft/dca/backend/project/dao/ProjectRepository.java | UTF-8 | 1,101 | 1.757813 | 2 | [] | no_license | package com.equisoft.dca.backend.project.dao;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.equisoft.dca.backend.project.model.Project;
@Repository
public interface ProjectRepository extends JpaRepository<Project, Integer> {
Optional<Project> findByIdentifier(String identifier);
@Query(value = "select DISTINCT(p.Identifier) from projectsyncsettings pss join projects p on p.PK_Projects = pss.FK_Projects "
+ "where pss.fk_locations = :locationId", nativeQuery = true)
List<String> findLocationInProjectSyncSettings(@Param("locationId") int locationId);
@Query(value = "select DISTINCT(p.Identifier) from projectsystems ps join projects p on p.PK_Projects = ps.FK_Projects "
+ "where ps.fk_locations = :locationId", nativeQuery = true)
List<String> findLocationInProjectSystems(@Param("locationId") int locationId);
}
| true |
c7ad4fe959aa4fa5e5a6ad514869fa1b3c32f081 | Java | s3nd3r5/padlock-cli | /src/main/java/main/CommandLineMain.java | UTF-8 | 1,630 | 2.734375 | 3 | [] | no_license | package main;
import cli.CommandLineRunner;
import main.params.MainCLIParameter;
import java.util.Arrays;
public class CommandLineMain {
public static void main(String[] args) {
try{
if(null == args || args.length < 1){
System.out.println(MainCLIParameter.getUsage());
System.exit(-1);
}
MainCLIParameter mainParam = MainCLIParameter.valueOf(args[0].toLowerCase());
if(args.length > 1){
args = Arrays.copyOfRange(args,1,args.length);
}
switch(mainParam){
case get:{
CommandLineRunner.get(args);
break;
}
case update:{
CommandLineRunner.update(args);
break;
}
case change:{
CommandLineRunner.change(args);
break;
}
case remove:{
CommandLineRunner.remove(args);
break;
}
case add:{
CommandLineRunner.add(args);
break;
}
case generate:{
CommandLineRunner.generate(args);
break;
}
default: System.out.println(MainCLIParameter.getUsage());
}
}catch(Exception e){
System.out.println("Unable to process arguments: " + Arrays.toString(args));
System.out.println(MainCLIParameter.getUsage());
}
}
}
| true |
9f07b7e8086f1d1ebbf89eaabdff92f8e0a49812 | Java | kamil-olejniczak/ClientDatabase | /src/main/java/com/company/controller/ClientRestController.java | UTF-8 | 3,994 | 2.25 | 2 | [] | no_license | package com.company.controller;
import com.company.model.Client;
import com.company.service.ClientService;
import com.company.util.LocalizedMessages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import static com.company.util.Mappings.*;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
@RestController
@RequestMapping(REST_API_PREFIX)
public class ClientRestController {
private final String clientSuccessfullyRemoved = "clientSuccessfullyRemoved";
private final String clientNotFound = "clientNotFound";
private final String clientSuccessfullyEdited = "clientSuccessfullyEdited";
private final ClientService clientService;
private final LocalizedMessages localizedMessages;
@Autowired
public ClientRestController(ClientService clientService, LocalizedMessages localizedMessages) {
this.clientService = clientService;
this.localizedMessages = localizedMessages;
}
@GetMapping(value = REST_GET_ALL_CLIENTS, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Client[]> getAllClients() {
Client[] clients = clientService.getAllClientsAsArray();
return new ResponseEntity<>(clients, OK);
}
@GetMapping(value = REST_GET_CLIENT, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Client> getClient(@RequestParam long id, HttpServletRequest request) {
Client client = clientService.findClientById(id, request);
return new ResponseEntity<>(client, OK);
}
//Passing a request with a body to an HTTP DELETE action is not currently supported in Angular 2
@PostMapping(value = REST_DELETE_CLIENT, consumes = APPLICATION_JSON_UTF8_VALUE,
produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> deleteClient(@Valid @RequestBody Client client, HttpServletRequest request) {
clientService.deleteClient(client.getId(), request);
return new ResponseEntity<>(localizedMessages.getMessage(clientSuccessfullyRemoved), OK);
}
@PutMapping(value = REST_UPDATE_CLIENT, consumes = APPLICATION_JSON_UTF8_VALUE,
produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> updateClient(@Valid @RequestBody Client clientEditData, BindingResult result,
HttpServletRequest request) {
if (result.hasErrors()) {
return new ResponseEntity<>(localizedMessages.getMessage(clientNotFound), UNPROCESSABLE_ENTITY);
}
clientService.updateClient(clientEditData, request);
return new ResponseEntity<>(localizedMessages.getMessage(clientSuccessfullyEdited), OK);
}
@PostMapping(value = REST_SAVE_NEW_CLIENT, consumes = APPLICATION_JSON_UTF8_VALUE,
produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Long> processAddNewClient(@Valid @RequestBody Client newClient, BindingResult result,
HttpServletRequest request) {
if (result.hasErrors()) {
return new ResponseEntity<>(ID_NOT_FOUND, UNPROCESSABLE_ENTITY);
}
clientService.saveClient(newClient, request);
return new ResponseEntity<>(newClient.getId(), OK);
}
}
| true |
f75f69e369a4d6716ea6fa0e091aeb57d051f934 | Java | ghousseyn/DzBac-Android | /app/src/main/java/com/squalala/dzbac/ui/list_followers/ListFollowerView.java | UTF-8 | 318 | 1.710938 | 2 | [
"MIT"
] | permissive | package com.squalala.dzbac.ui.list_followers;
import java.util.ArrayList;
import it.gmariotti.cardslib.library.internal.Card;
/**
* Created by Back Packer
* Date : 24/09/15
*/
public interface ListFollowerView {
void displayListUsers(ArrayList<Card> cards);
void initScrollDown();
void clearCards();
}
| true |