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
6e946fa74ae65722af2763ecc0cc4956e96d8a44
Java
nipunthathsara/wso2-security-question-client
/org.wso2.challenge.question.metadata.migration.client/src/main/java/org/wso2/recovery/client/util/AuthenticationServiceClient.java
UTF-8
2,459
1.984375
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.recovery.client.util; import org.apache.axis2.AxisFault; import org.apache.axis2.context.ServiceContext; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.log4j.Logger; import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub; import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException; import org.wso2.carbon.authenticator.stub.LogoutAuthenticationExceptionException; import java.rmi.RemoteException; /** * This class provides functionality to authenticate the tenant admin to use the stub. */ public class AuthenticationServiceClient { private final static Logger log = Logger.getLogger(AuthenticationServiceClient.class); private static AuthenticationAdminStub authenticationAdminStub; public AuthenticationServiceClient(String serviceUrl) throws AxisFault { authenticationAdminStub = new AuthenticationAdminStub(serviceUrl); } public String authenticate(String userName, String password, String tenant) throws RemoteException, LoginAuthenticationExceptionException { //TODO what is localhost here if (authenticationAdminStub.login(userName, password, "localhost")) { log.info("Successfully authenticated for tenant : " + tenant); ServiceContext serviceContext = authenticationAdminStub. _getServiceClient().getLastOperationContext().getServiceContext(); return (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING); } else { log.error("Authentication failure for tenant : " + tenant); return null; } } public void logOut() throws RemoteException, LogoutAuthenticationExceptionException { authenticationAdminStub.logout(); } }
true
dc9d35766c03fda4cc918321d6cd165d1c968b3c
Java
DarkStorm652/DarkMod
/src/org/darkstorm/tools/events/EventSender.java
UTF-8
1,125
3.125
3
[]
no_license
package org.darkstorm.tools.events; import java.util.ArrayList; class EventSender { private ArrayList<EventListener> listeners; private Class<? extends Event> listenerEventClass; private Object listenersLock; public EventSender(Class<? extends Event> listenerEventClass) { listeners = new ArrayList<EventListener>(); this.listenerEventClass = listenerEventClass; listenersLock = new Object(); } public boolean addListener(EventListener listener) { synchronized(listenersLock) { return listeners.add(listener); } } public boolean removeListener(EventListener listener) { synchronized(listenersLock) { return listeners.remove(listener); } } public EventListener[] getListeners() { return listeners.toArray(new EventListener[listeners.size()]); } public void sendEvent(Event event) { synchronized(listenersLock) { Class<?> eventClass = event.getClass(); if(eventClass.isAssignableFrom(listenerEventClass)) for(EventListener listener : listeners) listener.onEvent(event); } } public Class<? extends Event> getListenerEventClass() { return listenerEventClass; } }
true
0e0cd57887a90d045718be14af9261a1c849a322
Java
abigailz/2014-2015
/diplomaProject/tsv_android_20150318/src/com/tsv/activity/ListActivity.java
UTF-8
4,213
2.421875
2
[]
no_license
package com.tsv.activity; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.os.Bundle; import android.view.View; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.tsv.R; import com.tsv.model.db.Question; public class ListActivity extends BaseActivity { private SimpleAdapter adapter; private List<HashMap<String, Object>> data; private int count = 30; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list); // service = new PersonService(this); ListView listView = (ListView) this.findViewById(R.id.listView); // 获取到集合数据 // List<Person> persons = service.getScrollData(0, 10); // List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); // for (Person person : persons) { // HashMap<String, Object> item = new HashMap<String, Object>(); // item.put("id", person.getId()); // item.put("name", person.getName()); // item.put("phone", person.getPhone()); // item.put("amount", person.getAmount()); // data.add(item); // } List<Question> list = new ArrayList<Question>(); for(int i = 0;i< 30;i++){ Question q = new Question(); q.setQid(""+i); q.setTitle("title"+i); q.setCreateTime(System.currentTimeMillis()); q.setState(1); list.add(q); } data = new ArrayList<HashMap<String,Object>>(); for(Question ques : list){ HashMap<String, Object> item = new HashMap<String, Object>(); item.put("qid", ques.getQid()); item.put("question", ques.getTitle()); item.put("time", ques.getCreateTime()); item.put("state", ques.getState()); data.add(item); } // 创建SimpleAdapter适配器将数据绑定到item显示控件上 adapter = new SimpleAdapter(this, data, R.layout.list_item, new String[] { "question", "time", "state" }, new int[] { R.id.txQuestion, R.id.txTime, R.id.txState }); // 实现列表的显示 listView.setAdapter(adapter); // 条目点击事件 listView.setOnItemClickListener(new ItemClickListener()); listView.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub System.out.println("onScrollStateChanged"); int num = adapter.getCount(); if(num > 300){ return; } List<Question> list = new ArrayList<Question>(); for(int i = 0;i< 30;i++){ Question q = new Question(); q.setQid(""+i); q.setTitle("title"+i); q.setCreateTime(System.currentTimeMillis()); q.setState(1); list.add(q); } for(Question ques : list){ HashMap<String, Object> item = new HashMap<String, Object>(); item.put("qid", ques.getQid()); item.put("question", ques.getTitle()); item.put("time", ques.getCreateTime()); item.put("state", ques.getState()); data.add(item); } // adapter. = data; adapter.notifyDataSetChanged(); //Toast.makeText(TestAdapter.this, "正在刷新", Toast.LENGTH_SHORT).show(); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { System.out.println("onScroll"); } }); } private class ItemClickListener implements OnItemClickListener{ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ListView listView = (ListView) parent; @SuppressWarnings("unchecked") HashMap<String, Object> data = (HashMap<String, Object>) listView.getItemAtPosition(position); String qid = data.get("qid").toString(); Toast.makeText(getApplicationContext(), qid, 1).show(); } } }
true
43ea4d45f1c8d30db48b39b1dc35ab346c29ae93
Java
turbolent/lila
/src/java/lila/runtime/dispatch/predicate/Case.java
UTF-8
866
2.484375
2
[ "MIT" ]
permissive
package lila.runtime.dispatch.predicate; import java.util.LinkedHashSet; import java.util.Set; import lila.runtime.Expression; public class Case { public Predicate conjunction; public Set<Method> methods = new LinkedHashSet<>(); public Case(Predicate conjunction) { this.conjunction = conjunction; } // NOTE: constraint calculation depends on order: // LinkedHashMap keeps order LinkedHashSet<Expression> getExpressions() { LinkedHashSet<Expression> result = new LinkedHashSet<>(); for (Predicate atom : this.conjunction.getAtoms()) result.add(((TypePredicate)atom).expression); return result; } Set<Predicate> getAtoms() { return conjunction.getAtoms(); } @Override public String toString() { return String.format("%s%s", this.conjunction, this.methods); } // Debugging String name = "c" + ids++; static int ids = 1; }
true
0a5325b7237c9d623fb58f21ce50979ff692e6cc
Java
javers/javers
/javers-core/src/main/java/org/javers/core/metamodel/type/PrimitiveOrValueType.java
UTF-8
2,048
2.59375
3
[ "Apache-2.0" ]
permissive
package org.javers.core.metamodel.type; import org.javers.common.collections.Primitives; import org.javers.common.string.PrettyPrintBuilder; import org.javers.core.diff.custom.CustomValueComparator; import java.lang.reflect.Type; /** * @author bartosz walacik */ public abstract class PrimitiveOrValueType<T> extends ClassType implements CustomComparableType { private final CustomValueComparator<T> valueComparator; @Override public boolean hasCustomValueComparator() { return valueComparator != null; } PrimitiveOrValueType(Type baseJavaType) { this(baseJavaType, null); } PrimitiveOrValueType(Type baseJavaType, CustomValueComparator<T> comparator) { super(baseJavaType); this.valueComparator = (comparator == null || comparator.handlesNulls()) ? comparator : new CustomValueComparatorNullSafe<>(comparator); } @Override public boolean equals(Object left, Object right) { if (valueComparator != null) { return valueComparator.equals((T)left, (T)right); } return super.equals(left, right); } public boolean isNumber() { return Number.class.isAssignableFrom(getBaseJavaClass()) || Primitives.isPrimitiveNumber(getBaseJavaClass()); } public boolean isBoolean() { return Boolean.class == getBaseJavaClass() || boolean.class == getBaseJavaClass(); } public boolean isStringy() { return String.class == getBaseJavaClass() || CharSequence.class == getBaseJavaClass() || char.class == getBaseJavaClass() || Character.class == getBaseJavaClass(); } public boolean isJsonPrimitive() { return isStringy() || isBoolean() || isNumber(); } CustomValueComparator getValueComparator() { return valueComparator; } @Override protected PrettyPrintBuilder prettyPrintBuilder() { return super.prettyPrintBuilder().addField("valueComparator", valueComparator); } }
true
bdfa4d70739d6b5dd2fe763aadff6553b7855ed7
Java
muxanasov/ConesC
/src/tests/ConfigurationTest.java
UTF-8
1,843
2.5
2
[]
no_license
package tests; import static org.junit.Assert.*; import java.io.File; import org.junit.After; import org.junit.Before; import org.junit.Test; import core.Component; import core.Configuration; import core.FileManager; public class ConfigurationTest { String TEST_CNC = "configuration DemoAppC { }\n" + "implementation {\n" + " context groups\n" + " Temperature;\n" + " components\n" + " MainC,\n" + " DemoC,\n" + " new TimerMilliC();\n" + " DemoC.Temperature -> Temperature;\n" + " DemoC.Boot -> MainC;\n" + " DemoC.Timer -> TimerMilliC;\n" + "}"; String TEST_CONF_CNC = "context configuration Temperature { }\n" + "implementation {\n" + "}"; @Before public void setUp() throws Exception { FileManager.fwrite("DemoAppC.cnc", TEST_CNC); FileManager.fwrite("Temperature.cnc", TEST_CONF_CNC); String makeFile = "COMPONENT = DemoAppC\n" + "PFLAGS += -I ./interfaces -I ./\n" + "include $(MAKERULES)\n"; FileManager.fwrite("Makefile", makeFile); } @After public void tearDown() throws Exception { File app = new File ("DemoAppC.cnc"); app.delete(); File temperature = new File ("Temperature.cnc"); temperature.delete(); File makefile = new File ("Makefile"); makefile.delete(); } @Test public void test() { String test_nc = "configuration DemoAppC {\n" + "}\n" + "implementation {\n" + " components\n" + " TemperatureConfiguration,\n" + " MainC,\n" + " DemoC,\n" + " new TimerMilliC();\n" + " DemoC.TemperatureGroup -> TemperatureConfiguration;\n" + " DemoC.Boot -> MainC;\n" + " DemoC.Timer -> TimerMilliC;\n" + "}"; FileManager fm = new FileManager(); Component conf = fm.getMainComponent(); conf.build(); assertEquals(test_nc, conf.getGeneratedFiles().get("DemoAppC.nc")); } }
true
fb14ba8a3de2ae9e4e8281c026a387f443a5c95d
Java
Joels5563/IPX
/Agent/app/src/main/java/com/ipx/agent/net/parser/StringParser.java
UTF-8
521
2.34375
2
[]
no_license
package com.ipx.agent.net.parser; import com.ipx.agent.net.ResponseParser; import java.io.IOException; import okhttp3.Response; /** * 图片解析器 * * @author joels on 2017/8/18 **/ public class StringParser implements ResponseParser<String> { @Override public String parseResponse(Response response) { String result = ""; try { result = response.body().string(); } catch (IOException e) { e.printStackTrace(); } return result; } }
true
34b4b44c2bf335ab0c9e07f26d8cbd866e889459
Java
AbhayKS007/cosyapp
/app/src/main/java/co/project/cosy/StudioListHome.java
UTF-8
8,987
1.789063
2
[]
no_license
package co.project.cosy; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RatingBar; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import co.project.cosy.Constant.Constant; import co.project.cosy.WebService.WE_GetTimeSloat; import co.project.cosy.configuration.Configuration; import me.anwarshahriar.calligrapher.Calligrapher; public class StudioListHome extends AppCompatActivity implements OnMapReadyCallback { AdapterPassbook adapterForDownload; private GoogleMap mMap; private GoogleApiClient mGoogleApiClient; RecyclerView myList; String stetus; Dialog Loader; String studioID; String studioType; JSONObject jsonnn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_studio_list_home); Calligrapher calligrapher=new Calligrapher(this); calligrapher.setFont(this,"Ubuntu-L.ttf",true); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationIcon(R.drawable.miku_back); toolbar.setTitle(" "); setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //startActivity(new Intent(getApplicationContext(),drawer.class)); onBackPressed(); } }); stetus = "studio";//getIntent().getExtras().getString("stetus","defaultKey"); SendDateWebServiceCall(); myList=(RecyclerView)findViewById(R.id.studio_page_recyclerview); myList.setHasFixedSize(true); LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext()); llm.setOrientation(LinearLayoutManager.VERTICAL); myList.setLayoutManager(llm); } public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); MarkerOptions options = new MarkerOptions(); ArrayList<LatLng> latlngs = new ArrayList<>(); // for(int i =0; i<Constant.latitude.size();i++) // { // latlngs.add(new LatLng(Double.parseDouble(Constant.latitude.get(i)),Double.parseDouble(Constant.longitude.get(i)))); // // createMarker(Double.parseDouble(Constant.latitude.get(i)),Double.parseDouble(Constant.longitude.get(i))); // // } //some latitude and logitude value // // for (LatLng point : latlngs) { // options.position(point); // options.title("Studio Location"); // mMap.addMarker(options); // } LatLng newdelhi = new LatLng(28.489638,77.055884); mMap.addMarker(new MarkerOptions().position(newdelhi).title("Studio Location")); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(28.489638, 77.055884), 14.0f)); mMap.moveCamera(CameraUpdateFactory.newLatLng(newdelhi)); } protected Marker createMarker(double latitude, double longitude) { return mMap.addMarker(new MarkerOptions() .position(new LatLng(latitude, longitude)) .anchor(0.5f, 0.5f) .title("Studio List") .icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon))); } public void SendDateWebServiceCall() { if (Configuration.isInternetConnection(getApplicationContext())) { //String userID = Configuration.getSharedPrefrenceValue(getApplicationContext(), Constant.USER_ID); String jsonData = toJSon3(stetus); new GET_DATA3().execute(jsonData); } else { Intent intent = new Intent(getApplicationContext(), ErrorScreen.class); startActivity(intent); } } public static String toJSon3(String userid) { try { // Here we convert Java Object to JSON JSONObject jsonObj = new JSONObject(); jsonObj.put("type", userid); return jsonObj.toString(); } catch (JSONException ex) { ex.printStackTrace(); } return null; } private class GET_DATA3 extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { NamePopUp(); } @Override protected String doInBackground(String... params) { WE_GetTimeSloat selectArea = new WE_GetTimeSloat(); String result = selectArea.sendDetail(getApplicationContext(), params[0]); return result; } @Override protected void onPostExecute(String s) { try { if (s.equalsIgnoreCase("success")) { SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.studio); mapFragment.getMapAsync(StudioListHome.this); adapterForDownload=new AdapterPassbook(getApplicationContext()); myList.setAdapter(adapterForDownload); } else { } } catch (Exception e) { e.printStackTrace(); } finally { Loader.dismiss(); } } } public void NamePopUp() { Loader = new Dialog(StudioListHome.this, android.R.style.Theme_Translucent_NoTitleBar); Loader.setContentView(R.layout.loder); Loader.show(); } public class AdapterPassbook extends RecyclerView.Adapter<AdapterPassbook.ViewHolder> { Context mContext; String cityName,activityName; public AdapterPassbook(Context context) { this.mContext = context; } // 3 public class ViewHolder extends RecyclerView.ViewHolder { ImageView imageblanck,imagered; TextView name,address,phone; LinearLayout main_layout; RatingBar simpleRatingBar; public ViewHolder(View itemView) { super(itemView); name = itemView.findViewById(R.id.name); address = itemView.findViewById(R.id.address); phone = itemView.findViewById(R.id.phone); simpleRatingBar = itemView.findViewById(R.id.simpleRatingBar); main_layout = itemView.findViewById(R.id.main_layout); } } @Override public int getItemCount() { int i=0; try{ i= Constant.studioID_list.size(); } catch (Exception e) { i=0; e.printStackTrace(); } return i; } @Override public AdapterPassbook.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_list, parent, false); return new AdapterPassbook.ViewHolder(view); } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return position; } @Override public void onBindViewHolder(final AdapterPassbook.ViewHolder holder, final int position) { try { holder.name.setText(Constant.name_list.get(position)); holder.address.setText(Constant.address_list.get(position)); holder.phone.setText(Constant.contact.get(position)); holder.simpleRatingBar.setRating(Float.parseFloat(Constant.review_list.get(position))); } catch (Exception e) { e.printStackTrace(); } } } }
true
127bde88029fd66f50cf0553a8a12230ae078830
Java
bazzceeh/Pixelmon
/minecraft/pixelmon/battles/attacks/specialAttacks/modifiers/ModifierBase.java
UTF-8
239
2.390625
2
[]
no_license
package pixelmon.battles.attacks.specialAttacks.modifiers; public abstract class ModifierBase { public ModifierType type; public float value; public float value2; public ModifierBase(ModifierType type){ this.type = type; } }
true
2d6d016c076cb3c9cd5e6a8c87823032f43621ad
Java
cinchapi/ccl
/src/test/java/com/cinchapi/ccl/JavaCCParserLogicTest.java
UTF-8
63,056
2.0625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2013-2017 Cinchapi Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cinchapi.ccl; import com.cinchapi.ccl.grammar.ConjunctionSymbol; import com.cinchapi.ccl.grammar.ExpressionSymbol; import com.cinchapi.ccl.grammar.FunctionKeySymbol; import com.cinchapi.ccl.grammar.FunctionValueSymbol; import com.cinchapi.ccl.grammar.OperatorSymbol; import com.cinchapi.ccl.grammar.ParenthesisSymbol; import com.cinchapi.ccl.grammar.PostfixNotationSymbol; import com.cinchapi.ccl.grammar.ValueSymbol; import com.cinchapi.ccl.grammar.KeySymbol; import com.cinchapi.ccl.grammar.Symbol; import com.cinchapi.ccl.syntax.AbstractSyntaxTree; import com.cinchapi.ccl.syntax.AndTree; import com.cinchapi.ccl.syntax.ConjunctionTree; import com.cinchapi.ccl.syntax.ExpressionTree; import com.cinchapi.ccl.syntax.OrTree; import com.cinchapi.ccl.type.Operator; import com.cinchapi.ccl.type.function.IndexFunction; import com.cinchapi.ccl.type.function.KeyConditionFunction; import com.cinchapi.ccl.type.function.KeyRecordsFunction; import com.cinchapi.ccl.type.function.ImplicitKeyRecordFunction; import com.cinchapi.concourse.Tag; import com.cinchapi.concourse.lang.Criteria; import com.cinchapi.concourse.util.Convert; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import org.junit.Assert; import org.junit.Test; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.function.Function; /** * Tests for {@link JavaCCParser}. * * These tests include utput tests (postfix, abstract * syntax tree, tokens) * * @deprecated Replaced by {@link CompilerJavaCCLogicTest} */ @Deprecated public class JavaCCParserLogicTest { @Test public void testSingleExpressionTokenize() { String ccl = "a = 1"; // Build expected queue List<Object> expectedTokens = Lists.newArrayList(); expectedTokens.add(new KeySymbol("a")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("1"))); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); List<Symbol> tokens = parser.tokenize(); Assert.assertEquals(expectedTokens, tokens); } @Test public void testSingleBinaryExpressionTokenize() { String ccl = "a >< 1 3"; // Build expected queue List<Object> expectedTokens = Lists.newArrayList(); expectedTokens.add(new KeySymbol("a")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("><"))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("1"))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("3"))); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); List<Symbol> tokens = parser.tokenize(); Assert.assertEquals(expectedTokens, tokens); } @Test public void testSingleNRegexExpressionTokenize() { String ccl = "name nregex (?i:%jeff%)"; // Build expected queue List<Object> expectedTokens = Lists.newArrayList(); expectedTokens.add(new KeySymbol("name")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("nregex"))); expectedTokens.add(new ValueSymbol( PARSER_TRANSFORM_VALUE_FUNCTION.apply("(?i:%jeff%)"))); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); List<Symbol> tokens = parser.tokenize(); Assert.assertEquals(expectedTokens, tokens); } @Test public void testSingleLikeExpressionTokenize() { String ccl = "name like (?i:%jeff%)"; // Build expected queue List<Object> expectedTokens = Lists.newArrayList(); expectedTokens.add(new KeySymbol("name")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("like"))); expectedTokens.add(new ValueSymbol( PARSER_TRANSFORM_VALUE_FUNCTION.apply("(?i:%jeff%)"))); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); List<Symbol> tokens = parser.tokenize(); Assert.assertEquals(expectedTokens, tokens); } @Test public void testSingleConjunctionTokenize() { String ccl = "a = 1 and b = 2"; // Build expected queue List<Symbol> expectedTokens = Lists.newArrayList(); expectedTokens.add(new KeySymbol("a")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("1"))); expectedTokens.add(ConjunctionSymbol.AND); expectedTokens.add(new KeySymbol("b")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2"))); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); List<Symbol> tokens = parser.tokenize(); Assert.assertEquals(expectedTokens, tokens); } @Test public void testSingleDisjunctionTokenize() { String ccl = "a = 1 or b = 2"; // Build expected queue List<Symbol> expectedTokens = Lists.newArrayList(); expectedTokens.add(new KeySymbol("a")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("1"))); expectedTokens.add(ConjunctionSymbol.OR); expectedTokens.add(new KeySymbol("b")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2"))); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); List<Symbol> tokens = parser.tokenize(); Assert.assertEquals(expectedTokens, tokens); } @Test public void testDoubleConjunctionTokenize() { String ccl = "a = 1 and b = 2 and c = 3"; // Build expected queue List<Symbol> expectedTokens = Lists.newArrayList(); expectedTokens.add(new KeySymbol("a")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("1"))); expectedTokens.add(ConjunctionSymbol.AND); expectedTokens.add(new KeySymbol("b")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2"))); expectedTokens.add(ConjunctionSymbol.AND); expectedTokens.add(new KeySymbol("c")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("3"))); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); List<Symbol> tokens = parser.tokenize(); Assert.assertEquals(expectedTokens, tokens); } @Test public void testDoubleDisjunctionTokenize() { String ccl = "a = 1 or b = 2 or c = 3"; // Build expected queue List<Symbol> expectedTokens = Lists.newArrayList(); expectedTokens.add(new KeySymbol("a")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("1"))); expectedTokens.add(ConjunctionSymbol.OR); expectedTokens.add(new KeySymbol("b")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2"))); expectedTokens.add(ConjunctionSymbol.OR); expectedTokens.add(new KeySymbol("c")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("3"))); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); List<Symbol> tokens = parser.tokenize(); Assert.assertEquals(expectedTokens, tokens); } @Test public void testConjunctionDisjunctionTokenize() { String ccl = "a = 1 and b = 2 or c = 3"; // Build expected queue List<Symbol> expectedTokens = Lists.newArrayList(); expectedTokens.add(new KeySymbol("a")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("1"))); expectedTokens.add(ConjunctionSymbol.AND); expectedTokens.add(new KeySymbol("b")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2"))); expectedTokens.add(ConjunctionSymbol.OR); expectedTokens.add(new KeySymbol("c")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("3"))); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); List<Symbol> tokens = parser.tokenize(); Assert.assertEquals(expectedTokens, tokens); } @Test public void testDisjunctionConjunctionTokenize() { String ccl = "a = 1 or b = 2 and c = 3"; // Build expected queue List<Symbol> expectedTokens = Lists.newArrayList(); expectedTokens.add(new KeySymbol("a")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("1"))); expectedTokens.add(ConjunctionSymbol.OR); expectedTokens.add(new KeySymbol("b")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2"))); expectedTokens.add(ConjunctionSymbol.AND); expectedTokens.add(new KeySymbol("c")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("3"))); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); List<Symbol> tokens = parser.tokenize(); Assert.assertEquals(expectedTokens, tokens); } @Test public void testDisjunctionParenthesizedConjunctionTokenize() { String ccl = "a = 1 and (b = 2 or c = 3)"; // Build expected queue List<Symbol> expectedTokens = Lists.newArrayList(); expectedTokens.add(new KeySymbol("a")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("1"))); expectedTokens.add(ConjunctionSymbol.AND); expectedTokens.add(ParenthesisSymbol.LEFT); expectedTokens.add(new KeySymbol("b")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2"))); expectedTokens.add(ConjunctionSymbol.OR); expectedTokens.add(new KeySymbol("c")); expectedTokens.add(new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("="))); expectedTokens.add( new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("3"))); expectedTokens.add(ParenthesisSymbol.RIGHT); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); List<Symbol> tokens = parser.tokenize(); Assert.assertEquals(expectedTokens, tokens); } @Test public void testSingleConjunctionPostFix() { String ccl = "a = 1 and b = 2"; // Build expected queue Queue<PostfixNotationSymbol> expectedOrder = new LinkedList<>(); KeySymbol key = new KeySymbol("a"); OperatorSymbol operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); ValueSymbol value = new ValueSymbol( PARSER_TRANSFORM_VALUE_FUNCTION.apply("1")); ExpressionSymbol expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); key = new KeySymbol("b"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); expectedOrder.add(ConjunctionSymbol.AND); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); Queue<PostfixNotationSymbol> order = parser.order(); Assert.assertEquals(expectedOrder, order); } @Test public void testSingleDisjunctionPostFix() { String ccl = "a = 1 or b = 2"; // Build expected queue Queue<PostfixNotationSymbol> expectedOrder = new LinkedList<>(); KeySymbol key = new KeySymbol("a"); OperatorSymbol operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); ValueSymbol value = new ValueSymbol( PARSER_TRANSFORM_VALUE_FUNCTION.apply("1")); ExpressionSymbol expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); key = new KeySymbol("b"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); expectedOrder.add(ConjunctionSymbol.OR); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); Queue<PostfixNotationSymbol> order = parser.order(); Assert.assertEquals(expectedOrder, order); } @Test public void testDoubleConjunctionPostFix() { String ccl = "a = 1 and b = 2 and c = 3"; // Build expected queue Queue<PostfixNotationSymbol> expectedOrder = new LinkedList<>(); KeySymbol key = new KeySymbol("a"); OperatorSymbol operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); ValueSymbol value = new ValueSymbol( PARSER_TRANSFORM_VALUE_FUNCTION.apply("1")); ExpressionSymbol expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); key = new KeySymbol("b"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); expectedOrder.add(ConjunctionSymbol.AND); key = new KeySymbol("c"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("3")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); expectedOrder.add(ConjunctionSymbol.AND); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); Queue<PostfixNotationSymbol> order = parser.order(); Assert.assertEquals(expectedOrder, order); } @Test public void testDoubleDisjunctionPostFix() { String ccl = "a = 1 or b = 2 or c = 3"; // Build expected queue Queue<PostfixNotationSymbol> expectedOrder = new LinkedList<>(); KeySymbol key = new KeySymbol("a"); OperatorSymbol operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); ValueSymbol value = new ValueSymbol( PARSER_TRANSFORM_VALUE_FUNCTION.apply("1")); ExpressionSymbol expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); key = new KeySymbol("b"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); expectedOrder.add(ConjunctionSymbol.OR); key = new KeySymbol("c"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("3")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); expectedOrder.add(ConjunctionSymbol.OR); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); Queue<PostfixNotationSymbol> order = parser.order(); Assert.assertEquals(expectedOrder, order); } @Test public void testConjunctionDisjunctionPostFix() { String ccl = "a = 1 and b = 2 or c = 3"; // Build expected queue Queue<PostfixNotationSymbol> expectedOrder = new LinkedList<>(); KeySymbol key = new KeySymbol("a"); OperatorSymbol operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); ValueSymbol value = new ValueSymbol( PARSER_TRANSFORM_VALUE_FUNCTION.apply("1")); ExpressionSymbol expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); key = new KeySymbol("b"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); expectedOrder.add(ConjunctionSymbol.AND); key = new KeySymbol("c"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("3")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); expectedOrder.add(ConjunctionSymbol.OR); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); Queue<PostfixNotationSymbol> order = parser.order(); Assert.assertEquals(expectedOrder, order); } @Test public void testDisjunctionConjunctionPostFix() { String ccl = "a = 1 or b = 2 and c = 3"; // Build expected queue Queue<PostfixNotationSymbol> expectedOrder = new LinkedList<>(); KeySymbol key = new KeySymbol("a"); OperatorSymbol operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); ValueSymbol value = new ValueSymbol( PARSER_TRANSFORM_VALUE_FUNCTION.apply("1")); ExpressionSymbol expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); key = new KeySymbol("b"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); key = new KeySymbol("c"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("3")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); expectedOrder.add(ConjunctionSymbol.AND); expectedOrder.add(ConjunctionSymbol.OR); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); Queue<PostfixNotationSymbol> order = parser.order(); Assert.assertEquals(expectedOrder, order); } @Test public void testDisjunctionParenthesizedConjunctionPostFix() { String ccl = "a = 1 or (b = 2 and c = 3)"; // Build expected queue Queue<PostfixNotationSymbol> expectedOrder = new LinkedList<>(); KeySymbol key = new KeySymbol("a"); OperatorSymbol operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); ValueSymbol value = new ValueSymbol( PARSER_TRANSFORM_VALUE_FUNCTION.apply("1")); ExpressionSymbol expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); key = new KeySymbol("b"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("2")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); key = new KeySymbol("c"); operator = new OperatorSymbol( PARSER_TRANSFORM_OPERATOR_FUNCTION.apply("=")); value = new ValueSymbol(PARSER_TRANSFORM_VALUE_FUNCTION.apply("3")); expression = ExpressionSymbol.create(key, operator, value); expectedOrder.add(expression); expectedOrder.add(ConjunctionSymbol.AND); expectedOrder.add(ConjunctionSymbol.OR); // Generate queue Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); Queue<PostfixNotationSymbol> order = parser.order(); Assert.assertEquals(expectedOrder, order); } @Test public void testSingleExpressionAbstractSyntaxTree() { String ccl = "a = 1"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("a", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("1", expression.values().get(0).toString()); } @Test public void testSingleBinaryExpressionAbstractSyntaxTree() { String ccl = "a >< 1 2"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("a", expression.key().toString()); Assert.assertEquals("><", expression.operator().toString()); Assert.assertEquals("1", expression.values().get(0).toString()); Assert.assertEquals("2", expression.values().get(1).toString()); } @Test public void testSingleConjunctionAbstractSyntaxTree() { String ccl = "a = 1 and b = 2"; Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof AndTree); ConjunctionTree rootNode = (ConjunctionTree) tree; // Left node Assert.assertTrue(rootNode.left() instanceof ExpressionTree); ExpressionSymbol leftExpression = (ExpressionSymbol) (rootNode.left()) .root(); Assert.assertEquals("a", leftExpression.key().toString()); Assert.assertEquals("=", leftExpression.operator().toString()); Assert.assertEquals("1", leftExpression.values().get(0).toString()); // Right node Assert.assertTrue(rootNode.right() instanceof ExpressionTree); ExpressionSymbol rightExpression = (ExpressionSymbol) (rootNode.right()) .root(); Assert.assertEquals("b", rightExpression.key().toString()); Assert.assertEquals("=", rightExpression.operator().toString()); Assert.assertEquals("2", rightExpression.values().get(0).toString()); } @Test public void testSingleDisjunctionAbstractSyntaxTree() { String ccl = "a = 1 or b = 2"; Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof OrTree); ConjunctionTree rootNode = (ConjunctionTree) tree; // Left node Assert.assertTrue(rootNode.left() instanceof ExpressionTree); ExpressionSymbol leftExpression = (ExpressionSymbol) (rootNode.left()) .root(); Assert.assertEquals("a", leftExpression.key().toString()); Assert.assertEquals("=", leftExpression.operator().toString()); Assert.assertEquals("1", leftExpression.values().get(0).toString()); // Right node Assert.assertTrue(rootNode.left() instanceof ExpressionTree); ExpressionSymbol rightExpression = (ExpressionSymbol) (rootNode.right()) .root(); Assert.assertEquals("b", rightExpression.key().toString()); Assert.assertEquals("=", rightExpression.operator().toString()); Assert.assertEquals("2", rightExpression.values().get(0).toString()); } @Test public void testDoubleConjunctionAbstractSyntaxTree() { String ccl = "a = 1 and b = 2 and c = 3"; Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof AndTree); ConjunctionTree rootNode = (ConjunctionTree) tree; // left node Assert.assertTrue(rootNode.left() instanceof AndTree); ConjunctionTree leftNode = (ConjunctionTree) rootNode.left(); // right node Assert.assertTrue(rootNode.right() instanceof ExpressionTree); ExpressionSymbol rightExpression = (ExpressionSymbol) (rootNode.right()) .root(); Assert.assertEquals("c", rightExpression.key().toString()); Assert.assertEquals("=", rightExpression.operator().toString()); Assert.assertEquals("3", rightExpression.values().get(0).toString()); // Left left node Assert.assertTrue(leftNode.left() instanceof ExpressionTree); ExpressionSymbol leftLeftExpression = (ExpressionSymbol) (leftNode .left()).root(); Assert.assertEquals("a", leftLeftExpression.key().toString()); Assert.assertEquals("=", leftLeftExpression.operator().toString()); Assert.assertEquals("1", leftLeftExpression.values().get(0).toString()); // Left right node Assert.assertTrue(leftNode.right() instanceof ExpressionTree); ExpressionSymbol rightRightExpression = (ExpressionSymbol) (leftNode .right()).root(); Assert.assertEquals("b", rightRightExpression.key().toString()); Assert.assertEquals("=", rightRightExpression.operator().toString()); Assert.assertEquals("2", rightRightExpression.values().get(0).toString()); } @Test public void testDoubleDisjunctionAbstractSyntaxTree() { String ccl = "a = 1 or b = 2 or c = 3"; Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof OrTree); ConjunctionTree rootNode = (ConjunctionTree) tree; // left node Assert.assertTrue(rootNode.left() instanceof OrTree); ConjunctionTree leftNode = (ConjunctionTree) rootNode.left(); // right node Assert.assertTrue(rootNode.right() instanceof ExpressionTree); ExpressionSymbol rightExpression = (ExpressionSymbol) (rootNode.right()) .root(); Assert.assertEquals("c", rightExpression.key().toString()); Assert.assertEquals("=", rightExpression.operator().toString()); Assert.assertEquals("3", rightExpression.values().get(0).toString()); // Left left node Assert.assertTrue(leftNode.left() instanceof ExpressionTree); ExpressionSymbol leftLeftExpression = (ExpressionSymbol) (leftNode .left()).root(); Assert.assertEquals("a", leftLeftExpression.key().toString()); Assert.assertEquals("=", leftLeftExpression.operator().toString()); Assert.assertEquals("1", leftLeftExpression.values().get(0).toString()); // Left right node Assert.assertTrue(leftNode.right() instanceof ExpressionTree); ExpressionSymbol leftRightExpression = (ExpressionSymbol) (leftNode .right()).root(); Assert.assertEquals("b", leftRightExpression.key().toString()); Assert.assertEquals("=", leftRightExpression.operator().toString()); Assert.assertEquals("2", leftRightExpression.values().get(0).toString()); } @Test public void testConjunctionDisjunctionAbstractSyntaxTree() { String ccl = "a = 1 and b = 2 or c = 3"; Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof OrTree); ConjunctionTree rootNode = (ConjunctionTree) tree; // left node Assert.assertTrue(rootNode.left() instanceof AndTree); ConjunctionTree leftNode = (ConjunctionTree) rootNode.left(); // right node Assert.assertTrue(rootNode.right() instanceof ExpressionTree); ExpressionSymbol rightExpression = (ExpressionSymbol) (rootNode.right()) .root(); Assert.assertEquals("c", rightExpression.key().toString()); Assert.assertEquals("=", rightExpression.operator().toString()); Assert.assertEquals("3", rightExpression.values().get(0).toString()); // Left left node Assert.assertTrue(leftNode.left() instanceof ExpressionTree); ExpressionSymbol leftLeftExpression = (ExpressionSymbol) (leftNode .left()).root(); Assert.assertEquals("a", leftLeftExpression.key().toString()); Assert.assertEquals("=", leftLeftExpression.operator().toString()); Assert.assertEquals("1", leftLeftExpression.values().get(0).toString()); // Left right node Assert.assertTrue(leftNode.right() instanceof ExpressionTree); ExpressionSymbol leftRightExpression = (ExpressionSymbol) (leftNode .right()).root(); Assert.assertEquals("b", leftRightExpression.key().toString()); Assert.assertEquals("=", leftRightExpression.operator().toString()); Assert.assertEquals("2", leftRightExpression.values().get(0).toString()); } @Test public void testDisjunctionConjunctionAbstractSyntaxTree() { String ccl = "a = 1 or b = 2 and c = 3"; Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof OrTree); ConjunctionTree rootNode = (ConjunctionTree) tree; // Right node Assert.assertTrue(rootNode.right() instanceof AndTree); ConjunctionTree rightNode = (ConjunctionTree) rootNode.right(); // right node Assert.assertTrue(rootNode.left() instanceof ExpressionTree); ExpressionSymbol leftExpression = (ExpressionSymbol) (rootNode.left()) .root(); Assert.assertEquals("a", leftExpression.key().toString()); Assert.assertEquals("=", leftExpression.operator().toString()); Assert.assertEquals("1", leftExpression.values().get(0).toString()); // Right left node Assert.assertTrue(rightNode.left() instanceof ExpressionTree); ExpressionSymbol rightLeftExpression = (ExpressionSymbol) (rightNode .left()).root(); Assert.assertEquals("b", rightLeftExpression.key().toString()); Assert.assertEquals("=", rightLeftExpression.operator().toString()); Assert.assertEquals("2", rightLeftExpression.values().get(0).toString()); // Right right node Assert.assertTrue(rightNode.right() instanceof ExpressionTree); ExpressionSymbol rightRightExpression = (ExpressionSymbol) (rightNode .right()).root(); Assert.assertEquals("c", rightRightExpression.key().toString()); Assert.assertEquals("=", rightRightExpression.operator().toString()); Assert.assertEquals("3", rightRightExpression.values().get(0).toString()); } @Test public void testDisjunctionParenthesizedConjunctionAbstractSyntaxTree() { String ccl = "a = 1 and (b = 2 or c = 3)"; Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof AndTree); ConjunctionTree rootNode = (ConjunctionTree) tree; // Left node Assert.assertTrue(rootNode.left() instanceof ExpressionTree); ExpressionSymbol leftExpression = (ExpressionSymbol) (rootNode.left()) .root(); Assert.assertEquals("a", leftExpression.key().toString()); Assert.assertEquals("=", leftExpression.operator().toString()); Assert.assertEquals("1", leftExpression.values().get(0).toString()); // Right node Assert.assertTrue(rootNode.right() instanceof OrTree); ConjunctionTree rightNode = (ConjunctionTree) rootNode.right(); // Right left node Assert.assertTrue(rightNode.left() instanceof ExpressionTree); ExpressionSymbol rightLeftExpression = (ExpressionSymbol) (rightNode .left()).root(); Assert.assertEquals("b", rightLeftExpression.key().toString()); Assert.assertEquals("=", rightLeftExpression.operator().toString()); Assert.assertEquals("2", rightLeftExpression.values().get(0).toString()); // Right right node Assert.assertTrue(rightNode.right() instanceof ExpressionTree); ExpressionSymbol leftRightExpression = (ExpressionSymbol) (rightNode .right()).root(); Assert.assertEquals("c", leftRightExpression.key().toString()); Assert.assertEquals("=", leftRightExpression.operator().toString()); Assert.assertEquals("3", leftRightExpression.values().get(0).toString()); } @Test public void testParseCclLocalReferences() { String ccl = "name = $name"; Multimap<String, Object> data = LinkedHashMultimap.create(); data.put("name", "Lebron James"); data.put("age", 30); data.put("team", "Cleveland Cavaliers"); // Generate tree Parser parser = Parser.create(ccl, data, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("name", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("\"Lebron James\"", expression.values().get(0).toString()); } @Test public void testEscapedCclLocalReferences() { String ccl = "name = \\$name"; Multimap<String, Object> data = LinkedHashMultimap.create(); data.put("name", "Lebron James"); data.put("age", 30); data.put("team", "Cleveland Cavaliers"); // Generate tree Parser parser = Parser.create(ccl, data, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("name", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("$name", expression.values().get(0).toString()); } @Test public void testDoubleQuotedValue() { String ccl = "name = \"Javier Lores\""; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("name", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("\"Javier Lores\"", expression.values().get(0).toString()); } @Test public void testDoubleRightAndLeftQuotedValue() { String ccl = "name = “Javier Lores”"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("name", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("\"Javier Lores\"", expression.values().get(0).toString()); } @Test public void testQuotedValueWithinQuotedString() { String ccl = "name = \"Javier \\\"Lores\""; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("name", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("'Javier \"Lores'", expression.values().get(0).toString()); } @Test public void testNonQuoteEscapedValueWithinQuoteString() { String ccl = "name = \"Javier \\\"\\@Lores\""; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("name", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("'Javier \"\\@Lores'", expression.values().get(0).toString()); } @Test public void validEscapedLocalResolution() { String ccl = "name = \\$name"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("name", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("$name", expression.values().get(0).toString()); } @Test public void validEscapedImplicitLink() { String ccl = "name = \\@name"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("name", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("@name", expression.values().get(0).toString()); } @Test public void validLink() { String ccl = "name -> 30"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("name", expression.key().toString()); Assert.assertEquals("LINKS_TO", expression.operator().toString()); Assert.assertEquals("30", expression.values().get(0).toString()); } @Test public void validOperatorEnum() { String ccl = "name LINKS_TO 30"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("name", expression.key().toString()); Assert.assertEquals("LINKS_TO", expression.operator().toString()); Assert.assertEquals("30", expression.values().get(0).toString()); } @Test public void testNavigationKey() { String ccl = "mother.children = 3"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("mother.children", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("3", expression.values().get(0).toString()); } @Test public void testLongNavigationKey() { String ccl = "mother.mother.siblings = 3"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("mother.mother.siblings", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("3", expression.values().get(0).toString()); } @Test public void testPeriodSeparatedValue() { String ccl = "mother = a.b.c"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("mother", expression.key().toString()); Assert.assertEquals("=", expression.operator().toString()); Assert.assertEquals("a.b.c", expression.values().get(0).toString()); } @Test public void testImplicitRecordFunctionAsEvaluationKey() { String ccl = "friends | avg > 3"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertTrue(expression.key() instanceof FunctionKeySymbol); FunctionKeySymbol symbol = expression.key(); Assert.assertEquals("avg", symbol.key().operation()); Assert.assertEquals("friends", symbol.key().key()); Assert.assertEquals(">", expression.operator().toString()); Assert.assertEquals("3", expression.values().get(0).toString()); } @Test public void testImplicitIndexFunctionAsEvaluationValue() { String ccl = "age > avg(age)"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("age", expression.key().toString()); Assert.assertEquals(">", expression.operator().toString()); Assert.assertTrue( expression.values().get(0) instanceof FunctionValueSymbol); Assert.assertEquals("avg", ((IndexFunction) expression.values().get(0).value()) .operation()); Assert.assertEquals("age", ((IndexFunction) expression.values().get(0).value()).key()); } @Test public void testExplicitFunctionWithSingleRecordAsEvaluationValue() { String ccl = "age > avg(age, 1)"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("age", expression.key().toString()); Assert.assertEquals(">", expression.operator().toString()); Assert.assertTrue( expression.values().get(0) instanceof FunctionValueSymbol); Assert.assertEquals("avg", ((KeyRecordsFunction) expression.values().get(0).value()) .operation()); Assert.assertEquals("age", ((KeyRecordsFunction) expression.values().get(0).value()) .key()); Assert.assertEquals(1, ((List<Long>) ((KeyRecordsFunction) expression .values().get(0).value()).source()).size()); Assert.assertEquals((long) 1, (long) ((List<Long>) ((KeyRecordsFunction) expression.values() .get(0).value()).source()).get(0)); } @Test public void testExplicitFunctionWithBetween() { String ccl = "age bw avg(age) 1000"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("age", expression.key().toString()); Assert.assertEquals("><", expression.operator().toString()); Assert.assertTrue( expression.values().get(0) instanceof FunctionValueSymbol); Assert.assertEquals("avg", ((IndexFunction) expression.values().get(0).value()) .operation()); Assert.assertEquals("age", ((IndexFunction) expression.values().get(0).value()).key()); Assert.assertEquals("1000", expression.values().get(1).toString()); } @Test public void testExplicitFunctionWithBetweenCCL() { String ccl = "age bw avg(age, age > 10) 1000"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("age", expression.key().toString()); Assert.assertEquals("><", expression.operator().toString()); KeyConditionFunction function = (KeyConditionFunction) expression .values().get(0).value(); Assert.assertTrue(function.source() instanceof ExpressionTree); ExpressionTree t = (ExpressionTree) function.source(); ExpressionSymbol root = (ExpressionSymbol) t.root(); Assert.assertEquals("age", root.key().key()); Assert.assertEquals(">", root.operator().operator().symbol()); Assert.assertEquals(10, root.values().get(0).value()); Assert.assertEquals("1000", expression.values().get(1).toString()); } @Test public void testExplicitFunctionWithMultipleRecordsAsEvaluationValue() { String ccl = "age > avg(age, 1, 2)"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("age", expression.key().toString()); Assert.assertEquals(">", expression.operator().toString()); Assert.assertTrue( expression.values().get(0) instanceof FunctionValueSymbol); Assert.assertEquals("avg", ((KeyRecordsFunction) expression.values().get(0).value()) .operation()); Assert.assertEquals("age", ((KeyRecordsFunction) expression.values().get(0).value()) .key()); Assert.assertEquals(2, ((List<Long>) ((KeyRecordsFunction) expression .values().get(0).value()).source()).size()); Assert.assertEquals((long) 1, (long) ((List<Long>) ((KeyRecordsFunction) expression.values() .get(0).value()).source()).get(0)); Assert.assertEquals((long) 2, (long) ((List<Long>) ((KeyRecordsFunction) expression.values() .get(0).value()).source()).get(1)); } @Test public void testExplicitFunctionWithCCLAsEvaluationValue() { String ccl = "age > avg(age, age < 30)"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("age", expression.key().toString()); Assert.assertEquals(">", expression.operator().toString()); Assert.assertTrue( expression.values().get(0) instanceof FunctionValueSymbol); Assert.assertEquals("avg", ((KeyConditionFunction) expression.values().get(0).value()) .operation()); Assert.assertEquals("age", ((KeyConditionFunction) expression.values().get(0).value()) .key()); Assert.assertTrue( (((KeyConditionFunction) expression.values().get(0).value()) .source()) instanceof ExpressionTree); Assert.assertEquals("age", ((ExpressionSymbol) ((AbstractSyntaxTree) ((KeyConditionFunction) expression .values().get(0).value()).source()).root()).key() .toString()); Assert.assertEquals("<", ((ExpressionSymbol) ((AbstractSyntaxTree) ((KeyConditionFunction) expression .values().get(0).value()).source()).root()).operator() .toString()); Assert.assertEquals("30", ((ExpressionSymbol) ((AbstractSyntaxTree) ((KeyConditionFunction) expression .values().get(0).value()).source()).root()).values() .get(0).toString()); } @Test public void validImplicitRecordFunctionAsEvaluationKeyAndExplicitFunctionWithCCLAsEvaluationValue() { String ccl = "age | avg > avg(age, age < 30)"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertTrue(expression.key() instanceof FunctionKeySymbol); Assert.assertEquals("avg", ((ImplicitKeyRecordFunction) expression.key().key()) .operation()); Assert.assertEquals(">", expression.operator().toString()); Assert.assertTrue( expression.values().get(0) instanceof FunctionValueSymbol); Assert.assertEquals("avg", ((KeyConditionFunction) expression.values().get(0).value()) .operation()); Assert.assertEquals("age", ((KeyConditionFunction) expression.values().get(0).value()) .key()); Assert.assertTrue( (((KeyConditionFunction) expression.values().get(0).value()) .source()) instanceof ExpressionTree); Assert.assertEquals("age", ((ExpressionSymbol) ((AbstractSyntaxTree) ((KeyConditionFunction) expression .values().get(0).value()).source()).root()).key() .toString()); Assert.assertEquals("<", ((ExpressionSymbol) ((AbstractSyntaxTree) ((KeyConditionFunction) expression .values().get(0).value()).source()).root()).operator() .toString()); Assert.assertEquals("30", ((ExpressionSymbol) ((AbstractSyntaxTree) ((KeyConditionFunction) expression .values().get(0).value()).source()).root()).values() .get(0).toString()); } @Test public void testJsonReservedIdentifier() { String ccl = "$id$ != 40"; // Generate tree Parser parser = Parser.create(ccl, PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); AbstractSyntaxTree tree = parser.parse(); // Root node Assert.assertTrue(tree instanceof ExpressionTree); ExpressionSymbol expression = (ExpressionSymbol) tree.root(); Assert.assertEquals("$id$", expression.key().toString()); Assert.assertEquals("!=", expression.operator().toString()); Assert.assertEquals("40", expression.values().get(0).toString()); } @Test public void testReproIX5A() { Criteria criteria = Criteria.where() .group(Criteria.where().key("_") .operator(com.cinchapi.concourse.thrift.Operator.EQUALS) .value("org.internx.model.data.user.Student")) .and() .group(Criteria.where() .group(Criteria.where().key("group").operator( com.cinchapi.concourse.thrift.Operator.LIKE) .value("%Accounting And Business/management%")) .or() .group(Criteria.where().key("major").operator( com.cinchapi.concourse.thrift.Operator.LIKE) .value("%accounting and business/management%"))); // Generate tree Parser parser = Parser.create(criteria.ccl(), PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); parser.tokenize().forEach(token -> { if(token instanceof ValueSymbol) { Assert.assertEquals(String.class, ((ValueSymbol) token).value().getClass()); } }); } @Test public void testReproIX5B() { Criteria criteria = Criteria.where() .group(Criteria.where().key("_") .operator(com.cinchapi.concourse.thrift.Operator.EQUALS) .value(Tag .create("org.internx.model.data.user.Student"))) .and() .group(Criteria.where().group(Criteria.where().key("group") .operator(com.cinchapi.concourse.thrift.Operator.EQUALS) .value(Tag .create("Accounting And Business/management"))) .or() .group(Criteria.where().key("major").operator( com.cinchapi.concourse.thrift.Operator.EQUALS) .value(Tag.create( "accounting and business/management")))); // Generate tree Parser parser = Parser.create(criteria.ccl(), PARSER_TRANSFORM_VALUE_FUNCTION, PARSER_TRANSFORM_OPERATOR_FUNCTION); parser.tokenize().forEach(token -> { if(token instanceof ValueSymbol) { Assert.assertEquals(Tag.class, ((ValueSymbol) token).value().getClass()); } }); } /** * The canonical function to transform strings to java values in a * {@link Parser}. */ public final Function<String, Object> PARSER_TRANSFORM_VALUE_FUNCTION = value -> Convert .stringToJava(value); /** * The canonical function to transform strings to operators in a * {@link Parser}. */ public final Function<String, Operator> PARSER_TRANSFORM_OPERATOR_FUNCTION = operator -> Convert .stringToOperator(operator); /** * */ @SuppressWarnings("unused") private void printPreOrder(AbstractSyntaxTree tree) { System.out.println(tree.root()); for (AbstractSyntaxTree child : tree.children()) { printPreOrder(child); } } }
true
8a80a95671e8172300c6f68f12c675ba612be640
Java
dreadiscool/YikYak-Decompiled
/src/com/parse/ParseAnalytics.java
UTF-8
3,960
1.820313
2
[]
no_license
package com.parse; import android.content.Intent; import android.os.Bundle; import java.util.Date; import java.util.Map; import m; import org.json.JSONException; import org.json.JSONObject; public class ParseAnalytics { private static final String APP_OPENED = "AppOpened"; private static final String OP = "client_events"; private static final String TAG = "com.parse.ParseAnalytics"; static Map<String, Boolean> lruSeenPushes = new ParseAnalytics.1(); private static ParseCommand createCommand(String paramString) { ParseCommand localParseCommand = new ParseCommand("client_events", ParseUser.getCurrentSessionToken()); localParseCommand.put("at", Parse.encodeDate(new Date())); localParseCommand.put("name", paramString); return localParseCommand; } @Deprecated public static void trackAppOpened(Intent paramIntent) { trackAppOpenedInBackground(paramIntent); } public static m<Void> trackAppOpenedInBackground(Intent paramIntent) { if ((paramIntent != null) && (paramIntent.getExtras() != null)) {} m localm; for (String str1 = paramIntent.getExtras().getString("com.parse.Data");; str1 = null) { ParseCommand localParseCommand = createCommand("AppOpened"); if (str1 != null) {} try { str2 = new JSONObject(str1).optString("push_hash"); if (str2.length() <= 0) {} } catch (JSONException localJSONException) { for (;;) { String str2; Parse.logE("com.parse.ParseAnalytics", "Failed to parse push data: " + localJSONException.getMessage()); } } synchronized (lruSeenPushes) { if (lruSeenPushes.containsKey(str2)) { localm = m.a(null); } else { lruSeenPushes.put(str2, Boolean.valueOf(true)); localParseCommand.put("push_hash", str2); localm = Parse.getEventuallyQueue().enqueueEventuallyAsync(localParseCommand, null).j(); } } } return localm; } public static void trackAppOpenedInBackground(Intent paramIntent, SaveCallback paramSaveCallback) { Parse.callbackOnMainThreadAsync(trackAppOpenedInBackground(paramIntent), paramSaveCallback); } @Deprecated public static void trackEvent(String paramString) { trackEventInBackground(paramString); } @Deprecated public static void trackEvent(String paramString, Map<String, String> paramMap) { trackEventInBackground(paramString, paramMap); } public static m<Void> trackEventInBackground(String paramString) { return trackEventInBackground(paramString, (Map)null); } public static m<Void> trackEventInBackground(String paramString, Map<String, String> paramMap) { if ((paramString == null) || (paramString.trim().length() == 0)) { throw new RuntimeException("A name for the custom event must be provided."); } ParseCommand localParseCommand = createCommand(paramString); if (paramMap != null) { localParseCommand.put("dimensions", (JSONObject)Parse.encode(paramMap, NoObjectsEncodingStrategy.get())); } return Parse.getEventuallyQueue().enqueueEventuallyAsync(localParseCommand, null).j(); } public static void trackEventInBackground(String paramString, SaveCallback paramSaveCallback) { Parse.callbackOnMainThreadAsync(trackEventInBackground(paramString), paramSaveCallback); } public static void trackEventInBackground(String paramString, Map<String, String> paramMap, SaveCallback paramSaveCallback) { Parse.callbackOnMainThreadAsync(trackEventInBackground(paramString, paramMap), paramSaveCallback); } } /* Location: C:\Users\dreadiscool\Desktop\tools\classes-dex2jar.jar * Qualified Name: com.parse.ParseAnalytics * JD-Core Version: 0.7.0.1 */
true
81b5274fa801dbaefc8e15bec42de2c7a299462e
Java
kruszczynski/old_java_projects
/Numeryczne/Projekt1/ProjektNumeryczne0.1/src/Main.java
UTF-8
931
2.96875
3
[]
no_license
public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // float[][] a = {{3,5,5,3,3},{3,3,3},{3,3,3},{3,3,3}}; // System.out.print(a.length + " " + a[0].length); double[][] A = {{2,1,1},{1,2,1},{1,1,2}}; for(int i = 0; i<A.length; i++){ for(int j = 0; j<A[i].length; j++){ System.out.print(A[i][j]+" "); } System.out.println(); } System.out.println(); DecompHelper helper = new DecompHelper(A); helper.decompMatrix(); double[][] L = helper.getL(); double[][] LT = helper.getLT(); for(int i = 0; i<L.length; i++){ for(int j = 0; j<L[i].length; j++){ System.out.print(L[i][j]+" "); } System.out.println(); } System.out.println(); for(int i = 0; i<LT.length; i++){ for(int j = 0; j<LT[i].length; j++){ System.out.print(LT[i][j]+" "); } System.out.println(); } System.out.println(); } }
true
471504f9a4ab499832250237ce194bb661965621
Java
zerabat/TSI2
/src/main/java/com/tsijee01/persistence/model/ProveedorContenido.java
UTF-8
1,120
2.015625
2
[]
no_license
package com.tsijee01.persistence.model; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; @Entity public class ProveedorContenido { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; private String nombre; @OneToMany(fetch = FetchType.LAZY, cascade={CascadeType.ALL}) @JoinColumn(name = "id") private List<AdminTenant> admins; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } // public List<PaqueteContenido> getPaqueteContenido() { // return paqueteContenido; // } // // public void setPaqueteContenido(List<PaqueteContenido> paqueteContenido) { // this.paqueteContenido = paqueteContenido; // } }
true
3a6d797153049e57fa6dea7d56293e411c285bc1
Java
bassages/home-server
/src/test/java/nl/homeserver/energy/meterreading/MeterstandControllerTest.java
UTF-8
2,397
2.3125
2
[ "Apache-2.0" ]
permissive
package nl.homeserver.energy.meterreading; import nl.homeserver.DatePeriod; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.time.LocalDate; import java.util.List; import java.util.Optional; import static java.time.Month.FEBRUARY; import static java.time.Month.JANUARY; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class MeterstandControllerTest { @InjectMocks MeterstandController meterstandController; @Mock MeterstandService meterstandService; @Test void whenGetMostRecentThenDelegatedToMeterstandService() { // given final Meterstand mostRecentMeterstand = mock(Meterstand.class); when(meterstandService.getMostRecent()).thenReturn(Optional.of(mostRecentMeterstand)); // when final Meterstand mostRecent = meterstandController.getMostRecent(); // then assertThat(mostRecent).isEqualTo(mostRecentMeterstand); } @Test void whenGetOldestOfTodayThenDelegatedToMeterstandService() { // given final Meterstand oldestMeterReadingOfToday = mock(Meterstand.class); when(meterstandService.findOldestOfToday()).thenReturn(Optional.of(oldestMeterReadingOfToday)); // when final Meterstand oldestOfToday = meterstandController.getOldestOfToday(); // then assertThat(oldestOfToday).isSameAs(oldestMeterReadingOfToday); } @Test void whenGetPerDagThenDelegatedToMeterstandService() { // given final LocalDate from = LocalDate.of(2017, JANUARY, 1); final LocalDate to = LocalDate.of(2018, FEBRUARY, 2); final List<MeterstandOpDag> meterReadingsPerDay = List.of( new MeterstandOpDag(LocalDate.now(), mock(Meterstand.class)), new MeterstandOpDag(LocalDate.now(), mock(Meterstand.class))); when(meterstandService.getPerDag(DatePeriod.aPeriodWithToDate(from, to))).thenReturn(meterReadingsPerDay); // when final List<MeterstandOpDag> actual = meterstandController.perDag(from, to); // then assertThat(actual).isSameAs(meterReadingsPerDay); } }
true
c4cd8be3d77ab2fffabdc6789f96e7230e8cfc96
Java
moonk1212/spring_basic
/src/main/java/com/spring/web/service/IScoreService.java
UTF-8
384
1.773438
2
[]
no_license
package com.spring.web.service; import java.util.List; import com.spring.web.model.ScoreVO; public interface IScoreService { //점수 저장 기능. void insertScoreProcess(ScoreVO scores); //점수 전체 조회 기능 List<ScoreVO> selectAllScores(); //점수 수정 기능 void modifyScore(); //점수 삭제 기능 void deleteScore(int stuNo); }
true
afa3fb79ab6ec5a64890bb4dc65c52fc4c5a15bf
Java
Bilygine/Analyzer_old
/analyzer-core/src/main/java/com/bilygine/analyzer/controller/AnalyzeController.java
UTF-8
2,886
2.046875
2
[]
no_license
package com.bilygine.analyzer.controller; import com.bilygine.analyzer.analyze.Analyze; import com.bilygine.analyzer.analyze.Status; import com.bilygine.analyzer.entity.error.AnalyzerError; import com.bilygine.analyzer.entity.json.input.CreateAnalyzeInput; import com.bilygine.analyzer.entity.json.input.UpdateAnalyzeStatusInput; import com.bilygine.analyzer.entity.json.model.AnalyzeModel; import com.bilygine.analyzer.service.AnalyzeService; import com.bilygine.analyzer.analyze.result.Result; import com.bilygine.analyzer.io.Json; import com.bilygine.analyzer.service.DatabaseService; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import spark.Request; import spark.Spark; import java.util.List; public class AnalyzeController implements Controller { private final AnalyzeService analyzeService = new AnalyzeService(); private final DatabaseService databaseService = new DatabaseService(); public AnalyzeController() { /** Firebase */ databaseService.connect(); } @Override public void register() { Spark.get("/analyze", (req, res) -> list(), Json::toJson); Spark.post("/analyze", (req, res) -> create(req), Json::toJson); Spark.post("/analyze/status/:id", (req, res) -> status(req, req.params("id"))); Spark.post("/analyze/execute/:id", (req, res) -> execute(req.params("id")), Json::toJson); Spark.get("/analyze/result/:id", (req, res) -> getResult(req.params("id")), Json::toJson); // temp } private Result getResult(String analyzeId) { return analyzeService.findAnalyzeById(analyzeId).getResult(); } private String create(Request request) { String body = request.body(); CreateAnalyzeInput input = Json.fromJson(body, CreateAnalyzeInput.class); AnalyzeModel output = new AnalyzeModel(); output.id = RandomStringUtils.randomAlphabetic(8); output.metadata = input.getMetadata(); output.submitted = System.currentTimeMillis(); output.username = input.getUsername(); output.version = "0.1"; output.audio = input.getAudioPath(); return databaseService.createAnalyze(output); } private String execute(String id) { AnalyzeModel model = databaseService.findAnalyzeById(id); if (model == null) { throw new AnalyzerError("Unknown analyze id"); } if (StringUtils.isBlank(model.audio) || !model.audio.startsWith("gs://")) { //TODO: Check if path exist on specified bucket. throw new AnalyzerError("Google Storage path is invalid: " + model.audio); } return analyzeService.execute(model.audio, model.metadata).getUniqueID(); } public List<Analyze> list() { return analyzeService.getAnalyzes(); } private String status(Request request, String id) { String body = request.body(); UpdateAnalyzeStatusInput input = Json.fromJson(body, UpdateAnalyzeStatusInput.class); databaseService.updateStatus(id, Status.valueOf(input.status)); return "{}"; } }
true
654173123463de445ed5fde30b0b1022cc0d02b9
Java
fermadeiral/StyleErrors
/CesarValiente-quitesleep/47f3f88ce710f8ee6c2a04e6dbe4086d5256b9b2/64/ScheduleTab.java
UTF-8
11,957
1.78125
2
[]
no_license
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep 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 General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.activities; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; import android.widget.Toast; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Schedule; import es.cesar.quitesleep.dialogs.EndTimeDialog; import es.cesar.quitesleep.dialogs.StartTimeDialog; import es.cesar.quitesleep.interfaces.IDialogs; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail [email protected] * */ public class ScheduleTab extends Activity implements OnClickListener { private final String CLASS_NAME = getClass().getName(); private final int START_TIME_DIALOG = 0; private final int END_TIME_DIALOG = 1; private final int ABOUT_DIALOG = 2; private final int HELP_DIALOG = 3; //Ids for the button widgets private final int startTimeButtonId = R.id.schedule_button_startTime; private final int endTimeButtonId = R.id.schedule_button_endTime; private final int daysWeekButtonId = R.id.schedule_button_daysweek; //Ids for thextViews widgets private final int startTimeLabelId = R.id.schedule_textview_startTime; private final int endTimeLabelId = R.id.schedule_textview_endTime; //Days of the week checkboxes Ids private final int mondayCheckId = R.id.schedule_checkbox_monday; private final int tuesdayCheckId = R.id.schedule_checkbox_tuesday; private final int wednesdayCheckId = R.id.schedule_checkbox_wednesday; private final int thursdayCheckId = R.id.schedule_checkbox_thursday; private final int fridayCheckId = R.id.schedule_checkbox_friday; private final int saturdayCheckId = R.id.schedule_checkbox_saturday; private final int sundayCheckId = R.id.schedule_checkbox_sunday; //Used dialogs in this activity private StartTimeDialog startTimeDialog; private EndTimeDialog endTimeDialog; //labels for start and end times private TextView startTimeLabel; private TextView endTimeLabel; //Days of the week checkboxes private CheckBox mondayCheck; private CheckBox tuesdayCheck; private CheckBox wednesdayCheck; private CheckBox thursdayCheck; private CheckBox fridayCheck; private CheckBox saturdayCheck; private CheckBox sundayCheck; //Ids for option menu final int aboutMenuId = R.id.menu_information_about; final int helpMenuId = R.id.menu_information_help; final private String CALCULATOR_FONT = "fonts/calculator_script_mt.ttf"; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.scheduletab); startTimeDialog = new StartTimeDialog(this); endTimeDialog = new EndTimeDialog(this); Button startTimeButton = (Button)findViewById(startTimeButtonId); Button endTimeButton = (Button)findViewById(endTimeButtonId); Button daysWeekButton = (Button)findViewById(daysWeekButtonId); //--------- Define our own text style used a custom font ------// startTimeLabel = (TextView)findViewById(startTimeLabelId); endTimeLabel = (TextView)findViewById(endTimeLabelId); Typeface face = Typeface.createFromAsset(getAssets(), CALCULATOR_FONT); startTimeLabel.setTypeface(face); endTimeLabel.setTypeface(face); //-------------------------------------------------------------------// //Sets the timeLabes into start and end time dialogs for update the changes startTimeDialog.setStartTimeLabel(startTimeLabel); endTimeDialog.setEndTimeLabel(endTimeLabel); //Instantiate the days of the week checkboxes mondayCheck = (CheckBox)findViewById(mondayCheckId); tuesdayCheck = (CheckBox)findViewById(tuesdayCheckId); wednesdayCheck = (CheckBox)findViewById(wednesdayCheckId); thursdayCheck = (CheckBox)findViewById(thursdayCheckId); fridayCheck = (CheckBox)findViewById(fridayCheckId); saturdayCheck = (CheckBox)findViewById(saturdayCheckId); sundayCheck = (CheckBox)findViewById(sundayCheckId); //Define the onClick listeners startTimeButton.setOnClickListener(this); endTimeButton.setOnClickListener(this); daysWeekButton.setOnClickListener(this); /* Set the default saved data when this activity is run for first time * (not for first time globally, else for all times that we run * the application and show this activity for first time) */ setDefaultSavedData(); } /** * Listener for all buttons in this Activity */ public void onClick (View view) { int viewId = view.getId(); switch (viewId) { case startTimeButtonId: showDialog(START_TIME_DIALOG); break; case endTimeButtonId: showDialog(END_TIME_DIALOG); break; case daysWeekButtonId: saveDayWeeksSelection(); break; } } /** * For the first time that create the dialogs */ @Override protected Dialog onCreateDialog (int id) { Dialog dialog; switch (id) { case START_TIME_DIALOG: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Create the StartTimeDialog for 1st time"); dialog = startTimeDialog.getTimePickerDialog(); break; case END_TIME_DIALOG: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Create the EndTimeDialog for 1st time"); dialog = endTimeDialog.getTimePickerDialog(); break; case ABOUT_DIALOG: dialog = showWebviewDialog(IDialogs.ABOUT_URI); break; case HELP_DIALOG: dialog = showWebviewDialog(IDialogs.HELP_SCHEDULE_URI); break; default: dialog = null; } return dialog; } /** * Create the webview dialog using the file (uri) specified to show the information. * * @return */ public Dialog showWebviewDialog(String uri) { try { View contentView = getLayoutInflater().inflate(R.layout.webview_dialog, null, false); WebView webView = (WebView) contentView.findViewById(R.id.webview_content); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(uri); return new AlertDialog.Builder(this) .setCustomTitle(null) .setPositiveButton(android.R.string.ok, null) .setView(contentView) .create(); }catch (Exception e) { if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * This function prepare the dalogs every time to call for some of this * * @param int * @param dialog */ @Override protected void onPrepareDialog (int idDialog, Dialog dialog) { try { switch (idDialog) { case START_TIME_DIALOG: break; case END_TIME_DIALOG: break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { //TODO if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "en onActiviryResult"); } @Override public boolean onCreateOptionsMenu (Menu menu) { try { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.informationmenu, menu); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * @param item * @return boolean */ @Override public boolean onOptionsItemSelected (MenuItem item) { try { switch (item.getItemId()) { case aboutMenuId: showDialog(ABOUT_DIALOG); break; case helpMenuId: showDialog(HELP_DIALOG); break; default: break; } return false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Save the days of the weeks checkboxes state into a Schedule object from the * database. If the Schedule object isn't create, we don't do nothing, not save the * checkboxes state. * * @return true or false if the schedule save was good or not * @see boolean */ private boolean saveDayWeeksSelection () { try { ClientDDBB clientDDBB = new ClientDDBB(); Schedule schedule = clientDDBB.getSelects().selectSchedule(); if (schedule != null) { schedule.setMonday(mondayCheck.isChecked()); schedule.setTuesday(tuesdayCheck.isChecked()); schedule.setWednesday(wednesdayCheck.isChecked()); schedule.setThursday(thursdayCheck.isChecked()); schedule.setFriday(fridayCheck.isChecked()); schedule.setSaturday(saturdayCheck.isChecked()); schedule.setSunday(sundayCheck.isChecked()); clientDDBB.getInserts().insertSchedule(schedule); clientDDBB.commit(); clientDDBB.close(); if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.schedule_toast_daysweek_ok), Toast.LENGTH_SHORT); return true; }else { if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.schedule_toast_daysweek_ko), Toast.LENGTH_SHORT); return false; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Error(e.toString()); } } /** * Set the default saved data in the start and end time labels and * all checkboxes associated to a day of the week. */ private void setDefaultSavedData () { try { ClientDDBB clientDDBB = new ClientDDBB(); Schedule schedule = clientDDBB.getSelects().selectSchedule(); if (schedule != null) { if (schedule.getStartFormatTime()!= null && !schedule.getStartFormatTime().equals("")) startTimeLabel.setText(schedule.getStartFormatTime()); if (schedule.getEndFormatTime() != null && !schedule.getEndFormatTime().equals("")) endTimeLabel.setText(schedule.getEndFormatTime()); mondayCheck.setChecked(schedule.isMonday()); tuesdayCheck.setChecked(schedule.isTuesday()); wednesdayCheck.setChecked(schedule.isWednesday()); thursdayCheck.setChecked(schedule.isThursday()); fridayCheck.setChecked(schedule.isFriday()); saturdayCheck.setChecked(schedule.isSaturday()); sundayCheck.setChecked(schedule.isSunday()); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
true
6482d263e8518d5d4698a3dfb69bb712ab95fc69
Java
cha63506/CompSecurity
/Entertainment/xfinity_source/src/com/xfinity/playerlib/view/videoplay/VideoPlayerFragment$VolumeSliderOnSeekBarChangeListener.java
UTF-8
2,004
1.648438
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.xfinity.playerlib.view.videoplay; import android.media.AudioManager; import android.widget.SeekBar; import com.xfinity.playerlib.model.videoplay.adobeplayer.VideoStateController; import com.xfinity.playerlib.view.CustomStateImageView; // Referenced classes of package com.xfinity.playerlib.view.videoplay: // VideoPlayerFragment class this._cls0 implements android.widget.SeekBarChangeListener { private int startVolume; final VideoPlayerFragment this$0; public void onProgressChanged(SeekBar seekbar, int i, boolean flag) { flag = false; if (!VideoPlayerFragment.access$5100(VideoPlayerFragment.this)) { VideoPlayerFragment.access$200(VideoPlayerFragment.this).setStreamVolume(3, i, 0); if (VideoPlayerFragment.access$5300(VideoPlayerFragment.this)) { seekbar = volumeIndicator; if (i > 0) { flag = true; } seekbar.setAppearEnabled(flag); } return; } else { VideoPlayerFragment.access$5402(VideoPlayerFragment.this, seekbar.getProgress()); return; } } public void onStartTrackingTouch(SeekBar seekbar) { int i = seekbar.getProgress(); VideoPlayerFragment.access$900(VideoPlayerFragment.this).Timeout(); startVolume = i; } public void onStopTrackingTouch(SeekBar seekbar) { if (seekbar.getProgress() > startVolume && VideoPlayerFragment.access$5100(VideoPlayerFragment.this)) { setMuteState(false); } VideoPlayerFragment.access$500(VideoPlayerFragment.this).onVolumeChanged(); } () { this$0 = VideoPlayerFragment.this; super(); } }
true
e7f6a871a243c48713323c8b59dd190464ca3cf6
Java
Yasenia/tetris
/src/main/java/com/pineislet/swing/tetris/model/event/OnStatusChangedListener.java
UTF-8
301
1.882813
2
[]
no_license
package com.pineislet.swing.tetris.model.event; import java.util.EventListener; /** * Create on 2015/1/17 * * @author Yasenia */ public interface OnStatusChangedListener extends EventListener { /** * 游戏状态改变 * */ void onStatusChanged(StatusChangedEvent event); }
true
e1298bf06807ec5a4be0bdc529e6eb6a8f0eefc2
Java
rocimartiz16/JHIPSTER2
/target/generated-sources/annotations/co/edu/sena/ghostceet/domain/ResultadoAprendizaje_.java
UTF-8
836
1.59375
2
[]
no_license
package co.edu.sena.ghostceet.domain; import javax.annotation.Generated; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(ResultadoAprendizaje.class) public abstract class ResultadoAprendizaje_ { public static volatile SingularAttribute<ResultadoAprendizaje, String> descripcion; public static volatile SingularAttribute<ResultadoAprendizaje, String> codigo; public static volatile SetAttribute<ResultadoAprendizaje, ResultadosVistos> resultadosVistos; public static volatile SingularAttribute<ResultadoAprendizaje, Long> id; public static volatile SetAttribute<ResultadoAprendizaje, LimitacionAmbiente> limitacionAmbientes; }
true
f25989de64e7678f05c5c1bb70709f7c80ba6d91
Java
wangminpku/explore_maze
/src/main/java/cn/edu/pku/sei/shared/PathFinder.java
UTF-8
6,120
3.171875
3
[]
no_license
package cn.edu.pku.sei.shared; import java.util.*; /** * @author wangmin */ public class PathFinder { /** * This member always holds the cost of the path (if any) * found by the most recently finished solving operation. * MIN_VALUE is used to signal that the value is not yet valid. */ public static int lastCost = Integer.MIN_VALUE; /** * First, computes a shortest path from a source vertex to a destination * vertex in a graph by using Dijkstra's algorithm. Second, visits and saves * (in a stack) each vertex in the path, in reverse order starting from the * destination vertex, by using the map object pred. Third, uses a * List and Stack to generate the return Integer List by first pushing * each vertex into the stack, and then poping vertices * from the stack and adding the index of each to the * return list. The vertex indices in the return object are now in the * right order. Note that the getIndex() method is called from a * BareV object (vertex) to get its original integer name. * * @param G * - The graph in which a shortest path is to be computed * @param source * - The first vertex of the shortest path * @param dest * - The last vertex of the shortest path * @return A List of Integers corresponding the the vertices on the path * in order from source to dest. * * The contents of an example String object: Path Length: 5 Path * Cost: 4 Path: 0 4 2 5 7 9 * * @throws NullPointerException * - If any arugment is null * * @throws RuntimeException * - If the given source or dest vertex is not in the graph * */ public static List<Integer> findPath(BareG g, BareV source, BareV dest) { lastCost = Integer.MIN_VALUE; // // the supplied heap, and stack. // you may also use HashMap and HashSet from JCF. // the following is only here so that the app will run (but not // product correct results when first unpacked from the templates. int vertex_num = ((Graph) g).vertices.size(); int[] prev = new int[vertex_num]; int[] dist = new int[vertex_num]; int[][] mMatrix = new int[vertex_num][vertex_num]; List<Integer> P = new ArrayList<Integer>(); for (int i = 0; i < vertex_num; i++) { for (int j = 0; j < vertex_num; j++) { mMatrix[i][j] = Integer.MAX_VALUE; } Iterator<BareE> iterator = g.getVertex(i).getBareEdges().iterator(); while (iterator.hasNext()) { BareE edge = iterator.next(); mMatrix[i][edge.getToVertex().getIndex()] = edge.getWeight(); } } boolean[] flag = new boolean[vertex_num]; for (int i = 0; i < vertex_num; i++) { flag[i] = false; prev[i] = -1; dist[i] = mMatrix[source.getIndex()][i]; } flag[source.getIndex()] = true; dist[source.getIndex()] = 0; int k = 0; for (int i = 1; i < vertex_num; i++) { // 寻找当前最小的路径; // 即,在未获取最短路径的顶点中,找到离vs最近的顶点(k)。 int min = Integer.MAX_VALUE; for (int j = 0; j < vertex_num; j++) { if (flag[j] == false && dist[j] < min) { min = dist[j]; k = j; } } // 标记"顶点k"为已经获取到最短路径 flag[k] = true; // 修正当前最短路径和前驱顶点 // 即,当已经"顶点k的最短路径"之后,更新"未获取最短路径的顶点的最短路径和前驱顶点"。 for (int j = 0; j < vertex_num; j++) { int tmp = (mMatrix[k][j] == Integer.MAX_VALUE ? Integer.MAX_VALUE : (min + mMatrix[k][j])); if (flag[j] == false && (tmp < dist[j])) { dist[j] = tmp; prev[j] = k; } } } // for(int i=0;i<vertex_num;i++){ // System.out.println("shortest path:-----------------"); // System.out.println(dist[i]); // } LinkedStack<Integer> path = new LinkedStack<Integer>(); int index = dest.getIndex(); while (prev[index] != -1) { path.push(prev[index]); // System.out.println(prev[index]); index = prev[index]; } // System.out.println("PATH:"); int path_len = path.size(); P.add(source.getIndex()); for (int i = 0; i < path_len; i++) { P.add(path.pop()); } P.add(dest.getIndex()); lastCost = dist[dest.getIndex()]; return P; } /** * A pair class with two components of types V and C, where V is a vertex * type and C is a cost type. */ private static class Vpair<V, C extends Comparable<? super C>> implements Comparable<Vpair<V, C>> { private V node; private C cost; Vpair(V n, C c) { node = n; cost = c; } public V getVertex() { return node; } public C getCost() { return cost; } public int compareTo(Vpair<V, C> other) { return cost.compareTo(other.getCost()); } public String toString() { return "<" + node.toString() + ", " + cost.toString() + ">"; } public int hashCode() { return node.hashCode(); } public boolean equals(Object obj) { if (this == obj) return true; if ((obj == null) || (obj.getClass() != this.getClass())) return false; // object must be Vpair at this point Vpair<?, ?> test = (Vpair<?, ?>) obj; return (node == test.node || (node != null && node .equals(test.node))); } } }
true
b4cf1c9b998a0721478a90fab56e72918b749a3b
Java
alex2410/instruments
/src/test/java/ru/trushkin/instruments/reader/InstrumentReaderTest.java
UTF-8
1,713
2.296875
2
[]
no_license
package ru.trushkin.instruments.reader; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import ru.trushkin.instruments.TestConfig; import ru.trushkin.instruments.consumer.DataConsumer; import ru.trushkin.instruments.entity.Instrument; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TestConfig.class}) public class InstrumentReaderTest { @Autowired private InstrumentReader instrumentReader; @Test public void readData() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US); List<Instrument> expected = new ArrayList<>(); expected.add(Instrument.of("INSTRUMENT1", sdf.parse("01-Jan-1996"), new BigDecimal("1.1"))); expected.add(Instrument.of("INSTRUMENT1", sdf.parse("02-Jan-1996"), new BigDecimal("2.2"))); expected.add(Instrument.of("INSTRUMENT1", sdf.parse("03-Jan-1996"), new BigDecimal("3.3"))); List<Instrument> actual = new ArrayList<>(); instrumentReader.readData(new DataConsumer<>() { @Override public void onData(Instrument data) { actual.add(data); } @Override public void finish() { } }); assertEquals(expected, actual); } }
true
fee41d4f365a573c690ed493a26ceb4e3f10e927
Java
brownsands/HelloDropwizard
/src/main/java/com/javaeeee/service/PlayerInterface.java
UTF-8
166
2.03125
2
[]
no_license
package com.javaeeee.service; import com.javaeeee.bean.Game; public interface PlayerInterface { public String addPlayer(String name , int guess , Game game); }
true
3ec024119c7e8d295c0de84ce8986e8a5a790096
Java
dykdykdyk/decompileTools
/android/nut-dex2jar.src/com/nut/blehunter/d/p.java
UTF-8
711
1.828125
2
[]
no_license
package com.nut.blehunter.d; import android.text.TextUtils; import b.a.a; public final class p { public static int a(String paramString) { if (TextUtils.isEmpty(paramString)) return 0; int j = 0; int i = 0; if (j < paramString.length()) { int k = Character.codePointAt(paramString, j); if ((k >= 0) && (k <= 255)) i += 1; while (true) { j += 1; break; i += 2; } } a.b("计算混合字符串长度=" + i, new Object[0]); return i; } } /* Location: C:\crazyd\work\ustone\odm2016031702\baidu\android\nut-dex2jar.jar * Qualified Name: com.nut.blehunter.d.p * JD-Core Version: 0.6.2 */
true
d3a365ad6a08a16405bec71feeba242acdd1c147
Java
LucianoBernal/feeds_api
/src/main/java/com/etermax/conversations/resource/ConversationResource.java
UTF-8
1,178
2.390625
2
[]
no_license
package com.etermax.conversations.resource; import com.etermax.conversations.adapter.ConversationAdapter; import com.etermax.conversations.dto.ConversationDisplayDTO; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; @Api(value = "/conversations", tags = "Conversations") @Path("/conversations/{conversationId}") @Produces("application/json") public class ConversationResource { private ConversationAdapter conversationAdapter; public ConversationResource(ConversationAdapter conversationAdapter) { this.conversationAdapter = conversationAdapter; } @GET @ApiOperation(value = "Retrieves a conversation") @ApiResponses(value = { @ApiResponse(code = 404, message = "Not found"), @ApiResponse(code = 500, message = "Server error"), }) public ConversationDisplayDTO getConversation(@PathParam("conversationId") String conversationId) { return conversationAdapter.getConversation(conversationId); } }
true
a4964ce6a98539696e9b2e307ea719650ee830de
Java
1123Javayanglei/myJava
/src/com/java1805/lesson6/textList.java
UTF-8
1,385
3.703125
4
[]
no_license
package com.java1805.lesson6; import java.util.ArrayList; public class textList { public static void main(String[] args) { ArrayList<String> list=new ArrayList<String>(); list.add("张三"); list.add("李四"); list.add("王五"); list.add("刘六"); System.out.println("第一次输入list的内容:"); System.out.println(list.toString()); list.add(1,"南阳"); list.set(2,"西峡"); System.out.println("list的长度是:"+list.size()); System.out.println("list的第三个索引位置的元素是:"+list.get(3)); list.remove("王五"); System.out.println("删除王五之后list的结果是:"+list.toString()); System.out.println("list是否包含南阳"+list.contains("南阳")); System.out.println("张三在list中第一次出现是在:"+list.indexOf("张三")); System.out.println("张三在list中最后一次出现是在:"+list.lastIndexOf("张三")); list.removeAll(list); System.out.println("list清空之后是:"+list.toString()); } private static String listToString(ArrayList<? extends Object> l){ StringBuffer sb=new StringBuffer(); sb.append("|"); for (Object o:l) { sb.append(o.toString()).append(" "); } sb.append("|"); return sb.toString(); } }
true
719ccfe5ae4bca83f9abf0b6578dd02c23af19e8
Java
preethamkosuri/Java2019
/JavaModules/src/Projects/P1/Main.java
UTF-8
2,872
2.96875
3
[]
no_license
package Projects.P1; import java.util.ArrayList; import java.util.Scanner; public class Main { public void disp(){ ArrayList<Product> pro = Productfile.readPrducts(); for(int i = 0; i < pro.size(); i++) { System.out.println(pro.get(i)); } } public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("**********************"); System.out.println("Welecome to shopping!"); System.out.println("**********************"); Main s=new Main(); s.disp(); Cart[] list= new Cart[100]; ArrayList<Cart> detail=new ArrayList<Cart>(); int sum=0; int size=0; int s1=1; ArrayList<Product> pro = Productfile.readPrducts(); do { System.out.println("enter product Id to add cart or 0 to exit:"); s1=sc.nextInt(); if(s1>0){ System.out.println(pro.get(s1-1)); System.out.println("enter the quantitty below the quantity available:"); int qty=sc.nextInt(); int price=pro.get(s1-1).getPrice(); Cart item = new Cart(s1, qty, price); detail.add(item); sum=sum+(qty*price); list[size]=item; size++; } } while (s1!=0); if(size>0){ System.out.println("to generate bill, press 1, or press 0 to exit the application:"); int k=sc.nextInt(); if(k==1){ System.out.println("Sign in required!"); System.out.println("enter username:"); String uname=sc.next(); for(int j=0;j<size;j++){ System.out.println(list[j]); } System.out.println("you bill amount is:"+sum); System.out.println("enter 1 to pay or 2 to exit:"); int a1=sc.nextInt(); Admin a=new Admin(); if(a1==1 && uname!=null){ for(int e=0;e<size;e++){ int p1=list[e].getPid(); int q1=list[e].getQyt(); a.update(p1,1,-q1); } System.out.println("uname:"+uname); Log l = new Log(uname, detail); System.out.println("T1"); ArrayList<Log> ro = Productfile.readLogs(); System.out.println("T2"); if (ro == null) ro = new ArrayList<Log>(); ro.add(l); Productfile.writeLogs(ro); System.out.println("T3"); } } //Arrays.fill(list, 0); } sc.close(); } }
true
6eca4e3f7dd5111c2d73f8db1139aa4d9bdc8936
Java
shibli049/spring-boot-2-sample
/src/test/java/com/sunkuet02/springboot2/services/Impls/GreetingsServiceImplsTest.java
UTF-8
929
2.328125
2
[]
no_license
package com.sunkuet02.springboot2.services.Impls; import com.sunkuet02.springboot2.services.GreetingsService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; @RunWith(SpringRunner.class) public class GreetingsServiceImplsTest { @TestConfiguration static class GreetingsServiceImplsTestConfig { @Bean public GreetingsService greetingsService() { return new GreetingsServiceImpls(); } } @Autowired private GreetingsService greetingsService; @Test public void hello() { String helloResponse = greetingsService.hello(); assertEquals("hello", helloResponse); } }
true
8cbce5725e981ee462c0e73b037b629a7efa5a1d
Java
theamith/spring_boot
/src/main/java/com/amith/arsbilling/web/ProductsController.java
UTF-8
2,767
2.125
2
[]
no_license
package com.amith.arsbilling.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.amith.arsbilling.exception.RecordNotFoundException; import com.amith.arsbilling.model.ProductsEntity; import com.amith.arsbilling.service.ProductsService; @RestController @RequestMapping("/api/v1/products") public class ProductsController { @Autowired ProductsService service; //list all products @GetMapping public ResponseEntity<List<ProductsEntity>> getAllProducts() { List<ProductsEntity> list = service.getAllProducts(); return new ResponseEntity<List<ProductsEntity>>(list, new HttpHeaders(), HttpStatus.OK); } //user submit for billing @PostMapping("/purchase") public ResponseEntity<String> purchaseProducts(@RequestBody ProductsEntity payload) { String status = service.purchaseProducts(payload); return new ResponseEntity<String>(status, new HttpHeaders(), HttpStatus.OK); } //purchased item @GetMapping("/purchaseditems") public ResponseEntity<List<ProductsEntity>> getPurchasedItems() { List<ProductsEntity> list = service.getPurchasedProducts(); return new ResponseEntity<List<ProductsEntity>>(list, new HttpHeaders(), HttpStatus.OK); } //new stock list @GetMapping("/newstocks") public ResponseEntity<List<ProductsEntity>> getAllNewStocks() { List<ProductsEntity> list = service.getNewStocks(); return new ResponseEntity<List<ProductsEntity>>(list, new HttpHeaders(), HttpStatus.OK); } //end purchase @GetMapping("/endpurchase") public ResponseEntity<List<ProductsEntity>> endPurchase() { service.endPurchase(); List<ProductsEntity> list = service.getPurchasedProducts(); return new ResponseEntity<List<ProductsEntity>>(list, new HttpHeaders(), HttpStatus.OK); } @DeleteMapping("/{id}") public HttpStatus deleteProductById(@PathVariable("id") Long id) throws RecordNotFoundException { service.deleteProductById(id); return HttpStatus.FORBIDDEN; } }
true
32e2a5b5bae3db15abb106a41e14aacae4e992c0
Java
nn98/Algorithm
/src/BaekJoon/_Before_Tagging/P1259.java
UTF-8
439
2.5
2
[]
no_license
package BaekJoon._Before_Tagging; import java.util.Scanner; class P1259 { public static void main(String[] a){ Scanner s=new Scanner(System.in); String i=s.nextLine(); while(!i.equals("0")) { boolean b=true; for(int j=0;j<i.length()/2;j++) { if(i.charAt(j)!=i.charAt(i.length()-(1+j))) { System.out.println("no"); b=false; break; } } if(b) System.out.println("yes"); i=s.nextLine(); } } }
true
cb9f5297ff7cacdeefad5d0d876fce08a7674d14
Java
paulinek/romaPK
/src/net/panda2/roma/card/cards/CardLocation.java
UTF-8
442
1.992188
2
[]
no_license
package net.panda2.roma.card.cards; import net.panda2.RingInteger1; /** * Created with IntelliJ IDEA. * User: pacchi * Date: 21/05/12 * Time: 2:02 AM * To change this template use File | Settings | File Templates. */ public class CardLocation { public String name; public RingInteger1 location; public CardLocation(String name, RingInteger1 location) { this.name = name; this.location = location; } }
true
bc2e2dc0d2aca320ae5e52727883009bc67377b0
Java
liys96/pets-store
/src/edu/lys/entity/ProductVO.java
UTF-8
3,067
2.328125
2
[]
no_license
package edu.lys.entity; /** * @Author lys * @Date 2018年12月13日16:48:36 * @Description 商品详情类 * */ public class ProductVO { private int commodityId; //商品id private String commodityTitle; //商品标题 private String commodityHeadPic; //商品图片 private int commodityPrice; //商品价格 private String commodityQuantity; //商品净含量 private String commodityUnit; //商品单位 private int compositionId; //成分id private int commodityInventory; //商品库存 private int appraiseAmount; //评价数量 private int saleAmount; //销售数量 private String description; //描述 private String AccSale; //按销量 private String AccTime; //按时间 private String AccAppraise; //按评价 private String AccPrice; //按价格 public String getAccTime() { return AccTime; } public void setAccTime(String accTime) { AccTime = accTime; } public String getAccAppraise() { return AccAppraise; } public void setAccAppraise(String accAppraise) { AccAppraise = accAppraise; } public String getAccPrice() { return AccPrice; } public void setAccPrice(String accPrice) { AccPrice = accPrice; } public String getAccSale() { return AccSale; } public void setAccSale(String accSale) { AccSale = accSale; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getSaleAmount() { return saleAmount; } public void setSaleAmount(int saleAmount) { this.saleAmount = saleAmount; } public int getAppraiseAmount() { return appraiseAmount; } public void setAppraiseAmount(int appraiseAmount) { this.appraiseAmount = appraiseAmount; } public int getCompositionId() { return compositionId; } public void setCompositionId(int compositionId) { this.compositionId = compositionId; } public int getCommodityId() { return commodityId; } public void setCommodityId(int commodityId) { this.commodityId = commodityId; } public String getCommodityTitle() { return commodityTitle; } public void setCommodityTitle(String commodityTitle) { this.commodityTitle = commodityTitle; } public String getCommodityHeadPic() { return commodityHeadPic; } public void setCommodityHeadPic(String commodityHeadPic) { this.commodityHeadPic = commodityHeadPic; } public int getCommodityPrice() { return commodityPrice; } public void setCommodityPrice(int commodityPrice) { this.commodityPrice = commodityPrice; } public String getCommodityQuantity() { return commodityQuantity; } public void setCommodityQuantity(String commodityQuantity) { this.commodityQuantity = commodityQuantity; } public String getCommodityUnit() { return commodityUnit; } public void setCommodityUnit(String commodityUnit) { this.commodityUnit = commodityUnit; } public int getCommodityInventory() { return commodityInventory; } public void setCommodityInventory(int commodityInventory) { this.commodityInventory = commodityInventory; } }
true
c6dbe0ad4f35b1f930bf0ef5371032efc5ee2d09
Java
fCheng715/2020-09-9-SSM-CRUD
/src/main/java/com/f/crud/service/EmployeeService.java
UTF-8
447
1.898438
2
[]
no_license
package com.f.crud.service; import com.f.crud.bean.Employee; import java.util.List; /** * @author shkstart * @create 2020-09-09-16:36 */ public interface EmployeeService { List<Employee> getAll(); int insertEmp(Employee employee); boolean checkEmail(String email); Employee getEmp(Integer id); void updateEmp(Employee employee); void deleteOneEmp(Integer empId); void deleteAnyEmp(List<String> asList); }
true
411fea62946d3b583c2e33323cc31987a8befe99
Java
activeliang/tv.taobao.android
/sources/com/alibaba/sdk/android/oss/model/ListObjectsResult.java
UTF-8
2,428
2.125
2
[]
no_license
package com.alibaba.sdk.android.oss.model; import java.util.ArrayList; import java.util.List; public class ListObjectsResult extends OSSResult { private String bucketName; private List<String> commonPrefixes = new ArrayList(); private String delimiter; private String encodingType; private boolean isTruncated; private String marker; private int maxKeys; private String nextMarker; private List<OSSObjectSummary> objectSummaries = new ArrayList(); private String prefix; public List<OSSObjectSummary> getObjectSummaries() { return this.objectSummaries; } public void addObjectSummary(OSSObjectSummary objectSummary) { this.objectSummaries.add(objectSummary); } public void clearObjectSummaries() { this.objectSummaries.clear(); } public List<String> getCommonPrefixes() { return this.commonPrefixes; } public void addCommonPrefix(String commonPrefix) { this.commonPrefixes.add(commonPrefix); } public void clearCommonPrefixes() { this.commonPrefixes.clear(); } public String getNextMarker() { return this.nextMarker; } public void setNextMarker(String nextMarker2) { this.nextMarker = nextMarker2; } public String getBucketName() { return this.bucketName; } public void setBucketName(String bucketName2) { this.bucketName = bucketName2; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix2) { this.prefix = prefix2; } public String getMarker() { return this.marker; } public void setMarker(String marker2) { this.marker = marker2; } public int getMaxKeys() { return this.maxKeys; } public void setMaxKeys(int maxKeys2) { this.maxKeys = maxKeys2; } public String getDelimiter() { return this.delimiter; } public void setDelimiter(String delimiter2) { this.delimiter = delimiter2; } public String getEncodingType() { return this.encodingType; } public void setEncodingType(String encodingType2) { this.encodingType = encodingType2; } public boolean isTruncated() { return this.isTruncated; } public void setTruncated(boolean isTruncated2) { this.isTruncated = isTruncated2; } }
true
f6382e036ee1e89e1d61c00683e77af57baa279f
Java
takipi/dynalite-java
/src/main/java/com/takipi/oss/dynajava/Utils.java
UTF-8
2,061
2.84375
3
[]
no_license
package com.takipi.oss.dynajava; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); private static File createFileEntry(ZipEntry ze, String dirName) throws IOException { File entry = new File(dirName, ze.getName()); if (ze.isDirectory()) { entry.mkdirs(); } else { entry.getParentFile().mkdirs(); } return entry; } private static void copyFileContent(ZipInputStream zipInput, File toFile) throws IOException { FileOutputStream fos = new FileOutputStream(toFile); byte[] buffer = new byte[1024]; int len; while ((len = zipInput.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } public static boolean unzip(InputStream is, String destDir) { File dir = new File(destDir); dir.mkdirs(); try { ZipInputStream zis = new ZipInputStream(is); ZipEntry ze = zis.getNextEntry(); while(ze != null) { File newFile = createFileEntry(ze, destDir); if (! ze.isDirectory()) { copyFileContent(zis, newFile); } zis.closeEntry(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); is.close(); } catch (Exception e) { logger.error("Error unzipping", e); return false; } return true; } public static File createTempDirectory(String prefix) throws IOException { final File temp; temp = File.createTempFile(prefix, Long.toString(System.nanoTime())); if ((!(temp.delete())) || (!(temp.mkdir()))) { throw new IOException("Failed to create temp directory: " + temp.getAbsolutePath()); } return (temp); } public static boolean createDirectory(String dirName) { File dir = new File(dirName); if (dir.exists()) { return dir.isDirectory(); } return dir.mkdirs(); } }
true
683bdcec2622de01a67340dc16534b8c227b2e29
Java
gaohongbin/leetcode
/leetcode376.java
UTF-8
2,038
3.640625
4
[]
no_license
/** * 题目:参数为整数数组nums,找出最长的wiggle数列长度。 * wiggle: 例如:1,7,4,9,2,5 相邻数相减为:6,-3,5,-7,3正负数相隔出现。则原数列为wiggle。 * * 思路:根据leetcode300,我们用相似的方法,d[i]为nums数组0--i子数组包含nums[i]的最长wiggle数列长度。 * 所以d[i]初值为1(只包含nums[i]). * boolean[] flag表示到现在为止,概数与wiggle前一个数的关系。 * * @author: hongbin.gao * */ public class Leetcode376 { public static void main(String[] args){ int[] nums = {0,0}; int result = wiggleMaxLength(nums); System.out.println(result); } public static int wiggleMaxLength(int[] nums) { if(nums == null) return 0; if(nums.length <=1) return nums.length; int[] d = new int[nums.length]; boolean[] flag = new boolean[nums.length]; //true表示加入wiggle的列表中,该数大于前面的那个数。false表示该数小于前面那个数 d[0] = 1; flag[0] = false; int max = 1; for(int i=1;i<nums.length;i++){ d[i] = 1; for(int j = 0;j<i;j++){ if(nums[i]>nums[j] && d[j] > 1 && !flag[j]){ if(d[i]< d[j]+1){ d[i] = d[j]+1; flag[i] = !flag[j]; if(d[i]>max) max = d[i]; } } else if(nums[i]<nums[j] && d[j] > 1 && flag[j]){ if(d[i]<d[j]+1){ d[i] = d[j]+1; flag[i] = !flag[j]; if(d[i]>max) max = d[i]; } } else if(d[j] == 1){ if(nums[i]<nums[j] && d[i] == 1){ d[i] = 2; flag[i] = false; if(d[i]>max) max = d[i]; } else if(nums[i]>nums[j] && d[i] == 1){ d[i] = 2; flag[i] = true; if(d[i]>max) max = d[i]; } } } } return max; } }
true
56b1ac0bd13bb5bead6fdc977dcb759d7f4d4549
Java
dizhaung/zcloud-1
/zcloud-system/zcloud-system-service/src/main/java/com/jfatty/zcloud/system/service/impl/UserGroupServiceImpl.java
UTF-8
1,988
2.015625
2
[]
no_license
package com.jfatty.zcloud.system.service.impl; import com.jfatty.zcloud.base.vo.SystemTree; import com.jfatty.zcloud.system.entity.AccountUnique; import com.jfatty.zcloud.system.entity.UserGroup; import com.jfatty.zcloud.system.mapper.UserGroupMapper; import com.jfatty.zcloud.system.service.UserGroupService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 描述 * * @author jfatty on 2019/11/13 * @email [email protected] */ @Slf4j @Service public class UserGroupServiceImpl extends BaseSystemServiceImpl<UserGroup,UserGroupMapper> implements UserGroupService { private UserGroupMapper userGroupMapper ; @Autowired public void setUserGroupMapper(UserGroupMapper userGroupMapper) { super.setBaseMapper(userGroupMapper); this.userGroupMapper = userGroupMapper; } @Override public List<SystemTree> getUserGroupList(AccountUnique user, String userId) { Map<String, Object> map = new HashMap<String, Object>(); //supermanager Boolean sm = user.getUserName().equals("root"); map.put("sm", sm ? 1 : 0); map.put("currentUserId", user.getId()); map.put("userId", null); List<SystemTree> all = userGroupMapper.getUserGroupList(map); // if (StringUtils.isNotEmpty(userId) && StringUtils.isNotBlank(userId)) { map = new HashMap<String, Object>(); map.put("userId", userId); List<SystemTree> selecteds = userGroupMapper.getUserGroupList(map); for (SystemTree a : all) { for (SystemTree sed : selecteds) { if (sed.getValue().equals(a.getValue())) { a.setChecked(true); } } } } return all; } }
true
e4caada6099c645b1a0cfe90e83a0e6fab2b57cc
Java
AYuaner/Java-AtGuiGu
/Day4/src/com/test1/java/Encapsulation2.java
UTF-8
468
3.03125
3
[]
no_license
package com.test1.java; public class Encapsulation2 { public static void main(String[] args) { DefaultClass c1 = new DefaultClass(); // System.out.println(c1.privateNum); //private修饰的成员变量 不能被类外直接引用 System.out.println(c1.defaultNum); System.out.println(c1.protectedNum); System.out.println(c1.publicNum); //缺省、protected、public修饰的成员变量 可以被同一个package内的文件引用 } }
true
d9916ae10f9cd9ab676f3756450c4f070dd892f0
Java
lnfernal/minecraft-clone
/src/voxelGame/blocks/WoodPlankBlock.java
UTF-8
730
2.46875
2
[ "MIT" ]
permissive
package voxelGame.blocks; import org.lwjgl.util.vector.Vector3f; import voxelEngine.World; import voxelGame.ParticleEmitter; import voxelGame.entities.Entity; public class WoodPlankBlock extends Block{ private static Vector3f particleColor = new Vector3f(0.4f,0.24f,0.12f); public String getName(){ return "wooden plank block"; } public WoodPlankBlock(){ } protected int getTextureId(int side){ return 8; } public void onDestroy(Entity causer, World w, int x, int y, int z){ ParticleEmitter.emitBlockDestroy( causer, x, y, z, particleColor, 0.025f, 0, 0.003f, 30, 60, 0.2f, 0.4f, 3000, 6000 ); } public WoodPlankBlock copy(){ return new WoodPlankBlock(); } }
true
4d488ef9a7d2378018a8e835b0f2d2046b1cf2ad
Java
pxhitbk/pdtv1
/com.pdt.core/src/main/java/com/pdt/core/service/impl/TourServiceImpl.java
UTF-8
1,220
2.34375
2
[]
no_license
package com.pdt.core.service.impl; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import com.pdt.core.model.ContentType; import com.pdt.core.model.StaticContent; import com.pdt.core.model.TravelSubject; import com.pdt.core.service.CoreService; import com.pdt.core.service.TourService; @Transactional public class TourServiceImpl implements TourService { private static final String GET_STATIC_CONTENT = "SELECT c FROM " + StaticContent.class.getName() + " c WHERE c.contentType = :ct"; @Autowired private CoreService coreService; @Override public TravelSubject updateTravelSubject(TravelSubject subject) { if (subject.isStick()) { coreService.getEntityManager().createQuery("UPDATE " + TravelSubject.class.getName() + " SET stick = 0") .executeUpdate(); } return coreService.insertOrUpdate(subject); } @Override public List<StaticContent> getStaticContent(ContentType type) { List<StaticContent> contents = coreService.getEntityManager() .createQuery(GET_STATIC_CONTENT, StaticContent.class).setParameter("ct", type).getResultList(); return contents; } }
true
b27ae54ff2486ca360de3826f385f8b39f28d2cd
Java
noRelax/dubbo-springboot-demo
/dubbo-user/src/main/java/com/norelax/www/service/ArticleServiceImpl.java
UTF-8
633
2.03125
2
[]
no_license
package com.norelax.www.service; import com.alibaba.dubbo.config.annotation.Service; import com.norealx.www.base.service.ArticleService; import java.util.HashMap; import java.util.Map; /** * @author wusong * @create 2021-05-25 14:57 **/ @Service public class ArticleServiceImpl implements ArticleService { @Override public Map getArticleInfo(Long articleId) { Map<String, Object> map = new HashMap<>(); map.put("article_id", articleId); map.put("list_title", "“数一数二”之上市公司一季报②丨绿色发展大省 浙江的碳中和赛道有多宽?"); return map; } }
true
4bcf425b951ff1ada56854408224968a1e40c258
Java
tectronics/rise-of-mutants
/dev/trunk/TechDemo/src/com/bigboots/scene/BBMaterialComposer.java
UTF-8
11,517
2.1875
2
[]
no_license
/* * Copyright (C) 2011 BigBoots Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * See <http://www.gnu.org/licenses/>. */ package com.bigboots.scene; import com.jme3.asset.AssetManager; import com.jme3.asset.TextureKey; import com.jme3.material.*; import com.jme3.renderer.queue.RenderQueue.ShadowMode; import com.jme3.scene.*; import com.jme3.texture.Texture; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * * @author mifth */ public class BBMaterialComposer { private AssetManager asset; private Node nodeMain; private ArrayList geometries; private JSONObject jsObj; private String modelPath; private FileReader fileRead; public BBMaterialComposer (Node node, AssetManager assetManager, String modelPATH) { asset = assetManager; nodeMain = node; modelPath = modelPATH; geometries = new ArrayList(); System.out.println("Nodeee " + node); System.out.println("modelPATH " + modelPATH); getGeometries(nodeMain); // Load JSON script JSONParser json = new JSONParser(); fileRead = null; try { fileRead = new FileReader(new File("assets/" + modelPath + ".json")); } catch (FileNotFoundException ex) { Logger.getLogger(BBMaterialComposer.class.getName()).log(Level.SEVERE, null, ex); } try { jsObj = (JSONObject) json.parse(fileRead); } catch (IOException ex) { Logger.getLogger(BBMaterialComposer.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(BBMaterialComposer.class.getName()).log(Level.SEVERE, null, ex); } setShader(); jsObj.clear(); try { fileRead.close(); } catch (IOException ex) { Logger.getLogger(BBMaterialComposer.class.getName()).log(Level.SEVERE, null, ex); } } // Get all Geometries private void getGeometries(Node nodeMat) { Node ndMat = nodeMat; //Search for geometries SceneGraphVisitor sgv = new SceneGraphVisitor() { public void visit(Spatial spatial) { // System.out.println(spatial + " Visited Spatial"); if (spatial instanceof Geometry) { Geometry geom_sc = (Geometry) spatial; geometries.add(geom_sc); } } }; ndMat.depthFirstTraversal(sgv); // sc.breadthFirstTraversal(sgv); } private void setShader(){ JSONObject jsonMat = (JSONObject) jsObj.get("Materials"); for (Object geo : geometries.toArray()) { Geometry geom = (Geometry) geo; JSONObject jsonMatName = (JSONObject) jsonMat.get(geom.getName()); String jsonShaderName = (String) jsonMatName.get("Shader"); // set Shadows String shadowStr = (String) jsonMatName.get("Shadows"); if (shadowStr != null && shadowStr.equals("Cast")) geom.setShadowMode(ShadowMode.Cast); else if (shadowStr != null && shadowStr.equals("Receive")) geom.setShadowMode(ShadowMode.Receive); else if (shadowStr != null && shadowStr.equals("Inherit")) geom.setShadowMode(ShadowMode.Inherit); else if (shadowStr != null && shadowStr.equals("CastAndReceive")) geom.setShadowMode(ShadowMode.CastAndReceive); // setLightBlow if (jsonShaderName.equals("LightBlow")) setLightBlow(jsonMatName, geom); } } private void setLightBlow(JSONObject material, Geometry geo){ Geometry geomLB = geo; Material matNew = new Material(asset, "MatDefs/LightBlow/LightBlow.j3md"); matNew.setName(geomLB.getMaterial().getName()); geomLB.setMaterial(matNew); // DiffuseMap if (material.get("DiffuseMap") != null) { // Set Diffuse Map String strDif = (String) material.get("DiffuseMap"); TextureKey tkDif = new TextureKey(strDif, false); tkDif.setAnisotropy(2); if (strDif.indexOf(".dds") < 0) tkDif.setGenerateMips(true); Texture diffuseTex = asset.loadTexture(tkDif); matNew.setTexture("DiffuseMap", diffuseTex); // set Wrap String checkWrap = (String) material.get("WrapMode"); if (checkWrap != null && checkWrap.equals("Repeat")) diffuseTex.setWrap(Texture.WrapMode.Repeat); // set uv_Scale_0 if (material.get("UV_Scale_0") != null) { String uv_scale_0 = (String) material.get("UV_Scale_0"); float f = Float.valueOf(uv_scale_0).floatValue(); matNew.setFloat("uv_0_scale", f); } } // NormalMap if (material.get("NormalMap") != null) { // Set Normal Map String strNor = (String) material.get("NormalMap"); TextureKey tkNor = new TextureKey(strNor, false); tkNor.setAnisotropy(2); if (strNor.indexOf(".dds") < 0) tkNor.setGenerateMips(true); Texture normalTex = asset.loadTexture(tkNor); matNew.setTexture("NormalMap", normalTex); matNew.setBoolean("Nor_Inv_Y", true); // set Wrap String checkWrap = (String) material.get("WrapMode"); if (checkWrap != null && checkWrap.equals("Repeat")) normalTex.setWrap(Texture.WrapMode.Repeat); } // Specular if (material.get("Specular") != null) { // Set Specular matNew.setBoolean("Specular_Lighting", true); String strSpec = (String) material.get("Specular"); if (strSpec.equals("Dif") == true) matNew.setBoolean("Spec_A_Dif", true); else if (strSpec.equals("Nor") == true) matNew.setBoolean("Spec_A_Nor", true); } // Emission if (material.get("Emission") != null) { // Set Specular if ((Boolean) material.get("Emission") == true)matNew.setBoolean("EmissiveMap", true); } // DiffuseMap_1 if (material.get("DiffuseMap_1") != null) { // Set Diffuse Map String strDif1 = (String) material.get("DiffuseMap_1"); TextureKey tkDif = new TextureKey(strDif1, false); tkDif.setAnisotropy(2); if (strDif1.indexOf(".dds") < 0) tkDif.setGenerateMips(true); Texture diffuseTex = asset.loadTexture(tkDif); matNew.setTexture("DiffuseMap_1", diffuseTex); // set Wrap String checkWrap = (String) material.get("WrapMode"); if (checkWrap != null && checkWrap.equals("Repeat")) diffuseTex.setWrap(Texture.WrapMode.Repeat); // set uv_Scale_1 if (material.get("UV_Scale_1") != null) { String uv_scale_1 = (String) material.get("UV_Scale_1"); float f = Float.valueOf(uv_scale_1).floatValue(); matNew.setFloat("uv_1_scale", f); } } // NormalMap_1 if (material.get("NormalMap_1") != null) { // Set Normal Map String strNor1 = (String) material.get("NormalMap_1"); TextureKey tkNor = new TextureKey(strNor1, false); tkNor.setAnisotropy(2); if (strNor1.indexOf(".dds") < 0) tkNor.setGenerateMips(true); Texture normalTex = asset.loadTexture(tkNor); matNew.setTexture("NormalMap_1", normalTex); matNew.setBoolean("Nor_Inv_Y", true); // set Wrap String checkWrap = (String) material.get("WrapMode"); if (checkWrap != null && checkWrap.equals("Repeat")) normalTex.setWrap(Texture.WrapMode.Repeat); } // TextureMask if (material.get("TextureMask") != null) { // Set Diffuse Map String strMask = (String) material.get("TextureMask"); TextureKey tkTexMask = new TextureKey(strMask, false); tkTexMask.setAnisotropy(2); if (strMask.indexOf(".dds") < 0) tkTexMask.setGenerateMips(true); Texture diffuseTex = asset.loadTexture(tkTexMask); matNew.setBoolean("SeperateTexCoord", true); matNew.setTexture("TextureMask", diffuseTex); // set Wrap String checkWrap = (String) material.get("WrapMode"); if (checkWrap != null && checkWrap.equals("Repeat")) diffuseTex.setWrap(Texture.WrapMode.Repeat); } // set LightMap if (material.get("LightMap") != null || material.get("LightMap_R") != null || material.get("LightMap_G") != null || material.get("LightMap_B") != null) { // Set LightMap String lightmap = null; if(material.get("LightMap") != null) lightmap = (String) material.get("LightMap"); else if(material.get("LightMap_R") != null) lightmap = (String) material.get("LightMap_R"); else if(material.get("LightMap_G") != null) lightmap = (String) material.get("LightMap_G"); else if(material.get("LightMap_B") != null) lightmap = (String) material.get("LightMap_B"); TextureKey tkAO = new TextureKey(lightmap, false); tkAO.setAnisotropy(2); if (lightmap.indexOf(".dds") < 0) tkAO.setGenerateMips(true); Texture AOTex = asset.loadTexture(tkAO); // set a Texture and RGB channels matNew.setBoolean("SeperateTexCoord", true); matNew.setTexture("LightMap", AOTex); if(material.get("LightMap_R") != null) matNew.setBoolean("LightMap_R", true); else if(material.get("LightMap_G") != null) matNew.setBoolean("LightMap_G", true); else if(material.get("LightMap_B") != null) matNew.setBoolean("LightMap_B", true); // set Wrap String checkWrap = (String) material.get("WrapMode"); if (checkWrap != null && checkWrap.equals("Repeat")) AOTex.setWrap(Texture.WrapMode.Repeat); } } // // Set Transparency // if (matName.indexOf("a") == 0) { // matThis.setBoolean("Alpha_A_Dif", true); // matThis.setFloat("AlphaDiscardThreshold", 0.01f); // matThis.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); // // geo.setQueueBucket(Bucket.Transparent); // } else if (matName.indexOf("a") == 1) { // matThis.setBoolean("Alpha_A_Nor", true); // matThis.setFloat("AlphaDiscardThreshold", 0.01f); // matThis.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); // // geo.setQueueBucket(Bucket.Transparent); // } }
true
9960d7b238ef366edd2e528564b507b42870fddb
Java
wjffwj/Test1
/src/main/创建线程/MyRunnableTest.java
UTF-8
814
3.78125
4
[]
no_license
package 创建线程; public class MyRunnableTest implements Runnable { private int i; @Override /** * 重写run方法,该方法同样是该线程的线程执行体 */ public void run() { for (i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } public static void main(String[] args) { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); if (i == 20) { MyRunnableTest runnable = new MyRunnableTest(); //该Thread对象才是真正的线程对象. new Thread(runnable, "新线程-1").start(); new Thread(runnable, "新线程-2").start(); } } } }
true
424f9c02ad4934141f3d7bc35f2d4fb8825d65c7
Java
jeongjinhwi/Algorithm_2020
/Programmers_Level3/src/예산/Solution.java
UHC
755
3.203125
3
[]
no_license
package ; import java.util.*; public class Solution { public static int solution(int[] budgets, int M) { int answer = 0; Arrays.sort(budgets); long result = 0; int min = 0; int max = budgets[budgets.length - 1]; int center = 0; while (min <= max) { result = 0; center = (min + max) / 2; for (int t : budgets) { if (t >= center) { result += center; } else { result += t; } } if (result > M) { max = center - 1; } else { answer = center; min = center + 1; } } return answer; } public static void main(String[] args) { // TODO ڵ ޼ҵ int[] budgets = { 120, 110, 140, 150 }; int M = 485; System.out.println(solution(budgets, M)); } }
true
58a4c700cc18c112e2c34d16b6941f566b48d3ee
Java
zteeed/tempmail-apks
/sources-2020-11-04-tempmail/sources/com/google/android/gms/internal/ads/zzday.java
UTF-8
1,197
1.804688
2
[]
no_license
package com.google.android.gms.internal.ads; import com.google.android.gms.common.util.Clock; import com.google.android.gms.internal.ads.zzddz; import java.util.concurrent.atomic.AtomicReference; /* compiled from: com.google.android.gms:play-services-ads@@19.2.0 */ public final class zzday<S extends zzddz<?>> implements zzdec<S> { /* renamed from: a reason: collision with root package name */ private final AtomicReference<zr<S>> f7988a = new AtomicReference<>(); /* renamed from: b reason: collision with root package name */ private final Clock f7989b; /* renamed from: c reason: collision with root package name */ private final zzdec<S> f7990c; /* renamed from: d reason: collision with root package name */ private final long f7991d; public zzday(zzdec<S> zzdec, long j, Clock clock) { this.f7989b = clock; this.f7990c = zzdec; this.f7991d = j; } public final zzdvf<S> b() { zr zrVar = this.f7988a.get(); if (zrVar == null || zrVar.a()) { zrVar = new zr(this.f7990c.b(), this.f7991d, this.f7989b); this.f7988a.set(zrVar); } return zrVar.f5672a; } }
true
992fbebd0d7d3959f99e573d38ac28144923ce9a
Java
bendeleon1226/shortprograms
/AllKinds/src/com/aliza/food.java
UTF-8
1,358
3.328125
3
[]
no_license
package com.aliza; import java.util.Scanner; public class food { Scanner scan = new Scanner(System.in); double MTotal = 0, Total; public void intro() { System.out.println("Enter 1 for M1 ---- P10.00"); System.out.println("Enter 2 for M2 ---- P20.00"); System.out.println("Enter 3 for M3 ---- P25.00"); } public void compute() { System.out.print("Enter choice: "); int choice = scan.nextInt(); switch(choice) { case 1: { MTotal = MTotal + 10; Total = MTotal; System.out.println(Total); break; } case 2: { MTotal = MTotal + 20; Total = MTotal; System.out.println(Total); break; } case 3: { MTotal = MTotal + 25; Total = MTotal; System.out.println(Total); break; } default: { System.out.println("Error"); break; } } } }
true
c0a5f38b270d3aeab014012581792cf139dccd8c
Java
swenginator/LCAJava
/src/main/java/LCA.java
UTF-8
1,369
3.640625
4
[ "MIT" ]
permissive
package main.java; import java.util.HashSet; import java.util.Set; public class LCA { /** * Get the Lowest Common Ancestor of any two nodes in an n-ary tree. * * @param root The root node of the n-ary tree * @param nodea The first node to find the ancestor of * @param nodeb The second node to find the ancestor of * @param <V> The type of the nodes the tree holds * @return The ancestor of the two input nodes, or null if not found */ public static <V> Node<V> getLCA(Node<V> root, Node<V> nodea, Node<V> nodeb) { if (root == null || nodea == root || nodeb == root) return root; int childrenFound = 0; Node<V> lastFoundNode = null; for (Node<V> child : root.children) { Node<V> node = getLCA(child, nodea, nodeb); if (node != null) { lastFoundNode = node; childrenFound++; } if (childrenFound >= 2) return root; } return lastFoundNode; } /** * A node of a n-ary tree. Has children and data. The key is equivalent to the reference. * * @param <V> */ public static class Node<V> { public final Set<Node<V>> children = new HashSet<>(); public final V data; public Node(V data) { this.data = data; } } }
true
65271f85a5ca586c214f993104ff702b22695aed
Java
HoodyH/POO-Uni
/agenzia_imobiliare/src/agenziaimmobiliare/Appuntamento.java
UTF-8
966
2.75
3
[]
no_license
package agenziaimmobiliare; public class Appuntamento { private String nomeCliente; private Abitazione abitazione; private Data data; public Appuntamento(String nomeCliente, Abitazione abitazione, Data data) { this.nomeCliente = nomeCliente; this.abitazione = abitazione; this.data = data; } public Data getData() { return data; } public String getNome() { return nomeCliente; } public boolean isDataLibera(Appuntamento b) { if (data.getGiorno() == b.getData().getGiorno() && data.getOra() == b.getData().getOra()) { return false; } else { return true; } } public boolean equals(Appuntamento b) { if (data.getGiorno() == b.getData().getGiorno() && data.getOra() == b.getData().getOra()) { return true; } else { return false; } } }
true
f9702cd2e94b062f9f8af864294ace79a20e24ec
Java
oyzh888/ChordMixer
/app/src/main/java/com/ftboys/ChordMixer/ChordMixerAlgorithm/StdScore.java
UTF-8
5,184
2.890625
3
[]
no_license
package com.ftboys.ChordMixer.ChordMixerAlgorithm; //所有的音乐信息 都使用StdScore在各个类之间传递 import java.util.ArrayList; /** * @author OYZH * 曲谱类 */ public class StdScore { public int defNumOfTrack = 5; public ArrayList< StdChord > chordTrack; public ArrayList<StdTrack> musicTrack ; public int toneChenge = 0; //乐曲其他信息 private int volume = 100; public int tempo = 120; public String scoreName = "UnKnown"; public String author = "UnKnown"; public StdScore(){ super(); //noteTrack = new ArrayList [maxNumOfTrack];//注意泛型数组的使用(泛型声明时不能实例化) musicTrack = new ArrayList<StdTrack>(); for(int i=0; i<defNumOfTrack; i++){ musicTrack.add(new StdTrack()); } chordTrack = new ArrayList< StdChord >(); //给所有的轨道分配空间 //给和弦模式分配默认值 // for(int i = 0; i < defNumOfTrack; i++){ // noteTrack.get(i).noteTrack = new ArrayList< StdNote >(); // noteTrack.get(i).instrument = 0; // } } public void initScore() { musicTrack.get(0).noteTrack.clear(); for(int i=0; i<musicTrack.size(); i++){ musicTrack.get(i).noteTrack.clear(); } chordTrack.clear(); } //ADD BY FJC //oyzh has deleted FJC's code since the structure of StdScore was changed. public void setVolume(int volume) { this.volume = volume; } public int getVolume() { return volume; } //region encoder: public String scoreToStringNotes(){ String str = ""; for(StdNote tNote : musicTrack.get(0).noteTrack){ str += tNote.name + tNote.getOctave() + 0 + (tNote.duration-2) + " " ; if(tNote.barPoint == 1) str += ','; } return str.trim();//去掉前后空格 } // 088 0 5 1 00 // 100 1 6 1 00 // // name // author // // 08805100 08805100 08805100 // C Dm Em C4 Cadd //0-2absoluteposition 3是否升降 4时长 5附点 6-7占位符 8分隔符 public String scoreTo8BitsStringNotes(){ String str = "", placeholder = "00",seperator = " "; for(StdNote tNote : musicTrack.get(0).noteTrack){ str += String.format("%03d",tNote.absolutePosition) + tNote.downFlatSharp + tNote.duration + tNote.dot + placeholder + seperator; //这里要这样写么?? if(tNote.barPoint == 1) str += ','; } return str.trim();//去掉前后空格 } public String scoreToChord(){ String str = ""; for(StdChord tChord : chordTrack){ str += tChord.chordName + " " ; } return str.trim();//去掉了前后空格 } //保留方法 public String scoreToHeadInfo(){ String str = ""; return str; } public String scoreToFileString(){ String str = "", seperator = "$"; //头信息 str += author + seperator + scoreName + seperator + tempo + seperator + volume + seperator + toneChenge + seperator + musicTrack.size() + seperator //主旋律信息和和弦信息 + scoreTo8BitsStringNotes() + seperator + scoreToChord(); return str; } //endregion //region decoder: public StdScore fileToScore(String fileStr){ String seperator = "\\$", author, scoreName; int tempo, volume, toneChange, musicTrackSize; String[] splitedStr = fileStr.split(seperator); author = splitedStr[0]; scoreName = splitedStr[1]; tempo = Integer.valueOf(splitedStr[2]); volume = Integer.valueOf(splitedStr[3]); toneChange = Integer.valueOf(splitedStr[4]); musicTrackSize = Integer.valueOf(splitedStr[5]); StdScore scoreRet = new StdScore(); //赋值头部信息 scoreRet.scoreName = scoreName; scoreRet.author = author; scoreRet.tempo = tempo; scoreRet.volume = volume; scoreRet. toneChenge = toneChange; scoreRet.musicTrack.clear(); for(int i = 0; i<musicTrackSize; i++) scoreRet.musicTrack.add(new StdTrack()); String strArr[]; //加入主旋律 strArr = splitedStr[6].split(" "); for(String tmpStr : strArr){ scoreRet.musicTrack.get(0).noteTrack.add( stringToNote(tmpStr) ); } //加入和弦 strArr = splitedStr[7].split(" ");//chord的分隔符 for(String tmpStr : strArr){ scoreRet.chordTrack.add( stringToChord(tmpStr)); } return scoreRet; } public StdChord stringToChord(String strChord){ return new StdChord((strChord)); } public StdNote stringToNote(String strNote){ // 08805100 08805100 08805100 // C Dm Em C4 Cadd //0-2absoluteposition 3是否升降 4时长 5附点 6-7占位符 8分隔符 StdNote noteRet = new StdNote(Integer.valueOf(strNote.substring(0,3)) ); noteRet.downFlatSharp = strNote.charAt(3) - '0'; noteRet.duration = strNote.charAt(4) - '0'; noteRet.dot = strNote.charAt(5) - '0'; //System.out.println(noteRet.description()); return noteRet; } //endregion public String description(){ String str = ""; str += "numOfTrarck = " + musicTrack.size() + "\n"; str += "MainMelody:\n"; for(StdNote tmp : musicTrack.get(0).noteTrack){ str += tmp.name + tmp.getOctave() + tmp.duration + " "; } str += "\n"; str += "ChordTrack:\n"; for(StdChord tmp :chordTrack){ str += tmp.chordName + " "; } return str; } }
true
dc40a9ea1ca09e892f37412568f92a5c0a6bc73a
Java
girtel/Net2Plan
/Net2Plan-GUI/Net2Plan-GUI-Plugins/Net2Plan-NetworkDesign/src/main/java/com/net2plan/gui/plugins/networkDesign/topologyPane/TopologySideBar.java
UTF-8
20,038
1.75
2
[ "BSD-2-Clause" ]
permissive
/******************************************************************************* * Copyright (c) 2017 Pablo Pavon Marino and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the 2-clause BSD License * which accompanies this distribution, and is available at * https://opensource.org/licenses/BSD-2-Clause * * Contributors: * Pablo Pavon Marino and others - initial API and implementation *******************************************************************************/ package com.net2plan.gui.plugins.networkDesign.topologyPane; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.ScrollPaneLayout; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.plaf.basic.BasicScrollBarUI; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.bidimap.DualHashBidiMap; import com.net2plan.gui.plugins.GUINetworkDesign; import com.net2plan.gui.plugins.networkDesign.interfaces.ITopologyCanvas; import com.net2plan.gui.plugins.networkDesign.visualizationControl.VisualizationConstants; import com.net2plan.gui.plugins.networkDesign.visualizationControl.VisualizationState; import com.net2plan.interfaces.networkDesign.NetPlan; import com.net2plan.interfaces.networkDesign.NetworkLayer; import net.miginfocom.swing.MigLayout; public class TopologySideBar extends JPanel implements ActionListener { private final GUINetworkDesign callback; private final TopologyPanel topologyPanel; private final ITopologyCanvas canvas; private final JToolBar layerToolBar; private final JButton btn_increaseInterLayerDistance, btn_decreaseInterLayerDistance, btn_moveUpLayer, btn_moveDownLayer; private final JButton btn_npChangeUndo, btn_npChangeRedo; private final JToggleButton btn_showLowerLayerInfo, btn_showUpperLayerInfo, btn_showThisLayerInfo; private final JPanel layersPanel; public TopologySideBar(GUINetworkDesign callback, TopologyPanel topologyPanel, ITopologyCanvas canvas) { super(); this.callback = callback; this.topologyPanel = topologyPanel; this.canvas = canvas; this.setLayout(new BorderLayout()); this.layerToolBar = new JToolBar(); this.layerToolBar.setLayout(new MigLayout("insets 0 0 0 0, fillx, gap 0, wrap 1")); this.layerToolBar.setOrientation(JToolBar.VERTICAL); this.layerToolBar.setRollover(true); this.layerToolBar.setFloatable(false); this.layerToolBar.setOpaque(false); /* Multilayer buttons */ this.btn_increaseInterLayerDistance = new JButton(); this.btn_increaseInterLayerDistance.setToolTipText("Increase the distance between layers (when more than one layer is visible)"); this.btn_decreaseInterLayerDistance = new JButton(); this.btn_decreaseInterLayerDistance.setToolTipText("Decrease the distance between layers (when more than one layer is visible)"); this.btn_showLowerLayerInfo = new JToggleButton(); this.btn_showLowerLayerInfo.setToolTipText("Shows the links in lower layers that carry traffic of the picked element"); this.btn_showLowerLayerInfo.setSelected(callback.getVisualizationState().isShowInCanvasLowerLayerPropagation()); this.btn_showUpperLayerInfo = new JToggleButton(); this.btn_showUpperLayerInfo.setToolTipText("Shows the links in upper layers that carry traffic that appears in the picked element"); this.btn_showUpperLayerInfo.setSelected(callback.getVisualizationState().isShowInCanvasUpperLayerPropagation()); this.btn_showThisLayerInfo = new JToggleButton(); this.btn_showThisLayerInfo.setToolTipText("Shows the links in the same layer as the picked element, that carry traffic that appears in the picked element"); this.btn_showThisLayerInfo.setSelected(callback.getVisualizationState().isShowInCanvasThisLayerPropagation()); this.btn_npChangeUndo = new JButton(); this.btn_npChangeUndo.setToolTipText("Navigate back to the previous state of the network (last time the network design was changed)"); this.btn_npChangeRedo = new JButton(); this.btn_npChangeRedo.setToolTipText("Navigate forward to the next state of the network (when network design was changed"); this.btn_increaseInterLayerDistance.setIcon(new ImageIcon(TopologyPanel.class.getResource("/resources/gui/increaseLayerDistance.png"))); this.btn_decreaseInterLayerDistance.setIcon(new ImageIcon(TopologyPanel.class.getResource("/resources/gui/decreaseLayerDistance.png"))); this.btn_showThisLayerInfo.setIcon(new ImageIcon(TopologyPanel.class.getResource("/resources/gui/showLayerPropagation.png"))); this.btn_showUpperLayerInfo.setIcon(new ImageIcon(TopologyPanel.class.getResource("/resources/gui/showLayerUpperPropagation.png"))); this.btn_showLowerLayerInfo.setIcon(new ImageIcon(TopologyPanel.class.getResource("/resources/gui/showLayerLowerPropagation.png"))); this.btn_npChangeUndo.setIcon(new ImageIcon(TopologyPanel.class.getResource("/resources/gui/undoButton.png"))); this.btn_npChangeRedo.setIcon(new ImageIcon(TopologyPanel.class.getResource("/resources/gui/redoButton.png"))); this.btn_increaseInterLayerDistance.addActionListener(this); this.btn_decreaseInterLayerDistance.addActionListener(this); this.btn_showLowerLayerInfo.addActionListener(this); this.btn_showUpperLayerInfo.addActionListener(this); this.btn_showThisLayerInfo.addActionListener(this); this.btn_npChangeUndo.addActionListener(this); this.btn_npChangeRedo.addActionListener(this); /* Layers panel */ layersPanel = new JPanel(new MigLayout("insets 0, gap 1, fillx, wrap 1")); final JScrollPane scPane = new JScrollPane(layersPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scPane.setLayout(new ScrollPaneLayout() { @Override public void layoutContainer(Container parent) { JScrollPane scrollPane = (JScrollPane)parent; Rectangle availR = scrollPane.getBounds(); availR.x = availR.y = 0; Insets insets = parent.getInsets(); availR.x = insets.left; availR.y = insets.top; availR.width -= insets.left + insets.right; availR.height -= insets.top + insets.bottom; Rectangle vsbR = new Rectangle(); vsbR.width = 5; vsbR.height = availR.height; vsbR.x = availR.x + availR.width - vsbR.width; vsbR.y = availR.y; if(viewport != null) { viewport.setBounds(availR); } if(vsb != null) { vsb.setVisible(true); vsb.setBounds(vsbR); } } }); scPane.getVerticalScrollBar().setUI(new BasicScrollBarUI() { private final Dimension d = new Dimension(); @Override protected JButton createDecreaseButton(int orientation) { return new JButton() { @Override public Dimension getPreferredSize() { return d; } }; } @Override protected JButton createIncreaseButton(int orientation) { return new JButton() { @Override public Dimension getPreferredSize() { return d; } }; } @Override protected void paintTrack(Graphics g, JComponent c, Rectangle r) {} @Override protected void paintThumb(Graphics g, JComponent c, Rectangle r) { Graphics2D g2 = (Graphics2D)g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Color color = null; JScrollBar sb = (JScrollBar)c; if(!sb.isEnabled() || r.width>r.height) return; else color = Color.LIGHT_GRAY; g2.setPaint(color); g2.fillRoundRect(r.x,r.y,r.width,r.height,10,10); g2.setPaint(Color.WHITE); g2.drawRoundRect(r.x,r.y,r.width,r.height,10,10); g2.dispose(); } @Override protected void setThumbBounds(int x, int y, int width, int height) { super.setThumbBounds(x, y, width, height); scrollbar.repaint(); } }); scPane.setPreferredSize(new Dimension(0, 200)); scPane.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY)); final JPanel upDownButtonsPanel = new JPanel(); final Border insetsBorder = BorderFactory.createEmptyBorder(10, 0, 0, 0); final Border lineBorder = BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY); upDownButtonsPanel.setBorder(new CompoundBorder(insetsBorder, lineBorder)); /* Up down active layer buttons */ btn_moveUpLayer = new JButton("\u25B2"); btn_moveUpLayer.setOpaque(false); btn_moveUpLayer.setContentAreaFilled(false); btn_moveUpLayer.setBorder(null); btn_moveUpLayer.setBorderPainted(false); btn_moveUpLayer.setBorderPainted(false); btn_moveUpLayer.setFocusable(false); btn_moveUpLayer.setMargin(new Insets(0, 0, 0, 0)); btn_moveUpLayer.setToolTipText("Move up the active layer"); btn_moveUpLayer.addActionListener(this); btn_moveDownLayer = new JButton("\u25BC"); btn_moveDownLayer.setOpaque(false); btn_moveDownLayer.setContentAreaFilled(false); btn_moveDownLayer.setBorder(null); btn_moveDownLayer.setBorderPainted(false); btn_moveDownLayer.setBorderPainted(false); btn_moveDownLayer.setFocusable(false); btn_moveDownLayer.setMargin(new Insets(0, 0, 0, 0)); btn_moveDownLayer.setToolTipText("Move down the active layer"); btn_moveDownLayer.addActionListener(this); upDownButtonsPanel.add(btn_moveUpLayer); upDownButtonsPanel.add(btn_moveDownLayer); updateLayersPanel(); this.layerToolBar.add(btn_increaseInterLayerDistance, "growx"); this.layerToolBar.add(btn_decreaseInterLayerDistance, "growx"); this.layerToolBar.add(btn_showLowerLayerInfo, "growx"); this.layerToolBar.add(btn_showUpperLayerInfo, "growx"); this.layerToolBar.add(btn_showThisLayerInfo, "growx"); //multiLayerToolbar.add(btn_npChangeUndo); //multiLayerToolbar.add(btn_npChangeRedo); this.layerToolBar.addSeparator(); this.layerToolBar.add(upDownButtonsPanel, "growx"); this.layerToolBar.add(scPane, "growx"); this.layerToolBar.add(Box.createVerticalGlue()); this.add(layerToolBar, BorderLayout.WEST); } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); final VisualizationState vs = callback.getVisualizationState(); if (src == btn_increaseInterLayerDistance) { if (vs.getCanvasNumberOfVisibleLayers() == 1) return; final int currentInterLayerDistance = vs.getInterLayerSpaceInPixels(); final int newInterLayerDistance = currentInterLayerDistance + (int) Math.ceil(currentInterLayerDistance * (VisualizationConstants.SCALE_IN - 1)); vs.setInterLayerSpaceInPixels(newInterLayerDistance); canvas.updateInterLayerDistanceInNpCoordinates(newInterLayerDistance); canvas.updateAllVerticesXYPosition(); canvas.refresh(); } else if (src == btn_decreaseInterLayerDistance) { if (vs.getCanvasNumberOfVisibleLayers() == 1) return; final int currentInterLayerDistance = vs.getInterLayerSpaceInPixels(); int newInterLayerDistance = currentInterLayerDistance - (int) Math.ceil(currentInterLayerDistance * (1 - VisualizationConstants.SCALE_OUT)); if (newInterLayerDistance <= 0) newInterLayerDistance = 1; vs.setInterLayerSpaceInPixels(newInterLayerDistance); canvas.updateInterLayerDistanceInNpCoordinates(newInterLayerDistance); canvas.updateAllVerticesXYPosition(); canvas.refresh(); } else if (src == btn_showLowerLayerInfo) { vs.setShowInCanvasLowerLayerPropagation(btn_showLowerLayerInfo.isSelected()); canvas.refresh(); } else if (src == btn_showUpperLayerInfo) { vs.setShowInCanvasUpperLayerPropagation(btn_showUpperLayerInfo.isSelected()); canvas.refresh(); } else if (src == btn_showThisLayerInfo) { vs.setShowInCanvasThisLayerPropagation(btn_showThisLayerInfo.isSelected()); canvas.refresh(); } else if (src == btn_npChangeUndo) { callback.requestUndoAction(); } else if (src == btn_npChangeRedo) { callback.requestRedoAction(); } else if (src == btn_moveUpLayer) { final NetworkLayer defaultLayer = callback.getDesign().getNetworkLayerDefault(); final BidiMap<NetworkLayer, Integer> layerOrderMapConsideringNonVisible = new DualHashBidiMap<>(vs.getCanvasLayerOrderIndexMap(true)); final int defaultLayerIndex = layerOrderMapConsideringNonVisible.get(defaultLayer); if (defaultLayerIndex == 0) return; final NetworkLayer neighbourLayer = layerOrderMapConsideringNonVisible.inverseBidiMap().get(defaultLayerIndex - 1); // Swap the selected layer with the one on top of it. this.swap(layerOrderMapConsideringNonVisible, defaultLayer, neighbourLayer); vs.setCanvasLayerVisibilityAndOrder(callback.getDesign(), layerOrderMapConsideringNonVisible, vs.getCanvasLayerVisibilityMap()); callback.updateVisualizationAfterChanges(); updateLayersPanel(); } else if (src == btn_moveDownLayer) { final NetworkLayer defaultLayer = callback.getDesign().getNetworkLayerDefault(); final BidiMap<NetworkLayer, Integer> layerOrderMapConsideringNonVisible = new DualHashBidiMap<>(vs.getCanvasLayerOrderIndexMap(true)); final int defaultLayerIndex = layerOrderMapConsideringNonVisible.get(defaultLayer); if (defaultLayerIndex == layerOrderMapConsideringNonVisible.size() - 1) return; final NetworkLayer neighbourLayer = layerOrderMapConsideringNonVisible.inverseBidiMap().get(defaultLayerIndex + 1); // Swap the selected layer with the one on top of it. this.swap(layerOrderMapConsideringNonVisible, defaultLayer, neighbourLayer); vs.setCanvasLayerVisibilityAndOrder(callback.getDesign(), layerOrderMapConsideringNonVisible, vs.getCanvasLayerVisibilityMap()); callback.updateVisualizationAfterChanges(); updateLayersPanel(); } } public void updateLayersPanel() { layersPanel.removeAll(); final NetPlan netPlan = callback.getDesign(); final VisualizationState vs = callback.getVisualizationState(); for (NetworkLayer layer : vs.getCanvasLayersInVisualizationOrder(true)) { final String layerName = layer.getName().replaceAll(" ", ""); final String buttonText = layerName.isEmpty() || layerName.contains("Layer") ? "LAY" + layer.getIndex() : (layerName.length() <= 4 ? layerName : layerName.substring(0, 4)); final JButton layerButton = new JButton(); layerButton.setOpaque(false); layerButton.setContentAreaFilled(false); layerButton.setBorder(null); layerButton.setBorderPainted(false); layerButton.setBorderPainted(false); layerButton.setFocusable(false); layerButton.setMargin(new Insets(0, 0, 0, 0)); layerButton.setText(buttonText.toUpperCase()); final String layerState; final Font buttonFont; if (layer.isDefaultLayer()) { buttonFont = new Font("Segoe UI", Font.BOLD, 16); layerButton.setFont(buttonFont.deriveFont(Font.BOLD)); layerState = "active layer"; } else if (vs.isLayerVisibleInCanvas(layer)) { buttonFont = new Font("Segoe UI", Font.PLAIN, 14); layerState = "visible layer"; } else { buttonFont = new Font("Segoe UI", Font.PLAIN, 14); layerButton.setForeground(Color.GRAY); layerState = "hidden layer"; } layerButton.setFont(buttonFont); layerButton.setToolTipText(layer + " (" + layerState + ")"); layerButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (!layer.isDefaultLayer()) { if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 1) { callback.getVisualizationState().setCanvasLayerVisibility(layer, !vs.isLayerVisibleInCanvas(layer)); callback.updateVisualizationAfterChanges(); } else if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) { callback.getDesign().setNetworkLayerDefault(layer); callback.getVisualizationState().setCanvasLayerVisibility(layer, true); callback.updateVisualizationAfterChanges(); } updateLayersPanel(); } } }); layersPanel.add(layerButton, "align center"); } layersPanel.revalidate(); layersPanel.updateUI(); /* Update up/down buttons */ final NetworkLayer defaultLayer = netPlan.getNetworkLayerDefault(); final Map<NetworkLayer, Integer> layerOrderMapConsideringNonVisible = vs.getCanvasLayerOrderIndexMap(true); final int defaultLayerIndex = layerOrderMapConsideringNonVisible.get(defaultLayer); if (defaultLayerIndex == 0) { btn_moveUpLayer.setEnabled(false); btn_moveUpLayer.setForeground(Color.GRAY); } else { btn_moveUpLayer.setEnabled(true); btn_moveUpLayer.setForeground(Color.BLACK); } if (defaultLayerIndex == layerOrderMapConsideringNonVisible.size() - 1) { btn_moveDownLayer.setEnabled(false); btn_moveDownLayer.setForeground(Color.GRAY); } else { btn_moveDownLayer.setEnabled(true); btn_moveDownLayer.setForeground(Color.BLACK); } } private <K, V> void swap(Map<K, V> map, K k1, K k2) { final V value1 = map.get(k1); final V value2 = map.get(k2); if ((value1 == null) || (value2 == null)) throw new RuntimeException(); map.remove(k1); map.remove(k2); map.put(k1, value2); map.put(k2, value1); } }
true
758d92c416f0015345c343abc0b60ba113330c67
Java
ABCurado/University-Projects
/eCafetaria/ecafeteria.core/src/test/java/eapli/ecafeteria/domain/meals/DishTest.java
UTF-8
1,871
2.46875
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 eapli.ecafeteria.domain.meals; import eapli.ecafeteria.domain.meals.Dish.Dish; import eapli.framework.domain.Money; import java.util.Currency; import java.util.Locale; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author Rui Freitas */ public class DishTest { public DishTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test(expected = IllegalArgumentException.class) public void testNameMustNotBeEmpty() { System.out.println("must have non-empty name"); new Dish(new DishType("Carne", "Carne"), "", 10.2, 12.3, 0, new Money(10, Currency. getInstance(Locale. getDefault()))); } @Test(expected = IllegalArgumentException.class) public void testNameMustNotBeNull() { System.out.println("must have an name"); new Dish(new DishType("Carne", "Carne"), null, 10.2, 12.3, 0, new Money(10, Currency. getInstance(Locale. getDefault()))); } @Test(expected = IllegalArgumentException.class) public void testDishTypeMustNotBeNull() { System.out.println("must have an dish type"); new Dish(null, "Rojões", 10.2, 12.3, 0, new Money(10, Currency. getInstance(Locale. getDefault()))); } @Test(expected = IllegalArgumentException.class) public void testDishPriceMustNotBeNull() { System.out.println("must have dish price"); new Dish(new DishType("Carne", "Carne"), "Rojões", 10.2, 12.3, 0, null); } }
true
b48d592a29c865d6a151e82cdf9c86b2de61b70d
Java
swarup176/Design_Pattern
/BehavorialDP/src/com/StrategyDP/TravelStrategy.java
UTF-8
96
1.765625
2
[]
no_license
package com.StrategyDP; public interface TravelStrategy { public void gotoAirport(); }
true
ac320e18245740e31573339312cc0c746af84edb
Java
rose-0/leetcode
/src/leecode/DP/零钱兑换_322.java
UTF-8
4,463
3.34375
3
[]
no_license
package leecode.DP; import java.util.Arrays; //对比数组累加和为aim 数组选择数累加为aim //这个其实也可以作为二维dp,和左神换钱的最少货币数一样!!p191 //可以参考 换钱的最少货币数_任意张method_dp2 都多一行一列 public class 零钱兑换_322 { static int res=Integer.MAX_VALUE; public static int coinChange(int[] coins, int amount) { return 0; } //https://github.com/labuladong/fucking-algorithm/blob/master/%E7%AE%97%E6%B3%95%E6%80%9D%E7%BB%B4%E7%B3%BB%E5%88%97/%E5%AD%A6%E4%B9%A0%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E5%92%8C%E7%AE%97%E6%B3%95%E7%9A%84%E9%AB%98%E6%95%88%E6%96%B9%E6%B3%95.md public static void baoli(int[]coins,int amount,int count){//可以看出变量只有一个 if(amount<0){//像是树的遍历结构,(或者回溯框架),回溯框架的终止条件 return ; } if(amount==0){ res=Math.min(res,count); } for (int i = 0; i <coins.length ; i++) {//回溯框架的选择列表就是树的所有子节点 baoli(coins,amount-coins[i],count+1); } } /* public static int coinChangedp(int[] coins, int amount) { int[]memo=new int[amount+1];//memo[n]凑成n需要最少的硬币数目,一定要初始化 for (int i = 1; i <memo.length ; i++) { int min=Integer.MAX_VALUE; for (int j = 0; j <coins.length ; j++) { if(i-coins[j]>=0){ min=Math.min(min,memo[i-coins[j]]+1); } } memo[i]=min; } return memo[amount]==Integer.MAX_VALUE?-1:memo[amount]; } */ //二维转化成一维就是左神的空间压缩算法。。 // dp[i]=k 目标金额为i时,最少需要k枚硬币 public static int coinChangedp(int[] coins, int amount) { int[]memo=new int[amount+1];//memo[n]凑成n需要最少的硬币数目,一定要初始化 for (int i = 1; i <memo.length ; i++) { memo[i]=amount+1; } //dp[0]是0!!注意,如果上面把所有数都初始化为amount+1,这儿要把dp[0]重新初始化为0; for (int i = 1; i <memo.length ; i++) { for (int j = 0; j <coins.length ; j++) { //这里对于每个i,不管你前面有没有用过coin[j],都可以再用,所以是任意张 if(i-coins[j]>=0){ memo[i]=Math.min(memo[i],memo[i-coins[j]]+1);//不要丢到+1 } } } for (int i = 0; i <memo.length ; i++) { System.out.println("i="+i+"->"+memo[i]); } return memo[amount]==(amount+1)?-1:memo[amount]; } //二维dp 左神的方法 可以简化成一位dp,与左神P153 类似,只是没有初始化为最大值 public static int coinChangewithZUOSHEN(int[] coins, int amount) { int[][]dp=new int[coins.length+1][amount+1];//多申请一行一列 for(int i=0;i<dp[0].length;i++){ dp[0][i]=Integer.MAX_VALUE;//第一行初始化为max } for(int i=1;i<dp.length;i++){ for (int j = 1; j < dp[0].length; ++j) { // dp[i][j]=dp[i-1][j]; if(j-coins[i-1]>=0&&dp[i][j-coins[i-1]]!=Integer.MAX_VALUE){//不要忘记后面这个条件 dp[i][j]=Math.min(dp[i][j],dp[i][j-coins[i-1]]+1); } } } return dp[coins.length][amount]==Integer.MAX_VALUE?-1:dp[coins.length][amount]; } //左神二维转一维dp public static int coinChangewithZUOSHEN2(int[] coins, int amount) { int[] dp = new int[amount+1]; Arrays.fill(dp,1,dp.length,Integer.MAX_VALUE); for (int i = 0; i < coins.length; i++) {//这个和上面那个内外层循环正好相反,还需要再理解 for (int j=0; j <= amount; j++) { if(j-coins[i]>=0&&dp[j-coins[i]]!=Integer.MAX_VALUE){ dp[j]=Math.min(dp[j], dp[j-coins[i]]+1); } } } return dp[amount]==Integer.MAX_VALUE?-1:dp[amount]; } public static void main(String[] args) { int[]coins={1,2,5}; // baoli(coins,11,0); // System.out.println(res); // System.out.println(coinChangedp(coins,11)); System.out.println(coinChangewithZUOSHEN2(coins,11)); } }
true
2c766bf1a88e4ff6e7c43c9dea6989b05df77550
Java
RCuencam/Jobag-Backend
/src/main/java/com/example/jobagapi/service/LanguagesServiceImpl.java
UTF-8
2,022
2.328125
2
[]
no_license
package com.example.jobagapi.service; import com.example.jobagapi.domain.model.Languages; import com.example.jobagapi.domain.model.Sector; import com.example.jobagapi.domain.repository.LanguagesRepository; import com.example.jobagapi.domain.service.LanguagesService; import com.example.jobagapi.exception.ResourceNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @Service public class LanguagesServiceImpl implements LanguagesService { @Autowired private LanguagesRepository languagesRepository; @Override public Page<Languages> getAllLanguages(Pageable pageable) { return languagesRepository.findAll(pageable); } @Override public Languages getLanguagesById(Long languagesId) { return languagesRepository.findById(languagesId) .orElseThrow(() -> new ResourceNotFoundException("Languages","Id",languagesId)); } @Override public Languages createLanguages(Languages languages) { return languagesRepository.save(languages); } @Override public Languages updateLanguages(Long languagesId, Languages languagesRequest) { Languages languages = languagesRepository.findById(languagesId) .orElseThrow(() -> new ResourceNotFoundException("Languages","Id",languagesId)); return languagesRepository.save( languages.setName(languagesRequest.getName()) .setLevel(languagesRequest.getLevel())); } @Override public ResponseEntity<?> deleteLanguages(Long languagesId) { Languages languages = languagesRepository.findById(languagesId) .orElseThrow(() -> new ResourceNotFoundException("Languages","Id",languagesId)); languagesRepository.delete(languages); return ResponseEntity.ok().build(); } }
true
24319d4e84fcc562c610be243e56050a94ea9122
Java
ldcloud/rhh-ace-pam
/src/main/java/au/com/leonardo/poc/sms_test/Flight.java
UTF-8
2,615
2.0625
2
[]
no_license
package au.com.leonardo.poc.sms_test; import java.math.BigInteger; /** * This class was automatically generated by the data modeler tool. */ public class Flight implements java.io.Serializable { static final long serialVersionUID = 1L; private BigInteger flightID; private java.lang.String flightNumber; private java.util.List<au.com.leonardo.poc.sms_test.FlightLeg> flightLegs; private java.lang.String aircraftManufacturer; private java.lang.String aircraftModel; private au.com.leonardo.poc.sms_test.Aircraft aircraft; private au.com.leonardo.poc.sms_test.ThisFlight thisFlight; public Flight() { } public java.lang.String getFlightNumber() { return this.flightNumber; } public void setFlightNumber(java.lang.String flightNumber) { this.flightNumber = flightNumber; } public java.util.List<au.com.leonardo.poc.sms_test.FlightLeg> getFlightLegs() { return this.flightLegs; } public void setFlightLegs( java.util.List<au.com.leonardo.poc.sms_test.FlightLeg> flightLegs) { this.flightLegs = flightLegs; } public java.lang.String getAircraftManufacturer() { return this.aircraftManufacturer; } public void setAircraftManufacturer(java.lang.String aircraftManufacturer) { this.aircraftManufacturer = aircraftManufacturer; } public java.lang.String getAircraftModel() { return this.aircraftModel; } public void setAircraftModel(java.lang.String aircraftModel) { this.aircraftModel = aircraftModel; } public au.com.leonardo.poc.sms_test.Aircraft getAircraft() { return this.aircraft; } public void setAircraft(au.com.leonardo.poc.sms_test.Aircraft aircraft) { this.aircraft = aircraft; } public au.com.leonardo.poc.sms_test.ThisFlight getThisFlight() { return this.thisFlight; } public void setThisFlight(au.com.leonardo.poc.sms_test.ThisFlight thisFlight) { this.thisFlight = thisFlight; } public java.math.BigInteger getFlightID() { return this.flightID; } public void setFlightID(java.math.BigInteger flightID) { this.flightID = flightID; } public Flight(java.math.BigInteger flightID, java.lang.String flightNumber, java.util.List<au.com.leonardo.poc.sms_test.FlightLeg> flightLegs, java.lang.String aircraftManufacturer, java.lang.String aircraftModel, au.com.leonardo.poc.sms_test.Aircraft aircraft, au.com.leonardo.poc.sms_test.ThisFlight thisFlight) { this.flightID = flightID; this.flightNumber = flightNumber; this.flightLegs = flightLegs; this.aircraftManufacturer = aircraftManufacturer; this.aircraftModel = aircraftModel; this.aircraft = aircraft; this.thisFlight = thisFlight; } }
true
68ea066286c07ebd78ce7544dd12c4a6437ca3d1
Java
amendiI/SimpleFraction
/src/Serveur.java
UTF-8
391
2.75
3
[]
no_license
import java.util.List; import java.util.ArrayList; public class Serveur { private List<Client> liste; public Serveur() { liste=new ArrayList<Client>(); } public boolean Connecter(Client C) { liste.add(C); //System.out.println(C.getnom()); return true; } public void diffuser(String str) { for(int i=0;i<liste.size();i++) { liste.get(i).recevoir(str); } } }
true
5bec3bb3a95a922003865e2554feb7fe45a002f3
Java
ulasalasreenath/corejava
/src/main/java/org/itext/MergePDF.java
UTF-8
3,083
2.546875
3
[]
no_license
package org.itext; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfImportedPage; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfWriter; import java.io.*; public class MergePDF { //public static final String dest = "C:\\Altisource\\Virtual Box-Data\\shared\\Altisource\\origination-docs\\1000"; //public static final String dest = "C:\\Altisource\\Virtual Box-Data\\shared\\Altisource\\origination-docs\\12"; //public static final String dest = "C:\\Altisource\\Virtual Box-Data\\shared\\Altisource\\origination-docs\\69\\split"; public static final String dest = "C:\\Altisource\\Virtual Box-Data\\shared\\Altisource\\origination-docs" + "\\image_test"; public static void main(String[] args) { File folder = new File(dest); File[] files = folder.listFiles(); Document document = new Document(PageSize.LETTER, 0, 0, 0, 0); OutputStream outputStream = null; try { outputStream = new FileOutputStream(dest+"\\69_merged.pdf"); PdfWriter writer = PdfWriter.getInstance(document, outputStream); //writer.setFullCompression(); document.open(); PdfContentByte cb = writer.getDirectContent(); for(File aFile : files) { if(aFile.getName().toUpperCase().endsWith("PDF")) { PdfReader reader = new PdfReader(new FileInputStream(aFile)); for (int i = 1; i <= reader.getNumberOfPages(); i++) { document.newPage(); PdfImportedPage page = writer.getImportedPage(reader, i); cb.addTemplate(page, 0, 0); } } else if(aFile.getName().toUpperCase().endsWith("PNG")) { Image image = Image.getInstance(aFile.getAbsolutePath()); scaleImage(image, document); document.newPage(); document.setPageSize(image); image.setAbsolutePosition(0, 0); cb.addImage(image); } } outputStream.flush(); document.close(); outputStream.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void scaleImage(Image image, Document document) { float scalar = 0.0F; float xScalar = document.getPageSize().getWidth() / image.getWidth(); float yScalar = document.getPageSize().getHeight() / image.getHeight(); if (xScalar > yScalar) { scalar = yScalar * 100.0F; } else { scalar = xScalar * 100.0F; } image.scalePercent(scalar); } }
true
1364673ab565d6e918fb3b1e40e0e0aa74ec3cac
Java
jsuabur/libro-de-actividades
/actividades/prog/files/java/mil-ejemplos/src/gui/poo/herencia/Hijo.java
UTF-8
220
2.625
3
[ "CC0-1.0", "CC-BY-SA-3.0" ]
permissive
package gui.poo.herencia; public class Hijo extends Padre { public Hijo(String nombre) { super(nombre); this.tipo="Hijo"; } public void verMisGustos() { System.out.println(getNombre()+": me gusta Jet"); } }
true
80241aa633bd133bbb5da9ee41edd5e7326be620
Java
14SOF/HotThink
/src/main/java/skhu/sof14/hotthink/model/dto/comment/CommentBase.java
UTF-8
121
1.59375
2
[]
no_license
package skhu.sof14.hotthink.model.dto.comment; import lombok.Setter; @Setter public class CommentBase { Long id; }
true
d32e870c383c1239b7d071b88079015ba9ef3c26
Java
Dauggie/AmzPracticeProject
/src/test/java/com/amz/testcases/AllPageTest.java
UTF-8
961
1.875
2
[]
no_license
package com.amz.testcases; import static org.testng.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.io.FileHandler; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import com.amz.pages.All_ListPage; public class AllPageTest extends BaseTest { @Test public void runAllPageTest() throws Throwable { setup(); All_ListPage all = new All_ListPage(driver); all.All_Pages(); System.out.println(driver.getTitle()); Thread.sleep(2000); all.computer_Components(); String WindowTitle = driver.getTitle(); all.inputBar(); assertEquals("Amazon.com", WindowTitle); } }
true
025e847087cd1f0ce27339967e0512c06dfc3090
Java
Richard2091/musicDemo
/src/main/java/com/example/demo/controller/FavoriteController.java
UTF-8
524
1.515625
2
[]
no_license
package com.example.demo.controller; import com.example.demo.sevice.FavoriteService; import com.example.demo.utils.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import javax.websocket.server.PathParam; @RestController public class FavoriteController { @Autowired FavoriteService favoriteService; // @PostMapping("/changefavorite") // public Result<String> }
true
6a3ca98445e720b31f6f8756d4b43fc83ebd28b8
Java
Jonily/JAVA
/Mybatis-study01/mybatis-08/src/main/java/com/my/dao/BlogMapper.java
UTF-8
392
1.953125
2
[]
no_license
package com.my.dao; import com.my.pojo.Blog; import java.util.List; import java.util.Map; public interface BlogMapper { //插入数据 int addBook(Blog blog); //查询博客 List<Blog> queryBlogIf(Map map); List<Blog> queryBlogChoose(Map map); //修改博客 int updateBlog(Map map); //查询1 2 4号博客 List<Blog> queryBlogForeach(Map map); }
true
b6f24478169a9517129e44f0a995de48eb0d4003
Java
Whitexzf/Algorithm
/Algorithms/Snake.java
UTF-8
1,296
3.25
3
[]
no_license
package cn.com; import java.util.Scanner; public class Snake { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int m=1; int n=s.nextInt(); int a[][]=new int[n][n]; int row=0; int col=n-1; for(int i=0;i<=n-1;i++){ for(int j=0;j<=n-1;j++){ a[i][j]=0; } } for(int i=0;i<=n-1;i++){ for(int j=0;j<=n-1;j++){ System.out.print(a[i][j]+" "); } System.out.println(); } while(m<=n*n){ while(row<n&&a[row][col]==0){ a[row][col]=m; m++; row++; } row--; col--; while(col>=0&&a[row][col]==0){ a[row][col]=m; col--; m++; } col++; row--; while(row>=0&&a[row][col]==0){ a[row][col]=m; row--; m++; } row++; col++; while(col<n&&a[row][col]==0){ a[row][col]=m; m++; col++; } col--; row++; } for(int i=0;i<=n-1;i++){ for(int j=0;j<=n-1;j++){ System.out.print(a[i][j]+" "); } System.out.println(); } } }
true
6f230e4dd5904b71c76161e18fde2a84c81f392d
Java
dingjing0518/jqHome
/admin/src/main/java/com/by/factory/ShoppingMallFactory.java
UTF-8
460
2.515625
3
[]
no_license
package com.by.factory; import com.by.model.ShoppingMall; /** * Created by yagamai on 16-3-29. */ public enum ShoppingMallFactory { MALL; public ShoppingMall nanXiang() { return new ShoppingMall(1); } public ShoppingMall jinQiao() { return new ShoppingMall(2); } public ShoppingMall fromString(String mall) { if (mall.equals("nx")) { return nanXiang(); } else if (mall.equals("jq")) { return jinQiao(); } else return null; } }
true
d2089c363d459b664f5a2f647ccfb34093be39b4
Java
ugocottin/rollingball
/core/src/fr/ul/rollingball/models/Ball.java
UTF-8
2,159
2.75
3
[]
no_license
package fr.ul.rollingball.models; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.World; public abstract class Ball { public static float NORMAL_RADIUS = (float) GameWorld.DIM_WIDTH / 50; public static float SMALL_RADIUS = (float) GameWorld.DIM_WIDTH / 100; private float currentRadius; private Body body; public Ball(Vector2 position, World world) { // Définition du rayon this.currentRadius = Ball.NORMAL_RADIUS; // Construction du body BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.DynamicBody; bodyDef.position.set(position); this.body = world.createBody(bodyDef); FixtureDef fixtureDef = new FixtureDef(); CircleShape circleShape = new CircleShape(); circleShape.setRadius(this.currentRadius); fixtureDef.shape = circleShape; fixtureDef.density = 1; fixtureDef.restitution = 0.25f; fixtureDef.friction = 0; this.body.createFixture(fixtureDef); this.body.setUserData("B"); } public float getRadius() { return this.currentRadius; } public void setRadius(float radius) { this.currentRadius = radius; this.body.getFixtureList().first().getShape().setRadius(radius); } Vector2 getPosition() { return this.body.getPosition(); } void setPosition(Vector2 position) { this.body.setTransform(position, 0); } public void applyForce(Vector2 force) { //this.body.applyForce(force, this.body.getPosition(), true); this.body.applyForceToCenter(force, true); } boolean isOut() { Vector2 position = this.getPosition(); position.x += this.currentRadius / 2f; position.y += this.currentRadius / 2f; return (position.x > GameWorld.DIM_WIDTH) || (position.x < 0) || (position.y > GameWorld.DIM_HEIGHT) || (position.y < 0); } }
true
f86157357c54c1dc723c122837ce7cd2eed461e5
Java
dinhdeveloper/LazadaFakes
/app/src/main/java/tcd/project/seller/ui/fragment/list_export/FragmentListProductExportViewCallback.java
UTF-8
505
1.507813
2
[]
no_license
package tcd.project.seller.ui.fragment.list_export; import tcd.project.seller.dialog.option.OptionModel; public interface FragmentListProductExportViewCallback { void onClickBackHeader(); void refreshLoadingList(); void onRequestLoadMoreList(); void onRequestSearchOrFilter(String key); void onItemListSelected(OptionModel item); void onClickAddItem(); void onDeleteItemSelected(OptionModel item); void onClickFilter(); void onClickMore(OptionModel item); }
true
d7eacf7d6268d6f94871fe75fb6f42b143789172
Java
JasonYe1989/CareNebulizer
/app/src/main/java/com/elinkcare/nebulizer/controller/BtDeviceScanner.java
UTF-8
4,127
2.265625
2
[]
no_license
package com.elinkcare.nebulizer.controller; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Timer; import java.util.TimerTask; /** * Created by Administrator on 2016/3/22. */ public class BtDeviceScanner { private static BtDeviceScanner manager = new BtDeviceScanner(); private BluetoothAdapter mBtAdapter; private Set<BluetoothDevice> mDeviceSet = new HashSet<BluetoothDevice>(); private Timer mTimer; private long mScanPeriod = 2000; private boolean mIsConnected = false; private Set<IScanChangedWatcher> mScanChangedWatcherSet = new HashSet<IScanChangedWatcher>(); private IScanResultFilter mScanResultFilter; private BtDeviceScanner() { //TODO: nothing } public static synchronized BtDeviceScanner getInstance(Context context) { if(context == null) throw new NullPointerException("BluetoothManager.getInstance(context), context couldn't be null"); if(manager.mBtAdapter == null) { manager.mBtAdapter = ((BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter(); } return manager; } public static interface IScanChangedWatcher { public void onChanged(List<BluetoothDevice> devices); } public static interface IScanResultFilter { public boolean filter(BluetoothDevice device); } public static class WHQFilter implements IScanResultFilter { @Override public boolean filter(BluetoothDevice device) { return device.getName().startsWith("eLinkCareWHQ"); } } public synchronized void enableBluetooth() { mBtAdapter.enable(); } public synchronized void disableBluetooth() { mBtAdapter.disable(); } public synchronized void startScanDevice() { mDeviceSet.clear(); mBtAdapter.startLeScan(mLeScanCallback); if(mTimer != null) { mTimer.purge(); } mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { mBtAdapter.stopLeScan(mLeScanCallback); mTimer = null; refreshDevice(null); } }, mScanPeriod); } public synchronized void stopScanDevice() { mTimer.purge(); mBtAdapter.stopLeScan(mLeScanCallback); mTimer = null; } public BluetoothDevice getDevice(String address) { return mBtAdapter.getRemoteDevice(address); } public void addScanChangedWatcher(IScanChangedWatcher watcher) { mScanChangedWatcherSet.add(watcher); } public void removeScanChangedWatcher(IScanChangedWatcher watcher) { mScanChangedWatcherSet.remove(watcher); } public void setmScanResultFilter(IScanResultFilter filter) { mScanResultFilter = filter; } private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public synchronized void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { if(mScanResultFilter != null) { if(!mScanResultFilter.filter(device))return; } mDeviceSet.add(device); ArrayList<BluetoothDevice> deviceList = new ArrayList<BluetoothDevice>(); for(BluetoothDevice item : mDeviceSet) { deviceList.add(item); } refreshDevice(deviceList); } }; private synchronized void refreshDevice(ArrayList<BluetoothDevice> deviceList) { Iterator<IScanChangedWatcher> iterator = mScanChangedWatcherSet.iterator(); while(iterator.hasNext()) { iterator.next().onChanged(deviceList); } } }
true
82676898c038d0d230baaaea1fbdc3be72d73b4f
Java
RMSnow/CMMCompiler-v3
/src/test/java/V3.java
UTF-8
743
2.34375
2
[]
no_license
import v3.lexer.Lexer; import v3.vm.IRGenerator; import v3.parser.Parser; import v3.vm.CMMCompiler; import java.io.File; import java.io.IOException; import java.util.Scanner; /** * Created by snow on 14/12/2017. */ public class V3 { public static void main(String[] args) throws IOException { //从文件中获取 String file = ""; Scanner scanner = new Scanner(new File(args[0])); while (scanner.hasNext()){ file = file + scanner.nextLine() + "\n"; } Lexer lexer = new Lexer(file); Parser parser = new Parser(lexer); IRGenerator inter = new IRGenerator(parser); CMMCompiler compiler = new CMMCompiler(inter); compiler.getOutcome(); } }
true
9b0a0b9c84ba5ca24bd2c41632b08c2b15893023
Java
jeffreire/ifc-programming-study
/Portifolio_pg2/funcionarios/teste.java
UTF-8
706
2.625
3
[]
no_license
package funcionarios; import arquivos.ManipuladorDeArquivos; import funcionarios.coreFuncionarios.Funcionario; import funcionarios.coreFuncionarios.ManipuladorDeFuncionarios; public class teste { public static void main(String[] args) { Funcionario funcionario = new Funcionario(1, "Jefferson", 12, "09797970012", 5005); ManipuladorDeArquivos manipuladorDeArquivos = new ManipuladorDeArquivos(); manipuladorDeArquivos.criarArquivo("teste.bin"); ManipuladorDeFuncionarios.escreverFuncionario("funcionarios.txt", funcionario); funcionario = ManipuladorDeFuncionarios.lerFuncionario("funcionarios.txt"); System.out.println(funcionario.nome); } }
true
1ffc2948b1e26ee86f21ebb67ae937febb0a2001
Java
ziglef/asset-tracing
/src/main/java/com/mogtechnologies/assettracing/web/TitanWebService.java
UTF-8
1,696
2.1875
2
[ "Apache-2.0" ]
permissive
package com.mogtechnologies.assettracing.web; import com.mogtechnologies.assettracing.CreateAndFillGraph; import com.mogtechnologies.assettracing.GroovyGraphOps; import org.codehaus.jettison.json.JSONException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; @Path("/") @Component public class TitanWebService { @Autowired GroovyGraphOps groovyOp; @PostConstruct private void init() { System.out.println("Initialized Titan Web Example Service"); } @GET @Path("/listVertices") @Produces(MediaType.TEXT_PLAIN) public String listVertices(@Context UriInfo info) throws JSONException { String res = groovyOp.listVertices(); return "\"" + res + "\""; } @GET @Path("/plutosBrothers") @Produces(MediaType.TEXT_PLAIN) public String pipeline(@Context UriInfo info) throws JSONException { String res = groovyOp.getPlutosBrothers(); return "\"" + res + "\""; } @GET @Path("/listEdges") @Produces(MediaType.TEXT_PLAIN) public String getEdges(@Context UriInfo info) throws JSONException { String res = groovyOp.listEdges(); return "\"" + res + "\""; } @GET @Path("/getJsonGraph") @Produces(MediaType.APPLICATION_JSON) public String getJsonGraph(@Context UriInfo info) throws JSONException { groovyOp.getJsonGraph(); return "\"" + "ok" + "\""; } }
true
17c886f61d7a26f9848e7bf1350ed0d79a36160e
Java
JulongChain/julongchain-sdk-ftsafe
/src/main/java/org/bcia/javachain/sdk/security/csp/factory/CspOptsManager.java
UTF-8
3,704
2.078125
2
[ "Apache-2.0" ]
permissive
/** * Copyright Dingxuan. All Rights Reserved. * <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 org.bcia.javachain.sdk.security.csp.factory; import org.bcia.javachain.sdk.security.csp.gm.dxct.GmFactoryOpts; import org.bcia.javachain.sdk.security.csp.gm.sdt.SdtGmFactoryOpts; import org.bcia.javachain.common.exception.ValidateException; import org.bcia.javachain.sdk.common.log.JavaChainLog; import org.bcia.javachain.sdk.common.log.JavaChainLogFactory; import org.bcia.javachain.common.util.ValidateUtils; import java.util.*; /** * 类描述 * * @author zhouhui * @date 2018/06/13 * @company Dingxuan */ public class CspOptsManager { private static JavaChainLog log = JavaChainLogFactory.getLog(CspOptsManager.class); private Map<String, IFactoryOpts> factoryOptsMap = new HashMap<>(); private List<IFactoryOpts> factoryOptsList = new ArrayList<>(); private String defaultOpts; private static CspOptsManager instance; private CspOptsManager() { } public static CspOptsManager getInstance() { if (instance == null) { synchronized (CspOptsManager.class) { if (instance == null) { instance = new CspOptsManager(); } } } return instance; } public void addFactoryOpts(String name, Map<String, String> optionMap) throws ValidateException { IFactoryOpts factoryOpts = null; if (IFactoryOpts.PROVIDER_GM.equalsIgnoreCase(name)) { factoryOpts = new GmFactoryOpts(); } else if (IFactoryOpts.PROVIDER_GM_SDT.equalsIgnoreCase(name)) { factoryOpts = new SdtGmFactoryOpts(); } else if (IFactoryOpts.PROVIDER_GMT0016.equals(name)) { factoryOpts = new GmFactoryOpts(); } else if (IFactoryOpts.PROVIDER_PKCS11.equals(name)) { factoryOpts = new GmFactoryOpts(); } ValidateUtils.isNotNull(factoryOpts, "can not support this csp yet: " + name); factoryOpts.parseFrom(optionMap); factoryOptsMap.put(name, factoryOpts); factoryOptsList.add(factoryOpts); } public void addAll(String defaultOpts, Map<String, Map<String, String>> optionsMap) { this.defaultOpts = defaultOpts; if (optionsMap != null && optionsMap.size() > 0) { Iterator<Map.Entry<String, Map<String, String>>> iterator = optionsMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Map<String, String>> entry = iterator.next(); try { addFactoryOpts(entry.getKey(), entry.getValue()); } catch (ValidateException e) { log.error(e.getMessage(), e); } } } } public String getDefaultOpts() { return defaultOpts; } public IFactoryOpts getDefaultFactoryOpts() { return factoryOptsMap.get(defaultOpts); } public IFactoryOpts getFactoryOpts(String providerName) { return factoryOptsMap.get(providerName); } public List<IFactoryOpts> getFactoryOptsList() { return factoryOptsList; } }
true
96e205f7ec7fd7521edfe5e2ca17325e23586930
Java
soon14/parking-cloud-dev
/parking-cloud-platform/src/main/java/com/yxytech/parkingcloud/platform/form/ParkingOwnerForm.java
UTF-8
1,562
1.976563
2
[]
no_license
package com.yxytech.parkingcloud.platform.form; import com.yxytech.parkingcloud.core.enums.ApproveEnum; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; public class ParkingOwnerForm implements Serializable { private Long id; @NotNull(message = "产权单位不能为空") private Long ownerOrgId; @NotNull(message = "停车场不能为空") private Long parkingId; private ApproveEnum approveStatus; @NotBlank(message = "产权证明不能为空") private String proveImages; private Boolean isUsing; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getOwnerOrgId() { return ownerOrgId; } public void setOwnerOrgId(Long ownerOrgId) { this.ownerOrgId = ownerOrgId; } public Long getParkingId() { return parkingId; } public void setParkingId(Long parkingId) { this.parkingId = parkingId; } public String getProveImages() { return proveImages; } public void setProveImages(String proveImages) { this.proveImages = proveImages; } public ApproveEnum getApproveStatus() { return approveStatus; } public void setApproveStatus(ApproveEnum approveStatus) { this.approveStatus = approveStatus; } public Boolean getUsing() { return isUsing; } public void setUsing(Boolean using) { isUsing = using; } }
true
83117a81df447c8867890b6a9419ee302f733ad0
Java
biaazv/JavaLoiane
/licaodecasa19/ex15.java
ISO-8859-1
1,037
3.875
4
[]
no_license
package com.loiane.cursojava.licaodecasa19; import java.util.Scanner; public class ex15 { public static void main(String[] args) { //vetorA 10ninteiros; //if else para pares e impares //percentual de pares e de mpares Scanner scan = new Scanner(System.in); int [] vetorA = new int [10]; for(int i =0; i<vetorA.length; i++) { System.out.println("Digite um valor"); vetorA[i] = scan.nextInt(); } int par = 0; for(int i=0; i<vetorA.length; i++) { if(vetorA[i] %2 == 0) { par++; } } int impar = vetorA.length - par; //com diviso legal usar o double double porcentagemPar = (par *100)/vetorA.length; double porcentagemImpar = 100 - porcentagemPar; System.out.print("Vetor A = "); for (int i=0; i<vetorA.length; i++){ System.out.print(vetorA[i] + " "); } System.out.println(); System.out.println("Porcentagem Pares: " + porcentagemPar); System.out.println("Porcentagem mpares: " + porcentagemImpar); } }
true
e54daff1b31b268a80d96be070702f1c3d74886b
Java
sarvex/intellij-community
/platform/vcs-impl/src/com/intellij/openapi/vcs/configurable/VcsCommitMessageMarginConfigurable.java
UTF-8
4,716
1.90625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs.configurable; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.UnnamedConfigurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vcs.VcsConfiguration; import com.intellij.ui.components.JBCheckBox; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class VcsCommitMessageMarginConfigurable implements UnnamedConfigurable { @NotNull private final VcsConfiguration myConfiguration; @NotNull private final MySpinnerConfigurable mySpinnerConfigurable; @NotNull private final JBCheckBox myWrapCheckbox; public VcsCommitMessageMarginConfigurable(@NotNull Project project, @NotNull VcsConfiguration vcsConfiguration) { myConfiguration = vcsConfiguration; mySpinnerConfigurable = new MySpinnerConfigurable(project); myWrapCheckbox = new JBCheckBox(ApplicationBundle.message("checkbox.wrap.typing.on.right.margin"), false); } @Nullable @Override public JComponent createComponent() { JComponent spinnerComponent = mySpinnerConfigurable.createComponent(); mySpinnerConfigurable.myHighlightRecentlyChanged.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myWrapCheckbox.setEnabled(mySpinnerConfigurable.myHighlightRecentlyChanged.isSelected()); } }); JPanel rootPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); rootPanel.add(spinnerComponent); rootPanel.add(myWrapCheckbox); return rootPanel; } @Override public boolean isModified() { return mySpinnerConfigurable.isModified() || myWrapCheckbox.isSelected() != myConfiguration.WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN; } @Override public void apply() throws ConfigurationException { mySpinnerConfigurable.apply(); myConfiguration.WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN = myWrapCheckbox.isSelected(); } @Override public void reset() { mySpinnerConfigurable.reset(); myWrapCheckbox.setSelected(myConfiguration.WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN); myWrapCheckbox.setEnabled(mySpinnerConfigurable.myHighlightRecentlyChanged.isSelected()); } @Override public void disposeUIResources() { mySpinnerConfigurable.disposeUIResources(); } private class MySpinnerConfigurable extends VcsCheckBoxWithSpinnerConfigurable { public MySpinnerConfigurable(Project project) { super(project, VcsBundle.message("configuration.commit.message.margin.prompt"), ""); } @Override protected SpinnerNumberModel createSpinnerModel() { final int columns = myConfiguration.COMMIT_MESSAGE_MARGIN_SIZE; return new SpinnerNumberModel(columns, 0, 10000, 1); } @Nls @Override public String getDisplayName() { return VcsBundle.message("configuration.commit.message.margin.title"); } @Override public boolean isModified() { if (myHighlightRecentlyChanged.isSelected() != myConfiguration.USE_COMMIT_MESSAGE_MARGIN) { return true; } if (!Comparing.equal(myHighlightInterval.getValue(), myConfiguration.COMMIT_MESSAGE_MARGIN_SIZE)) { return true; } return false; } @Override public void apply() throws ConfigurationException { myConfiguration.USE_COMMIT_MESSAGE_MARGIN = myHighlightRecentlyChanged.isSelected(); myConfiguration.COMMIT_MESSAGE_MARGIN_SIZE = ((Number) myHighlightInterval.getValue()).intValue(); } @Override public void reset() { myHighlightRecentlyChanged.setSelected(myConfiguration.USE_COMMIT_MESSAGE_MARGIN); myHighlightInterval.setValue(myConfiguration.COMMIT_MESSAGE_MARGIN_SIZE); myHighlightInterval.setEnabled(myHighlightRecentlyChanged.isSelected()); } } }
true
88c230cb6ba4ad2a739f37c879f9dc48fcb568fc
Java
NischayKG/java_OOPS
/applet4.java
UTF-8
445
2.96875
3
[]
no_license
import java.awt.*; import java.applet.*; /*<applet code="applet4" width=900 height=800> </applet>*/ public class applet4 extends Applet { public void init() { setBackground(Color.pink); } public void paint(Graphics g) { Color c1=new Color(157,133,208); g.setColor(c1); g.drawString("Hello",20,90); Font f=new Font("Jokerman",Font.ITALIC,90); g.setFont(f); g.drawString("This is my inovation",50,90); } }
true
3da1fac0f9d401ea1fa077566b9224667adfb183
Java
kmuppidi1/fdd-test-center
/src/main/java/com/fangdd/testcenter/bean/Menu.java
UTF-8
1,497
2.40625
2
[]
no_license
package com.fangdd.testcenter.bean; public class Menu { /** * 菜单id */ private long menuId; /** * 菜单名 */ private String name; /** * 菜单访问URL */ private String url; /** * 优先级,数字越小优先级越高 */ private int priority; /** * 父菜单ID */ private long parentId; /** * 父菜单名 */ private String parentName; /** * 态状,0:启用,1:禁用 */ private int status = -1; /** * 状态文本描述,0:启用,1:禁用 */ private String statusText; public long getMenuId() { return menuId; } public void setMenuId(long menuId) { this.menuId = menuId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public long getParentId() { return parentId; } public void setParentId(long parentId) { this.parentId = parentId; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getStatusText() { return statusText; } public void setStatusText(String statusText) { this.statusText = statusText; } }
true
f7424003c2ffa1dca2f0e6325ae8d5a1299ccb96
Java
unong/batch
/proto.boston/src/main/java/com/unong/proto/boston/common/modules/ILockManager.java
UTF-8
531
1.90625
2
[]
no_license
package com.unong.proto.boston.common.modules; import java.io.IOException; import org.apache.zookeeper.KeeperException; /** * * @author unong * */ public interface ILockManager { // i wanna be master public void wannaBeMaster() throws IOException, InterruptedException, KeeperException; // context destroyed public void destroyed() throws InterruptedException; // notify if i'm master // i am available worker // who (or what?) was failed ? // who is available ? // notify if some job finished }
true
0de83e5f3521d0fde48ae396b98c633ca51c84ed
Java
Saigot/Asteroids
/src/pewpew/entities/Player.java
UTF-8
15,504
2.390625
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pewpew.entities; import java.util.ArrayList; import java.util.Arrays; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.geom.Polygon; import org.newdawn.slick.geom.Transform; import pewpew.Util; import pewpew.entities.guns.BulletBomb; import pewpew.entities.guns.BulletBounce; import pewpew.entities.guns.BulletMissle; import pewpew.entities.guns.BulletNormal; import pewpew.entities.guns.BulletShotGun; /** * * @author michael */ public class Player implements Entity { // <editor-fold defaultstate="collapsed" desc="Variables"> public float x = Entity.FORM_WIDTH / 2; public float y = Entity.FORM_HEIGHT / 2; int BounceTick; int BounceCool = 20; public float xv; public float yv; public float xa; public float ya; public float friction = 0.02f; public int damageCoolDown = 30; public int damagetick = 0; public int MAX_HEALTH = 100; public int health = MAX_HEALTH; public float MaxSpeed = 10; public float HEIGHT = 50; public float WIDTH = 50; public Polygon shape; private float scale = 1f; public Image Ship; public Image Flame; public Image ReverseFlame; public Image Barrel = null; public ArrayList<Bullet> b = new ArrayList<>(); public float BulletAngle = (float) -Math.PI / 2; // RADIANS private byte ammoType = 0; public int shotRate; public int shotCoolDown = 0; private boolean fixedGun = true; private float rotation = 0; public boolean isReverse = false; public boolean isForward = false; public int tick = 0; public int score = 100; public static final byte GUN_TYPES = 5; public static double dmgRecieveMult = 1; public static double priceMult = 1; // </editor-fold> public Player(Boolean main) { shape = new Polygon( new float[]{x + 25, y, x, y + 50, x + 50, y + 50}); try { Ship = new Image(("Res/Ship/Ship.png")); Flame = new Image("Res/Ship/ShipFlame.png"); ReverseFlame = new Image("Res/Ship/ShipReverse.png"); } catch (Exception ex) { Ship = null; return; } setScale(1); if(main){ changeBulletType(ammoType);} x -= Ship.getWidth() / 2; y -= Ship.getHeight() / 2; } // <editor-fold defaultstate="collapsed" desc="Getters & Setters"> public float getBulletAngle() { return BulletAngle; } public void setFixedGun(boolean FixedGun) { if (ammoType != 3) { fixedGun = FixedGun; } } public boolean getFixedGun() { return fixedGun; } public void toggleFixedGun() { if (ammoType != 3) { fixedGun = !fixedGun; } } public float getRotation() { return rotation; } // IN DEGREES public float getSpeed() { return (float) Math.sqrt(xv * xv + yv * yv); } public void setScale(float i) { scale = i; float shapeScale = 1 / (shape.getWidth() / (50 * i)); shape = (Polygon) shape.transform(Transform.createScaleTransform( shapeScale, shapeScale)); } public float getScale() { return scale; } @Override public Polygon getBounds() { return shape; } public float getRotatedFirePointX() { float yi = getFirePointY(); float dy = y - yi; float theta = (float) Math.toRadians(getRotation() - 90); return (float) -(dy * Math.cos(theta)) + (x + (WIDTH * scale / 2)); } public float getRotatedFirePointY() { float yi = getFirePointY(); float dy = y - yi; float theta = (float) Math.toRadians(getRotation() - 90); return (float) -(dy * Math.sin(theta)) + (y + (HEIGHT * scale / 2)); } private float getFirePointX() { float a; a = x + (WIDTH * scale / 2); return a; } private float getFirePointY() { float a; a = y + (HEIGHT * scale / 2) - (15 * scale); return a; } public byte getAmmoType() { return ammoType; } // </editor-fold> public void rotateGun(float rad) { if (ammoType == 3) { if (BulletAngle + rad > Math.PI * 3 / 2) { BulletAngle = (float) Math.PI * 3 / 2; } // if(BulletAngle + rad < Math.PI*3/2 && BulletAngle > Math.PI*3/2 // ){ // BulletAngle = 0; // } } BulletAngle += rad; } public void changeBulletType(byte type) { if (ammoType == 3) { fixedGun = BulletBomb.previousStickState; } ammoType = type; switch (type) { case 0: // normal bullet Bullet.CoolDown = BulletNormal.SuggestedCooldown; Bullet.cost = BulletNormal.SuggestedCost; Bullet.FireSound = BulletNormal.NORMAL_SOUND; Barrel = BulletNormal.NORMAL_BARREL; break; case 1: // shotgun Bullet.CoolDown = BulletShotGun.SuggestedCooldown; Bullet.cost = BulletShotGun.SuggestedCost; Bullet.FireSound = BulletShotGun.SHOTGUN_SOUND; Barrel = BulletShotGun.SHOTGUN_BARREL; break; case 2: // bounce Bullet.CoolDown = BulletBounce.SuggestedCooldown; Bullet.cost = BulletBounce.SuggestedCost; Bullet.FireSound = BulletBounce.BOUNCE_SOUND; Barrel = BulletBounce.BOUNCE_BARREL; break; case 3: // bomb Bullet.CoolDown = BulletBomb.SuggestedCooldown; Bullet.cost = BulletBomb.SuggestedCost; Bullet.FireSound = BulletBomb.BOMB_SOUND; BulletBomb.previousStickState = fixedGun; Barrel = BulletBomb.BOMB_BARREL; fixedGun = true; break; case 4: Bullet.CoolDown = BulletMissle.SuggestedCooldown; Bullet.cost = BulletMissle.SuggestedCost; Bullet.FireSound = BulletBomb.BOMB_SOUND; BulletBomb.previousStickState = fixedGun; Barrel = BulletMissle.MISSLE_BARREL; fixedGun = true; break; } } public void fireBullet() { if (shotCoolDown > 0 || score <= 0) { return; } Bullet bu = null; if (score - Bullet.cost < 0) { return; } switch (ammoType) { case 0: // Normal bu = new BulletNormal(getRotatedFirePointX(), getRotatedFirePointY(), BulletAngle, getSpeed(), Entity.FORM_WIDTH); break; case 1: // shotgun bu = new BulletShotGun(getRotatedFirePointX(), getRotatedFirePointY(), BulletAngle); break; case 2: // bouncer bu = new BulletBounce(getRotatedFirePointX(), getRotatedFirePointY(), BulletAngle, getSpeed(), 0); break; case 3: // bomb bu = new BulletBomb(getRotatedFirePointX(), getRotatedFirePointY(), (float) (BulletAngle - Math.toRadians(getRotation()))); break; case 4: // missle bu = new BulletMissle(getRotatedFirePointX(), getRotatedFirePointY(), BulletAngle); break; } if (bu != null) { b.add(bu); } shotRate = Bullet.CoolDown; // shotRate = 120; //TEMPORARY score -= (Bullet.cost * priceMult); shotCoolDown = shotRate; if (Bullet.FireSound != null) { Bullet.FireSound.playAsSoundEffect(1.0f, 0.5f, false); } } @Override public void move(Entity e) { if (health < 0) { return; } if(BounceTick >= 0){ BounceTick--; } // things done every tick // score+=1; if (damagetick > 0) { damagetick -= 1; } tick++; // friction xv = Util.doFrictionX(xv, yv, friction); yv = Util.doFrictionY(xv, yv, friction); // move ship x += xv; y += yv; // Wrap Screen if (x > FORM_WIDTH) { x = 0; } else if (x < 0) { x = FORM_WIDTH; } if (y > FORM_HEIGHT) { y = 0; } else if (y < 0) { y = FORM_HEIGHT; } // move bounds MoveBounds(); // move and cull bullets for (int i = 0; i <= b.size() - 1; i++) { b.get(i).move(this); } for (int i = 0; i <= b.size() - 1; i++) { if (b.get(i).cull()) { score += b.get(i).getScore(); b.remove(i); } } // do Cooldown if (shotCoolDown > 0) { shotCoolDown--; } isForward = false; isReverse = false; } public void MoveBounds() { shape.setCenterX(x + 25 * scale); shape.setCenterY(y + 25 * scale); } public void Forward(float up, float dn, int delta, Entity e) { if(BounceTick >= 0){ return; } isForward = true; xa = up; ya = dn; // apply acceleration if below speed limit float speed = (float) Math.sqrt((xv * xv) + (yv * yv)); if (speed < MaxSpeed || (xv < 0 && xa > 0) || (xv > 0 && xa < 0)) { xv += xa; } if (speed < MaxSpeed || (yv > 0 && ya < 0) || (yv < 0 && ya > 0)) { yv += ya; } } public void Forward(float up, float dn, int delta) { Forward(up, dn, delta, this); } public void Reverse(float up, float dn, int delta, Entity e) { if(BounceTick >= 0){ return; } isReverse = true; xa = -up; ya = -dn; // apply acceleration if below speed limit float speed = (float) Math.sqrt((xv * xv) + (yv * yv)); if (speed < MaxSpeed / 4 || (xv < 0 && xa > 0) || (xv > 0 && xa < 0)) { xv += xa; } if (speed < MaxSpeed / 4 || (yv > 0 && ya < 0) || (yv < 0 && ya > 0)) { yv += ya; } } public void Reverse(float up, float dn, int delta) { Reverse(up, dn, delta, this); } public void Rotate(float rad) { if (Ship != null) { Ship.rotate((float) Math.toDegrees(rad)); } Flame.rotate((float) Math.toDegrees(rad)); ReverseFlame.rotate((float) Math.toDegrees(rad)); // change centre of rotation shape = (Polygon) shape.transform(Transform.createRotateTransform(rad, x, y)); rotation += Math.toDegrees(rad); while (rotation > 360 || rotation < 0) { if (rotation > 360) { rotation -= 360; } else if (rotation < 0) { rotation += 360; } } // rotate bullets if gun is fixed if (fixedGun) { BulletAngle += rad; } while (BulletAngle > Math.PI * 2 || BulletAngle < 0) { if (BulletAngle > Math.PI * 2) { BulletAngle -= Math.PI * 2; } else if (BulletAngle < 0) { BulletAngle += Math.PI * 2; } } } // IN RADIANS public void Bounce(float exv, float eyv){ xv = -(xv+exv)/2; yv = -(yv+eyv)/2; if(Math.sqrt(xv*xv + yv*yv) < 2){ xv *= 5; yv *= 5; } BounceTick = BounceCool; } @Override public void render(GameContainer gc, Graphics g) { if (health < 0) { return; } if (Ship != null) { Ship.draw(x, y, scale); } else { g.setColor(Color.green); g.draw(shape); } g.setColor(Color.red); // Draw Debug // g.draw(shape); //bounds // g.drawOval(GetRotatedFirePointX(), GetRotatedFirePointY(), 5, 5); // //firepoint // g.drawOval(x, y, 5, 5);//true location // gun barrel if (Barrel != null) { Barrel.rotate((float) Math.toDegrees(BulletAngle) + 90 - Barrel.getRotation()); Barrel.draw(getRotatedFirePointX() - (Barrel.getWidth() * scale / 2), getRotatedFirePointY() - (Barrel.getHeight() * scale / 2), scale); } // exhuast flame if a != 0 if (isForward) {// (xa != 0 || ya != 0) { Flame.draw(x, y, scale); } if (isReverse) {// (xa != 0 || ya != 0) { ReverseFlame.draw(x, y, scale); } // bullets for (int i = 0; i <= b.size() - 1; i++) { b.get(i).render(gc, g); } } @Override public void death(byte conditions) { // temp debug invincibility System.out.println("DEAD: " + score); } @Override public float doDamage() { score += 10; return (int) (float)(50 * Bullet.dmgDealMult); } @Override public void takeDamage(float Damage) { // no damage if cooldown hasn't expired else damage and rest counter if (damagetick > 0) { return; } health -= (Damage * dmgRecieveMult); damagetick = damageCoolDown; if (health < 0) { death((byte) 0); } } @Override public void collides(Entity... en) { if (health < 0) { return; } for (Entity e : en) { if (e == null || e.getBounds() == null || e == this || e.cull()) { continue; } if (shape.intersects(e.getBounds())) { takeDamage(e.doDamage()); e.takeDamage(doDamage()); return; } // for (int i = 0; i <= b.size() - 1; i++) { // // if (b.get(i).Collides(e) != null) { // b.get(i).TakeDamage(e.DoDamage()); // e.TakeDamage(b.get(i).DoDamage()); // return b.get(i); // } // } } return; } @Override public boolean cull() { return false; } @Override public String getType() { return "Player"; } @Override public String getSuperType() { return "Player"; } @Override public Entity[] getAllChildren() { if (health < 0) { return null; } ArrayList<Entity> e = new ArrayList<>(); e.add(this); for (int i = 0; i <= b.size() - 1; i++) { e.addAll(Arrays.asList(b.get(i).getAllChildren())); } return e.toArray(new Entity[e.size()]); // Entity[] e = new Entity[b.size()+1]; // // for(int i = 0; i <= b.size()-1;){ // e[i] = b.get(i); // } // e[b.size()+1] = this; // return e; } }
true
aadfdac07f9b8490dd02b025b59faabc0dd40f9e
Java
rajashree/Catalog
/ePharma/Scheduler_Prepak/src/com/rdta/dhforms/SendDHForm.java
UTF-8
52,444
1.757813
2
[]
no_license
package com.rdta.dhforms; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Calendar; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.fop.apps.Fop; import org.apache.fop.apps.MimeConstants; import org.pdfbox.examples.persistence.AppendDoc; import org.pdfbox.exceptions.COSVisitorException; import org.w3c.dom.Node; import com.Ostermiller.util.Base64; import com.rdta.eag.epharma.commons.CommonUtil; import com.rdta.eag.epharma.commons.persistence.PersistanceException; import com.rdta.eag.epharma.commons.persistence.QueryRunner; import com.rdta.eag.epharma.commons.persistence.QueryRunnerFactory; import com.rdta.eag.epharma.commons.xml.XMLUtil; import com.rdta.tlapi.xql.Connection; import com.rdta.tlapi.xql.Statement; public class SendDHForm { static final QueryRunner queryRunner = QueryRunnerFactory.getInstance().getDefaultQueryRunner(); static final Log log = LogFactory.getLog(SendDHForm.class); static final SimpleDateFormat stf = new SimpleDateFormat("HHmmss"); public String sendPDF(String pedigreeID,String toMailID,String pedshipMessages){ //pedigreeID = "fff36ab3-21b8-1600-c001-304fb97d4548"; try { String query="tlsp:getRepackagedInfo('"+pedigreeID+"')"; String str=queryRunner.returnExecuteQueryStringsAsString(query); if(str !=null){ Node n1=XMLUtil.parse(str); log.info("-------ni is-----"+n1); Node n2=XMLUtil.getNode(n1,"/shippedPedigree"); Node n3 = XMLUtil.getNode(n2,"descendant::repackagedPedigree"); if(n3 != null){ sendRepackagePDF(str,pedigreeID,toMailID,pedshipMessages);//DH2135 }else{ sendInitialPDF(str,pedigreeID,toMailID,pedshipMessages);//DH2129 } } } catch (PersistanceException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } private void sendRepackagePDF(String str, String pedigreeID,String toMailId,String pedshipMessages) { // TODO Auto-generated method stub try { Date time = Calendar.getInstance().getTime(); String theTime = stf.format(time); System.out.println("Start of Creating Repackage 2135 PDF :"+theTime); log.info(" here in sendRepackagePDF....."+str); String xmlString = getRepackageXSLString(str,pedigreeID,".",pedshipMessages); boolean checkMan = checkManufacturer(str); SendDHFormEmail mail=new SendDHFormEmail(); String emailBody ="Attached are the drug pedigrees required by state law to be included with your order. Drug pedigrees are documents that trace the ownership of each prescription drug product throughout the distribution chain from manufacturer to dispenser. Pedigrees are not required for over-the-counter drugs.Your shipping history and drug pedigrees generated since July 1, 2006 may be accessed by logging into your secure ScriptPlus Account at www.southwoodhealthcare.com/scriptplus. If you require support with the login process, please email [email protected]"; File baseDir = new File("."); File outDir = new File(baseDir, "out"); outDir.mkdirs(); // Setup input and output files File xmlfile = File.createTempFile("User", ".xml"); //xmlfile.createNewFile(); // Delete temp file when program exits. xmlfile.deleteOnExit(); // Write to temp file BufferedWriter bw = new BufferedWriter(new FileWriter(xmlfile)); bw.write(xmlString); bw.close(); File xsltfile = null; if(checkMan){ xsltfile = new File(baseDir, "/xsl/repackFromManufaturer.fo"); } else{ xsltfile = new File(baseDir, "/xsl/repackFromWholesaler.fo"); } File pdffile = new File(outDir, "repack.pdf"); // Construct fop with desired output format Fop fop = new Fop(MimeConstants.MIME_PDF); // Setup output OutputStream out = new java.io.FileOutputStream(pdffile); out = new java.io.BufferedOutputStream(out); fop.setOutputStream(out); // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsltfile)); // Set the value of a <param> in the stylesheet transformer.setParameter("versionParam", "2.0"); // Setup input for XSLT transformation Source src = new StreamSource(xmlfile); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); out.close(); String[] filePath = new String[2]; filePath[0] = pdffile.getAbsolutePath(); String mergeFilePath = ""; if(!checkMan){ //String query = "(for $i in collection('tig:///ePharma/ShippedPedigree')/*:pedigreeEnvelope/*:pedigree/*:shippedPedigree[*:documentInfo/*:serialNumber = '"+pedigreeID+"']/*:repackagedPedigree/*:previousPedigrees/*:initialPedigree "; //query = query + "return $i/*:altPedigree/*:data/string())"; String query = "for $i in collection('tig:///ePharma/ShippedPedigree')/*:pedigreeEnvelope/*:pedigree/*:shippedPedigree[*:documentInfo/*:serialNumber = '"+pedigreeID+"']/*:repackagedPedigree/*:previousPedigrees/*:initialPedigree "; query = query + "return tlsp:GetBinaryImageForServlet(binary{$i/*:altPedigree/*:data},'data')"; log.info("Query : "+query); List initialStatus = queryRunner.executeQuery(query); filePath[1] = getInitialPedigreePDF(initialStatus,str); log.info("file path : "+filePath[1]); mergeFilePath=mergePDF(filePath[1],filePath[0]); }else mergeFilePath = pdffile.getAbsolutePath(); /* String query = "for $i in collection('tig:///ePharma/ShippedPedigree')/pedigreeEnvelope/pedigree/shippedPedigree[documentInfo/serialNumber = '"+pedigreeID+"']/repackagedPedigree/previousPedigrees/initialPedigree "; query = query + "return $i/altPedigree/data/string()"; log.info("Query : "+query); List initialStatus = queryRunner.executeQuery(query); String[] mergeFilePath = new String[1]; if(initialStatus != null && initialStatus.size()>0){ filePath[1] = getInitialPedigreePDF(initialStatus,str); log.info("file path : "+filePath[1]); mergeFilePath[0]=mergePDF(filePath[1],filePath[0]); }else mergeFilePath[0] = pdffile.getAbsolutePath();*/ log.info(" file path : "+mergeFilePath); Date time1 = Calendar.getInstance().getTime(); String theTime1 = stf.format(time1); log.info("Time after create Repackage 2135 PDF.. "+theTime1); log.info("Time taken to create Repackage 2135 PDF.. "+(Integer.valueOf(theTime1).intValue() - Integer.valueOf(theTime).intValue())+" secs"); String subj = "DHFORMS TEST FROM Southwood STAGING StartTime: "+theTime+" and EndTime: "+theTime1; String emailIds[] = {toMailId,"[email protected]"}; //String result=SendDHFormEmail.sendDHFormEmailAttachementToMultipleRecipients("[email protected]",emailIds,"smtp.rainingdata.com",subj,emailBody,"mgambhir","119714",mergeFilePath); //******** Sending mail to Single recipient ******* //String result=SendDHFormEmail.sendDHFormEmailAttachement("[email protected]",toMailId,"smarthost.coxmail.com", // "Southwood",emailBody,"[email protected]","60empire",mergeFilePath); //******* Sending mail to multiple recipients ******** String result=SendDHFormEmail.sendDHFormEmailAttachementToMultipleRecipients("[email protected]",emailIds,"smarthost.coxmail.com", "Southwood",emailBody,"[email protected]","60empire",mergeFilePath); Date time2 = Calendar.getInstance().getTime(); String theTime2 = stf.format(time2); log.info("Time after sending Repackage 2135 PDF.. "+theTime2); log.info(" here in sendRepackagePDF....."+result); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void sendInitialPDF(String str, String pedigreeID,String toMailId,String pedshipMessages) { log.info(" here in sendInitialPDF....."+str); try { Date time = Calendar.getInstance().getTime(); String theTime = stf.format(time); log.info("Start of Creating Initial 2129 PDF :"+theTime); String xmlString = getInitialXSLString(str,pedigreeID,".",pedshipMessages); File baseDir = new File("."); String emailBody ="Attached are the drug pedigrees required by state law to be included with your order. Drug pedigrees are documents that trace the ownership of each prescription drug product throughout the distribution chain from manufacturer to dispenser. Pedigrees are not required for over-the-counter drugs.Your shipping history and drug pedigrees generated since July 1, 2006 may be accessed by logging into your secure ScriptPlus Account at www.southwoodhealthcare.com/scriptplus. If you require support with the login process, please email [email protected]"; File outDir = new File(baseDir, "out"); outDir.mkdirs(); // Setup input and output files File xmlfile = File.createTempFile("User", ".xml"); // Delete temp file when program exits. xmlfile.deleteOnExit(); // Write to temp file BufferedWriter bw = new BufferedWriter(new FileWriter(xmlfile)); bw.write(xmlString); bw.close(); File xsltfile = new File(baseDir, "/xsl/initial.fo"); //File pdffile = File.createTempFile("initial", ".pdf"); File pdffile = new File(outDir, "1.pdf"); // Construct fop with desired output format Fop fop = new Fop(MimeConstants.MIME_PDF); // Setup output OutputStream out = new java.io.FileOutputStream(pdffile); out = new java.io.BufferedOutputStream(out); try { fop.setOutputStream(out); // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsltfile)); // Set the value of a <param> in the stylesheet transformer.setParameter("versionParam", "2.0"); // Setup input for XSLT transformation Source src = new StreamSource(xmlfile); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); out.close(); //MessageResources messageResources = getResources(request); String[] filePath = new String[2]; filePath[0] = pdffile.getAbsolutePath(); //String query = "for $i in collection('tig:///ePharma/ShippedPedigree')/*:pedigreeEnvelope/*:pedigree/*:shippedPedigree[*:documentInfo/*:serialNumber = '"+pedigreeID+"']//*:initialPedigree "; //query = query + "return $i/*:altPedigree/*:data/string()"; //String query = "for $i in collection('tig:///ePharma/ShippedPedigree')/*:pedigreeEnvelope/*:pedigree/*:shippedPedigree[*:documentInfo/*:serialNumber = '"+pedigreeID+"']//*:initialPedigree "; //query = query + "return tlsp:GetBinaryImageForServlet(binary{$i/*:altPedigree/*:data},'data')"; String query = "for $i in collection('tig:///ePharma/ShippedPedigree')/*:pedigreeEnvelope/*:pedigree/*:shippedPedigree "; query = query + "where $i/*:documentInfo/*:serialNumber = '"+pedigreeID+"' "; query = query + "return if(exists($i//*:initialPedigree/*:altPedigree)) then tlsp:GetBinaryImageForServlet(binary{$i//*:initialPedigree/*:altPedigree/*:data},'data') else ()"; log.info("Query : "+query); List initialStatus = queryRunner.executeQuery(query); String[] mergeFilePath = new String[1]; if(initialStatus != null && initialStatus.size()>0){ filePath[1] = getInitialPedigreePDF(initialStatus,str); log.info("file path : "+filePath[1]); mergeFilePath[0]=mergePDF(filePath[1],filePath[0]); }else mergeFilePath[0] = pdffile.getAbsolutePath(); log.info(" file path : "+mergeFilePath[0]); Date time1 = Calendar.getInstance().getTime(); String theTime1 = stf.format(time1); log.info("Time after create Initial 2129 PDF.. "+theTime1); log.info("Time taken to create Initial 2129 PDF.. "+(Integer.valueOf(theTime1).intValue() - Integer.valueOf(theTime).intValue())+" secs"); String subj = "DHFORMS TEST FROM Southwood STAGING StartTime: "+theTime+" and EndTime: "+theTime1; String emailIds[] = {toMailId,"[email protected]"}; // String result=SendDHFormEmail.sendDHFormEmailAttachementToMultipleRecipients("[email protected]",emailIds,"smtp.rainingdata.com",subj,emailBody,"mgambhir","119714",mergeFilePath[0]); //******** Sending mail to Single recipient ******* // String result=SendDHFormEmail.sendDHFormEmailAttachement("[email protected]",toMailId,"smarthost.coxmail.com", // "southwood",emailBody,"[email protected]","60empire",mergeFilePath[0]); //******** Sending mail to multiple recipients ******* String result=SendDHFormEmail.sendDHFormEmailAttachementToMultipleRecipients("[email protected]",emailIds,"smarthost.coxmail.com", "southwood",emailBody,"[email protected]","60empire",mergeFilePath[0]); Date time2 = Calendar.getInstance().getTime(); String theTime2 = stf.format(time2); log.info("Time after sending Initial 2129 PDF.. "+theTime2); log.info(" here in sendInitialPDF....."+result); }finally{ } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getInitialXSLString(String str,String pedigreeID,String uri,String pedshipMessages)throws Exception{ StringBuffer buffer = new StringBuffer("<shippedPedigree>"); Node n1=XMLUtil.parse(str); Node n2=XMLUtil.getNode(n1,"/shippedPedigree"); String strName =XMLUtil.getValue(n2,"signatureInfo/signerInfo/name"); String signEmail=XMLUtil.getValue(n2,"signatureInfo/signerInfo/email"); //adding business name buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"transactionInfo/senderInfo/businessAddress/businessName"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"descendant::initialPedigree/productInfo/drugName"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"descendant::initialPedigree/productInfo/strength"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"descendant::initialPedigree/productInfo/dosageForm"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"descendant::initialPedigree/productInfo/containerSize"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"descendant::initialPedigree/productInfo/productCode"),true)); Node n3 = XMLUtil.getNode(n2,"descendant::initialPedigree"); log.info("Value of node ***** : "+n2 + " signer Name : "+str); if((XMLUtil.getNode(n2,"descendant::initialPedigree/altPedigree"))!=null){ buffer.append("<altPedigree>yes</altPedigree>"); } List lotMessages = getLotInfo(pedshipMessages); Iterator lotMessageIterator = lotMessages.iterator(); int i=0; List ls= new ArrayList(); Iterator it=XMLUtil.executeQuery(n2,"itemInfo").iterator(); //Iterator it=XMLUtil.executeQuery(n3,"itemInfo").iterator(); while(it.hasNext()){ Node n4= (Node)it.next(); buffer.append(XMLUtil.convertToString(n4,true)); i++; if(i==1){ String lotNumber = XMLUtil.getValue(n4,"lot"); while(lotMessageIterator.hasNext()){ Node lotInfoNode = (Node)lotMessageIterator.next(); String lotNum = XMLUtil.getValue(lotInfoNode,"lot"); if(lotNum!=null){ if(lotNum.equals(lotNumber)){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(lotInfoNode,"Comment"),true)); break; } } } break; } log.info("Value of i in iterator loop***** : "+i); } //adding new code here... log.info("Value of i ***** : "+i); if(i==0){ Node shippedNode = XMLUtil.getNode(n2,"child::*/child::shippedPedigree"); while(true){ if(shippedNode!=null){ Iterator itemIterator = XMLUtil.executeQuery(shippedNode,"itemInfo").iterator(); //Iterator it=XMLUtil.executeQuery(n3,"itemInfo").iterator(); while(it.hasNext()){ Node itemNode= (Node)itemIterator.next(); buffer.append(XMLUtil.convertToString(itemNode,true)); i++; if(i==1){ String lotNumber = XMLUtil.getValue(itemNode,"lot"); while(lotMessageIterator.hasNext()){ Node lotInfoNode = (Node)lotMessageIterator.next(); String lotNum = XMLUtil.getValue(lotInfoNode,"lot"); if(lotNum!=null){ if(lotNum.equals(lotNumber)){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(lotInfoNode,"Comment"),true)); break; } } } break; } } shippedNode = XMLUtil.getNode(shippedNode,"child::*/child::shippedPedigree"); } if(i>0 || shippedNode == null)break; } if(i==0){ Iterator initialItemInfoIt=XMLUtil.executeQuery(n3,"itemInfo").iterator(); //Iterator it=XMLUtil.executeQuery(n3,"itemInfo").iterator(); while(initialItemInfoIt.hasNext()){ Node n4= (Node)initialItemInfoIt.next(); buffer.append(XMLUtil.convertToString(n4,true)); i++; if(i==1){ String lotNumber = XMLUtil.getValue(n4,"lot"); while(lotMessageIterator.hasNext()){ Node lotInfoNode = (Node)lotMessageIterator.next(); String lotNum = XMLUtil.getValue(lotInfoNode,"lot"); if(lotNum!=null){ if(lotNum.equals(lotNumber)){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(lotInfoNode,"Comment"),true)); break; } } } break; } } } } buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"transactionInfo/transactionDate"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"productInfo/manufacturer"),true)); Node n5 = XMLUtil.getNode(n3,"descendant::transactionInfo"); /*if(n3!=null && n5 != null){ boolean flag = compare(n3); buffer.append("<initialTransaction>"); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/senderInfo/businessAddress"),true)); //Setting the business Address buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/transactionDate"),true)); //buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/senderInfo/contactInfo"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/recipientInfo"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/senderInfo/contactInfo"),true)); //Setting the Shipping Address if(!flag){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/senderInfo/shippingAddress"),true)); } buffer.append("</initialTransaction>"); }*/ buffer.append("<custodyChain>"); String serialNumber=""; Node intialShipped = XMLUtil.getNode(n2,"descendant-or-self::*[initialPedigree]"); if(intialShipped!=null){ buffer.append("<transactionInfo>"); boolean flag = compare(intialShipped); serialNumber = XMLUtil.getValue(intialShipped,"documentInfo/serialNumber"); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/senderInfo/businessAddress"),true)); //Setting the business Address /*buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/transactionDate"),true)); */ if(n5!=null){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/transactionDate"),true)); }else{ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/transactionDate"),true)); } if(XMLUtil.getNode(intialShipped,"transactionInfo/senderInfo/contactInfo")!=null) buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/senderInfo/contactInfo"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/recipientInfo"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"signatureInfo/signerInfo"),true)); if(!flag){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/senderInfo/shippingAddress"),true)); } /*if((XMLUtil.getNode(n2,"descendant::initialPedigree/transactionInfo"))!=null){ buffer.append("<checkPedigree>yes</checkPedigree>"); }*/ if((XMLUtil.getNode(n2,"descendant::initialPedigree/altPedigree"))!=null){ buffer.append("<altPedigree>yes</altPedigree>"); } buffer.append("</transactionInfo>"); } //intialTransaction information inside the custody chain /* if(n5!=null){ buffer.append("<transactionInfo>"); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n3,"transactionInfo/transactionDate"),true)); buffer.append("</transactionInfo>"); } */ if(!(pedigreeID.equals(serialNumber))){ Node shippedNode = XMLUtil.getNode(intialShipped,"ancestor::shippedPedigree"); Node testNode = intialShipped; while(true){ //Node shippedNode = XMLUtil.getNode(n2,".[descendant-or-self::*/shippedPedigree/documentInfo/serialNumber='"+serialNumber+"']"); if(shippedNode!=null){ buffer.append("<transactionInfo>"); boolean flag = compare(shippedNode); serialNumber = XMLUtil.getValue(shippedNode,"documentInfo/serialNumber"); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/senderInfo/businessAddress"),true)); //Setting the business Address /*buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/transactionDate"),true)); */ if(n5!=null){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(testNode,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(testNode,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(testNode,"transactionInfo/transactionDate"),true)); }else{ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/transactionDate"),true)); } if(XMLUtil.getNode(shippedNode,"transactionInfo/senderInfo/contactInfo")!=null) buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/senderInfo/contactInfo"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/recipientInfo"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"signatureInfo/signerInfo"),true)); //Setting the Shipping Address if(!flag){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/senderInfo/shippingAddress"),true)); } /*if((XMLUtil.getNode(n2,"descendant::initialPedigree/transactionInfo"))!=null){ buffer.append("<checkPedigree>yes</checkPedigree>"); }*/ testNode = shippedNode; shippedNode = XMLUtil.getNode(shippedNode,"ancestor::shippedPedigree"); buffer.append("</transactionInfo>"); } if(pedigreeID.equals(serialNumber) || shippedNode==null)break; } } buffer.append("</custodyChain>"); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"signatureInfo/signerInfo"),true)); buffer.append("<date>"+CommonUtil.dateToString(new Date())+"</date>"); //buffer.append("<path>C:\\Documents and Settings\\Ajay Reddy\\workspace\\ePharma_SW\\xsl\\logo.gif</path>"); buffer.append("<path>"+uri+"</path>"); buffer.append("<signPath>"+uri+"</signPath>"); buffer.append("</shippedPedigree>"); log.info("XML :"+buffer.toString()); getSignatureImage(strName,signEmail); return buffer.toString(); } public static void getSignatureImage(String strName,String strSignEmail)throws Exception{ try{ Helper helper =new Helper(); Connection Conn = helper.ConnectTL(); Statement Stmt = helper.getStatement(Conn); StringBuffer bfr = new StringBuffer(); bfr.append("let $userId := (for $i in collection('tig:///EAGRFID/SysUsers')/User"); bfr.append(" where concat(data($i/FirstName),' ',data($i/LastName))= '" +strName+"' and $i/Email='"+strSignEmail+"'"); bfr.append(" return data($i/UserID))"); bfr.append("for $k in collection('tig:///EAGRFID/UserSign')/User"); bfr.append(" where $k/UserID = $userId"); bfr.append(" return $k/UserSign/binary()"); byte[] rslt = helper.ReadTL(Stmt, bfr.toString()); File pictFile = new File("xsl\\Signature.jpeg"); if(pictFile.exists()){ pictFile.delete(); } if (rslt != null) { FileOutputStream fos = new FileOutputStream(pictFile); fos.write(rslt); fos.flush(); } Thread.sleep(1750); }catch(Exception ie) { } //return status; } public String mergePDF(String file1,String file2) throws COSVisitorException, IOException{ AppendDoc merge = new AppendDoc(); String fileout="C:/Temp/DHMergedPedigreeForm.pdf"; //merge.doIt("C:/Temp/ap-DH2135Pedigree.pdf", "C:/Temp/ap-DH2129Pedigree.pdf", "C:/Temp/out1.pdf"); merge.doIt(file2, file1, fileout); log.info("PDF merged..."); return fileout; } public String getRepackageXSLString(String str,String pedigreeID,String uri,String pedshipMessages)throws Exception{ StringBuffer buffer = new StringBuffer("<shippedPedigree>"); Node n1=XMLUtil.parse(str); Node n2=XMLUtil.getNode(n1,"/shippedPedigree"); String strName =XMLUtil.getValue(n2,"signatureInfo/signerInfo/name"); String signEmail=XMLUtil.getValue(n2,"signatureInfo/signerInfo/email"); //adding business name buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"transactionInfo/senderInfo/businessAddress/businessName"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"descendant::repackagedPedigree/productInfo/drugName"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"descendant::repackagedPedigree/productInfo/strength"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"descendant::repackagedPedigree/productInfo/dosageForm"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"descendant::repackagedPedigree/productInfo/containerSize"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"descendant::repackagedPedigree/productInfo/productCode"),true)); if((XMLUtil.getNode(n2,"descendant::repackagedPedigree/productInfo/manufacturer"))!=null){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"descendant::repackagedPedigree/productInfo/manufacturer"),true)); } buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"signatureInfo/signerInfo"),true)); Node n3 = XMLUtil.getNode(n2,"descendant::repackagedPedigree"); //to check if any altPedigree exists if((XMLUtil.getNode(n3,"descendant::altPedigree"))!=null){ buffer.append("<altPedigree>yes</altPedigree>"); } List lotMessages = getLotInfo(pedshipMessages); Iterator lotMessageIterator = lotMessages.iterator(); int i=0; List ls= new ArrayList(); Iterator it=XMLUtil.executeQuery(n2,"itemInfo").iterator(); //Iterator it=XMLUtil.executeQuery(n3,"itemInfo").iterator(); while(it.hasNext()){ Node n4= (Node)it.next(); buffer.append(XMLUtil.convertToString(n4,true)); i++; if(i==1){ String lotNumber = XMLUtil.getValue(n4,"lot"); while(lotMessageIterator.hasNext()){ Node lotInfoNode = (Node)lotMessageIterator.next(); String lotNum = XMLUtil.getValue(lotInfoNode,"lot"); if(lotNum!=null){ if(lotNum.equals(lotNumber)){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(lotInfoNode,"Comment"),true)); break; } } } break; } } //adding new code here... if(i==0){ Node shippedNode = XMLUtil.getNode(n2,"child::*/child::shippedPedigree"); while(true){ if(shippedNode!=null){ Iterator itemIterator = XMLUtil.executeQuery(shippedNode,"itemInfo").iterator(); //Iterator it=XMLUtil.executeQuery(n3,"itemInfo").iterator(); while(it.hasNext()){ Node itemNode= (Node)itemIterator.next(); buffer.append(XMLUtil.convertToString(itemNode,true)); i++; if(i==1){ String lotNumber = XMLUtil.getValue(itemNode,"lot"); while(lotMessageIterator.hasNext()){ Node lotInfoNode = (Node)lotMessageIterator.next(); String lotNum = XMLUtil.getValue(lotInfoNode,"lot"); if(lotNum!=null){ if(lotNum.equals(lotNumber)){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(lotInfoNode,"Comment"),true)); break; } } } break; } } shippedNode = XMLUtil.getNode(shippedNode,"child::*/child::shippedPedigree"); } if(i>0 || shippedNode == null)break; }if(i==0){ Iterator initialItemInfoIt=XMLUtil.executeQuery(n3,"itemInfo").iterator(); //Iterator it=XMLUtil.executeQuery(n3,"itemInfo").iterator(); while(initialItemInfoIt.hasNext()){ Node n4= (Node)initialItemInfoIt.next(); buffer.append(XMLUtil.convertToString(n4,true)); i++; if(i==1){ String lotNumber = XMLUtil.getValue(n4,"lot"); while(lotMessageIterator.hasNext()){ Node lotInfoNode = (Node)lotMessageIterator.next(); String lotNum = XMLUtil.getValue(lotInfoNode,"lot"); if(lotNum!=null){ if(lotNum.equals(lotNumber)){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(lotInfoNode,"Comment"),true)); break; } } } break; } } } } buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"transactionInfo/transactionDate"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(n2,"transactionInfo/transactionIdentifier/identifierType"),true)); Iterator it1=XMLUtil.executeQuery(n2,"descendant::repackagedPedigree/previousProducts").iterator(); while(it1.hasNext()){ Node n4= (Node)it1.next(); buffer.append(XMLUtil.convertToString(n4,true)); } buffer.append("<custodyChain>"); String serialNumber=""; Node intialShipped = XMLUtil.getNode(n2,"descendant-or-self::*[repackagedPedigree]"); Node repackTransactionInfo = getTransactionInfo(n3); if(intialShipped!=null){ buffer.append("<transactionInfo>"); boolean flag = compare(intialShipped); serialNumber = XMLUtil.getValue(intialShipped,"documentInfo/serialNumber"); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/senderInfo/businessAddress"),true)); //Setting the business Address /*buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/transactionDate"),true)); */ if(repackTransactionInfo!=null){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(repackTransactionInfo,"transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(repackTransactionInfo,"transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(repackTransactionInfo,"transactionDate"),true)); } if((XMLUtil.getNode(intialShipped,"transactionInfo/senderInfo/contactInfo"))!=null){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/senderInfo/contactInfo"),true)); } buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/recipientInfo"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"signatureInfo/signerInfo"),true)); if(!flag){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(intialShipped,"transactionInfo/senderInfo/shippingAddress"),true)); } buffer.append("</transactionInfo>"); } if(!(pedigreeID.equals(serialNumber))){ Node shippedNode = XMLUtil.getNode(intialShipped,"ancestor::shippedPedigree"); Node testNode = intialShipped; while(true){ //Node shippedNode = XMLUtil.getNode(n2,".[descendant-or-self::*/shippedPedigree/documentInfo/serialNumber='"+serialNumber+"']"); if(shippedNode!=null){ buffer.append("<transactionInfo>"); boolean flag = compare(shippedNode); serialNumber = XMLUtil.getValue(shippedNode,"documentInfo/serialNumber"); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/senderInfo/businessAddress"),true)); //Setting the business Address /*buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/transactionDate"),true)); */ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(testNode,"transactionInfo/transactionIdentifier/identifier"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(testNode,"transactionInfo/transactionIdentifier/identifierType"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(testNode,"transactionInfo/transactionDate"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/senderInfo/contactInfo"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/recipientInfo"),true)); buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"signatureInfo/signerInfo"),true)); //Setting the Shipping Address if(!flag){ buffer.append(XMLUtil.convertToString(XMLUtil.getNode(shippedNode,"transactionInfo/senderInfo/shippingAddress"),true)); } testNode = shippedNode; shippedNode = XMLUtil.getNode(shippedNode,"ancestor::shippedPedigree"); buffer.append("</transactionInfo>"); } if(pedigreeID.equals(serialNumber) || shippedNode==null)break; } } buffer.append("</custodyChain>"); buffer.append("<date>"+CommonUtil.dateToString(new Date())+"</date>"); buffer.append("<path>"+uri+"</path>"); buffer.append("<signPath>"+uri+"</signPath>"); buffer.append("</shippedPedigree>"); log.info("XML :"+buffer.toString()); getSignatureImage(strName,signEmail); return buffer.toString(); } public boolean compare(Node n1){ Node businessAddress = XMLUtil.getNode(n1,"transactionInfo/senderInfo/businessAddress"); Node shippingAddress = XMLUtil.getNode(n1,"transactionInfo/senderInfo/shippingAddress"); if(businessAddress!=null && shippingAddress != null){ /*if(XMLUtil.getValue(businessAddress,"businessName").equals(XMLUtil.getValue(shippingAddress,"businessName"))){ if(XMLUtil.getValue(businessAddress,"street1").equals(XMLUtil.getValue(shippingAddress,"street1"))){ if(XMLUtil.getValue(businessAddress,"street2").equals(XMLUtil.getValue(shippingAddress,"street2"))){ if(XMLUtil.getValue(businessAddress,"city").equals(XMLUtil.getValue(shippingAddress,"city"))){ if(XMLUtil.getValue(businessAddress,"stateOrRegion").equals(XMLUtil.getValue(shippingAddress,"stateOrRegion"))){ if(XMLUtil.getValue(businessAddress,"postalCode").equals(XMLUtil.getValue(shippingAddress,"postalCode"))){ if(XMLUtil.getValue(businessAddress,"country").equals(XMLUtil.getValue(shippingAddress,"country"))){ return true; } } } } } } }*/ if(check(XMLUtil.getValue(businessAddress,"businessName"),(XMLUtil.getValue(shippingAddress,"businessName")))){ if(check(XMLUtil.getValue(businessAddress,"street1"),(XMLUtil.getValue(shippingAddress,"street1")))){ if(check(XMLUtil.getValue(businessAddress,"street2"),(XMLUtil.getValue(shippingAddress,"street2")))){ if(check(XMLUtil.getValue(businessAddress,"city"),(XMLUtil.getValue(shippingAddress,"city")))){ if(check(XMLUtil.getValue(businessAddress,"stateOrRegion"),(XMLUtil.getValue(shippingAddress,"stateOrRegion")))){ if(check(XMLUtil.getValue(businessAddress,"postalCode"),(XMLUtil.getValue(shippingAddress,"postalCode")))){ if(check(XMLUtil.getValue(businessAddress,"country"),(XMLUtil.getValue(shippingAddress,"country")))){ return true; } } } } } } } }if(shippingAddress == null){ return true; } return false; } public boolean check(String str1, String str2){ if(str1!=null && str2!=null){ if(str1.equals(str2)){ return true; } }else if(str1 == null && str2 == null){ return true; } return false; } private String[] createRepackagePDF(String pedigreeID, String str) { // TODO Auto-generated method stub String[] filePath = new String[2]; try { log.info(" here in sendRepackagePDF....."+str); String xmlString = getRepackageXSLString(str,pedigreeID,".",""); boolean checkMan = checkManufacturer(str); File baseDir = getBaseDirectory(); File outDir = new File(baseDir, "out"); outDir.mkdirs(); // Setup input and output files File xmlfile = File.createTempFile("User", ".xml"); //xmlfile.createNewFile(); // Delete temp file when program exits. xmlfile.deleteOnExit(); // Write to temp file BufferedWriter bw = new BufferedWriter(new FileWriter(xmlfile)); bw.write(xmlString); bw.close(); File xsltfile = null; if(checkMan){ xsltfile = new File(baseDir, "/xsl/repackFromManufaturer.fo"); } else{ xsltfile = new File(baseDir, "/xsl/repackFromWholesaler.fo"); } File pdffile = new File(outDir, "repack.pdf"); // Construct fop with desired output format Fop fop = new Fop(MimeConstants.MIME_PDF); // Setup output OutputStream out = new java.io.FileOutputStream(pdffile); out = new java.io.BufferedOutputStream(out); fop.setOutputStream(out); // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsltfile)); // Set the value of a <param> in the stylesheet transformer.setParameter("versionParam", "2.0"); // Setup input for XSLT transformation Source src = new StreamSource(xmlfile); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); out.close(); filePath[0] = pdffile.getAbsolutePath(); String mergeFilePath = ""; if(!checkMan){ String query = "(for $i in collection('tig:///ePharma/ShippedPedigree')/*:pedigreeEnvelope/*:pedigree/*:shippedPedigree[*:documentInfo/*:serialNumber = '"+pedigreeID+"']/*:repackagedPedigree/*:previousPedigrees/*:initialPedigree "; query = query + "return $i/*:altPedigree/*:data/string())"; log.info("Query : "+query); List initialStatus = queryRunner.executeQuery(query); filePath[1] = getInitialPedigreePDF(initialStatus,str); log.info("file path : "+filePath[1]); mergeFilePath=mergePDF(filePath[1],filePath[0]); }else mergeFilePath = pdffile.getAbsolutePath(); log.info(" file path : "+mergeFilePath); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return filePath; } private File getBaseDirectory(){ String propVal = System.getProperty("com.rdta.dhforms.path"); if( propVal == null){ log.info("Setting the FO base to current directory as the system property is missing"); propVal = "."; } File baseDirectory = new File(propVal); if(!baseDirectory.exists()){ throw new RuntimeException("The input directory of FO files '" + baseDirectory.getAbsolutePath() + "' doesn't exist" ); } return baseDirectory; } private String createInitialPDF(String str, String pedigreeID) { String filePath1=""; log.info(" here in createInitialPDF....."); try { String xmlString = getInitialXSLString(str,pedigreeID,".",""); File baseDir = getBaseDirectory(); File outDir = new File(baseDir, "out"); outDir.mkdirs(); // Setup input and output files File xmlfile = File.createTempFile("User", ".xml"); // Delete temp file when program exits. xmlfile.deleteOnExit(); // Write to temp file BufferedWriter bw = new BufferedWriter(new FileWriter(xmlfile)); bw.write(xmlString); bw.close(); File xsltfile = new File(baseDir, "/xsl/initial.fo"); //File pdffile = File.createTempFile("initial", ".pdf"); File pdffile = new File(outDir, "1.pdf"); // Construct fop with desired output format Fop fop = new Fop(MimeConstants.MIME_PDF); // Setup output OutputStream out = new java.io.FileOutputStream(pdffile); out = new java.io.BufferedOutputStream(out); try { fop.setOutputStream(out); // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsltfile)); // Set the value of a <param> in the stylesheet transformer.setParameter("versionParam", "2.0"); // Setup input for XSLT transformation Source src = new StreamSource(xmlfile); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); out.close(); //MessageResources messageResources = getResources(request); String[] filePath = new String[2]; filePath[0] = pdffile.getAbsolutePath(); String query = "for $i in collection('tig:///ePharma/ShippedPedigree')/*:pedigreeEnvelope/*:pedigree/*:shippedPedigree[*:documentInfo/*:serialNumber = '"+pedigreeID+"']//*:initialPedigree "; query = query + "return $i/*:altPedigree/*:data/string()"; log.info("Query : "+query); List initialStatus = queryRunner.executeQuery(query); String[] mergeFilePath = new String[1]; if(initialStatus != null && initialStatus.size()>0){ filePath[1] = getInitialPedigreePDF(initialStatus,str); log.info("file path : "+filePath[1]); filePath1=mergePDF(filePath[1],filePath[0]); }else mergeFilePath[0] = pdffile.getAbsolutePath(); log.info(" file path : "+mergeFilePath[0]); log.info(" here in sendInitialPDF....."+filePath1); }finally{ } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return filePath1; } /* public String[] createPDF(String pedigreeID){ //String pedigreeID = "fff36a77-284f-1040-c001-e75f0d664277"; String[] filePath= new String[2]; try { String query="tlsp:getRepackagedInfo('"+pedigreeID+"')"; log.info("Query"+query); log.info("-------query is-----"+query); String str=queryRunner.returnExecuteQueryStringsAsString(query); log.info("QueryResult"+str); log.info("-------str is-----"+str); if(str !=null){ Node n1=XMLUtil.parse(str); log.info("-------ni is-----"+n1); Node n2=XMLUtil.getNode(n1,"/shippedPedigree"); Node n3 = XMLUtil.getNode(n2,"descendant::repackagedPedigree"); if(n3 != null){ String f[]=createRepackagePDF(str,pedigreeID); log.info("filepath array length : "+f.length); for(int i=0;i<f.length;i++){ log.info(f[i]); if(f[i] != null){ filePath[i]=f[i]; } } }else{ filePath[0]=createInitialPDF(str,pedigreeID); } } } catch (PersistanceException e) { // TODO Auto-generated catch block e.printStackTrace(); } return filePath; }*/ public String[] createPDF(String pedigreeID){ //String pedigreeID = "fff36a77-284f-1040-c001-e75f0d664277"; String[] filePath= new String[2]; try { String query="tlsp:getRepackagedInfo('"+pedigreeID+"')"; String str=queryRunner.returnExecuteQueryStringsAsString(query); log.info("REsult in sendPDF method : "+str); if(str !=null){ Node n1=XMLUtil.parse(str); log.info("-------ni is-----"+n1); Node n2=XMLUtil.getNode(n1,"/shippedPedigree"); Node n3 = XMLUtil.getNode(n2,"descendant::repackagedPedigree"); if(n3 != null){ String f[]=createRepackagePDF(pedigreeID,str); log.info("filepath array length : "+f.length); for(int i=0;i<f.length;i++){ log.info(f[i]); if(f[i] != null){ filePath[i]=f[i]; } } }else{ filePath[0]=createInitialPDF(str,pedigreeID); } } } catch (PersistanceException e) { // TODO Auto-generated catch block e.printStackTrace(); } return filePath; } private String getInitialPedigreePDF(List data,String pedigreeID) { // TODO Auto-generated method stub try { //StringBuffer buff = new StringBuffer(); //buff.append("for $i in collection('tig:///ePharma/PaperPedigree')/initialPedigree[DocumentInfo/serialNumber = '31393843945529672246633950583774'] return $i/altPedigree/data/string()"); //List data = queryRunner.executeQuery(buff.toString()); InputStream stream = (ByteArrayInputStream) data.get(0); byte[] data1 = new byte[128]; File file = new File("C:\\temp\\InitialPedigree.pdf"); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); DataOutputStream dos = new DataOutputStream(fos); int x = stream.read(data1); while (x != -1) { //byte[] decoded = Base64.decode(data1); dos.write(data1); data1= new byte[128]; x = stream.read(data1); } stream.close(); dos.close(); fos.close(); File pdffile = new File("c:\\temp\\InitialPedigree.pdf"); return pdffile.getAbsolutePath(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public boolean checkManufacturer(String str){ Node n1=XMLUtil.parse(str); Node n2 = XMLUtil.getNode(n1,"descendant::repackagedPedigree"); if((XMLUtil.getNode(n2,"descendant::receivedPedigree"))==null){ if((XMLUtil.getNode(n2,"descendant::altPedigree"))==null){ return true; } else { String str1 = XMLUtil.getValue(n2, "descendant::altPedigree/data"); //log.info("+++++++++++++++++++altPedigreeee Dataaaaaaaaa: +++++++++++++++" + str1); if(str1 == null || str1.trim().equals("")) { return true; } } } return false; } public Node getTransactionInfo(Node n){ if(XMLUtil.getNode(n,"descendant::receivedPedigree")!=null){ return XMLUtil.getNode(n,"descendant::shippedPedigree/transactionInfo"); }else{ return XMLUtil.getNode(n,"descendant::initialPedigree/transactionInfo"); } } public static void main(String args[]){ try{ SendDHForm dh = new SendDHForm(); dh.createPDF("fff36ad9-680b-1c80-c001-9b625c14376b"); }catch(Exception e){ } } public List getLotInfo(String pedShipMessage) throws PersistanceException{ String query = "tlsp:ReturnLotInfo("+pedShipMessage+")"; String result = queryRunner.returnExecuteQueryStringsAsString(query); Node n1= XMLUtil.parse(result); List lotInfo = XMLUtil.executeQuery(n1,"LotInfo"); return lotInfo; } }
true
0be15eecfe85b37105db59e4812629380a3f3951
Java
linuxsch/ma-modules-public
/Graphical views/src/com/serotonin/m2m2/gviews/component/SimpleCompoundComponent.java
UTF-8
4,497
1.921875
2
[]
no_license
/* Copyright (C) 2014 Infinite Automation Systems Inc. All rights reserved. @author Matthew Lohbihler */ package com.serotonin.m2m2.gviews.component; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import com.serotonin.json.spi.JsonProperty; import com.serotonin.m2m2.i18n.Translations; import com.serotonin.m2m2.view.ImplDefinition; import com.serotonin.util.SerializationHelper; /** * @author Matthew Lohbihler */ public class SimpleCompoundComponent extends CompoundComponent { public static ImplDefinition DEFINITION = new ImplDefinition("simpleCompound", "SIMPLE_COMPOUND", "graphic.simpleCompound", null); public static final String LEAD_POINT = "leadPoint"; public static final String SUB_POINT_1 = "subPoint1"; public static final String SUB_POINT_2 = "subPoint2"; public static final String SUB_POINT_3 = "subPoint3"; public static final String SUB_POINT_4 = "subPoint4"; public static final String SUB_POINT_5 = "subPoint5"; public static final String SUB_POINT_6 = "subPoint6"; public static final String SUB_POINT_7 = "subPoint7"; public static final String SUB_POINT_8 = "subPoint8"; public static final String SUB_POINT_9 = "subPoint9"; public static final String SUB_POINT_10 = "subPoint10"; @JsonProperty private String backgroundColour; public SimpleCompoundComponent() { initialize(); } @Override protected void initialize() { SimplePointComponent lead = new SimplePointComponent(); lead.setLocation(0, 0); lead.setStyle("position:relative;"); lead.setDisplayControls(false); lead.setSettableOverride(false); addChild(LEAD_POINT, "graphic.simpleCompound." + LEAD_POINT, lead, null); addChild(SUB_POINT_1, "graphic.simpleCompound." + SUB_POINT_1, createComponent(), null); addChild(SUB_POINT_2, "graphic.simpleCompound." + SUB_POINT_2, createComponent(), null); addChild(SUB_POINT_3, "graphic.simpleCompound." + SUB_POINT_3, createComponent(), null); addChild(SUB_POINT_4, "graphic.simpleCompound." + SUB_POINT_4, createComponent(), null); addChild(SUB_POINT_5, "graphic.simpleCompound." + SUB_POINT_5, createComponent(), null); addChild(SUB_POINT_6, "graphic.simpleCompound." + SUB_POINT_6, createComponent(), null); addChild(SUB_POINT_7, "graphic.simpleCompound." + SUB_POINT_7, createComponent(), null); addChild(SUB_POINT_8, "graphic.simpleCompound." + SUB_POINT_8, createComponent(), null); addChild(SUB_POINT_9, "graphic.simpleCompound." + SUB_POINT_9, createComponent(), null); addChild(SUB_POINT_10, "graphic.simpleCompound." + SUB_POINT_10, createComponent(), null); } @Override public boolean hasInfo() { return false; } private SimplePointComponent createComponent() { SimplePointComponent c = new SimplePointComponent(); c.setLocation(0, 0); c.setStyle("position:relative;"); c.setDisplayControls(true); c.setSettableOverride(true); c.setDisplayPointName(true); c.setBkgdColorOverride("transparent"); return c; } public String getBackgroundColour() { return backgroundColour; } public void setBackgroundColour(String backgroundColour) { this.backgroundColour = backgroundColour; } @Override public ImplDefinition definition() { return DEFINITION; } public ViewComponent getLeadComponent() { return getChildComponent(LEAD_POINT); } @Override public String getStaticContent() { return null; } @Override public boolean isDisplayImageChart() { return false; } @Override public String getImageChartData(Translations translations) { return null; } // // / // / Serialization // / // private static final long serialVersionUID = -1; private static final int version = 1; private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(version); SerializationHelper.writeSafeUTF(out, backgroundColour); } private void readObject(ObjectInputStream in) throws IOException { int ver = in.readInt(); // Switch on the version of the class so that version changes can be elegantly handled. if (ver == 1) backgroundColour = SerializationHelper.readSafeUTF(in); } }
true
091ea0ee68b29f2bb087f66f38b48acb48f4efbb
Java
jonioliveira/interview
/api/users-api/src/main/java/com/jonioliveira/users/resource/model/request/LoginRequest.java
UTF-8
515
2.234375
2
[]
no_license
package com.jonioliveira.users.resource.model.request; import org.eclipse.microprofile.openapi.annotations.media.Schema; import javax.validation.constraints.NotNull; @Schema(name="Login Request Model", description="Model of request body to login users") public class LoginRequest { @NotNull @Schema(description = "Name of user", example = "jhon") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
4f691835a02465c0c9da976765522280b7678369
Java
konglinghai123/his
/his-inpatient/src/main/java/cn/honry/inpatient/outBalance/dao/impl/InpatientChangeprepayDAOImpl.java
UTF-8
836
2
2
[]
no_license
package cn.honry.inpatient.outBalance.dao.impl; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import cn.honry.base.bean.model.InpatientBalanceHead; import cn.honry.base.bean.model.InpatientChangeprepay; import cn.honry.base.dao.impl.HibernateEntityDao; import cn.honry.inpatient.outBalance.dao.InpatientBalanceHeadDAO; import cn.honry.inpatient.outBalance.dao.InpatientChangeprepayDAO; @Repository("inpatientChangeprepayDAO") @SuppressWarnings("all") public class InpatientChangeprepayDAOImpl extends HibernateEntityDao<InpatientChangeprepay> implements InpatientChangeprepayDAO{ @Resource(name="sessionFactory") private void setHibernateSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } }
true
23e39b1c4a757377aba19f527df5724b621e10e0
Java
smile2002/java-demo
/mybatis/interface/src/main/java/cn/smile/domain/User.java
UTF-8
491
2.296875
2
[]
no_license
package cn.smile.domain; /** * Created by Smile on 2018/7/19. */ public class User { private String userId; private Integer age; private String name; public String getUserId() {return this.userId;} public Integer getAge() {return this.age;} public String getName() {return this.name;} public void setUserId(String userId) {this.userId = userId;} public void setAge(Integer age) {this.age = age;} public void setName(String name) {this.name = name;} }
true
cea3b7dae1c023ac8db6a814005331d85e94d4ce
Java
GaryPoter/recomendmovie
/src/main/java/com/spring/recomendmovie/movie_api/pojo/ManagerInfo.java
UTF-8
1,237
2.21875
2
[]
no_license
package com.spring.recomendmovie.movie_api.pojo; public class ManagerInfo { public static final String TABLENAME="manager"; public static final String ID="id"; public static final String MNAME="mName"; public static final String MPASSWORD="mPassword"; private Long id; private String mName; private String mPassword; public ManagerInfo() { } public ManagerInfo(Long id, String mName, String mPassword) { this.id = id; this.mName = mName; this.mPassword = mPassword; } public static String getTABLENAME() { return TABLENAME; } public static String getID() { return ID; } public static String getMNAME() { return MNAME; } public static String getMPASSWORD() { return MPASSWORD; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getmName() { return mName; } public void setmName(String mName) { this.mName = mName; } public String getmPassword() { return mPassword; } public void setmPassword(String mPassword) { this.mPassword = mPassword; } }
true
e8506c8ee6b683bbb7ac7761642c13b105586ed7
Java
changlala/TreeView
/app/src/main/java/com/chang/treeview/view/TreeViewWrapper.java
UTF-8
5,395
2.25
2
[]
no_license
package com.chang.treeview.view; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.chang.treeview.MyDragHelperCallback; import com.chang.treeview.MyScaleGestureHandler; import com.nineoldandroids.view.ViewHelper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.customview.widget.ViewDragHelper; /** * TreeView的父布局 * 处理拖动缩放等事件 */ public class TreeViewWrapper extends FrameLayout implements ViewGroup.OnHierarchyChangeListener{ private static final String TAG = "TreeViewWrapper"; //像一个画布一样,包含一个treeView。是TreeViewWrapper的直接子布局 private CanvasLayout mCanvasLayout; //实际TreeView private TreeView mTreeView; private ScaleGestureDetector mScaleGestureDetector; private MyScaleGestureHandler mOnScaleGestureHandler; private ViewDragHelper mDragHelper; private Context mContext; //屏幕尺寸与控件尺寸相同 private int mScreenWidth; private int mScreenHeight; public TreeViewWrapper(@NonNull Context context) { super(context); } public TreeViewWrapper(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); mContext = context; //缩放回调 mOnScaleGestureHandler = new MyScaleGestureHandler(this); //缩放探测器 mScaleGestureDetector = new ScaleGestureDetector(mContext,mOnScaleGestureHandler); //拖拽探测器 mDragHelper = ViewDragHelper.create(this,new MyDragHelperCallback(this)); setOnHierarchyChangeListener(this); } private int curLeft = 0; private int curTop = 0; @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { //对子view的layout默认会放在左上角,传curLeft、curTop不起作用 // super.onLayout(changed,curLeft,curTop,curLeft+getMeasuredWidth(), curTop+getMeasuredHeight()); Log.d(TAG, "onLayout: changed,left,top,right,bottom" + left + top + right + bottom); mScreenWidth = getMeasuredWidth(); mScreenHeight = getMeasuredHeight(); //保留拖拽后的位置 mCanvasLayout.layout(curLeft, curTop, curLeft + mCanvasLayout.getMeasuredWidth(), curTop + mCanvasLayout.getMeasuredHeight()); Log.d(TAG, "onLayout: changed curleft curTop " + changed + " " + curLeft); } @Override public boolean onTouchEvent(MotionEvent event) { mScaleGestureDetector.onTouchEvent(event); mDragHelper.processTouchEvent(event); Log.d(TAG, "onTouchEvent: event" + event.toString()); return true; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { boolean flag = mDragHelper.shouldInterceptTouchEvent(ev); Log.d(TAG, "onInterceptTouchEvent: "+ev.getAction()+" "+flag); // TODO: 2020/9/4 多指情况下如果触摸到了node的情形是否需要拦截? //当前是互动模式 if(!mTreeView.isInAutoLayoutMode()){ if(ev.getPointerCount() <= 1){ //单指 //第二个判断保证在互动模式下拖动NodeVIew MOVE幅度较大,触点可能在一些时刻脱离Nodeview // isNodeUnder为false wrapper拦截的情况 if(mCanvasLayout.isNodeUnder((int)ev.getX(),(int)ev.getY()) ||mTreeView.getDragHelper().getViewDragState() == ViewDragHelper.STATE_DRAGGING){ return false; } }else if(ev.getPointerCount() == 2){ //多点触摸的情况 对第一种情况的处理 //取第二指的坐标 float x = ev.getX(ev.getActionIndex()); float y = ev.getY(ev.getActionIndex()); //如果第二指在NodeVIew 默认拦截 if(mCanvasLayout.isNodeUnder((int)x,(int)y)){ return true; } } } return flag; } @Override public boolean dispatchTouchEvent(MotionEvent ev) { Log.d(TAG, "dispatchTouchEvent: "); return super.dispatchTouchEvent(ev); } @Override public void onChildViewAdded(View parent, View child) { Log.d(TAG, "onChildViewAdded: parent child"+parent+" "+child); //取得子view实例 mCanvasLayout = (CanvasLayout)child; mTreeView = (TreeView) mCanvasLayout.getChildAt(0); } @Override public void onChildViewRemoved(View parent, View child) { } public CanvasLayout getCanvasLayout() { return mCanvasLayout; } public MyScaleGestureHandler getOnScaleGestureHandler() { return mOnScaleGestureHandler; } public int getScreenWidth() { return mScreenWidth; } public int getScreenHeight() { return mScreenHeight; } public void setCurLeft(int curLeft) { this.curLeft = curLeft; } public void setCurTop(int curTop) { this.curTop = curTop; } }
true
3e2faefa0f91dd208c59921dc8547b9ac1482147
Java
aditbro/Algeo_matriks
/src/Solver.java
UTF-8
8,208
3.234375
3
[]
no_license
//package spl_solve; public class Solver { public void SolveLinear(Matrix M) { //Merekondisi matriks ReconMatrix(M); //Swap dkk int IMax; for(int p = 0; p < (M.getNCol()-1)/2; p++) { IMax = p; for(int i = p; i < M.getNRow(); i++) if(M.get(i, p) > M.get(IMax, p)) { IMax = i; } M.SwapRow(IMax, p); //swap row imax dengan p /* System.out.println("After Swap"); M.ShowMatrix(); System.out.println(); */ if(Math.abs(M.get(p, p)) > 0) { pivot (p,p, M); } } } public void ReconMatrix(Matrix M) { int i, j; int NewNRow, NewNCol, OldNCol; //Pemindahan = ke 2NKol - 1 NewNRow = M.getNRow(); //Jumlah Row Baru OldNCol = M.getNCol(); //Indeks Kolom Akhir Lama NewNCol = M.getNCol()*2 - 1; //Jumlah Kolom Baru M.setNRow(NewNRow); M.setNCol(NewNCol); M.SwapColumn(OldNCol-1,NewNCol-1); //Pemasangan matriks identitas for(i = 0; i <= M.getNRow(); i++) { for(j = OldNCol-1 ; j <= M.getNCol()-2; j++) { if((j - OldNCol+1) == i) { M.set(i, j, 1.0); } else { M.set(i, j, 0.0); } } } } public void pivot(int p, int q, Matrix M) { Double mult; //Buat nol untuk semua row kecuali di p q. for(int i = 0; i < M.getNRow(); i++) { mult = M.get(i, q)/M.get(p, q); //multiplier pembuat nol for (int j = 0; j < M.getNCol(); j++) { if(i != p && j != q) { M.set(i, j, M.get(i, j) - M.get(p, j) * mult); } } } //Mengnolkan kolom q, agar tidak terjadi -0.00 for (int i = 0; i < M.getNRow(); i++) { if(i!=p) { M.set(i, q, 0.0); } } //Scale P for(int j = 0; j < M.getNCol(); j++) { if (j != q) { M.set(p, j, M.get(p, j)/M.get(p, q)); } } M.set(p, q, 1.0); /* System.out.println("After Pivot"); M.ShowMatrix(); System.out.println(); */ } public boolean isSolutionUnique(Matrix M) { return (singleSolution(M) != null); } public Double[] singleSolution(Matrix M) //Kondisi Matriks: telah di gauss jordan { Double[] x = new Double[M.getNRow()]; for (int i = 0; i < M.getNRow(); i++) { if(Math.abs(M.get(i, i)) > 0) { x[i] = M.get(i, M.getNCol()-1); } else if (Math.abs(M.get(i, M.getNCol()-1)) > 0) { return null; //no solution or many solutions. } } return x; } public String PrintSolution(Matrix M) /*FORMAT MATRIX JADI: + var1 var2 var3 var4 = 1 1 4 1 2 1 3 2 3 1 2 3 4 */ { String s = ""; System.out.println(); // enter sekali s += "\r\n"; for(int i = 0; (i < M.getNRow()); i++) { boolean startPrint = true; for(int j = 0; j < (M.getNCol()-1)/2; j++) { if(Math.abs(M.get(i, j)) > 0) { if(M.get(i, j) > 0 && !startPrint) { System.out.format(" + "); s += " + "; } if(M.get(i, j) > 0) { if(M.get(i, j) == 1.00) { System.out.format("%c", M.getVar(j)); s += M.getVar(j); }else { System.out.format("%.2f%c", M.get(i,j),M.getVar(j)); s += ""+M.get(i,j)+M.getVar(j); } } else if(M.get(i, j) < 0) { if(!startPrint) { System.out.format(" "); s += " "; } System.out.format("- %.2f%c", -M.get(i, j), M.getVar(j)); s += "- "+(-M.get(i, j))+M.getVar(j); } startPrint = false; } } //Print = if(!allColumnZero(i, M)) { System.out.format(" = %.2f\n",M.get(i, M.getNCol()-1)); s += " = "+M.get(i, M.getNCol()-1)+"\r\n"; } } return s; } public int findOne(int i, Matrix M) //Mencari nilai 1 pertama pada baris i { int j; if(!(allColumnZero(i,M) && solutionZero(i,M))) { j = 0; while((j < ((M.getNCol()-1)/2)) && (M.get(i, j) <= 0)) { if(M.get(i, j) <= 0) { j++; } } return j; } else { return 0; } } public void toComplement(boolean[] Idx) { for(int i = 0; i < Idx.length; i++) { Idx[i] = !Idx[i]; } } public String printParam(Matrix M) { String s = ""; char[] var = new char [(M.getNCol()-1)/2]; boolean[] paramIdx = new boolean[(M.getNCol()-1)/2]; for(int i = 0; (i < M.getNRow()); i++) { boolean startPrint = true; for(int j = 0; j < (M.getNCol()-1)/2; j++) { if(Math.abs(M.get(i, j)) > 0) { if(M.get(i, j) > 0 && !startPrint) { System.out.format(" + "); s += " + "; } if(M.get(i, j) > 0) { if(M.get(i, j) == 1.00) { System.out.format("%c", M.getVar(j)); s += M.getVar(j); }else { System.out.format("%.2f%c", M.get(i,j),M.getVar(j)); s += ""+M.get(i,j)+M.getVar(j); } } else if(M.get(i, j) < 0) { if(!startPrint) { System.out.format(" "); s += " "; } System.out.format("- %.2f%c", -M.get(i, j), M.getVar(j)); s += "- "+(-M.get(i, j))+M.getVar(j); } startPrint = false; } } //Print = if(!allColumnZero(i, M)) { System.out.format(" = %.2f\n",M.get(i, M.getNCol()-1)); s += " = "+M.get(i, M.getNCol()-1)+"\r\n"; } } System.out.format("\nJadi, dalam bentuk parametrik : \n"); s += "\r\nJadi, dalam bentuk parametrik : \r\n"; //Parametric Variable substitution for(int i = 0; i < M.getNRow();i++) { //recording if(!allColumnZero(i,M)) { paramIdx[findOne(i,M)] = true; } } //Substitution toComplement(paramIdx); char InitVar = 'r'; int N = 0; for(int j = 0; j < (M.getNCol()-1)/2; j++) { if(paramIdx[j]) { var[j] = M.getVar(j); M.setVar(j, (char)((int)(InitVar) + N++)); //Print Param Variables System.out.format("%c = %c\n", var[j], M.getVar(j)); s += var[j] + " = " + M.getVar(j) + "\r\n"; } } for(int i = 0; i < M.getNRow(); i++) { //print var if(!allColumnZero(i,M)) { boolean startPrint = true; for(int j = 0; j < (M.getNCol()-1)/2; j++) { //kasus pertama, "x = " if(j == findOne(i, M)) { System.out.format("%c =", M.getVar(findOne(i,M))); s += M.getVar(findOne(i,M)) +" ="; startPrint = true; } else { if(M.get(i, j) > 0) { System.out.format(" - %.2f%c", M.get(i, j), M.getVar(j)); s += " - " + M.get(i, j)+ M.getVar(j); } else if (M.get(i, j) < 0) { if(!startPrint) { System.out.format(" + %.2f%c", -M.get(i,j), M.getVar(j)); s += " + " + -M.get(i, j)+ M.getVar(j); } else { System.out.format(" %.2f%c", -M.get(i,j), M.getVar(j)); s += " " + -M.get(i, j)+ M.getVar(j); } } startPrint = false; } } //print = if(getSolution(i,M) < 0) { System.out.format(" - %.2f\n", -getSolution(i,M)); s += " - " + -getSolution(i,M) + "\r\n"; } else if (getSolution(i,M) > 0) { System.out.format(" + %.2f\n", getSolution(i,M)); s += " + " + getSolution(i,M) + "\r\n"; } //end of if } } return s; } public boolean allColumnZero(int i, Matrix M) { boolean foundNotZero = false; int j = 0; while (!foundNotZero && j < (M.getNCol() - 1)/2) { if (M.get(i, j) > 0) { foundNotZero = true; }else { j++; } } return !foundNotZero; } public boolean solutionZero(int i, Matrix M) //true jika paling kanan matriks = 0 { return (M.get(i, M.getNCol()-1) == 0); } public boolean noSolution(Matrix M) { boolean noSol = false; for (int i = 0; ((i < M.getNRow()) && !noSol);i++) { if (allColumnZero(i, M) && !solutionZero(i, M)) { noSol = true; } } return noSol; } public Double getSolution (int i, Matrix M) { return (M.get(i, M.getNCol()-1)); } }
true
bc21018454f9d4edd27b59fae81c264f1bc2bbdf
Java
tr4uma/MasterThesis
/arthastest/src/main/java/com/example/alessandro/computergraphicsexample/GraphicsView.java
UTF-8
4,794
2.25
2
[]
no_license
package com.example.alessandro.computergraphicsexample; import android.content.Context; import android.opengl.GLSurfaceView; import android.util.Log; import java.util.ArrayList; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import sfogl.integration.Node; import sfogl2.SFOGLSystemState; import shadow.math.SFMatrix3f; import shadow.math.SFTransform3f; import thesis.Graphics.NodesKeeper; import thesis.Graphics.ShadersKeeper; import thesis.touch.TouchActivity; /** * Created by Alessandro on 13/03/15. */ public class GraphicsView extends GLSurfaceView implements TouchActivity{ private Context context; private static final String STANDARD_SHADER = "stdShader"; private static final int CUBE_ROWS = 5; private static final int CUBE_COLS = 5; private float[] projection={ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1, }; private GraphicsRenderer renderer; public GraphicsView(Context context) { super(context); setEGLContextClientVersion(2); this.context=context; super.setEGLConfigChooser(8, 8, 8, 8, 16, 0); renderer = new GraphicsRenderer(); setRenderer(renderer); } @Override public void onRightSwipe(float distance) { Log.e("TOUCH", "RIGHT SWIPE"); renderer.incrementTX(-0.01f); } @Override public void onLeftSwipe(float distance) { Log.e("TOUCH", "LEFT SWIPE"); renderer.incrementTX(0.01f); } @Override public void onUpSwipe(float distance) { Log.e("TOUCH", "UP SWIPE"); renderer.incrementTY(-0.01f); } @Override public void onDownSwipe(float distance) { Log.e("TOUCH", "DOWN SWIPE"); renderer.incrementTY(0.01f); } @Override public void onDoubleTap() { Log.e("TOUCH", "DOUBLE TAP"); renderer.stopMovement(); } @Override public void onLongPress() { renderer.resetPosition(); } public class GraphicsRenderer implements Renderer{ private ArrayList<Node> nodes = new ArrayList<>(); Node father; private float t=0; private float t2=0; private float TX=0; private float TY=0; public void incrementTX(float t){ this.TX +=t; } public void incrementTY(float t){ this.TY +=t; } public void stopMovement(){ this.TX =0; this.TY =0; } public void resetPosition(){ this.t=0; this.t2=0; this.TX =0; this.TY=0; } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { int intColor; father = NodesKeeper.generateNode(context, "stdShader", R.drawable.arthas, "arthas.obj", "father"); father.getRelativeTransform().setPosition(0, -0.4f, 0); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { float r = (float)width/height; if(r<1) { projection[0] = 1; projection[5] = r; } else if(r>1){ projection[0] = 1/r; projection[5] = 1; } } @Override public void onDrawFrame(GL10 gl) { SFOGLSystemState.cleanupColorAndDepth(0, 0, 0, 1); //setup the View Projection ShadersKeeper.getProgram(STANDARD_SHADER).setupProjection(projection); //Change the Node transform t+=TX; t2+=TY; float rotation=0f+t; float rotation2=0f+t2; //float rotation=0; float scaling=0.3f; SFMatrix3f matrix3f=SFMatrix3f.getScale(scaling, scaling, scaling); matrix3f=matrix3f.MultMatrix(SFMatrix3f.getRotationY(rotation)); matrix3f=matrix3f.MultMatrix(SFMatrix3f.getRotationX(rotation2)); matrix3f=matrix3f.MultMatrix((SFMatrix3f.getRotationZ((float) Math.PI/2))); matrix3f= matrix3f.MultMatrix((SFMatrix3f.getRotationY(1.57079633f))); matrix3f = matrix3f.MultMatrix((SFMatrix3f.getRotationX(1.57079633f))); father.getRelativeTransform().setMatrix(matrix3f); father.updateTree(new SFTransform3f()); //matrix3f=SFMatrix3f.getIdentity().MultMatrix(SFMatrix3f.getRotationY(rotation)); Node node; father.draw(); //Draw the node //int[] viewport=new int[4]; //GLES20.glGetIntegerv(GLES20.GL_VIEWPORT,viewport,0); //Log.e("Graphics View Size", Arrays.toString(viewport)); } } }
true
605a70e75428a8804b08ac72a9258b33e9b3e21c
Java
devlinjunker/ec
/ec.base/src/main/java/com/eduworks/ec/remote/EcLevrHttp.java
UTF-8
1,128
2.03125
2
[ "Apache-2.0" ]
permissive
package com.eduworks.ec.remote; import org.stjs.javascript.annotation.GlobalScope; import org.stjs.javascript.annotation.STJSBridge; /** * @author fray */ @GlobalScope @STJSBridge() public class EcLevrHttp { /*function httpPost(vobj,vcontentType,vmultipart,vname,vauthToken){ var cru = new com.eduworks.cruncher.net.CruncherHttpPost(); cru.build('obj',com.eduworks.resolver.lang.LevrJsParser.jsToJava(vobj)); cru.build('contentType',com.eduworks.resolver.lang.LevrJsParser.jsToJava(vcontentType)); if (vmultipart != null) cru.build('multipart',com.eduworks.resolver.lang.LevrJsParser.jsToJava(vmultipart)); if (vname != null) cru.build('name',com.eduworks.resolver.lang.LevrJsParser.jsToJava(vname)); if (vauthToken != null) cru.build('authToken',com.eduworks.resolver.lang.LevrJsParser.jsToJava(vauthToken)); return cru.resolve(context,parameters,dataStreams); }*/ public static Object httpPost(Object obj, String url, String contentType, String multipart, String name) { return null; } public static Object httpGet(String url) { return null; } public static String httpDelete(String url) { return null; } }
true
5822c05b0f248f68dd7ef524c60814e6fb10ca6b
Java
123xuan456/LvJianCaiFu
/LvJianCaiFu/src/main/java/com/ryan/slidefragment/view/ShowBigPictrue.java
UTF-8
1,616
2.265625
2
[]
no_license
package com.ryan.slidefragment.view; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import com.lesogo.cu.custom.ScaleView.HackyViewPager; import com.ryan.slidefragment.generaldemo.R; /** * 显示大图界面 * @author lyz * */ public class ShowBigPictrue extends FragmentActivity { private HackyViewPager viewPager; private int[] resId = { R.drawable.a2, R.drawable.a1, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6 }; /**得到上一个界面点击图片的位置*/ private int position=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.show_big_pictrue_a); Intent intent=getIntent(); position=intent.getIntExtra("position", 0); initViewPager(); } private void initViewPager(){ viewPager = (HackyViewPager) findViewById(R.id.viewPager_show_bigPic); ViewPagerAdapter adapter=new ViewPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(adapter); //跳转到第几个界面 viewPager.setCurrentItem(position); } private class ViewPagerAdapter extends FragmentStatePagerAdapter{ public ViewPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { int show_resId=resId[position]; return new PictrueFragment(show_resId); } @Override public int getCount() { return resId.length; } } }
true
0c8ddb5bec71d8e3ae024e484eec65b3e8c32c5c
Java
pulumi/pulumi-gitlab
/sdk/java/src/main/java/com/pulumi/gitlab/GroupBadgeArgs.java
UTF-8
3,978
2.140625
2
[ "BSD-3-Clause", "Apache-2.0", "MPL-2.0" ]
permissive
// *** WARNING: this file was generated by pulumi-java-gen. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package com.pulumi.gitlab; import com.pulumi.core.Output; import com.pulumi.core.annotations.Import; import java.lang.String; import java.util.Objects; public final class GroupBadgeArgs extends com.pulumi.resources.ResourceArgs { public static final GroupBadgeArgs Empty = new GroupBadgeArgs(); /** * The id of the group to add the badge to. * */ @Import(name="group", required=true) private Output<String> group; /** * @return The id of the group to add the badge to. * */ public Output<String> group() { return this.group; } /** * The image url which will be presented on group overview. * */ @Import(name="imageUrl", required=true) private Output<String> imageUrl; /** * @return The image url which will be presented on group overview. * */ public Output<String> imageUrl() { return this.imageUrl; } /** * The url linked with the badge. * */ @Import(name="linkUrl", required=true) private Output<String> linkUrl; /** * @return The url linked with the badge. * */ public Output<String> linkUrl() { return this.linkUrl; } private GroupBadgeArgs() {} private GroupBadgeArgs(GroupBadgeArgs $) { this.group = $.group; this.imageUrl = $.imageUrl; this.linkUrl = $.linkUrl; } public static Builder builder() { return new Builder(); } public static Builder builder(GroupBadgeArgs defaults) { return new Builder(defaults); } public static final class Builder { private GroupBadgeArgs $; public Builder() { $ = new GroupBadgeArgs(); } public Builder(GroupBadgeArgs defaults) { $ = new GroupBadgeArgs(Objects.requireNonNull(defaults)); } /** * @param group The id of the group to add the badge to. * * @return builder * */ public Builder group(Output<String> group) { $.group = group; return this; } /** * @param group The id of the group to add the badge to. * * @return builder * */ public Builder group(String group) { return group(Output.of(group)); } /** * @param imageUrl The image url which will be presented on group overview. * * @return builder * */ public Builder imageUrl(Output<String> imageUrl) { $.imageUrl = imageUrl; return this; } /** * @param imageUrl The image url which will be presented on group overview. * * @return builder * */ public Builder imageUrl(String imageUrl) { return imageUrl(Output.of(imageUrl)); } /** * @param linkUrl The url linked with the badge. * * @return builder * */ public Builder linkUrl(Output<String> linkUrl) { $.linkUrl = linkUrl; return this; } /** * @param linkUrl The url linked with the badge. * * @return builder * */ public Builder linkUrl(String linkUrl) { return linkUrl(Output.of(linkUrl)); } public GroupBadgeArgs build() { $.group = Objects.requireNonNull($.group, "expected parameter 'group' to be non-null"); $.imageUrl = Objects.requireNonNull($.imageUrl, "expected parameter 'imageUrl' to be non-null"); $.linkUrl = Objects.requireNonNull($.linkUrl, "expected parameter 'linkUrl' to be non-null"); return $; } } }
true
da5694854261a17f5638de701972e2ce97fe3b0b
Java
Progressive-Learning-Platform/Plpclipse
/PluginSim1/PluginSim1/src/plptool/mods/PLPID.java
UTF-8
1,714
2.125
2
[ "Apache-2.0" ]
permissive
/* Copyright 2010 David Fritz, Brian Gordon, Wira Mulia This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package plptool.mods; import plptool.PLPSimBusModule; import plptool.Constants; /** * PLPID is a module that returns the version string and board frequency * of the system. * * @author wira */ public class PLPID extends PLPSimBusModule { long frequency = 20; public PLPID(long addr) { super(addr, addr + 4, true); } public void updateFrequency(long f) { frequency = f; } public int eval() { // No need to eval every cycle return Constants.PLP_OK; } public int gui_eval(Object x) { return Constants.PLP_OK; } @Override public Object read(long addr) { if(addr == startAddr) return new Long(0x202); else if(addr == startAddr + 4) return frequency; return null; } @Override public void reset() { super.clear(); } public String introduce() { return "PLPID"; } @Override public String toString() { return "PLPID"; } }
true
5da261499eda2826384d9d4635130f431f87983d
Java
yohotech/anaithum
/app/src/main/java/com/yoho/anaithumfinal/Model/ApplyCouponDatum.java
UTF-8
1,543
2.171875
2
[]
no_license
package com.yoho.anaithumfinal.Model; public class ApplyCouponDatum { private String coupon_amount; private String tax_percent; private String total; private String shipping_cost; private String tax; private String grand_total; public String getCoupon_amount () { return coupon_amount; } public void setCoupon_amount (String coupon_amount) { this.coupon_amount = coupon_amount; } public String getTax_percent () { return tax_percent; } public void setTax_percent (String tax_percent) { this.tax_percent = tax_percent; } public String getTotal () { return total; } public void setTotal (String total) { this.total = total; } public String getShipping_cost () { return shipping_cost; } public void setShipping_cost (String shipping_cost) { this.shipping_cost = shipping_cost; } public String getTax () { return tax; } public void setTax (String tax) { this.tax = tax; } public String getGrand_total () { return grand_total; } public void setGrand_total (String grand_total) { this.grand_total = grand_total; } @Override public String toString() { return "ClassPojo [coupon_amount = "+coupon_amount+", tax_percent = "+tax_percent+", total = "+total+", shipping_cost = "+shipping_cost+", tax = "+tax+", grand_total = "+grand_total+"]"; } }
true
9c148041532afdb53bdbdfdf60ab7131b2c9ece5
Java
runyamsoft/UgmScholar
/app/src/main/java/com/octopus/ugmscholar2/MainActivity.java
UTF-8
5,446
2.140625
2
[]
no_license
package com.octopus.ugmscholar2; import android.animation.LayoutTransition; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.twotoasters.jazzylistview.effects.FadeEffect; import com.twotoasters.jazzylistview.effects.SlideInEffect; import com.twotoasters.jazzylistview.recyclerview.JazzyRecyclerViewScrollListener; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private List <ItemData> itemDatas; RecyclerView rv; int pageCounter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); pageCounter=1; itemDatas = new ArrayList<ItemData>(); rv = (RecyclerView)findViewById(R.id.rv); rv.setHasFixedSize(true); final RvAdapter rvAdapter = new RvAdapter(itemDatas, new RvAdapter.OnItemClickListener() { @Override public void onItemClick(ItemData item) { Intent intent = new Intent(MainActivity.this, InfoDetailsActivity.class); intent.putExtra("title", item.getTitle()); intent.putExtra("author", item.getAuthor()); intent.putExtra("date", item.getTgl()); intent.putExtra("img", item.getImgUrl()); intent.putExtra("title", item.getTitle()); intent.putExtra("url",item.getDirectUrl()); startActivity(intent); } }); rv.setAdapter(rvAdapter); JazzyRecyclerViewScrollListener jrv = new JazzyRecyclerViewScrollListener(); jrv.setTransitionEffect(new FadeEffect()); rv.addOnScrollListener(jrv); LinearLayoutManager layoutManager = new LinearLayoutManager(this); rv.setLayoutManager(layoutManager); new ParsePage(itemDatas, rvAdapter).execute(); rv.addOnScrollListener(new EndlessRecyclerViewScrollListener(layoutManager) { @Override public void onLoadMore(int page, int totalItemsCount) { new ParsePage(itemDatas, rvAdapter).execute(); } }); } private class ParsePage extends AsyncTask <String, Void, Void>{ List <ItemData> datas; ItemData tmpData; RvAdapter rvAdapter; ParsePage(List<ItemData> datas, RvAdapter rvAdapter){ this.datas = datas; this.rvAdapter = rvAdapter; } @Override protected Void doInBackground(String... params) { Document doc; Elements articles; try { int limit = pageCounter +2; for(int i = pageCounter; i<=limit; i++) { doc = Jsoup.connect("http://ditmawa.ugm.ac.id/category/info-beasiswa/page/"+i).get(); articles = doc.select(".uk-article"); for (Element article : articles) { tmpData = new ItemData(); tmpData.setTitle(article.select(".uk-article-title").text()); tmpData.setAuthor(article.select(".uk-article-meta a").first().text()); tmpData.setTgl(article.select(".uk-article-meta time").first().text()); tmpData.setDirectUrl(article.select(".uk-article-title a").first().attr("href")); if (article.select("img").size() > 0) { tmpData.setImgUrl("http://ditmawa.ugm.ac.id" + article.select("img").first().attr("src")); } else { tmpData.setImgUrl(""); } datas.add(tmpData); } } } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { pageCounter+=3; rvAdapter.notifyDataSetChanged(); super.onPostExecute(aVoid); Log.d("wa", itemDatas.get(0).getTitle()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
0aa4ab16e411debb70dd431cbfb8aac9c84af920
Java
Umimi0315/MyJavaStudy
/Java/Java_codes/ScrollPaneTest/ScrollPaneTest.java
ISO-8859-13
314
2.9375
3
[]
no_license
import java.awt.*; public class ScrollPaneTest { public static void main(String[] args) { Frame f=new Frame(); ScrollPane sp=new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS); sp.add(new TextField(20)); sp.add(new Button("")); f.add(sp); f.setBounds(30,30,250,120); f.setVisible(true); } }
true
e8feee64fd846418645fe0c1a97372540d643434
Java
Denisacke/MazeGameSE
/src/com/maze/Wall.java
UTF-8
229
2.15625
2
[]
no_license
package com.maze; public class Wall extends MapSite{ @Override public void enter() { System.out.println("You just hit a wall!"); } @Override public String getName() { return "Wall"; } }
true
07c8dadeb6f347c91715bce948f02f2906ba8571
Java
sunilcodex/kuini
/src/pl/edu/uj/tcs/kuini/model/factories/AntFactory.java
UTF-8
1,698
2.484375
2
[]
no_license
package pl.edu.uj.tcs.kuini.model.factories; import java.util.LinkedList; import java.util.List; import java.util.Random; import pl.edu.uj.tcs.kuini.model.ActorType; import pl.edu.uj.tcs.kuini.model.Path; import pl.edu.uj.tcs.kuini.model.actions.AttackAction; import pl.edu.uj.tcs.kuini.model.actions.BoidMoveAction; import pl.edu.uj.tcs.kuini.model.actions.BounceAction; import pl.edu.uj.tcs.kuini.model.actions.CompoundAction; import pl.edu.uj.tcs.kuini.model.actions.EatFoodAction; import pl.edu.uj.tcs.kuini.model.actions.HealYourselfAction; import pl.edu.uj.tcs.kuini.model.actions.IAction; import pl.edu.uj.tcs.kuini.model.geometry.Position; import pl.edu.uj.tcs.kuini.model.live.Actor; import pl.edu.uj.tcs.kuini.model.live.ILiveActor; import pl.edu.uj.tcs.kuini.model.live.ILiveState; public class AntFactory implements IAntFactory { private final IAction antAction; public AntFactory(Random random, boolean healAnts){ this(random, true, true, healAnts); } public AntFactory(Random random, boolean attack, boolean collision, boolean healAnts){ List<IAction> actions = new LinkedList<IAction>(); actions.add(new EatFoodAction(2, 1.5f)); // eatingSpeed, eatingRadius actions.add(new BoidMoveAction(random, collision)); actions.add(new BounceAction()); if(healAnts) actions.add(new HealYourselfAction(1)); // healingSpeed if(attack) actions.add(new AttackAction(5, 1.5f)); // attackForce, attackRadius antAction = new CompoundAction(actions); } @Override public ILiveActor getAnt(ILiveState state, int playerId) { return new Actor(ActorType.ANT, state.nextActorId(), playerId, antAction, new Position(0,0), 0.3f, 0, 100, 100, Path.EMPTY_PATH); } }
true
eb5e8564417e880d45060c1771220c4a86bcbb6b
Java
anurag-rai/string-generator-from-regex
/src/org/anurag/stringGenerator/util/Util.java
UTF-8
315
2.515625
3
[]
no_license
package org.anurag.stringGenerator.util; import java.util.concurrent.ThreadLocalRandom; public final class Util { private Util() { } // min inclsuive // max not inclusive public static int getRandomInRange(int min, int max) { return ThreadLocalRandom.current().nextInt(min, max); } }
true
7a81034619479c18dab4061806c5163c2b243bb7
Java
BillTheBest/ovirt-engine
/frontend/webadmin/modules/sharedgwt-deployment/src/main/java/org/ovirt/engine/core/common/action/StorageServerConnectionParametersBase_CustomFieldSerializer.java
UTF-8
1,542
2.0625
2
[]
no_license
package org.ovirt.engine.core.common.action; import java.util.logging.Logger; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import org.ovirt.engine.core.common.businessentities.storage_server_connections; import org.ovirt.engine.core.compat.Guid; public class StorageServerConnectionParametersBase_CustomFieldSerializer { private static Logger logger = Logger.getLogger(StorageServerConnectionParametersBase.class.getName()); public static void deserialize(SerializationStreamReader streamReader, StorageServerConnectionParametersBase instance) throws SerializationException { } public static StorageServerConnectionParametersBase instantiate(SerializationStreamReader streamReader) throws SerializationException { logger.severe("Instantiating StorageServerConnectionParametersBase via custom serializer"); StorageServerConnectionParametersBase instance = new StorageServerConnectionParametersBase((storage_server_connections)streamReader.readObject(), (Guid)streamReader.readObject()); return instance; } public static void serialize(SerializationStreamWriter streamWriter, StorageServerConnectionParametersBase instance) throws SerializationException { logger.severe("Serializing StorageServerConnectionParametersBase."); streamWriter.writeObject(instance.getStorageServerConnection()); streamWriter.writeObject(instance.getVdsId()); } }
true
3bdbac7f0946e9b6316ef0aaffc22ba370fb54ad
Java
zhihongzhong/jy-java-boot
/parent/system/src/main/java/com/example/questionnaire/dto/AnswerModel.java
UTF-8
187
1.515625
2
[]
no_license
package com.example.questionnaire.dto; import lombok.Data; @Data public class AnswerModel { private String questionnaireId; private String subjectId; private String optionId; }
true
2c1956954871a795e3107822796011e19f9af026
Java
nanikaka/procon
/aoj/volume11/AOJ1137.java
UTF-8
956
3.3125
3
[]
no_license
package volume11; import java.util.Scanner; //Numeral System public class AOJ1137 { static int f(char[] s){ int r = 0; int x = 1; for(int i=0;i<s.length;i++){ if(Character.isDigit(s[i]))x = s[i]-'0'; else { switch(s[i]){ case 'm': r+=x*1000;break; case 'c': r+=x*100;break; case 'x': r+=x*10;break; case 'i': r+=x; } x = 1; } } return r; } static String g(int r){ String s = ""; if(r/1000>0){ if(r/1000>1)s+=r/1000; s+='m'; } r%=1000; if(r/100>0){ if(r/100>1)s+=r/100; s+='c'; } r%=100; if(r/10>0){ if(r/10>1)s+=r/10; s+='x'; } r%=10; if(r>=2)s+=r+"i"; else if(r==1)s+='i'; return s; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t--!=0){ System.out.println(g(f(sc.next().toCharArray()) + f(sc.next().toCharArray()))); } } }
true