hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
923b5ab13e849b4c9882a3952864032f61d63205
212
java
Java
T5ProyectoPiedraPapelTijera/src/programa/T5ClasePrincipal.java
rvs101/Curso_De_Programacion_Java
39e7796618fdc76da2c9c781719113315c52063c
[ "MIT" ]
null
null
null
T5ProyectoPiedraPapelTijera/src/programa/T5ClasePrincipal.java
rvs101/Curso_De_Programacion_Java
39e7796618fdc76da2c9c781719113315c52063c
[ "MIT" ]
null
null
null
T5ProyectoPiedraPapelTijera/src/programa/T5ClasePrincipal.java
rvs101/Curso_De_Programacion_Java
39e7796618fdc76da2c9c781719113315c52063c
[ "MIT" ]
null
null
null
13.25
42
0.622642
999,564
package programa; /** * Clase Principal del programa * * @author RVS * */ public class T5ClasePrincipal { public static void main(String[] args) { T5LogicaJuego.comenzarJuego(); } }
923b5bfe20f24aac62d23428f9d6a0e9b30cb298
747
java
Java
webviews/MainActivity.java
Ashleshk/Android-N-developer-Course
734aecfcc012d7ee474ca1e146a4ce78a03bd425
[ "MIT" ]
9
2020-05-12T13:32:03.000Z
2022-03-02T12:47:01.000Z
webviews/MainActivity.java
Ashleshk/Android-N-developer-Course
734aecfcc012d7ee474ca1e146a4ce78a03bd425
[ "MIT" ]
null
null
null
webviews/MainActivity.java
Ashleshk/Android-N-developer-Course
734aecfcc012d7ee474ca1e146a4ce78a03bd425
[ "MIT" ]
4
2020-10-12T08:51:31.000Z
2021-07-25T12:28:31.000Z
32.478261
116
0.713521
999,565
package com.lenovo.webviews; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView webView =(WebView)findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); //webView.loadUrl("https://www.google.com"); webView.loadData("<html><body><h1>hi hello!!</h1><p>this is my page</p></body></html>","text/html","UTF-8"); } }
923b5d14380d1fbe90f9a215de10ebc4cc21bf99
230
java
Java
src/main/java/club/tempvs/message/dto/GetConversationsDto.java
ahlinist/tempvs-message
1e8fbecb12e94c9d11c81a055dc93b18effadbce
[ "MIT" ]
null
null
null
src/main/java/club/tempvs/message/dto/GetConversationsDto.java
ahlinist/tempvs-message
1e8fbecb12e94c9d11c81a055dc93b18effadbce
[ "MIT" ]
68
2018-08-18T12:37:55.000Z
2019-08-09T15:20:11.000Z
src/main/java/club/tempvs/message/dto/GetConversationsDto.java
ahlinist/tempvs-message
1e8fbecb12e94c9d11c81a055dc93b18effadbce
[ "MIT" ]
null
null
null
16.428571
52
0.808696
999,566
package club.tempvs.message.dto; import lombok.AllArgsConstructor; import lombok.Data; import java.util.List; @Data @AllArgsConstructor public class GetConversationsDto { private List<ConversationDtoBean> conversations; }
923b5d211d2ad77b67385ee9ebb94f4c6aac1440
2,284
java
Java
eu.dariolucia.reatmetric.api/src/main/java/eu/dariolucia/reatmetric/api/common/UniqueItem.java
dariol83/reatmetric
5374d4326852c510d43fc468995b6392da214dd8
[ "Apache-2.0" ]
13
2020-04-29T08:45:43.000Z
2022-03-17T11:56:17.000Z
eu.dariolucia.reatmetric.api/src/main/java/eu/dariolucia/reatmetric/api/common/UniqueItem.java
dariol83/reatmetric
5374d4326852c510d43fc468995b6392da214dd8
[ "Apache-2.0" ]
5
2020-12-13T09:33:48.000Z
2021-02-03T16:28:51.000Z
eu.dariolucia.reatmetric.api/src/main/java/eu/dariolucia/reatmetric/api/common/UniqueItem.java
dariol83/reatmetric
5374d4326852c510d43fc468995b6392da214dd8
[ "Apache-2.0" ]
3
2020-05-02T06:40:39.000Z
2022-02-27T00:53:45.000Z
26.870588
121
0.643608
999,567
/* * Copyright (c) 2020 Dario Lucia (https://www.dariolucia.eu) * * 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 eu.dariolucia.reatmetric.api.common; import java.io.Serializable; /** * A unique item is an object that can be identified by a {@link IUniqueId}. * * This class is immutable with the exception of the data property, which shall be considered a transient volatile field, * provided as a convenience placeholder to store volatile user data. The hashCode and equals methods do not take this * property into account. */ public abstract class UniqueItem implements Serializable { /** * */ private static final long serialVersionUID = -4265552582009003032L; protected final IUniqueId internalId; protected transient volatile Object data; public UniqueItem(IUniqueId internalId, Object data) { this.internalId = internalId; this.data = data; } public IUniqueId getInternalId() { return internalId; } public Object getData() { return data; } public void setData(Object o) { this.data = o; } @Override public int hashCode() { int hash = 5; hash = 89 * hash + this.internalId.hashCode(); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final UniqueItem other = (UniqueItem) obj; return this.internalId == other.internalId; } @Override public String toString() { return "UniqueItem [" + "internalId=" + internalId + ']'; } }
923b5ddccfe5b13728bc3b612fa7eb2c4388e0bc
1,194
java
Java
src/main/java/tk/ddvudo/Mybatis/UseAnnotation/EnterpriseDao.java
ddv12138/HOW2JTest
b192af1e7ee071c22af093917e62ab0f97ef1f0f
[ "MIT" ]
1
2019-03-23T17:51:52.000Z
2019-03-23T17:51:52.000Z
src/main/java/tk/ddvudo/Mybatis/UseAnnotation/EnterpriseDao.java
ddv12138/HOW2JTest
b192af1e7ee071c22af093917e62ab0f97ef1f0f
[ "MIT" ]
null
null
null
src/main/java/tk/ddvudo/Mybatis/UseAnnotation/EnterpriseDao.java
ddv12138/HOW2JTest
b192af1e7ee071c22af093917e62ab0f97ef1f0f
[ "MIT" ]
null
null
null
30.615385
114
0.794807
999,568
package tk.ddvudo.Mybatis.UseAnnotation; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.ResultHandler; import tk.ddvudo.Mybatis.JavaBeans.Enterprise; import tk.ddvudo.Mybatis.JavaBeans.EnterpriseExample; import java.util.List; import java.util.Map; public interface EnterpriseDao { long countByExample(EnterpriseExample example); int deleteByExample(EnterpriseExample example); int deleteByPrimaryKey(Integer id); int insert(Enterprise record); int insertSelective(Enterprise record); List<Enterprise> selectByExample(EnterpriseExample example); List<Map> selectByExample_Map(EnterpriseExample example); void selectByExample_Map_Forward(EnterpriseExample example, ResultHandler<Enterprise> handler); Enterprise selectByPrimaryKey(Integer id); Map selectByPrimaryKey_Map(Integer id); int updateByExampleSelective(@Param("record") Enterprise record, @Param("example") EnterpriseExample example); int updateByExample(@Param("record") Enterprise record, @Param("example") EnterpriseExample example); int updateByPrimaryKeySelective(Enterprise record); int updateByPrimaryKey(Enterprise record); }
923b5ec649eed78a906c4d5d1bd0fe2266a80d08
1,697
java
Java
src/main/java/com/tcmsoso/webapplication/HistoryList.java
mingdunlan/papa
c4c37489156d6347531b90901c11485d19f6d5a7
[ "Apache-2.0" ]
null
null
null
src/main/java/com/tcmsoso/webapplication/HistoryList.java
mingdunlan/papa
c4c37489156d6347531b90901c11485d19f6d5a7
[ "Apache-2.0" ]
null
null
null
src/main/java/com/tcmsoso/webapplication/HistoryList.java
mingdunlan/papa
c4c37489156d6347531b90901c11485d19f6d5a7
[ "Apache-2.0" ]
null
null
null
33.94
132
0.684738
999,569
package com.tcmsoso.webapplication; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.tcmsoso.webapplication.adapter.HistoryAdapter; import com.tcmsoso.webapplication.db.History; import org.litepal.LitePal; import java.util.List; public class HistoryList extends AppCompatActivity { List<History> historyList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history_list); //初始化 historyList = LitePal.findAll(History.class); HistoryAdapter adapter = new HistoryAdapter(HistoryList.this,R.layout.history_item,historyList); ListView listView = (ListView) findViewById(R.id.history_list_view); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { History history = historyList.get(i); String url = history.getWebUrl(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } }); // for(History item: historyList){ // Log.d("MainActivity---History: ",item.getTitle()+"------"+item.getWebUrl()+"-----"+item.getHistoryDate().toString()); // } } }
923b5fc517dc0269f4bf66795c72442aaf357b57
1,741
java
Java
Gaoxi-Common-Service-Facade/src/main/java/com/gaoxi/entity/user/LocationEntity.java
shiyijun0/Dubbo_Docker_Jenkins
4fd61c845f7617f5e6032d13ce965ee2a2bca74f
[ "Apache-2.0" ]
null
null
null
Gaoxi-Common-Service-Facade/src/main/java/com/gaoxi/entity/user/LocationEntity.java
shiyijun0/Dubbo_Docker_Jenkins
4fd61c845f7617f5e6032d13ce965ee2a2bca74f
[ "Apache-2.0" ]
null
null
null
Gaoxi-Common-Service-Facade/src/main/java/com/gaoxi/entity/user/LocationEntity.java
shiyijun0/Dubbo_Docker_Jenkins
4fd61c845f7617f5e6032d13ce965ee2a2bca74f
[ "Apache-2.0" ]
1
2020-03-08T05:29:28.000Z
2020-03-08T05:29:28.000Z
18.521277
57
0.518667
999,570
package com.gaoxi.entity.user; import java.io.Serializable; /** * @author 大闲人柴毛毛 * @date 2017/11/6 上午11:40 * * @description 地址信息 */ /*@Table @Entity*/ public class LocationEntity implements Serializable{ /** 主键 */ /*@Id @GeneratedValue(strategy = GenerationType.IDENTITY)*/ private String id; /** 详细地址 */ private String location; /** 收货人姓名 */ private String name; /** 收货人手机号 */ private String phone; /** 邮编 */ private String postCode; private String userId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public String toString() { return "LocationEntity{" + "id='" + id + '\'' + ", location='" + location + '\'' + ", name='" + name + '\'' + ", phone='" + phone + '\'' + ", postCode='" + postCode + '\'' + ", userId='" + userId + '\'' + '}'; } }
923b5fceb849977fb54bf6797cca48a015a69e81
361
java
Java
src/main/java/net/unit8/example/invariant/tryexecute/OrderMemento.java
kawasima/completeness-purity-invariant
5ea4ae81ad3c7cde41ba8a33a2c7352efcf37fe3
[ "MIT" ]
1
2021-06-01T22:58:14.000Z
2021-06-01T22:58:14.000Z
src/main/java/net/unit8/example/invariant/tryexecute/OrderMemento.java
kawasima/completeness-purity-invariant
5ea4ae81ad3c7cde41ba8a33a2c7352efcf37fe3
[ "MIT" ]
null
null
null
src/main/java/net/unit8/example/invariant/tryexecute/OrderMemento.java
kawasima/completeness-purity-invariant
5ea4ae81ad3c7cde41ba8a33a2c7352efcf37fe3
[ "MIT" ]
null
null
null
25.785714
55
0.778393
999,571
package net.unit8.example.invariant.tryexecute; import lombok.Value; import net.unit8.example.invariant.share.Address; import net.unit8.example.invariant.share.DeliveryTime; import net.unit8.example.invariant.share.OrderStatus; @Value public class OrderMemento { OrderStatus orderStatus; Address address; DeliveryTime deliveryTime; }
923b6079230c70a2c7d0a3f5a0eefc10598ad4f8
578
java
Java
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/model/HookPhaseProcessType.java
theghost5800/cf-mta-deploy-service
274ef5bfbff23978df309352cb22ec1473e318b3
[ "Apache-2.0" ]
null
null
null
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/model/HookPhaseProcessType.java
theghost5800/cf-mta-deploy-service
274ef5bfbff23978df309352cb22ec1473e318b3
[ "Apache-2.0" ]
null
null
null
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/model/HookPhaseProcessType.java
theghost5800/cf-mta-deploy-service
274ef5bfbff23978df309352cb22ec1473e318b3
[ "Apache-2.0" ]
1
2020-03-20T07:17:03.000Z
2020-03-20T07:17:03.000Z
17
54
0.569204
999,572
package com.sap.cloud.lm.sl.cf.core.model; public enum HookPhaseProcessType { DEPLOY("deploy"), BLUE_GREEN_DEPLOY("blue-green"); private final String type; HookPhaseProcessType(String type) { this.type = type; } public String getType() { return type; } public enum HookProcessPhase { NONE(""), IDLE("idle"), LIVE("live"); private final String type; HookProcessPhase(String type) { this.type = type; } public String getType() { return type; } } }
923b613b2f4c21ac4540bfae159f480e13a57792
699
java
Java
Students/Farcas Silviu Vlad/Assignment 6.1/javasmmr.zoowsome/src/javasmmr/zoowsome/services/factories/ReptileFactory.java
JavaSummer/JavaMainRepo
262a3299b0135ba40ea4018a184dd3fdbf468d2e
[ "Apache-2.0" ]
31
2015-06-22T08:12:05.000Z
2021-01-09T08:39:16.000Z
Students/Farcas Silviu Vlad/Assignment 7/javasmmr.zoowsome/src/javasmmr/zoowsome/services/factories/ReptileFactory.java
souravsingpardeshi/JavaMainRepo
262a3299b0135ba40ea4018a184dd3fdbf468d2e
[ "Apache-2.0" ]
77
2015-06-24T05:40:30.000Z
2020-08-25T09:00:11.000Z
Students/Farcas Silviu Vlad/Assignment 7/javasmmr.zoowsome/src/javasmmr/zoowsome/services/factories/ReptileFactory.java
souravsingpardeshi/JavaMainRepo
262a3299b0135ba40ea4018a184dd3fdbf468d2e
[ "Apache-2.0" ]
68
2015-06-22T08:19:35.000Z
2021-08-17T09:29:39.000Z
38.833333
82
0.72103
999,573
package javasmmr.zoowsome.services.factories; import javasmmr.zoowsome.models.animals.*; public class ReptileFactory extends SpeciesFactory { public Animal getAnimal(String type) throws Exception { if (Constants.Animal.Reptile.Chameleon.equals(type)) { return new Chameleon(AnimalFactory.names[(int) (Math.random() * 100)], 2, 0); } else if (Constants.Animal.Reptile.Cobra.equals(type)) { return new Cobra(AnimalFactory.names[(int) (Math.random() * 100)], 1, 0.95); } else if (Constants.Animal.Reptile.Crocodile.equals(type)) { return new Crocodile(AnimalFactory.names[(int) (Math.random() * 100)], 4, 0.9); } else { throw new Exception("Invalid animal exception!"); } } }
923b61447bd429cc35d1de6725cf44d2e4819cdd
177
java
Java
socket-client/src/main/java/com/codereform/gui/components/factory/AbstractFactory.java
gdyrrahitis/pi-cluster-infrastructure
fc763290b37a5a2cf7b58704dcbaa7e46602011a
[ "Apache-2.0" ]
null
null
null
socket-client/src/main/java/com/codereform/gui/components/factory/AbstractFactory.java
gdyrrahitis/pi-cluster-infrastructure
fc763290b37a5a2cf7b58704dcbaa7e46602011a
[ "Apache-2.0" ]
19
2021-02-22T00:34:40.000Z
2021-03-04T00:30:15.000Z
socket-client/src/main/java/com/codereform/gui/components/factory/AbstractFactory.java
gdyrrahitis/pi-cluster-infrastructure
fc763290b37a5a2cf7b58704dcbaa7e46602011a
[ "Apache-2.0" ]
null
null
null
22.125
49
0.813559
999,574
package com.codereform.gui.components.factory; import com.codereform.gui.components.UiComponent; public interface AbstractFactory { UiComponent create(Class component); }
923b61887a9c27105f4862417e19600843461023
2,419
java
Java
src/main/java/org/homedns/mkh/util/scheduler/JobTemplateImpl.java
khomisha/util
22428f7cac6537c8e201fcec78d7415a5e0fa09a
[ "Apache-1.1" ]
null
null
null
src/main/java/org/homedns/mkh/util/scheduler/JobTemplateImpl.java
khomisha/util
22428f7cac6537c8e201fcec78d7415a5e0fa09a
[ "Apache-1.1" ]
null
null
null
src/main/java/org/homedns/mkh/util/scheduler/JobTemplateImpl.java
khomisha/util
22428f7cac6537c8e201fcec78d7415a5e0fa09a
[ "Apache-1.1" ]
null
null
null
24.683673
111
0.699876
999,575
/* * Copyright 2014-2020 Mikhail Khodonov * * 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. * * $Id$ */ package org.homedns.mkh.util.scheduler; import org.quartz.Job; import org.quartz.JobDataMap; /** * Implements @see org.homedns.mkh.ledgerpipe.JobTemplate * */ public class JobTemplateImpl implements JobTemplate { private String sName; private String sCronExp; private Class< ? extends Job > jobClazz; private JobDataMap jobData; /** * @param sName the name * @param sCronExp the cron expression * @param jobClazz the job class */ public JobTemplateImpl( String sName, String sCronExp, Class< ? extends Job > jobClazz ) { this.sName = sName; this.sCronExp = sCronExp; this.jobClazz = jobClazz; } /** * @param sName the name * @param sCronExp the cron expression * @param jobClazz the job class * @param jobData the input job data store */ public JobTemplateImpl( String sName, String sCronExp, Class< ? extends Job > jobClazz, JobDataMap jobData ) { this( sName, sCronExp, jobClazz ); this.jobData = jobData; } /** * @see org.homedns.mkh.util.scheduler.JobTemplate#getName() */ @Override public String getName( ) { return( sName ); } /** * @see org.homedns.mkh.util.scheduler.JobTemplate#getCronExp() */ @Override public String getCronExp( ) { return( sCronExp ); } /** * @see org.homedns.mkh.util.scheduler.JobTemplate#getJobClazz() */ @Override public Class< ? extends Job > getJobClazz( ) { return( jobClazz ); } /** * @see org.homedns.mkh.util.scheduler.JobTemplate#getJobData() */ @Override public JobDataMap getJobData( ) { return( jobData ); } /** * @see org.homedns.mkh.util.scheduler.JobTemplate#add2JobData(java.lang.String, java.lang.Object) */ public void add2JobData( String sKey, Object value ) { if( jobData == null ) { jobData = new JobDataMap( ); } jobData.put( sKey, value ); } }
923b621ae8ff0f1a3cc924ba2d56e07306a59123
1,789
java
Java
tapestry-examples/Vlib/src/org/apache/tapestry/vlib/AdminPage.java
JLLeitschuh/tapestry3
c4ab183a5e85f66f1611248b35acae8e6990c4cc
[ "Apache-2.0" ]
3
2016-05-09T08:34:38.000Z
2021-11-10T19:06:54.000Z
tapestry-examples/Vlib/src/org/apache/tapestry/vlib/AdminPage.java
srcclrapache1/tapestry3
c4ab183a5e85f66f1611248b35acae8e6990c4cc
[ "Apache-2.0" ]
1
2021-11-03T10:58:43.000Z
2021-11-03T10:58:43.000Z
tapestry-examples/Vlib/src/org/apache/tapestry/vlib/AdminPage.java
srcclrapache1/tapestry3
c4ab183a5e85f66f1611248b35acae8e6990c4cc
[ "Apache-2.0" ]
16
2015-03-18T11:57:28.000Z
2021-11-10T19:06:43.000Z
31.385965
89
0.698155
999,576
// Copyright 2004 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry.vlib; import org.apache.tapestry.IRequestCycle; import org.apache.tapestry.PageRedirectException; import org.apache.tapestry.callback.PageCallback; import org.apache.tapestry.event.PageEvent; import org.apache.tapestry.vlib.pages.Login; /** * Base page for any pages restricted to administrators. * * @author Howard Lewis Ship * @version $Id$ * **/ public abstract class AdminPage extends Protected implements IMessageProperty { public void pageValidate(PageEvent event) { IRequestCycle cycle = event.getRequestCycle(); Visit visit = (Visit) getEngine().getVisit(); if (visit == null || !visit.isUserLoggedIn()) { Login login = (Login) cycle.getPage("Login"); login.setCallback(new PageCallback(this)); throw new PageRedirectException(login); } if (!visit.getUser(cycle).isAdmin()) { VirtualLibraryEngine vengine = (VirtualLibraryEngine) getEngine(); vengine.presentError("That function is restricted to adminstrators.", cycle); throw new PageRedirectException(cycle.getPage()); } } }
923b62638a1186b1e592de8b9f47b99384cc1963
1,700
java
Java
zlcore/src/main/java/com/zaitunlabs/zlcore/utils/NotificationProgressUtil.java
ahsai001/zlcore
fbad7bfc695270d628872cc439cc7e371bc08c10
[ "MIT" ]
null
null
null
zlcore/src/main/java/com/zaitunlabs/zlcore/utils/NotificationProgressUtil.java
ahsai001/zlcore
fbad7bfc695270d628872cc439cc7e371bc08c10
[ "MIT" ]
null
null
null
zlcore/src/main/java/com/zaitunlabs/zlcore/utils/NotificationProgressUtil.java
ahsai001/zlcore
fbad7bfc695270d628872cc439cc7e371bc08c10
[ "MIT" ]
null
null
null
31.481481
103
0.688824
999,577
package com.zaitunlabs.zlcore.utils; import android.app.NotificationManager; import android.content.Context; import androidx.core.app.NotificationCompat; /** * Created by ahsai on 2/14/2018. */ public class NotificationProgressUtil { private int notifID; private NotificationManager mNotifyManager; private NotificationCompat.Builder mBuilder; private String title; private String desc; private int icon; public NotificationProgressUtil(Context context, String title, String desc, int icon, int notifID){ mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(context, CommonUtil.getPackageName(context)); mBuilder.setContentTitle(title) .setContentText(desc) .setSmallIcon(icon); this.notifID = notifID; this.title = title; this.desc = desc; this.icon = icon; } public void setProgress(int max, int progress){ mBuilder.setOngoing(true); mBuilder.setProgress(max, progress, false); mBuilder.setContentText(desc+" "+progress+" %"); mNotifyManager.notify(notifID, mBuilder.build()); } public void setIndeterminateProgress(){ mBuilder.setOngoing(true); mBuilder.setProgress(0, 0, true); mBuilder.setContentText(desc); mNotifyManager.notify(notifID, mBuilder.build()); } public void setComplete(String completeText){ mBuilder.setOngoing(false); mBuilder.setContentText(completeText); mBuilder.setProgress(0,0,false); mNotifyManager.notify(notifID, mBuilder.build()); } }
923b62c29d099e2898c96c162a4b268284a2337f
6,015
java
Java
app/models/User.java
etrupthi/casettaBE
5007b34ee57f85ebcde16d10002025458624bb22
[ "CC0-1.0" ]
null
null
null
app/models/User.java
etrupthi/casettaBE
5007b34ee57f85ebcde16d10002025458624bb22
[ "CC0-1.0" ]
null
null
null
app/models/User.java
etrupthi/casettaBE
5007b34ee57f85ebcde16d10002025458624bb22
[ "CC0-1.0" ]
null
null
null
20.252525
187
0.583209
999,578
package models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import javax.inject.Inject; import javax.persistence.*; import java.util.List; import java.util.Set; @Entity @SequenceGenerator(name="seq",initialValue = 0, allocationSize=100) public class User { public enum Role { ADMIN, USER } public enum State { PENDING, VERIFIED, LOCKED } // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "seq") // @JsonProperty("id") // private Integer id; @Id @JsonProperty("username") private String username; @Basic @JsonIgnore @JsonProperty("passwordHash") private String passwordHash; @Basic @JsonIgnore @JsonProperty("salt") private String salt; @Basic @JsonIgnore @JsonProperty("hashIterations") private Integer hashIterations; @Basic @JsonProperty("email") private String email; @Basic @JsonProperty("mobileno") private String mobileno; @Basic @JsonProperty("role") private Role role; @Basic @JsonProperty("state") private State state; @Basic @JsonProperty("accessToken") private String accessToken; // @OneToMany // @JoinColumn(name = "username") // private List<Hotel> hotels; public User(){ } public User(String username, String passwordHash, String salt, Integer hashIterations, String email, String mobileno , Role role, State state, String accessToken, Set<Hotel> hotels) { //this.id = id; this.username = username; this.passwordHash = passwordHash; this.salt = salt; this.hashIterations = hashIterations; this.email = email; this.mobileno = mobileno; this.role = role; this.state = state; this.accessToken = accessToken; } // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPasswordHash() { return passwordHash; } public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public Integer getHashIterations() { return hashIterations; } public void setHashIterations(Integer hashIterations) { this.hashIterations = hashIterations; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public State getState() { return state; } public void setState(State state) { this.state = state; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public String getMobileno() { return mobileno; } public void setMobileno(String mobileno) { this.mobileno = mobileno; } } //package models; // //import com.fasterxml.jackson.annotation.JsonProperty; // //import javax.persistence.*; // //@Entity //public class User { // // public enum Role { // ADMIN, // USER // } // // public enum State { // PENDING, // VERIFIED, // LOCKED // } // //// @Id //// @GeneratedValue(strategy = GenerationType.AUTO) //// @JsonProperty("id") //// private Integer id; // // @Id // @JsonProperty("username") // private String username; // // @Basic // @JsonProperty(value = "password", access = JsonProperty.Access.WRITE_ONLY) // private String password; // // @Basic // @JsonProperty("email") // private String email; // // @Basic // @JsonProperty("role") // private Role role; // // @Basic // @JsonProperty("state") // private State state; // // @Basic // @JsonProperty("accessToken") // private String accessToken; // // public User() { // } // //// public User(Integer id, String username, String password, String email, Role role, State state, String accessToken) // // public User(String username, String password, String email, Role role, State state, String accessToken) // { // //this.id = id; // this.username = username; // this.password = password; // this.email = email; // this.role = role; // this.state = state; // this.accessToken = accessToken; // } // //// public Integer getId() { //// return id; //// } //// //// public void setId(Integer id) { //// this.id = id; //// } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Role getRole() { // return role; // } // // public void setRole(Role role) { // this.role = role; // } // // public State getState() { // return state; // } // // public void setState(State state) { // this.state = state; // } // // public String getAccessToken() { // return accessToken; // } // // public void setAccessToken(String accessToken) { // this.accessToken = accessToken; // } //}
923b62fb4018b673d897fbfc34fc0e2fd60e2ddd
21,402
java
Java
target/classes/org/projectfloodlight/openflow/protocol/ver14/OFQueueStatsEntryVer14.java
gameLoading/myopenflow
8865f9294a35bf047d5ca6c6ad1c743089e6c713
[ "Apache-2.0" ]
1
2020-06-17T05:09:38.000Z
2020-06-17T05:09:38.000Z
target/classes/org/projectfloodlight/openflow/protocol/ver14/OFQueueStatsEntryVer14.java
gameLoading/myopenflow
8865f9294a35bf047d5ca6c6ad1c743089e6c713
[ "Apache-2.0" ]
null
null
null
target/classes/org/projectfloodlight/openflow/protocol/ver14/OFQueueStatsEntryVer14.java
gameLoading/myopenflow
8865f9294a35bf047d5ca6c6ad1c743089e6c713
[ "Apache-2.0" ]
null
null
null
33.917591
171
0.617746
999,579
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver14; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import com.google.common.collect.ImmutableList; import java.util.Set; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFQueueStatsEntryVer14 implements OFQueueStatsEntry { private static final Logger logger = LoggerFactory.getLogger(OFQueueStatsEntryVer14.class); // version: 1.4 final static byte WIRE_VERSION = 5; final static int MINIMUM_LENGTH = 48; private final static OFPort DEFAULT_PORT_NO = OFPort.ANY; private final static long DEFAULT_QUEUE_ID = 0x0L; private final static U64 DEFAULT_TX_BYTES = U64.ZERO; private final static U64 DEFAULT_TX_PACKETS = U64.ZERO; private final static U64 DEFAULT_TX_ERRORS = U64.ZERO; private final static long DEFAULT_DURATION_SEC = 0x0L; private final static long DEFAULT_DURATION_NSEC = 0x0L; private final static List<OFQueueStatsProp> DEFAULT_PROPERTIES = ImmutableList.<OFQueueStatsProp>of(); // OF message fields private final OFPort portNo; private final long queueId; private final U64 txBytes; private final U64 txPackets; private final U64 txErrors; private final long durationSec; private final long durationNsec; private final List<OFQueueStatsProp> properties; // // Immutable default instance final static OFQueueStatsEntryVer14 DEFAULT = new OFQueueStatsEntryVer14( DEFAULT_PORT_NO, DEFAULT_QUEUE_ID, DEFAULT_TX_BYTES, DEFAULT_TX_PACKETS, DEFAULT_TX_ERRORS, DEFAULT_DURATION_SEC, DEFAULT_DURATION_NSEC, DEFAULT_PROPERTIES ); // package private constructor - used by readers, builders, and factory OFQueueStatsEntryVer14(OFPort portNo, long queueId, U64 txBytes, U64 txPackets, U64 txErrors, long durationSec, long durationNsec, List<OFQueueStatsProp> properties) { if(portNo == null) { throw new NullPointerException("OFQueueStatsEntryVer14: property portNo cannot be null"); } if(txBytes == null) { throw new NullPointerException("OFQueueStatsEntryVer14: property txBytes cannot be null"); } if(txPackets == null) { throw new NullPointerException("OFQueueStatsEntryVer14: property txPackets cannot be null"); } if(txErrors == null) { throw new NullPointerException("OFQueueStatsEntryVer14: property txErrors cannot be null"); } if(properties == null) { throw new NullPointerException("OFQueueStatsEntryVer14: property properties cannot be null"); } this.portNo = portNo; this.queueId = queueId; this.txBytes = txBytes; this.txPackets = txPackets; this.txErrors = txErrors; this.durationSec = durationSec; this.durationNsec = durationNsec; this.properties = properties; } // Accessors for OF message fields @Override public OFPort getPortNo() { return portNo; } @Override public long getQueueId() { return queueId; } @Override public U64 getTxBytes() { return txBytes; } @Override public U64 getTxPackets() { return txPackets; } @Override public U64 getTxErrors() { return txErrors; } @Override public long getDurationSec() { return durationSec; } @Override public long getDurationNsec() { return durationNsec; } @Override public List<OFQueueStatsProp> getProperties() { return properties; } @Override public OFVersion getVersion() { return OFVersion.OF_14; } public OFQueueStatsEntry.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFQueueStatsEntry.Builder { final OFQueueStatsEntryVer14 parentMessage; // OF message fields private boolean portNoSet; private OFPort portNo; private boolean queueIdSet; private long queueId; private boolean txBytesSet; private U64 txBytes; private boolean txPacketsSet; private U64 txPackets; private boolean txErrorsSet; private U64 txErrors; private boolean durationSecSet; private long durationSec; private boolean durationNsecSet; private long durationNsec; private boolean propertiesSet; private List<OFQueueStatsProp> properties; BuilderWithParent(OFQueueStatsEntryVer14 parentMessage) { this.parentMessage = parentMessage; } @Override public OFPort getPortNo() { return portNo; } @Override public OFQueueStatsEntry.Builder setPortNo(OFPort portNo) { this.portNo = portNo; this.portNoSet = true; return this; } @Override public long getQueueId() { return queueId; } @Override public OFQueueStatsEntry.Builder setQueueId(long queueId) { this.queueId = queueId; this.queueIdSet = true; return this; } @Override public U64 getTxBytes() { return txBytes; } @Override public OFQueueStatsEntry.Builder setTxBytes(U64 txBytes) { this.txBytes = txBytes; this.txBytesSet = true; return this; } @Override public U64 getTxPackets() { return txPackets; } @Override public OFQueueStatsEntry.Builder setTxPackets(U64 txPackets) { this.txPackets = txPackets; this.txPacketsSet = true; return this; } @Override public U64 getTxErrors() { return txErrors; } @Override public OFQueueStatsEntry.Builder setTxErrors(U64 txErrors) { this.txErrors = txErrors; this.txErrorsSet = true; return this; } @Override public long getDurationSec() { return durationSec; } @Override public OFQueueStatsEntry.Builder setDurationSec(long durationSec) { this.durationSec = durationSec; this.durationSecSet = true; return this; } @Override public long getDurationNsec() { return durationNsec; } @Override public OFQueueStatsEntry.Builder setDurationNsec(long durationNsec) { this.durationNsec = durationNsec; this.durationNsecSet = true; return this; } @Override public List<OFQueueStatsProp> getProperties() { return properties; } @Override public OFQueueStatsEntry.Builder setProperties(List<OFQueueStatsProp> properties) { this.properties = properties; this.propertiesSet = true; return this; } @Override public OFVersion getVersion() { return OFVersion.OF_14; } @Override public OFQueueStatsEntry build() { OFPort portNo = this.portNoSet ? this.portNo : parentMessage.portNo; if(portNo == null) throw new NullPointerException("Property portNo must not be null"); long queueId = this.queueIdSet ? this.queueId : parentMessage.queueId; U64 txBytes = this.txBytesSet ? this.txBytes : parentMessage.txBytes; if(txBytes == null) throw new NullPointerException("Property txBytes must not be null"); U64 txPackets = this.txPacketsSet ? this.txPackets : parentMessage.txPackets; if(txPackets == null) throw new NullPointerException("Property txPackets must not be null"); U64 txErrors = this.txErrorsSet ? this.txErrors : parentMessage.txErrors; if(txErrors == null) throw new NullPointerException("Property txErrors must not be null"); long durationSec = this.durationSecSet ? this.durationSec : parentMessage.durationSec; long durationNsec = this.durationNsecSet ? this.durationNsec : parentMessage.durationNsec; List<OFQueueStatsProp> properties = this.propertiesSet ? this.properties : parentMessage.properties; if(properties == null) throw new NullPointerException("Property properties must not be null"); // return new OFQueueStatsEntryVer14( portNo, queueId, txBytes, txPackets, txErrors, durationSec, durationNsec, properties ); } } static class Builder implements OFQueueStatsEntry.Builder { // OF message fields private boolean portNoSet; private OFPort portNo; private boolean queueIdSet; private long queueId; private boolean txBytesSet; private U64 txBytes; private boolean txPacketsSet; private U64 txPackets; private boolean txErrorsSet; private U64 txErrors; private boolean durationSecSet; private long durationSec; private boolean durationNsecSet; private long durationNsec; private boolean propertiesSet; private List<OFQueueStatsProp> properties; @Override public OFPort getPortNo() { return portNo; } @Override public OFQueueStatsEntry.Builder setPortNo(OFPort portNo) { this.portNo = portNo; this.portNoSet = true; return this; } @Override public long getQueueId() { return queueId; } @Override public OFQueueStatsEntry.Builder setQueueId(long queueId) { this.queueId = queueId; this.queueIdSet = true; return this; } @Override public U64 getTxBytes() { return txBytes; } @Override public OFQueueStatsEntry.Builder setTxBytes(U64 txBytes) { this.txBytes = txBytes; this.txBytesSet = true; return this; } @Override public U64 getTxPackets() { return txPackets; } @Override public OFQueueStatsEntry.Builder setTxPackets(U64 txPackets) { this.txPackets = txPackets; this.txPacketsSet = true; return this; } @Override public U64 getTxErrors() { return txErrors; } @Override public OFQueueStatsEntry.Builder setTxErrors(U64 txErrors) { this.txErrors = txErrors; this.txErrorsSet = true; return this; } @Override public long getDurationSec() { return durationSec; } @Override public OFQueueStatsEntry.Builder setDurationSec(long durationSec) { this.durationSec = durationSec; this.durationSecSet = true; return this; } @Override public long getDurationNsec() { return durationNsec; } @Override public OFQueueStatsEntry.Builder setDurationNsec(long durationNsec) { this.durationNsec = durationNsec; this.durationNsecSet = true; return this; } @Override public List<OFQueueStatsProp> getProperties() { return properties; } @Override public OFQueueStatsEntry.Builder setProperties(List<OFQueueStatsProp> properties) { this.properties = properties; this.propertiesSet = true; return this; } @Override public OFVersion getVersion() { return OFVersion.OF_14; } // @Override public OFQueueStatsEntry build() { OFPort portNo = this.portNoSet ? this.portNo : DEFAULT_PORT_NO; if(portNo == null) throw new NullPointerException("Property portNo must not be null"); long queueId = this.queueIdSet ? this.queueId : DEFAULT_QUEUE_ID; U64 txBytes = this.txBytesSet ? this.txBytes : DEFAULT_TX_BYTES; if(txBytes == null) throw new NullPointerException("Property txBytes must not be null"); U64 txPackets = this.txPacketsSet ? this.txPackets : DEFAULT_TX_PACKETS; if(txPackets == null) throw new NullPointerException("Property txPackets must not be null"); U64 txErrors = this.txErrorsSet ? this.txErrors : DEFAULT_TX_ERRORS; if(txErrors == null) throw new NullPointerException("Property txErrors must not be null"); long durationSec = this.durationSecSet ? this.durationSec : DEFAULT_DURATION_SEC; long durationNsec = this.durationNsecSet ? this.durationNsec : DEFAULT_DURATION_NSEC; List<OFQueueStatsProp> properties = this.propertiesSet ? this.properties : DEFAULT_PROPERTIES; if(properties == null) throw new NullPointerException("Property properties must not be null"); return new OFQueueStatsEntryVer14( portNo, queueId, txBytes, txPackets, txErrors, durationSec, durationNsec, properties ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFQueueStatsEntry> { @Override public OFQueueStatsEntry readFrom(ByteBuf bb) throws OFParseError { int start = bb.readerIndex(); int length = U16.f(bb.readShort()); if(length < MINIMUM_LENGTH) throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); // pad: 6 bytes bb.skipBytes(6); OFPort portNo = OFPort.read4Bytes(bb); long queueId = U32.f(bb.readInt()); U64 txBytes = U64.ofRaw(bb.readLong()); U64 txPackets = U64.ofRaw(bb.readLong()); U64 txErrors = U64.ofRaw(bb.readLong()); long durationSec = U32.f(bb.readInt()); long durationNsec = U32.f(bb.readInt()); List<OFQueueStatsProp> properties = ChannelUtils.readList(bb, length - (bb.readerIndex() - start), OFQueueStatsPropVer14.READER); OFQueueStatsEntryVer14 queueStatsEntryVer14 = new OFQueueStatsEntryVer14( portNo, queueId, txBytes, txPackets, txErrors, durationSec, durationNsec, properties ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", queueStatsEntryVer14); return queueStatsEntryVer14; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFQueueStatsEntryVer14Funnel FUNNEL = new OFQueueStatsEntryVer14Funnel(); static class OFQueueStatsEntryVer14Funnel implements Funnel<OFQueueStatsEntryVer14> { private static final long serialVersionUID = 1L; @Override public void funnel(OFQueueStatsEntryVer14 message, PrimitiveSink sink) { // FIXME: skip funnel of length // skip pad (6 bytes) message.portNo.putTo(sink); sink.putLong(message.queueId); message.txBytes.putTo(sink); message.txPackets.putTo(sink); message.txErrors.putTo(sink); sink.putLong(message.durationSec); sink.putLong(message.durationNsec); FunnelUtils.putList(message.properties, sink); } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFQueueStatsEntryVer14> { @Override public void write(ByteBuf bb, OFQueueStatsEntryVer14 message) { int startIndex = bb.writerIndex(); // length is length of variable message, will be updated at the end int lengthIndex = bb.writerIndex(); bb.writeShort(U16.t(0)); // pad: 6 bytes bb.writeZero(6); message.portNo.write4Bytes(bb); bb.writeInt(U32.t(message.queueId)); bb.writeLong(message.txBytes.getValue()); bb.writeLong(message.txPackets.getValue()); bb.writeLong(message.txErrors.getValue()); bb.writeInt(U32.t(message.durationSec)); bb.writeInt(U32.t(message.durationNsec)); ChannelUtils.writeList(bb, message.properties); // update length field int length = bb.writerIndex() - startIndex; bb.setShort(lengthIndex, length); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFQueueStatsEntryVer14("); b.append("portNo=").append(portNo); b.append(", "); b.append("queueId=").append(queueId); b.append(", "); b.append("txBytes=").append(txBytes); b.append(", "); b.append("txPackets=").append(txPackets); b.append(", "); b.append("txErrors=").append(txErrors); b.append(", "); b.append("durationSec=").append(durationSec); b.append(", "); b.append("durationNsec=").append(durationNsec); b.append(", "); b.append("properties=").append(properties); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFQueueStatsEntryVer14 other = (OFQueueStatsEntryVer14) obj; if (portNo == null) { if (other.portNo != null) return false; } else if (!portNo.equals(other.portNo)) return false; if( queueId != other.queueId) return false; if (txBytes == null) { if (other.txBytes != null) return false; } else if (!txBytes.equals(other.txBytes)) return false; if (txPackets == null) { if (other.txPackets != null) return false; } else if (!txPackets.equals(other.txPackets)) return false; if (txErrors == null) { if (other.txErrors != null) return false; } else if (!txErrors.equals(other.txErrors)) return false; if( durationSec != other.durationSec) return false; if( durationNsec != other.durationNsec) return false; if (properties == null) { if (other.properties != null) return false; } else if (!properties.equals(other.properties)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((portNo == null) ? 0 : portNo.hashCode()); result = prime * (int) (queueId ^ (queueId >>> 32)); result = prime * result + ((txBytes == null) ? 0 : txBytes.hashCode()); result = prime * result + ((txPackets == null) ? 0 : txPackets.hashCode()); result = prime * result + ((txErrors == null) ? 0 : txErrors.hashCode()); result = prime * (int) (durationSec ^ (durationSec >>> 32)); result = prime * (int) (durationNsec ^ (durationNsec >>> 32)); result = prime * result + ((properties == null) ? 0 : properties.hashCode()); return result; } }
923b638b2043020b5477e546f4b60748065d477f
1,000
java
Java
mobile-app-ws/src/main/java/com/dev/app/ws/model/AddressRequestModel.java
frsknalexis/RestAPI-SPRING-JAVA
74284187a5c27e38e2a15db3f0353b99587a2c2e
[ "Apache-2.0" ]
1
2019-08-23T19:12:59.000Z
2019-08-23T19:12:59.000Z
mobile-app-ws/src/main/java/com/dev/app/ws/model/AddressRequestModel.java
frsknalexis/RestAPI-SPRING-JAVA
74284187a5c27e38e2a15db3f0353b99587a2c2e
[ "Apache-2.0" ]
null
null
null
mobile-app-ws/src/main/java/com/dev/app/ws/model/AddressRequestModel.java
frsknalexis/RestAPI-SPRING-JAVA
74284187a5c27e38e2a15db3f0353b99587a2c2e
[ "Apache-2.0" ]
null
null
null
15.151515
68
0.712
999,580
package com.dev.app.ws.model; import java.io.Serializable; public class AddressRequestModel implements Serializable { /** * */ private static final long serialVersionUID = -6293164910186600629L; private String city; private String country; private String streetName; private String postalCode; private String type; public AddressRequestModel() { } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getStreetName() { return streetName; } public void setStreetName(String streetName) { this.streetName = streetName; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
923b641965f1046611da6cef1fa152dde6fde3ea
1,209
java
Java
source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/LocalPathCellEditor.java
benzman81/team-explorer-everywhere
eb3985c7cb629af9b0ff1c3678403f5c910b7d06
[ "MIT" ]
86
2019-05-13T02:21:26.000Z
2022-02-06T17:43:29.000Z
source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/LocalPathCellEditor.java
benzman81/team-explorer-everywhere
eb3985c7cb629af9b0ff1c3678403f5c910b7d06
[ "MIT" ]
82
2019-05-14T06:34:16.000Z
2022-03-23T20:20:19.000Z
source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/LocalPathCellEditor.java
benzman81/team-explorer-everywhere
eb3985c7cb629af9b0ff1c3678403f5c910b7d06
[ "MIT" ]
61
2019-05-10T19:34:33.000Z
2022-03-18T06:29:06.000Z
36.636364
100
0.712986
999,581
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the repository root. package com.microsoft.tfs.client.common.ui.controls; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Shell; import com.microsoft.tfs.client.common.ui.Messages; import com.microsoft.tfs.client.common.ui.framework.celleditor.TextWithDialogCellEditor; public class LocalPathCellEditor extends TextWithDialogCellEditor { public LocalPathCellEditor(final Composite parent, final int style) { super(parent, style); } @Override protected String openDialog(final Shell shell, final String currentValue) { final DirectoryDialog dialog = new DirectoryDialog(shell); dialog.setText(Messages.getString("LocalPathCellEditor.BrowseDialogTitle")); //$NON-NLS-1$ dialog.setMessage(Messages.getString("LocalPathCellEditor.BrowseDialogText")); //$NON-NLS-1$ if (currentValue != null) { dialog.setFilterPath(currentValue); } String s = dialog.open(); if (s == null) { s = currentValue; } return s; } }
923b65644963cfeba4127f1b2698e5b7ccc2d958
1,983
java
Java
src/main/java/com/test/design/ProxyDemo.java
qiuqiuqiuqiuqiuqiu/java-test
37b1d45ff0da761a20b2589adcf01ab298bbaa5a
[ "MIT" ]
null
null
null
src/main/java/com/test/design/ProxyDemo.java
qiuqiuqiuqiuqiuqiu/java-test
37b1d45ff0da761a20b2589adcf01ab298bbaa5a
[ "MIT" ]
null
null
null
src/main/java/com/test/design/ProxyDemo.java
qiuqiuqiuqiuqiuqiu/java-test
37b1d45ff0da761a20b2589adcf01ab298bbaa5a
[ "MIT" ]
null
null
null
23.329412
65
0.547655
999,582
package com.test.design; public class ProxyDemo { public static void main(String[] args) { Printable p = new PrinterProxy("Alice"); System.out.println("现在的名字是 " + p.getPrinterName() + "。"); p.setPrinterName("Bob"); System.out.println("现在的名字是 " + p.getPrinterName() + "。"); p.print("Hello, world."); } } interface Printable { void setPrinterName(String name); String getPrinterName(); void print(String string); } class Printer implements Printable { private String name; public Printer() { heavyJob("Printer的实例生成中 "); } public Printer(String name) { this.name = name; heavyJob("Printer 的实例生成中 (" + name + ")"); } public void setPrinterName(String name) { this.name = name; } public String getPrinterName() { return name; } public void print(String str) { System.out.println("=== " + name + " ==="); System.out.println(str); } private void heavyJob(String msg) { System.out.print(msg); for (int i=0; i< 5; i++){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.print("."); } System.out.println("结束。"); } } class PrinterProxy implements Printable { private String name; private Printer real; public PrinterProxy() { } public PrinterProxy(String name) { this.name = name; } public synchronized void setPrinterName(String name) { if (real != null) { real.setPrinterName(name); } this.name = name; } public String getPrinterName() { return name; } public void print(String str) { realize(); real.print(str); } private synchronized void realize() { if (real == null) { real = new Printer(name); } } }
923b65a9968ff2e0f07840a51961b6e2c1807219
2,184
java
Java
realtoken/src/main/java/com/zhpan/idea/net/converter/GsonResponseBodyConverter.java
guchuanhang/RealTokenApp
30521e7d9c2bf6c8282dbf9aa21a28079a7e2410
[ "Apache-2.0" ]
null
null
null
realtoken/src/main/java/com/zhpan/idea/net/converter/GsonResponseBodyConverter.java
guchuanhang/RealTokenApp
30521e7d9c2bf6c8282dbf9aa21a28079a7e2410
[ "Apache-2.0" ]
null
null
null
realtoken/src/main/java/com/zhpan/idea/net/converter/GsonResponseBodyConverter.java
guchuanhang/RealTokenApp
30521e7d9c2bf6c8282dbf9aa21a28079a7e2410
[ "Apache-2.0" ]
null
null
null
32.597015
96
0.647436
999,583
/* * Copyright (C) 2015 Square, 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.zhpan.idea.net.converter; import com.google.gson.TypeAdapter; import com.zhpan.idea.net.common.ErrorCode; import com.zhpan.idea.net.exception.ServerResponseException; import com.zhpan.idea.net.module.BasicResponse; import org.json.JSONObject; import java.io.IOException; import okhttp3.ResponseBody; import retrofit2.Converter; final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, Object> { private final TypeAdapter<T> adapter; GsonResponseBodyConverter(TypeAdapter<T> adapter) { this.adapter = adapter; } @Override public Object convert(ResponseBody value) throws IOException { try { JSONObject jsonObject; try { jsonObject = new JSONObject(new String(value.bytes())); } catch (Exception e) { e.printStackTrace(); throw new ServerResponseException(ErrorCode.ERR_JSON, "服务器返回的不是json格式数据"); } int status = jsonObject.optInt("status"); if (status == ErrorCode.SUCCESS) { if (jsonObject.has("data")) { BasicResponse rsp = (BasicResponse) adapter.fromJson(jsonObject.toString()); return rsp.getData(); } else { throw new ServerResponseException(ErrorCode.ERR_NO_DATA, "服务器没有返回data数据"); } } else { throw new ServerResponseException(status, jsonObject.optString("msg")); } } finally { value.close(); } } }
923b65ccf1ff6fcd21d03163cb32a1d1c7642152
480
java
Java
Algorithm/src/test/java/com/leetcode/offer/TopVotedCandidateTest.java
huangbinme/Bin
6741afde67878cd1e853395817cb9c63e1900e9c
[ "Apache-2.0" ]
null
null
null
Algorithm/src/test/java/com/leetcode/offer/TopVotedCandidateTest.java
huangbinme/Bin
6741afde67878cd1e853395817cb9c63e1900e9c
[ "Apache-2.0" ]
5
2021-05-26T15:03:42.000Z
2022-01-04T14:30:13.000Z
Algorithm/src/test/java/com/leetcode/offer/TopVotedCandidateTest.java
huangbinme/Bin
6741afde67878cd1e853395817cb9c63e1900e9c
[ "Apache-2.0" ]
null
null
null
32
120
0.683333
999,584
package com.leetcode.offer; import org.testng.annotations.Test; public class TopVotedCandidateTest { @Test public void testQ() { TopVotedCandidate topVotedCandidate = new TopVotedCandidate(new int[]{0, 0, 1, 1, 2}, new int[]{0,67,69,74,87}); System.out.println(topVotedCandidate.q(4)); System.out.println(topVotedCandidate.q(62)); System.out.println(topVotedCandidate.q(100)); System.out.println(topVotedCandidate.q(88)); } }
923b6739e5b8b3222f3313bcf7aad9154c48c58a
767
java
Java
src/main/java/Clock.java
oddeirikigland/tdt4186
894cf71b4a4f432c0a70bea3ef9212fa3fbc8627
[ "MIT" ]
null
null
null
src/main/java/Clock.java
oddeirikigland/tdt4186
894cf71b4a4f432c0a70bea3ef9212fa3fbc8627
[ "MIT" ]
null
null
null
src/main/java/Clock.java
oddeirikigland/tdt4186
894cf71b4a4f432c0a70bea3ef9212fa3fbc8627
[ "MIT" ]
null
null
null
25.566667
81
0.632334
999,585
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; public class Clock { Timer timer; public Clock(int seconds) { timer = new Timer(); //At this line a new Thread will be created timer.schedule(new RemindTask(), seconds * 1000); //delay in milliseconds } class RemindTask extends TimerTask { public void run() { SushiBar.isOpen = false; //prevents creating new customers. timer.cancel(); } } public static String getTime() { // get current time Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SS"); return sdf.format(cal.getTime()); } }
923b6798061011de6f2543181de4189fb7f2ae3d
1,659
java
Java
src/main/java/com/noobug/nooblog/config/CorsConfig.java
ElementCraft/nooblog-webflux
d0bb17108c07f6423c6fef76fde6f0473d98ba42
[ "MIT" ]
null
null
null
src/main/java/com/noobug/nooblog/config/CorsConfig.java
ElementCraft/nooblog-webflux
d0bb17108c07f6423c6fef76fde6f0473d98ba42
[ "MIT" ]
null
null
null
src/main/java/com/noobug/nooblog/config/CorsConfig.java
ElementCraft/nooblog-webflux
d0bb17108c07f6423c6fef76fde6f0473d98ba42
[ "MIT" ]
null
null
null
48.794118
229
0.747438
999,586
package com.noobug.nooblog.config; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import reactor.core.publisher.Mono; /** * 允许跨域的过滤器 * * @author noobug.com */ @Component public class CorsConfig implements WebFilter { @Override public Mono<Void> filter(final ServerWebExchange serverWebExchange, final WebFilterChain webFilterChain) { serverWebExchange.getResponse().getHeaders().add("Access-Control-Allow-Origin", "*"); serverWebExchange.getResponse().getHeaders().add("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS"); serverWebExchange.getResponse().getHeaders().add("Access-Control-Allow-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Authorization"); if (serverWebExchange.getRequest().getMethod() == HttpMethod.OPTIONS) { serverWebExchange.getResponse().getHeaders().add("Access-Control-Max-Age", "1728000"); serverWebExchange.getResponse().setStatusCode(HttpStatus.NO_CONTENT); return Mono.empty(); } else { serverWebExchange.getResponse().getHeaders().add("Access-Control-Expose-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range"); return webFilterChain.filter(serverWebExchange); } } }
923b680d99e183bf5437346de70fb01c8db7bfb9
47,694
java
Java
org.opentosca.container.connector.bps/src/org/apache/axiom/soap/xsd/SOAPVersion.java
fossabot/container
7d31f87a0d68f964b33004dd85f7765df40048a1
[ "Apache-2.0" ]
null
null
null
org.opentosca.container.connector.bps/src/org/apache/axiom/soap/xsd/SOAPVersion.java
fossabot/container
7d31f87a0d68f964b33004dd85f7765df40048a1
[ "Apache-2.0" ]
null
null
null
org.opentosca.container.connector.bps/src/org/apache/axiom/soap/xsd/SOAPVersion.java
fossabot/container
7d31f87a0d68f964b33004dd85f7765df40048a1
[ "Apache-2.0" ]
null
null
null
34.915081
177
0.568394
999,587
/** * SOAPVersion.java * * This file was auto-generated from WSDL by the Apache Axis2 version: SNAPSHOT Built on : Nov 10, * 2010 (06:34:21 UTC) */ package org.apache.axiom.soap.xsd; /** * SOAPVersion bean class */ public abstract class SOAPVersion implements org.apache.axis2.databinding.ADBBean { /* * This type was generated from the piece of schema that had name = SOAPVersion Namespace URI = * http://soap.axiom.apache.org/xsd Namespace Prefix = ns26 */ /** * */ private static final long serialVersionUID = 4338887726584034357L; /** * field for EncodingURI */ protected java.lang.String localEncodingURI; /* * This tracker boolean wil be used to detect whether the user called the set method for this * attribute. It will be used to determine whether to include this field in the serialized XML */ protected boolean localEncodingURITracker = false; /** * Auto generated getter method * * @return java.lang.String */ public java.lang.String getEncodingURI() { return this.localEncodingURI; } /** * Auto generated setter method * * @param param EncodingURI */ public void setEncodingURI(final java.lang.String param) { this.localEncodingURITracker = true; this.localEncodingURI = param; } /** * field for EnvelopeURI */ protected java.lang.String localEnvelopeURI; /* * This tracker boolean wil be used to detect whether the user called the set method for this * attribute. It will be used to determine whether to include this field in the serialized XML */ protected boolean localEnvelopeURITracker = false; /** * Auto generated getter method * * @return java.lang.String */ public java.lang.String getEnvelopeURI() { return this.localEnvelopeURI; } /** * Auto generated setter method * * @param param EnvelopeURI */ public void setEnvelopeURI(final java.lang.String param) { this.localEnvelopeURITracker = true; this.localEnvelopeURI = param; } /** * field for FaultCodeQName */ protected java.lang.Object localFaultCodeQName; /* * This tracker boolean wil be used to detect whether the user called the set method for this * attribute. It will be used to determine whether to include this field in the serialized XML */ protected boolean localFaultCodeQNameTracker = false; /** * Auto generated getter method * * @return java.lang.Object */ public java.lang.Object getFaultCodeQName() { return this.localFaultCodeQName; } /** * Auto generated setter method * * @param param FaultCodeQName */ public void setFaultCodeQName(final java.lang.Object param) { this.localFaultCodeQNameTracker = true; this.localFaultCodeQName = param; } /** * field for FaultDetailQName */ protected java.lang.Object localFaultDetailQName; /* * This tracker boolean wil be used to detect whether the user called the set method for this * attribute. It will be used to determine whether to include this field in the serialized XML */ protected boolean localFaultDetailQNameTracker = false; /** * Auto generated getter method * * @return java.lang.Object */ public java.lang.Object getFaultDetailQName() { return this.localFaultDetailQName; } /** * Auto generated setter method * * @param param FaultDetailQName */ public void setFaultDetailQName(final java.lang.Object param) { this.localFaultDetailQNameTracker = true; this.localFaultDetailQName = param; } /** * field for FaultReasonQName */ protected java.lang.Object localFaultReasonQName; /* * This tracker boolean wil be used to detect whether the user called the set method for this * attribute. It will be used to determine whether to include this field in the serialized XML */ protected boolean localFaultReasonQNameTracker = false; /** * Auto generated getter method * * @return java.lang.Object */ public java.lang.Object getFaultReasonQName() { return this.localFaultReasonQName; } /** * Auto generated setter method * * @param param FaultReasonQName */ public void setFaultReasonQName(final java.lang.Object param) { this.localFaultReasonQNameTracker = true; this.localFaultReasonQName = param; } /** * field for FaultRoleQName */ protected java.lang.Object localFaultRoleQName; /* * This tracker boolean wil be used to detect whether the user called the set method for this * attribute. It will be used to determine whether to include this field in the serialized XML */ protected boolean localFaultRoleQNameTracker = false; /** * Auto generated getter method * * @return java.lang.Object */ public java.lang.Object getFaultRoleQName() { return this.localFaultRoleQName; } /** * Auto generated setter method * * @param param FaultRoleQName */ public void setFaultRoleQName(final java.lang.Object param) { this.localFaultRoleQNameTracker = true; this.localFaultRoleQName = param; } /** * field for MustUnderstandFaultCode */ protected java.lang.Object localMustUnderstandFaultCode; /* * This tracker boolean wil be used to detect whether the user called the set method for this * attribute. It will be used to determine whether to include this field in the serialized XML */ protected boolean localMustUnderstandFaultCodeTracker = false; /** * Auto generated getter method * * @return java.lang.Object */ public java.lang.Object getMustUnderstandFaultCode() { return this.localMustUnderstandFaultCode; } /** * Auto generated setter method * * @param param MustUnderstandFaultCode */ public void setMustUnderstandFaultCode(final java.lang.Object param) { this.localMustUnderstandFaultCodeTracker = true; this.localMustUnderstandFaultCode = param; } /** * field for NextRoleURI */ protected java.lang.String localNextRoleURI; /* * This tracker boolean wil be used to detect whether the user called the set method for this * attribute. It will be used to determine whether to include this field in the serialized XML */ protected boolean localNextRoleURITracker = false; /** * Auto generated getter method * * @return java.lang.String */ public java.lang.String getNextRoleURI() { return this.localNextRoleURI; } /** * Auto generated setter method * * @param param NextRoleURI */ public void setNextRoleURI(final java.lang.String param) { this.localNextRoleURITracker = true; this.localNextRoleURI = param; } /** * field for ReceiverFaultCode */ protected java.lang.Object localReceiverFaultCode; /* * This tracker boolean wil be used to detect whether the user called the set method for this * attribute. It will be used to determine whether to include this field in the serialized XML */ protected boolean localReceiverFaultCodeTracker = false; /** * Auto generated getter method * * @return java.lang.Object */ public java.lang.Object getReceiverFaultCode() { return this.localReceiverFaultCode; } /** * Auto generated setter method * * @param param ReceiverFaultCode */ public void setReceiverFaultCode(final java.lang.Object param) { this.localReceiverFaultCodeTracker = true; this.localReceiverFaultCode = param; } /** * field for RoleAttributeQName */ protected java.lang.Object localRoleAttributeQName; /* * This tracker boolean wil be used to detect whether the user called the set method for this * attribute. It will be used to determine whether to include this field in the serialized XML */ protected boolean localRoleAttributeQNameTracker = false; /** * Auto generated getter method * * @return java.lang.Object */ public java.lang.Object getRoleAttributeQName() { return this.localRoleAttributeQName; } /** * Auto generated setter method * * @param param RoleAttributeQName */ public void setRoleAttributeQName(final java.lang.Object param) { this.localRoleAttributeQNameTracker = true; this.localRoleAttributeQName = param; } /** * field for SenderFaultCode */ protected java.lang.Object localSenderFaultCode; /* * This tracker boolean wil be used to detect whether the user called the set method for this * attribute. It will be used to determine whether to include this field in the serialized XML */ protected boolean localSenderFaultCodeTracker = false; /** * Auto generated getter method * * @return java.lang.Object */ public java.lang.Object getSenderFaultCode() { return this.localSenderFaultCode; } /** * Auto generated setter method * * @param param SenderFaultCode */ public void setSenderFaultCode(final java.lang.Object param) { this.localSenderFaultCodeTracker = true; this.localSenderFaultCode = param; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ @Override public org.apache.axiom.om.OMElement getOMElement(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException { final org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this, parentQName); return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl(parentQName, factory, dataSource); } @Override public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException { serialize(parentQName, xmlWriter, false); } @Override public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter, final boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException { java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter); if (serializeType) { final java.lang.String namespacePrefix = registerPrefix(xmlWriter, "http://soap.axiom.apache.org/xsd"); if (namespacePrefix != null && namespacePrefix.trim().length() > 0) { writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix + ":SOAPVersion", xmlWriter); } else { writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "SOAPVersion", xmlWriter); } } if (this.localEncodingURITracker) { namespace = "http://soap.axiom.apache.org/xsd"; writeStartElement(null, namespace, "encodingURI", xmlWriter); if (this.localEncodingURI == null) { // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); } else { xmlWriter.writeCharacters(this.localEncodingURI); } xmlWriter.writeEndElement(); } if (this.localEnvelopeURITracker) { namespace = "http://soap.axiom.apache.org/xsd"; writeStartElement(null, namespace, "envelopeURI", xmlWriter); if (this.localEnvelopeURI == null) { // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); } else { xmlWriter.writeCharacters(this.localEnvelopeURI); } xmlWriter.writeEndElement(); } if (this.localFaultCodeQNameTracker) { if (this.localFaultCodeQName != null) { if (this.localFaultCodeQName instanceof org.apache.axis2.databinding.ADBBean) { ((org.apache.axis2.databinding.ADBBean) this.localFaultCodeQName).serialize(new javax.xml.namespace.QName( "http://soap.axiom.apache.org/xsd", "faultCodeQName"), xmlWriter, true); } else { writeStartElement(null, "http://soap.axiom.apache.org/xsd", "faultCodeQName", xmlWriter); org.apache.axis2.databinding.utils.ConverterUtil.serializeAnyType(this.localFaultCodeQName, xmlWriter); xmlWriter.writeEndElement(); } } else { // write null attribute writeStartElement(null, "http://soap.axiom.apache.org/xsd", "faultCodeQName", xmlWriter); // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); xmlWriter.writeEndElement(); } } if (this.localFaultDetailQNameTracker) { if (this.localFaultDetailQName != null) { if (this.localFaultDetailQName instanceof org.apache.axis2.databinding.ADBBean) { ((org.apache.axis2.databinding.ADBBean) this.localFaultDetailQName).serialize(new javax.xml.namespace.QName( "http://soap.axiom.apache.org/xsd", "faultDetailQName"), xmlWriter, true); } else { writeStartElement(null, "http://soap.axiom.apache.org/xsd", "faultDetailQName", xmlWriter); org.apache.axis2.databinding.utils.ConverterUtil.serializeAnyType(this.localFaultDetailQName, xmlWriter); xmlWriter.writeEndElement(); } } else { // write null attribute writeStartElement(null, "http://soap.axiom.apache.org/xsd", "faultDetailQName", xmlWriter); // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); xmlWriter.writeEndElement(); } } if (this.localFaultReasonQNameTracker) { if (this.localFaultReasonQName != null) { if (this.localFaultReasonQName instanceof org.apache.axis2.databinding.ADBBean) { ((org.apache.axis2.databinding.ADBBean) this.localFaultReasonQName).serialize(new javax.xml.namespace.QName( "http://soap.axiom.apache.org/xsd", "faultReasonQName"), xmlWriter, true); } else { writeStartElement(null, "http://soap.axiom.apache.org/xsd", "faultReasonQName", xmlWriter); org.apache.axis2.databinding.utils.ConverterUtil.serializeAnyType(this.localFaultReasonQName, xmlWriter); xmlWriter.writeEndElement(); } } else { // write null attribute writeStartElement(null, "http://soap.axiom.apache.org/xsd", "faultReasonQName", xmlWriter); // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); xmlWriter.writeEndElement(); } } if (this.localFaultRoleQNameTracker) { if (this.localFaultRoleQName != null) { if (this.localFaultRoleQName instanceof org.apache.axis2.databinding.ADBBean) { ((org.apache.axis2.databinding.ADBBean) this.localFaultRoleQName).serialize(new javax.xml.namespace.QName( "http://soap.axiom.apache.org/xsd", "faultRoleQName"), xmlWriter, true); } else { writeStartElement(null, "http://soap.axiom.apache.org/xsd", "faultRoleQName", xmlWriter); org.apache.axis2.databinding.utils.ConverterUtil.serializeAnyType(this.localFaultRoleQName, xmlWriter); xmlWriter.writeEndElement(); } } else { // write null attribute writeStartElement(null, "http://soap.axiom.apache.org/xsd", "faultRoleQName", xmlWriter); // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); xmlWriter.writeEndElement(); } } if (this.localMustUnderstandFaultCodeTracker) { if (this.localMustUnderstandFaultCode != null) { if (this.localMustUnderstandFaultCode instanceof org.apache.axis2.databinding.ADBBean) { ((org.apache.axis2.databinding.ADBBean) this.localMustUnderstandFaultCode).serialize(new javax.xml.namespace.QName( "http://soap.axiom.apache.org/xsd", "mustUnderstandFaultCode"), xmlWriter, true); } else { writeStartElement(null, "http://soap.axiom.apache.org/xsd", "mustUnderstandFaultCode", xmlWriter); org.apache.axis2.databinding.utils.ConverterUtil.serializeAnyType(this.localMustUnderstandFaultCode, xmlWriter); xmlWriter.writeEndElement(); } } else { // write null attribute writeStartElement(null, "http://soap.axiom.apache.org/xsd", "mustUnderstandFaultCode", xmlWriter); // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); xmlWriter.writeEndElement(); } } if (this.localNextRoleURITracker) { namespace = "http://soap.axiom.apache.org/xsd"; writeStartElement(null, namespace, "nextRoleURI", xmlWriter); if (this.localNextRoleURI == null) { // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); } else { xmlWriter.writeCharacters(this.localNextRoleURI); } xmlWriter.writeEndElement(); } if (this.localReceiverFaultCodeTracker) { if (this.localReceiverFaultCode != null) { if (this.localReceiverFaultCode instanceof org.apache.axis2.databinding.ADBBean) { ((org.apache.axis2.databinding.ADBBean) this.localReceiverFaultCode).serialize(new javax.xml.namespace.QName( "http://soap.axiom.apache.org/xsd", "receiverFaultCode"), xmlWriter, true); } else { writeStartElement(null, "http://soap.axiom.apache.org/xsd", "receiverFaultCode", xmlWriter); org.apache.axis2.databinding.utils.ConverterUtil.serializeAnyType(this.localReceiverFaultCode, xmlWriter); xmlWriter.writeEndElement(); } } else { // write null attribute writeStartElement(null, "http://soap.axiom.apache.org/xsd", "receiverFaultCode", xmlWriter); // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); xmlWriter.writeEndElement(); } } if (this.localRoleAttributeQNameTracker) { if (this.localRoleAttributeQName != null) { if (this.localRoleAttributeQName instanceof org.apache.axis2.databinding.ADBBean) { ((org.apache.axis2.databinding.ADBBean) this.localRoleAttributeQName).serialize(new javax.xml.namespace.QName( "http://soap.axiom.apache.org/xsd", "roleAttributeQName"), xmlWriter, true); } else { writeStartElement(null, "http://soap.axiom.apache.org/xsd", "roleAttributeQName", xmlWriter); org.apache.axis2.databinding.utils.ConverterUtil.serializeAnyType(this.localRoleAttributeQName, xmlWriter); xmlWriter.writeEndElement(); } } else { // write null attribute writeStartElement(null, "http://soap.axiom.apache.org/xsd", "roleAttributeQName", xmlWriter); // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); xmlWriter.writeEndElement(); } } if (this.localSenderFaultCodeTracker) { if (this.localSenderFaultCode != null) { if (this.localSenderFaultCode instanceof org.apache.axis2.databinding.ADBBean) { ((org.apache.axis2.databinding.ADBBean) this.localSenderFaultCode).serialize(new javax.xml.namespace.QName( "http://soap.axiom.apache.org/xsd", "senderFaultCode"), xmlWriter, true); } else { writeStartElement(null, "http://soap.axiom.apache.org/xsd", "senderFaultCode", xmlWriter); org.apache.axis2.databinding.utils.ConverterUtil.serializeAnyType(this.localSenderFaultCode, xmlWriter); xmlWriter.writeEndElement(); } } else { // write null attribute writeStartElement(null, "http://soap.axiom.apache.org/xsd", "senderFaultCode", xmlWriter); // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); xmlWriter.writeEndElement(); } } xmlWriter.writeEndElement(); } private static java.lang.String generatePrefix(final java.lang.String namespace) { if (namespace.equals("http://soap.axiom.apache.org/xsd")) { return "ns26"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * Utility method to write an element start tag. */ private void writeStartElement(java.lang.String prefix, final java.lang.String namespace, final java.lang.String localPart, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { final java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, localPart); } else { if (namespace.length() == 0) { prefix = ""; } else if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, localPart, namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(final java.lang.String prefix, final java.lang.String namespace, final java.lang.String attName, final java.lang.String attValue, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace, attName, attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(final java.lang.String namespace, final java.lang.String attName, final java.lang.String attValue, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(final java.lang.String namespace, final java.lang.String attName, final javax.xml.namespace.QName qname, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { final java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(final javax.xml.namespace.QName qname, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { final java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix, namespaceURI); } if (prefix.trim().length() > 0) { xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(final javax.xml.namespace.QName[] qnames, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data final java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null || prefix.length() == 0) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix, namespaceURI); } if (prefix.trim().length() > 0) { stringToWrite.append(prefix).append(":") .append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(final javax.xml.stream.XMLStreamWriter xmlWriter, final java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ @Override public javax.xml.stream.XMLStreamReader getPullParser(final javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException { final java.util.ArrayList elementList = new java.util.ArrayList(); final java.util.ArrayList attribList = new java.util.ArrayList(); if (this.localEncodingURITracker) { elementList.add(new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "encodingURI")); elementList.add(this.localEncodingURI == null ? null : org.apache.axis2.databinding.utils.ConverterUtil.convertToString(this.localEncodingURI)); } if (this.localEnvelopeURITracker) { elementList.add(new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "envelopeURI")); elementList.add(this.localEnvelopeURI == null ? null : org.apache.axis2.databinding.utils.ConverterUtil.convertToString(this.localEnvelopeURI)); } if (this.localFaultCodeQNameTracker) { elementList.add(new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "faultCodeQName")); elementList.add(this.localFaultCodeQName == null ? null : this.localFaultCodeQName); } if (this.localFaultDetailQNameTracker) { elementList.add(new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "faultDetailQName")); elementList.add(this.localFaultDetailQName == null ? null : this.localFaultDetailQName); } if (this.localFaultReasonQNameTracker) { elementList.add(new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "faultReasonQName")); elementList.add(this.localFaultReasonQName == null ? null : this.localFaultReasonQName); } if (this.localFaultRoleQNameTracker) { elementList.add(new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "faultRoleQName")); elementList.add(this.localFaultRoleQName == null ? null : this.localFaultRoleQName); } if (this.localMustUnderstandFaultCodeTracker) { elementList.add(new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "mustUnderstandFaultCode")); elementList.add(this.localMustUnderstandFaultCode == null ? null : this.localMustUnderstandFaultCode); } if (this.localNextRoleURITracker) { elementList.add(new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "nextRoleURI")); elementList.add(this.localNextRoleURI == null ? null : org.apache.axis2.databinding.utils.ConverterUtil.convertToString(this.localNextRoleURI)); } if (this.localReceiverFaultCodeTracker) { elementList.add(new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "receiverFaultCode")); elementList.add(this.localReceiverFaultCode == null ? null : this.localReceiverFaultCode); } if (this.localRoleAttributeQNameTracker) { elementList.add(new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "roleAttributeQName")); elementList.add(this.localRoleAttributeQName == null ? null : this.localRoleAttributeQName); } if (this.localSenderFaultCodeTracker) { elementList.add(new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "senderFaultCode")); elementList.add(this.localSenderFaultCode == null ? null : this.localSenderFaultCode); } return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory { /** * static method to create the object Precondition: If this object is an element, the current or * next start element starts this object and any intervening reader events are ignorable If this * object is not an element, it is a complex type and the reader is at the event just after the * outer start element Postcondition: If this object is an element, the reader is positioned at its * end element If this object is a complex type, the reader is positioned at the end element of its * outer element */ public static SOAPVersion parse(final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception { final SOAPVersion object = null; final int event; java.lang.String nillableValue = null; final java.lang.String prefix = ""; final java.lang.String namespaceuri = ""; try { while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null) { final java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName != null) { java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1) { nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":")); } nsPrefix = nsPrefix == null ? "" : nsPrefix; final java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1); if (!"SOAPVersion".equals(type)) { // find namespace for the prefix final java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (SOAPVersion) org.apache.axis2.transaction.xsd.ExtensionMapper.getTypeObject(nsUri, type, reader); } throw new org.apache.axis2.databinding.ADBException( "The an abstract class can not be instantiated !!!"); } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. final java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "encodingURI").equals(reader.getName())) { nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (!"true".equals(nillableValue) && !"1".equals(nillableValue)) { final java.lang.String content = reader.getElementText(); object.setEncodingURI(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); } else { reader.getElementText(); // throw away text nodes if any. } reader.next(); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "envelopeURI").equals(reader.getName())) { nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (!"true".equals(nillableValue) && !"1".equals(nillableValue)) { final java.lang.String content = reader.getElementText(); object.setEnvelopeURI(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); } else { reader.getElementText(); // throw away text nodes if any. } reader.next(); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "faultCodeQName").equals(reader.getName())) { object.setFaultCodeQName(org.apache.axis2.databinding.utils.ConverterUtil.getAnyTypeObject(reader, org.apache.axis2.transaction.xsd.ExtensionMapper.class)); reader.next(); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "faultDetailQName").equals(reader.getName())) { object.setFaultDetailQName(org.apache.axis2.databinding.utils.ConverterUtil.getAnyTypeObject(reader, org.apache.axis2.transaction.xsd.ExtensionMapper.class)); reader.next(); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "faultReasonQName").equals(reader.getName())) { object.setFaultReasonQName(org.apache.axis2.databinding.utils.ConverterUtil.getAnyTypeObject(reader, org.apache.axis2.transaction.xsd.ExtensionMapper.class)); reader.next(); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "faultRoleQName").equals(reader.getName())) { object.setFaultRoleQName(org.apache.axis2.databinding.utils.ConverterUtil.getAnyTypeObject(reader, org.apache.axis2.transaction.xsd.ExtensionMapper.class)); reader.next(); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "mustUnderstandFaultCode").equals(reader.getName())) { object.setMustUnderstandFaultCode(org.apache.axis2.databinding.utils.ConverterUtil.getAnyTypeObject(reader, org.apache.axis2.transaction.xsd.ExtensionMapper.class)); reader.next(); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "nextRoleURI").equals(reader.getName())) { nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (!"true".equals(nillableValue) && !"1".equals(nillableValue)) { final java.lang.String content = reader.getElementText(); object.setNextRoleURI(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); } else { reader.getElementText(); // throw away text nodes if any. } reader.next(); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "receiverFaultCode").equals(reader.getName())) { object.setReceiverFaultCode(org.apache.axis2.databinding.utils.ConverterUtil.getAnyTypeObject(reader, org.apache.axis2.transaction.xsd.ExtensionMapper.class)); reader.next(); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "roleAttributeQName").equals(reader.getName())) { object.setRoleAttributeQName(org.apache.axis2.databinding.utils.ConverterUtil.getAnyTypeObject(reader, org.apache.axis2.transaction.xsd.ExtensionMapper.class)); reader.next(); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new javax.xml.namespace.QName("http://soap.axiom.apache.org/xsd", "senderFaultCode").equals(reader.getName())) { object.setSenderFaultCode(org.apache.axis2.databinding.utils.ConverterUtil.getAnyTypeObject(reader, org.apache.axis2.transaction.xsd.ExtensionMapper.class)); reader.next(); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement()) { // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException( "Unexpected subelement " + reader.getLocalName()); } } catch (final javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }// end of factory class }
923b68406b07de6494eedcb5409140e2a3b5441a
237
java
Java
src/main/java/org/gluu/ob/MainApp.java
GluuFederation/access-consent-ob
816dd5242f0a5a7c487737c9ba2fe1997f6fdb4f
[ "Apache-2.0" ]
null
null
null
src/main/java/org/gluu/ob/MainApp.java
GluuFederation/access-consent-ob
816dd5242f0a5a7c487737c9ba2fe1997f6fdb4f
[ "Apache-2.0" ]
null
null
null
src/main/java/org/gluu/ob/MainApp.java
GluuFederation/access-consent-ob
816dd5242f0a5a7c487737c9ba2fe1997f6fdb4f
[ "Apache-2.0" ]
null
null
null
15.8
50
0.683544
999,588
/** * */ package org.gluu.ob; import io.quarkus.runtime.Quarkus; import io.quarkus.runtime.annotations.QuarkusMain; @QuarkusMain public class MainApp { public static void main(String... args) { Quarkus.run(args); } }
923b68a9b4c93bccf9e4e1ff73de5e0f08a91e05
389
java
Java
blog/src/main/java/com/penghuang/blog/DemospringbootApplication.java
Hyman1993/demo-projects
e680b889450553e60c9903abb72d6d8731a5f67a
[ "Apache-2.0" ]
null
null
null
blog/src/main/java/com/penghuang/blog/DemospringbootApplication.java
Hyman1993/demo-projects
e680b889450553e60c9903abb72d6d8731a5f67a
[ "Apache-2.0" ]
null
null
null
blog/src/main/java/com/penghuang/blog/DemospringbootApplication.java
Hyman1993/demo-projects
e680b889450553e60c9903abb72d6d8731a5f67a
[ "Apache-2.0" ]
1
2021-05-14T17:07:13.000Z
2021-05-14T17:07:13.000Z
24.3125
68
0.835476
999,589
package com.penghuang.blog; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication public class DemospringbootApplication { public static void main(String[] args) { SpringApplication.run(DemospringbootApplication.class, args); } }
923b695e5a0d557ec7c56a1305e9a9f919695f9f
450
java
Java
src/main/java/com/waoss/lavadro/model/transaction/TransactionalEntity.java
rohan23chhabra/lavadro
dd140b1805076ad06df72b6fbd106244b534b29c
[ "Apache-2.0" ]
1
2018-06-29T07:42:04.000Z
2018-06-29T07:42:04.000Z
src/main/java/com/waoss/lavadro/model/transaction/TransactionalEntity.java
rohan23chhabra/lavadro
dd140b1805076ad06df72b6fbd106244b534b29c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/waoss/lavadro/model/transaction/TransactionalEntity.java
rohan23chhabra/lavadro
dd140b1805076ad06df72b6fbd106244b534b29c
[ "Apache-2.0" ]
null
null
null
22.5
55
0.784444
999,590
package com.waoss.lavadro.model.transaction; import com.waoss.lavadro.model.product.Product; import com.waoss.lavadro.model.user.User; import lombok.Data; import javax.persistence.ElementCollection; import java.util.ArrayList; import java.util.List; @Data @Deprecated public abstract class TransactionalEntity { @ElementCollection(targetClass = Product.class) private List<Product> products = new ArrayList<>(); private User user; }
923b69db1b8a7e62625de53c473b98436921f9ca
3,634
java
Java
modules/list-providers-service/src/test/java/org/opencastproject/list/util/ListProviderUtilTest.java
UCA-Squad/opencast
a44529ef9a5785d1bcaee3ce62b090d424153d17
[ "ECL-2.0" ]
300
2017-06-19T09:49:57.000Z
2022-03-15T09:23:32.000Z
modules/list-providers-service/src/test/java/org/opencastproject/list/util/ListProviderUtilTest.java
UCA-Squad/opencast
a44529ef9a5785d1bcaee3ce62b090d424153d17
[ "ECL-2.0" ]
1,907
2017-06-22T13:16:39.000Z
2022-03-31T22:34:24.000Z
modules/list-providers-service/src/test/java/org/opencastproject/list/util/ListProviderUtilTest.java
UCA-Squad/opencast
a44529ef9a5785d1bcaee3ce62b090d424153d17
[ "ECL-2.0" ]
228
2017-06-19T12:57:09.000Z
2022-03-29T11:29:17.000Z
31.327586
88
0.695377
999,591
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.list.util; import static org.junit.Assert.assertEquals; import static org.opencastproject.list.util.ListProviderUtil.filterMap; import static org.opencastproject.list.util.ListProviderUtil.sortMapByValue; import org.opencastproject.list.impl.ResourceListQueryImpl; import org.junit.Test; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.TreeSet; public class ListProviderUtilTest { private Map<String, String> getTestMap() { Map<String, String> map = new HashMap<>(); map.put("21", "b: a test value"); map.put("2", "c: second test value"); map.put("34", "x: another test value"); map.put("14", "o: one more"); map.put("35", "z: again"); map.put("26", "f: why not more"); map.put("7", "a: the last one"); return map; } @Test public void testFilterMap() { Map<String, String> testMap = getTestMap(); ResourceListQueryImpl query = new ResourceListQueryImpl(); query.setLimit(3); query.setOffset(0); assertEquals(3, filterMap(testMap, query).size()); query.setLimit(0); query.setOffset(testMap.size()); assertEquals(0, filterMap(testMap, query).size()); query.setLimit(6); query.setOffset(testMap.size() - 3); assertEquals(3, filterMap(testMap, query).size()); } @Test public void testSortingMap() { Map<String, String> testMap = getTestMap(); // Test ascent sorting Map<String, String> sortedMap = sortMapByValue(testMap, true); assertEquals(testMap.size(), sortedMap.size()); TreeSet<Object> sortedValues = new TreeSet<>((s1, s2) -> { if (s1 instanceof Comparable && s2 instanceof Comparable) { return ((Comparable) s1).compareTo(s2); } else { return -1; } }); sortedValues.addAll(testMap.values()); Iterator<Entry<String, String>> iteratorSortedMap = sortedMap.entrySet().iterator(); Iterator<Object> iteratorSortedValues = sortedValues.iterator(); while (iteratorSortedMap.hasNext()) { Entry<String, String> entry = iteratorSortedMap.next(); Object value = iteratorSortedValues.next(); assertEquals(value, entry.getValue()); } // Test descent sorting sortedMap = sortMapByValue(testMap, false); assertEquals(testMap.size(), sortedMap.size()); sortedValues = new TreeSet<>((s1, s2) -> -((Comparable) s1).compareTo(s2)); sortedValues.addAll(testMap.values()); iteratorSortedMap = sortedMap.entrySet().iterator(); iteratorSortedValues = sortedValues.iterator(); while (iteratorSortedMap.hasNext()) { Entry<String, String> entry = iteratorSortedMap.next(); Object value = iteratorSortedValues.next(); assertEquals(value, entry.getValue()); } } }
923b6a657e78021c934378d7e4c94f6f623fa152
13,073
java
Java
aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/UpdateSSHPublicKeyRequest.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
3,372
2015-01-03T00:35:43.000Z
2022-03-31T15:56:24.000Z
aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/UpdateSSHPublicKeyRequest.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,391
2015-01-01T12:55:24.000Z
2022-03-31T08:01:50.000Z
aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/UpdateSSHPublicKeyRequest.java
phambryan/aws-sdk-for-java
0f75a8096efdb4831da8c6793390759d97a25019
[ "Apache-2.0" ]
2,876
2015-01-01T14:38:37.000Z
2022-03-29T19:53:10.000Z
39.376506
121
0.631301
999,592
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.identitymanagement.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSSHPublicKey" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateSSHPublicKeyRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the IAM user associated with the SSH public key. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> */ private String userName; /** * <p> * The unique identifier for the SSH public key. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters that can consist of any upper or lowercased letter or digit. * </p> */ private String sSHPublicKeyId; /** * <p> * The status to assign to the SSH public key. <code>Active</code> means that the key can be used for authentication * with an CodeCommit repository. <code>Inactive</code> means that the key cannot be used. * </p> */ private String status; /** * <p> * The name of the IAM user associated with the SSH public key. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> * * @param userName * The name of the IAM user associated with the SSH public key.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also * include any of the following characters: _+=,.@- */ public void setUserName(String userName) { this.userName = userName; } /** * <p> * The name of the IAM user associated with the SSH public key. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> * * @return The name of the IAM user associated with the SSH public key.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also * include any of the following characters: _+=,.@- */ public String getUserName() { return this.userName; } /** * <p> * The name of the IAM user associated with the SSH public key. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> * * @param userName * The name of the IAM user associated with the SSH public key.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also * include any of the following characters: _+=,.@- * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateSSHPublicKeyRequest withUserName(String userName) { setUserName(userName); return this; } /** * <p> * The unique identifier for the SSH public key. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters that can consist of any upper or lowercased letter or digit. * </p> * * @param sSHPublicKeyId * The unique identifier for the SSH public key.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters that can consist of any upper or lowercased letter or digit. */ public void setSSHPublicKeyId(String sSHPublicKeyId) { this.sSHPublicKeyId = sSHPublicKeyId; } /** * <p> * The unique identifier for the SSH public key. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters that can consist of any upper or lowercased letter or digit. * </p> * * @return The unique identifier for the SSH public key.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters that can consist of any upper or lowercased letter or digit. */ public String getSSHPublicKeyId() { return this.sSHPublicKeyId; } /** * <p> * The unique identifier for the SSH public key. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters that can consist of any upper or lowercased letter or digit. * </p> * * @param sSHPublicKeyId * The unique identifier for the SSH public key.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters that can consist of any upper or lowercased letter or digit. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateSSHPublicKeyRequest withSSHPublicKeyId(String sSHPublicKeyId) { setSSHPublicKeyId(sSHPublicKeyId); return this; } /** * <p> * The status to assign to the SSH public key. <code>Active</code> means that the key can be used for authentication * with an CodeCommit repository. <code>Inactive</code> means that the key cannot be used. * </p> * * @param status * The status to assign to the SSH public key. <code>Active</code> means that the key can be used for * authentication with an CodeCommit repository. <code>Inactive</code> means that the key cannot be used. * @see StatusType */ public void setStatus(String status) { this.status = status; } /** * <p> * The status to assign to the SSH public key. <code>Active</code> means that the key can be used for authentication * with an CodeCommit repository. <code>Inactive</code> means that the key cannot be used. * </p> * * @return The status to assign to the SSH public key. <code>Active</code> means that the key can be used for * authentication with an CodeCommit repository. <code>Inactive</code> means that the key cannot be used. * @see StatusType */ public String getStatus() { return this.status; } /** * <p> * The status to assign to the SSH public key. <code>Active</code> means that the key can be used for authentication * with an CodeCommit repository. <code>Inactive</code> means that the key cannot be used. * </p> * * @param status * The status to assign to the SSH public key. <code>Active</code> means that the key can be used for * authentication with an CodeCommit repository. <code>Inactive</code> means that the key cannot be used. * @return Returns a reference to this object so that method calls can be chained together. * @see StatusType */ public UpdateSSHPublicKeyRequest withStatus(String status) { setStatus(status); return this; } /** * <p> * The status to assign to the SSH public key. <code>Active</code> means that the key can be used for authentication * with an CodeCommit repository. <code>Inactive</code> means that the key cannot be used. * </p> * * @param status * The status to assign to the SSH public key. <code>Active</code> means that the key can be used for * authentication with an CodeCommit repository. <code>Inactive</code> means that the key cannot be used. * @see StatusType */ public void setStatus(StatusType status) { withStatus(status); } /** * <p> * The status to assign to the SSH public key. <code>Active</code> means that the key can be used for authentication * with an CodeCommit repository. <code>Inactive</code> means that the key cannot be used. * </p> * * @param status * The status to assign to the SSH public key. <code>Active</code> means that the key can be used for * authentication with an CodeCommit repository. <code>Inactive</code> means that the key cannot be used. * @return Returns a reference to this object so that method calls can be chained together. * @see StatusType */ public UpdateSSHPublicKeyRequest withStatus(StatusType status) { this.status = status.toString(); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getUserName() != null) sb.append("UserName: ").append(getUserName()).append(","); if (getSSHPublicKeyId() != null) sb.append("SSHPublicKeyId: ").append(getSSHPublicKeyId()).append(","); if (getStatus() != null) sb.append("Status: ").append(getStatus()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateSSHPublicKeyRequest == false) return false; UpdateSSHPublicKeyRequest other = (UpdateSSHPublicKeyRequest) obj; if (other.getUserName() == null ^ this.getUserName() == null) return false; if (other.getUserName() != null && other.getUserName().equals(this.getUserName()) == false) return false; if (other.getSSHPublicKeyId() == null ^ this.getSSHPublicKeyId() == null) return false; if (other.getSSHPublicKeyId() != null && other.getSSHPublicKeyId().equals(this.getSSHPublicKeyId()) == false) return false; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getUserName() == null) ? 0 : getUserName().hashCode()); hashCode = prime * hashCode + ((getSSHPublicKeyId() == null) ? 0 : getSSHPublicKeyId().hashCode()); hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); return hashCode; } @Override public UpdateSSHPublicKeyRequest clone() { return (UpdateSSHPublicKeyRequest) super.clone(); } }
923b6aa05e181b845c36e70702c392c15ef80fe2
3,355
java
Java
clouddriver-web/src/main/groovy/com/netflix/spinnaker/clouddriver/controllers/admin/EntityTagsAdminController.java
sidmuls/clouddriver
c2de4b416bf15afbd09640013724e7f7b069ce09
[ "Apache-2.0" ]
382
2015-11-16T17:54:23.000Z
2022-03-24T05:35:37.000Z
clouddriver-web/src/main/groovy/com/netflix/spinnaker/clouddriver/controllers/admin/EntityTagsAdminController.java
sidmuls/clouddriver
c2de4b416bf15afbd09640013724e7f7b069ce09
[ "Apache-2.0" ]
2,541
2015-11-17T11:22:10.000Z
2022-03-28T22:30:12.000Z
clouddriver-web/src/main/groovy/com/netflix/spinnaker/clouddriver/controllers/admin/EntityTagsAdminController.java
sidmuls/clouddriver
c2de4b416bf15afbd09640013724e7f7b069ce09
[ "Apache-2.0" ]
1,229
2015-11-16T19:22:35.000Z
2022-03-28T18:32:40.000Z
39.470588
98
0.747839
999,593
/* * Copyright 2016 Netflix, 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.netflix.spinnaker.clouddriver.controllers.admin; import com.netflix.spinnaker.clouddriver.model.EntityTagsProvider; import java.util.Map; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/admin/tags") public class EntityTagsAdminController { private final Logger log = LoggerFactory.getLogger(getClass()); private final EntityTagsProvider entityTagsProvider; @Autowired public EntityTagsAdminController(Optional<EntityTagsProvider> entityTagsProvider) { this.entityTagsProvider = entityTagsProvider.orElse(null); } @RequestMapping(value = "/reindex", method = RequestMethod.POST) void reindex() { entityTagsProvider.reindex(); } @RequestMapping(value = "/delta", method = RequestMethod.GET) Map delta() { return entityTagsProvider.delta(); } @RequestMapping(value = "/reconcile", method = RequestMethod.POST) Map reconcile( @RequestParam(name = "dryRun", defaultValue = "true") Boolean dryRun, @RequestParam(name = "cloudProvider") String cloudProvider, @RequestParam(name = "account", required = false) String account, @RequestParam(name = "region", required = false) String region) { return entityTagsProvider.reconcile( cloudProvider, account, region, Optional.ofNullable(dryRun).orElse(true)); } @RequestMapping(value = "/deleteByNamespace/{namespace}", method = RequestMethod.POST) Map deleteByNamespace( @PathVariable("namespace") String namespace, @RequestParam(name = "dryRun", defaultValue = "true") Boolean dryRun, @RequestParam(name = "deleteFromSource", defaultValue = "false") Boolean deleteFromSource) { return entityTagsProvider.deleteByNamespace( namespace, Optional.ofNullable(dryRun).orElse(true), Optional.ofNullable(deleteFromSource).orElse(false)); } @RequestMapping(value = "/deleteByTag/{tag}", method = RequestMethod.POST) Map deleteByTag( @PathVariable("tag") String namespace, @RequestParam(name = "dryRun", defaultValue = "true") Boolean dryRun, @RequestParam(name = "deleteFromSource", defaultValue = "false") Boolean deleteFromSource) { return entityTagsProvider.deleteByTag( namespace, Optional.ofNullable(dryRun).orElse(true), Optional.ofNullable(deleteFromSource).orElse(false)); } }
923b6b29925be2b1f874066fe01f77a0b92b9cfc
4,259
java
Java
src/main/java/net/leberfinger/osm/nominatim/GeoJSONResolver.java
krizleebear/osm-tools
892a21a4a5d138ce5d0a515b79405fb3a508dda2
[ "MIT" ]
1
2021-09-06T10:10:11.000Z
2021-09-06T10:10:11.000Z
src/main/java/net/leberfinger/osm/nominatim/GeoJSONResolver.java
krizleebear/osm-tools
892a21a4a5d138ce5d0a515b79405fb3a508dda2
[ "MIT" ]
2
2019-10-29T23:52:20.000Z
2019-10-29T23:53:04.000Z
src/main/java/net/leberfinger/osm/nominatim/GeoJSONResolver.java
krizleebear/osm-tools
892a21a4a5d138ce5d0a515b79405fb3a508dda2
[ "MIT" ]
null
null
null
32.265152
524
0.728105
999,594
package net.leberfinger.osm.nominatim; import java.io.IOException; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import org.apache.commons.io.FilenameUtils; import org.locationtech.jts.io.ParseException; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import joptsimple.OptionParser; import joptsimple.OptionSet; import net.leberfinger.geo.GeoJSONUtils; public class GeoJSONResolver { // e.g. {"type":"Feature", // "properties":{"access":"permissive","amenity":"parking","ele":"622","fee":"yes","name":"Kampenwandbahn","note:fee":"5€ // im Winter bei Skibetrieb, 2€ im Sommer bis // mittags","osmType":"Way","wayID":"4439608"}, // "geometry":{"type":"LineString","coordinates":[[12.3246216,47.764686700000006],[12.3250828,47.7644864],[12.325169200000001,47.764477500000005],[12.325607000000002,47.7648224],[12.325173900000001,47.7650616],[12.3254827,47.7653313],[12.326057100000002,47.765092200000005],[12.3262151,47.7655946],[12.325594500000001,47.7657013],[12.3252178,47.765698500000006],[12.325133200000002,47.765490400000004],[12.325050000000001,47.7653011],[12.3248721,47.765119500000004],[12.324669,47.7648832],[12.3246216,47.764686700000006]]}} JsonParser parser = new JsonParser(); private final IAdminResolver resolver; public GeoJSONResolver(IAdminResolver resolver) { this.resolver = resolver; } public JsonObject addAddress(String geoJSON) throws IOException { JsonObject json = parser.parse(geoJSON).getAsJsonObject(); JsonArray coordinate = GeoJSONUtils.getCoordinate(json); double lon = coordinate.get(0).getAsDouble(); double lat = coordinate.get(1).getAsDouble(); Optional<AdminPlace> resolvedPlace = resolver.resolve(lat, lon); JsonObject properties = GeoJSONUtils.getProperties(json); if (resolvedPlace.isPresent()) { resolvedPlace.get().addMissingAddressProperties(properties); } else { json.addProperty("error", "unresolved"); } return json; } /** * Resolve all geo json entries in the given file, assuming that a full geo json * object is contained in a single line. * * Will write a new file with extension ".resolved.geojson". * * @param inputFile * @throws IOException */ public void resolveLinesInFile(Path inputFile) throws IOException { try (Writer resolvedWriter = Files.newBufferedWriter(getDestFile(inputFile)); Stream<String> lines = Files.lines(inputFile);) { AtomicInteger ai = new AtomicInteger(0); lines.forEach(line -> { try { JsonObject resolved = addAddress(line); resolvedWriter.write(resolved.toString()); resolvedWriter.write("\n"); int i = ai.incrementAndGet(); if (i % 1000 == 0) { System.out.println(i); } } catch (IOException e) { e.printStackTrace(); } }); } } private Path getDestFile(Path inputFile) { String origFilename = inputFile.getFileName().toString(); origFilename = FilenameUtils.removeExtension(origFilename); String destFilename = origFilename + ".resolved.geojson"; return Paths.get(destFilename); } public String getStatistics() { return resolver.getStatistics(); } public static void main(String[] args) throws IOException, ParseException { OptionParser parser = new OptionParser(); parser.accepts("poly-file") // .withRequiredArg().ofType(String.class) // .describedAs("input geojsonseq with admin polygons"); parser.accepts("input-file") // .withRequiredArg().ofType(String.class) // .describedAs("input geojsonseq with POIs"); OptionSet options = parser.parse(args); System.out.println(options.asMap()); if (args.length < 2) { parser.printHelpOn(System.err); throw new RuntimeException("Missing args."); } Path polygonFile = Paths.get(options.valueOf("poly-file").toString()); Path inputFile = Paths.get(options.valueOf("input-file").toString()); PolygonCache polygons = PolygonCache.fromGeoJSONStream(polygonFile); GeoJSONResolver resolver = new GeoJSONResolver(polygons); resolver.resolveLinesInFile(inputFile); } }
923b6b36faedccaab19e6db81bde24791ced6cca
5,957
java
Java
src/main/java/in/zapr/druid/druidry/query/config/Context.java
szymeker/druidry-query
9879ce8da55a90e952fbf1906dee7b1e8fd87fc0
[ "Apache-2.0" ]
194
2017-05-05T10:44:58.000Z
2021-12-07T08:08:12.000Z
src/main/java/in/zapr/druid/druidry/query/config/Context.java
szymeker/druidry-query
9879ce8da55a90e952fbf1906dee7b1e8fd87fc0
[ "Apache-2.0" ]
89
2017-11-14T09:46:18.000Z
2021-12-09T19:48:38.000Z
src/main/java/in/zapr/druid/druidry/query/config/Context.java
szymeker/druidry-query
9879ce8da55a90e952fbf1906dee7b1e8fd87fc0
[ "Apache-2.0" ]
88
2017-05-05T11:03:20.000Z
2022-03-29T23:45:26.000Z
39.713333
145
0.689777
999,595
/* * Copyright 2018-present Red Brick Lane Marketing Solutions Pvt. Ltd. * * 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 in.zapr.druid.druidry.query.config; import com.google.common.base.Preconditions; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; @Builder @Getter @JsonInclude(JsonInclude.Include.NON_NULL) @EqualsAndHashCode public class Context { // general query contexts @JsonProperty("timeout") private Long timeoutInMilliSeconds; private Integer priority; private String queryId; private Boolean useCache; private Boolean populateCache; private Boolean useResultLevelCache; private Boolean populateResultLevelCache; private Boolean bySegment; private Boolean finalize; private String chunkPeriod; private Long maxScatterGatherBytes; private Long maxQueuedBytes; private Boolean serializeDateTimeAsLong; private Boolean serializeDateTimeAsLongInner; // topN query contexts private Integer minTopNThreshold; // timeseries query contexts private Boolean skipEmptyBuckets; // groupBy query contexts private Long maxMergingDictionarySize; private Long maxOnDiskStorage; private GroupByStrategy groupByStrategy; private Boolean groupByIsSingleThreaded; private Integer bufferGrouperInitialBuckets; private Float bufferGrouperMaxLoadFactor; private Boolean forceHashAggregation; private Integer intermediateCombineDegree; private Integer numParallelCombineThreads; private Boolean sortByDimsFirst; private Boolean forceLimitPushDown; private Boolean applyLimitPushDown; private Integer maxIntermediateRows; private Integer maxResults; private Boolean useOffheap; // groupBy && timeseries query experimental contexts private Vectorize vectorize; private Integer vectorSize; private Context(Long timeoutInMilliSeconds, Integer priority, String queryId, Boolean useCache, Boolean populateCache, Boolean useResultLevelCache, Boolean populateResultLevelCache, Boolean bySegment, Boolean finalize, String chunkPeriod, Long maxScatterGatherBytes, Long maxQueuedBytes, Boolean serializeDateTimeAsLong, Boolean serializeDateTimeAsLongInner, Integer minTopNThreshold, Boolean skipEmptyBuckets, Long maxMergingDictionarySize, Long maxOnDiskStorage, GroupByStrategy groupByStrategy, Boolean groupByIsSingleThreaded, Integer bufferGrouperInitialBuckets, Float bufferGrouperMaxLoadFactor, Boolean forceHashAggregation, Integer intermediateCombineDegree, Integer numParallelCombineThreads, Boolean sortByDimsFirst, Boolean forceLimitPushDown, Boolean applyLimitPushDown, Integer maxIntermediateRows, Integer maxResults, Boolean useOffheap, Vectorize vectorize, Integer vectorSize) { this.timeoutInMilliSeconds = timeoutInMilliSeconds; this.priority = priority; this.queryId = queryId; this.useCache = useCache; this.populateCache = populateCache; this.useResultLevelCache = useResultLevelCache; this.populateResultLevelCache = populateResultLevelCache; this.bySegment = bySegment; this.finalize = finalize; this.chunkPeriod = chunkPeriod; this.maxScatterGatherBytes = maxScatterGatherBytes; this.maxQueuedBytes = maxQueuedBytes; this.serializeDateTimeAsLong = serializeDateTimeAsLong; this.serializeDateTimeAsLongInner = serializeDateTimeAsLongInner; this.minTopNThreshold = minTopNThreshold; this.skipEmptyBuckets = skipEmptyBuckets; this.maxMergingDictionarySize = maxMergingDictionarySize; this.maxOnDiskStorage = maxOnDiskStorage; this.groupByStrategy = groupByStrategy; this.groupByIsSingleThreaded = groupByIsSingleThreaded; this.bufferGrouperInitialBuckets = bufferGrouperInitialBuckets; this.bufferGrouperMaxLoadFactor = bufferGrouperMaxLoadFactor; this.forceHashAggregation = forceHashAggregation; this.intermediateCombineDegree = intermediateCombineDegree; this.numParallelCombineThreads = numParallelCombineThreads; this.sortByDimsFirst = sortByDimsFirst; this.forceLimitPushDown = forceLimitPushDown; this.applyLimitPushDown = applyLimitPushDown; this.maxIntermediateRows = maxIntermediateRows; this.maxResults = maxResults; this.useOffheap = useOffheap; this.vectorize = vectorize; this.vectorSize = vectorSize; if (timeoutInMilliSeconds != null) { Preconditions.checkArgument(timeoutInMilliSeconds >= 0, "Timeout must be a non negative value, but was [%s]", timeoutInMilliSeconds); } } }
923b6bfae407b5d5ae5a70daa4f67d29cd7a1947
330
java
Java
questPresentation/src/main/java/ru/nekit/android/qls/quest/formatter/IQuestTextContentFormatter.java
ru-nekit-android/QuestLockScreen
37a2037be2ecdbe19607b5fbb9e5f7852320a5a0
[ "Apache-2.0" ]
null
null
null
questPresentation/src/main/java/ru/nekit/android/qls/quest/formatter/IQuestTextContentFormatter.java
ru-nekit-android/QuestLockScreen
37a2037be2ecdbe19607b5fbb9e5f7852320a5a0
[ "Apache-2.0" ]
null
null
null
questPresentation/src/main/java/ru/nekit/android/qls/quest/formatter/IQuestTextContentFormatter.java
ru-nekit-android/QuestLockScreen
37a2037be2ecdbe19607b5fbb9e5f7852320a5a0
[ "Apache-2.0" ]
null
null
null
23.571429
68
0.790909
999,596
package ru.nekit.android.qls.quest.formatter; import android.content.Context; import android.support.annotation.NonNull; import ru.nekit.android.qls.domain.model.quest.Quest; public interface IQuestTextContentFormatter { String[] format(@NonNull Context context, @NonNull Quest quest); String getMissedCharacter(); }
923b6c7617eeb0ffca81d0f1b2f11ed9a10ad659
257
java
Java
blog-master/src/main/java/com/heriec/blogmaster/dto/PageDto.java
Heriec/heriecblog
639fb135bdb1795866ba237e271c455500c36016
[ "Apache-2.0" ]
null
null
null
blog-master/src/main/java/com/heriec/blogmaster/dto/PageDto.java
Heriec/heriecblog
639fb135bdb1795866ba237e271c455500c36016
[ "Apache-2.0" ]
null
null
null
blog-master/src/main/java/com/heriec/blogmaster/dto/PageDto.java
Heriec/heriecblog
639fb135bdb1795866ba237e271c455500c36016
[ "Apache-2.0" ]
null
null
null
18.357143
34
0.809339
999,597
package com.heriec.blogmaster.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class PageDto { private Integer currentPage; private Integer pageSize; }
923b6cb4168386d1de3cbeead0191447f9e8ec7d
367
java
Java
SampleDagger/src/main/java/com/imos/dagger/sample/dagger/DripCoffeeModule.java
aloktech/AllProjects
9a7f3318517083b2d0fa5313580bbf725b677989
[ "Apache-2.0" ]
1
2020-03-12T12:55:27.000Z
2020-03-12T12:55:27.000Z
SampleDagger/src/main/java/com/imos/dagger/sample/dagger/DripCoffeeModule.java
aloktech/AllProjects
9a7f3318517083b2d0fa5313580bbf725b677989
[ "Apache-2.0" ]
9
2021-09-20T20:36:53.000Z
2022-03-08T21:11:25.000Z
SampleDagger/src/main/java/com/imos/dagger/sample/dagger/DripCoffeeModule.java
aloktech/AllProjects
9a7f3318517083b2d0fa5313580bbf725b677989
[ "Apache-2.0" ]
null
null
null
15.956522
38
0.6703
999,598
package com.imos.dagger.sample.dagger; /** * * @author INVCH018 */ import dagger.Module; import dagger.Provides; import javax.inject.Singleton; @Module( injects = CoffeeApp.class, includes = PumpModule.class ) public class DripCoffeeModule { @Provides @Singleton Heater provideHeater() { return new ElectricHeater(); } }
923b6e6b3e135aafb9c9813ce7325f08b37d750a
277
java
Java
sources/physique/actions/vehicule/ActionVehicule.java
adeprez/Sources-Jeu
646484977569f14c1eb013cd1e6ae1f40f9cc493
[ "MIT" ]
null
null
null
sources/physique/actions/vehicule/ActionVehicule.java
adeprez/Sources-Jeu
646484977569f14c1eb013cd1e6ae1f40f9cc493
[ "MIT" ]
3
2015-09-05T13:05:36.000Z
2015-09-07T12:49:07.000Z
sources/physique/actions/vehicule/ActionVehicule.java
adeprez/Sources-Jeu
646484977569f14c1eb013cd1e6ae1f40f9cc493
[ "MIT" ]
null
null
null
18.466667
85
0.736462
999,599
package physique.actions.vehicule; import physique.actions.AbstractAction; import physique.vehicule.Vehicule; public abstract class ActionVehicule<E extends Vehicule> extends AbstractAction<E> { public ActionVehicule(E source) { super(source); } }
923b6ef526b5dec0bf95494b5b8316aef48d6529
84
java
Java
src/UnivaPushSpring/src/main/java/it/univaq/disim/mobile/myunivaq/domain/Lingua.java
paolozu/UnivaqPush
481c52ca24aec1ec0e8252b6a0ed1174ea105e02
[ "MIT" ]
7
2018-07-27T09:31:17.000Z
2018-09-12T11:39:26.000Z
src/UnivaPushSpring/src/main/java/it/univaq/disim/mobile/myunivaq/domain/Lingua.java
paolozu/UnivaqPush
481c52ca24aec1ec0e8252b6a0ed1174ea105e02
[ "MIT" ]
null
null
null
src/UnivaPushSpring/src/main/java/it/univaq/disim/mobile/myunivaq/domain/Lingua.java
paolozu/UnivaqPush
481c52ca24aec1ec0e8252b6a0ed1174ea105e02
[ "MIT" ]
3
2018-09-12T08:51:13.000Z
2019-06-24T13:26:16.000Z
12
47
0.738095
999,600
package it.univaq.disim.mobile.myunivaq.domain; public enum Lingua { ITA, ENG; }
923b700950220c19b61d22c9a89815ac6a94690b
1,478
java
Java
enjoy-web/src/main/java/com/ckh/enjoy/web/service/config/ApiConfigurerAdapter.java
ckh101/enjoy
9480ad4c28cb13a3fd29a392ae06909fff5860ca
[ "MIT" ]
2
2020-05-06T05:11:06.000Z
2020-05-06T05:11:09.000Z
enjoy-web/src/main/java/com/ckh/enjoy/web/service/config/ApiConfigurerAdapter.java
ckh101/enjoy
9480ad4c28cb13a3fd29a392ae06909fff5860ca
[ "MIT" ]
4
2021-05-08T17:56:48.000Z
2022-01-12T23:05:47.000Z
enjoy-web/src/main/java/com/ckh/enjoy/web/service/config/ApiConfigurerAdapter.java
ckh101/enjoy
9480ad4c28cb13a3fd29a392ae06909fff5860ca
[ "MIT" ]
null
null
null
33.590909
120
0.82544
999,601
package com.ckh.enjoy.web.service.config; import com.ckh.enjoy.web.interceptors.SystemLogInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; @Configuration public class ApiConfigurerAdapter implements WebMvcConfigurer{ @Bean public SystemLogInterceptor getSystemLogInterceptor() { return new SystemLogInterceptor(); } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { argumentResolvers.add(new ApiArgumentResolver()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**/*").addResourceLocations("classpath:/static/"); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getSystemLogInterceptor()).excludePathPatterns("/static/**/*").addPathPatterns("/admin/**/*"); } @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.setUseSuffixPatternMatch(false); } }
923b70aa9be7362af7bd04e2304fee46eac7d008
1,776
java
Java
src/boboPOM/view/Main.java
JeremieAstray/BoboPOM
2835688aba25cc4822a51aae9b1ec5ff7847f5f7
[ "Apache-2.0" ]
null
null
null
src/boboPOM/view/Main.java
JeremieAstray/BoboPOM
2835688aba25cc4822a51aae9b1ec5ff7847f5f7
[ "Apache-2.0" ]
null
null
null
src/boboPOM/view/Main.java
JeremieAstray/BoboPOM
2835688aba25cc4822a51aae9b1ec5ff7847f5f7
[ "Apache-2.0" ]
null
null
null
30.62069
118
0.653716
999,602
package boboPOM.view; import boboPOM.config.Config; import javafx.application.Application; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; import javafx.stage.WindowEvent; //import javafx.scene.layout.Pane; public class Main extends Application { public static void main(String[] args) { launch(args); } // public void setResulation(double x, double y) { // Config.stage.setMaxHeight(y + 38); // Config.stage.setMaxWidth(x); // Config.root.setScaleX(x / (Config.SCREEN_WIDTH)); // Config.root.setScaleY(y / (Config.SCREEN_HEIGHT)); // } /** * 主程序 * * @param primaryStage * * @throws Exception */ @Override public void start(Stage primaryStage) throws Exception { Config.init(); Config.stage = primaryStage; Parent root = FXMLLoader.load(getClass().getResource("BoboPom.fxml")); Config.root = root; primaryStage.setMaxHeight(Config.SCREEN_HEIGHT + 38); primaryStage.setMaxWidth(Config.SCREEN_WIDTH); // setResulation(Config.getSCREEN_WIDTH(), Config.getSCREEN_HEIGHT()); Scene scene = new Scene(root); primaryStage.setResizable(true); primaryStage.setTitle("BoboPom!"); primaryStage.getIcons().add(new Image(Main.class.getResource("resources/images/title.png").toExternalForm())); primaryStage.setScene(scene); primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent arg0) { System.exit(0); } }); primaryStage.show(); } }
923b71f4e1190b21a9143513b7c0338737ada185
1,389
java
Java
components/components-netsuite/components-netsuite-runtime/src/main/java/org/talend/components/netsuite/client/model/customfield/OtherCustomFieldAdapter.java
wwang-talend/components
273af8f4ec300684c65b8afef23b96107680f8d9
[ "Apache-2.0" ]
53
2016-03-06T10:52:48.000Z
2020-12-09T15:11:21.000Z
components/components-netsuite/components-netsuite-runtime/src/main/java/org/talend/components/netsuite/client/model/customfield/OtherCustomFieldAdapter.java
wwang-talend/components
273af8f4ec300684c65b8afef23b96107680f8d9
[ "Apache-2.0" ]
1,727
2016-01-28T09:05:53.000Z
2022-03-29T05:59:55.000Z
components/components-netsuite/components-netsuite-runtime/src/main/java/org/talend/components/netsuite/client/model/customfield/OtherCustomFieldAdapter.java
wwang-talend/components
273af8f4ec300684c65b8afef23b96107680f8d9
[ "Apache-2.0" ]
112
2016-01-28T03:27:24.000Z
2021-10-13T02:58:54.000Z
34.725
101
0.658027
999,603
// ============================================================================ // // Copyright (C) 2006-2020 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.components.netsuite.client.model.customfield; import static org.talend.components.netsuite.client.model.beans.Beans.getSimpleProperty; import org.talend.components.netsuite.client.model.BasicRecordType; /** * Custom field adapter for {@link BasicRecordType#OTHER_CUSTOM_FIELD} type. */ public class OtherCustomFieldAdapter<T> extends CustomFieldAdapter<T> { public OtherCustomFieldAdapter() { super(BasicRecordType.OTHER_CUSTOM_FIELD); } @Override public boolean appliesTo(String recordTypeName, T field) { String recTypeName = (String) getSimpleProperty(getSimpleProperty(field, "recType"), "name"); return recordTypeName != null ? recordTypeName.equalsIgnoreCase(recTypeName) : false; } @Override public CustomFieldRefType apply(T field) { return getFieldType(field); } }
923b731830dcf81ca71f14b146f1bbd1479c1e89
600
java
Java
shiro-core/src/main/java/com/suteng/shiro/business/vo/CustProjectConditionVo.java
supertonsystem/project_management
1bffd2358a3f2d65eadf39178e03f5eb65451f8a
[ "MIT" ]
null
null
null
shiro-core/src/main/java/com/suteng/shiro/business/vo/CustProjectConditionVo.java
supertonsystem/project_management
1bffd2358a3f2d65eadf39178e03f5eb65451f8a
[ "MIT" ]
null
null
null
shiro-core/src/main/java/com/suteng/shiro/business/vo/CustProjectConditionVo.java
supertonsystem/project_management
1bffd2358a3f2d65eadf39178e03f5eb65451f8a
[ "MIT" ]
1
2021-09-24T14:40:48.000Z
2021-09-24T14:40:48.000Z
20.689655
61
0.715
999,604
package com.suteng.shiro.business.vo; import com.suteng.shiro.business.entity.CustProjectEntity; import com.suteng.shiro.framework.object.BaseConditionVO; import lombok.Data; /** * @Author:louyi * @Description: * @Date:Create in 9:41 2019/5/17 */ @Data public class CustProjectConditionVo extends BaseConditionVO { //排除ids private String excludeIds; /** * 关联id */ private Long personId; private Long deptId; public CustProjectConditionVo() { this.custProjectEntity = new CustProjectEntity(); } private CustProjectEntity custProjectEntity; }
923b74450e98568f1cb35429af7857ad1680f767
611
java
Java
ExtractedJars/Shopkick_com.shopkick.app/javafiles/com/craftar/CraftARInternalInterfaces$CollectionEventsHandler.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/Shopkick_com.shopkick.app/javafiles/com/craftar/CraftARInternalInterfaces$CollectionEventsHandler.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/Shopkick_com.shopkick.app/javafiles/com/craftar/CraftARInternalInterfaces$CollectionEventsHandler.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
30.55
96
0.826514
999,605
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.craftar; // Referenced classes of package com.craftar: // CraftARInternalInterfaces, CraftAROnDeviceCollection static interface CraftARInternalInterfaces$CollectionEventsHandler { public abstract void onCollectionAdded(CraftAROnDeviceCollection craftarondevicecollection); public abstract void onCollectionDeleted(String s); public abstract void onCollectionModified(CraftAROnDeviceCollection craftarondevicecollection); }
923b744def6504f98d5084bf795a00336376324d
7,261
java
Java
src/java/socialite/util/FastOutputStream.java
Wangqge/PowerLog_AE
8546afbcb9a77d516e8c3f0dfbaf2041a4b888f9
[ "Apache-2.0" ]
49
2015-03-10T17:34:19.000Z
2021-11-10T22:23:18.000Z
src/java/socialite/util/FastOutputStream.java
Wangqge/PowerLog_AE
8546afbcb9a77d516e8c3f0dfbaf2041a4b888f9
[ "Apache-2.0" ]
null
null
null
src/java/socialite/util/FastOutputStream.java
Wangqge/PowerLog_AE
8546afbcb9a77d516e8c3f0dfbaf2041a4b888f9
[ "Apache-2.0" ]
32
2015-02-06T12:10:32.000Z
2019-06-18T03:21:36.000Z
25.124567
94
0.650599
999,606
package socialite.util; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import socialite.resource.SRuntime; import socialite.resource.SRuntimeWorker; import socialite.tables.TmpTableInst; public class FastOutputStream extends ObjectOutputStream { OutputStream out; FastClassLookup lookup; public FastOutputStream(OutputStream _out) throws IOException { super(); out=_out; lookup= new FastClassLookup(); } @Override public void close() throws IOException { out.close(); } @Override public void flush() throws IOException { out.flush(); } @Override public void write(int b) throws IOException { out.write(b); } @Override public void write(byte[] b) throws IOException { out.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); } static String[] classDescr; static { classDescr = new String[128]; for (int i=0; i<classDescr.length; i++) { classDescr[i] = "#"+i; } } private String getShortClassDescr(int idx) { if (idx < classDescr.length) return classDescr[idx]; return "#"+idx; } private String getClassDescr(Class cls) { int fastIdx=lookup.getIdx(cls); String className; if (fastIdx>=0) className=getShortClassDescr(fastIdx); else className=cls.getName(); return className; } @Override protected void writeObjectOverride(Object obj) throws IOException { if (obj instanceof Object[]) { writeObjectArray(obj); } else if (obj.getClass().isArray()) { writePrimArray(obj); } else { String className = getClassDescr(obj.getClass()); writeInt(className.length()); writeClassName(className, obj.getClass()); if (TmpTableInst.class.isAssignableFrom(obj.getClass())) { TmpTableInst inst = (TmpTableInst)obj; writeTableInstSize(inst); } if (obj instanceof String) { String s=(String)obj; writeInt(s.length()); writeChars(s); } else if (obj instanceof Externalizable) { Externalizable e=(Externalizable)obj; e.writeExternal(this); } else { String msg="Only Externalizable object can be written in fast mode"; throw new UnsupportedOperationException(msg); } } } void writeTableInstSize(TmpTableInst inst) throws IOException { char size; if (inst.isSmall()) size=1; else size=2; writeChar(size); } void writeClassName(String className, Class cls) throws IOException { writeChars(className); /*if (className.charAt(0)=='#') lookup.addClass(cls);*/ } void writePrimArray(Object a) throws IOException { Class itemType = a.getClass().getComponentType(); assert itemType.isPrimitive(); String className=getClassDescr(itemType); writeInt(1+className.length()); writeChar('['); writeClassName(className, itemType); if (itemType.equals(int.class)) { int[] array=(int[])a; writeInt(array.length); for (int i=0; i<array.length; i++) { writeInt(array[i]); } } else if (itemType.equals(long.class)) { long[] array=(long[])a; writeInt(array.length); for (int i=0; i<array.length; i++) { writeLong(array[i]); } } else if (itemType.equals(float.class)) { float[] array=(float[])a; writeInt(array.length); for (int i=0; i<array.length; i++) { writeFloat(array[i]); } } else if (itemType.equals(double.class)) { double[] array=(double[])a; writeInt(array.length); for (int i=0; i<array.length; i++) { writeDouble(array[i]); } } else if (itemType.equals(byte.class)) { byte[] array=(byte[])a; writeInt(array.length); for (int i=0; i<array.length; i++) { writeByte(array[i]); } } else if (itemType.equals(boolean.class)) { boolean[] array=(boolean[])a; writeInt(array.length); for (int i=0; i<array.length; i++) { writeBoolean(array[i]); } } else if (itemType.equals(short.class)) { short[] array=(short[])a; writeInt(array.length); for (int i=0; i<array.length; i++) { writeShort(array[i]); } } else if (itemType.equals(char.class)) { char[] array=(char[])a; writeInt(array.length); for (int i=0; i<array.length; i++) { writeChar(array[i]); } } else { throw new UnsupportedOperationException("Unsupported primitive array type:"+itemType+"["); } } void writeObjectArray(Object a) throws IOException { Object[] array=(Object[])a; Class itemType = array.getClass().getComponentType(); String className=getClassDescr(itemType); for (int i=0; i<array.length; i++) { if (array[i]!=null) { itemType = array[i].getClass(); className=getClassDescr(itemType); break; } } boolean tableArray=false; if (TmpTableInst.class.isAssignableFrom(itemType)) tableArray=true; writeInt(1+className.length()); writeChar('['); writeClassName(className, itemType); writeInt(array.length); for (int i=0; i<array.length; i++) { if (array[i]==null) { writeBoolean(false); } else { writeBoolean(true); assert array[i] instanceof Externalizable || array[i] instanceof String; if (tableArray) { TmpTableInst inst = (TmpTableInst)array[i]; writeTableInstSize(inst); } if (itemType.equals(String.class)) { String s=(String)array[i]; writeInt(s.length()); writeChars(s); } else { Externalizable ext=(Externalizable)array[i]; ext.writeExternal(this); } } } } @Override public void writeBoolean(boolean f) throws IOException { if (f) out.write(1); else out.write(0); } @Override public void writeByte(int b) throws IOException { out.write(b); } @Override public void writeBytes(String s) throws IOException { for (int i=0; i<s.length(); i++) { char c=s.charAt(i); out.write(c); } } @Override public void writeChar(int v) throws IOException { writeByte((byte)(0xff & (v >> 8))); writeByte((byte)(0xff & v)); } @Override public void writeChars(String s) throws IOException { for (int i=0; i<s.length(); i++) { char c=s.charAt(i); writeChar(c); } } @Override public void writeDouble(double v) throws IOException { long l = Double.doubleToRawLongBits(v); writeLong(l); } @Override public void writeFloat(float v) throws IOException { int i = Float.floatToRawIntBits(v); writeInt(i); } @Override public void writeInt(int i) throws IOException { out.write((byte)(0xff & (i >> 24))); out.write((byte)(0xff & (i >> 16))); out.write((byte)(0xff & (i >> 8))); out.write((byte)(0xff & i)); } @Override public void writeLong(long l) throws IOException { out.write((byte)(0xff & (l >> 56))); out.write((byte)(0xff & (l >> 48))); out.write((byte)(0xff & (l >> 40))); out.write((byte)(0xff & (l >> 32))); out.write((byte)(0xff & (l >> 24))); out.write((byte)(0xff & (l >> 16))); out.write((byte)(0xff & (l >> 8))); out.write((byte)(0xff & l)); } public void writeShort(short s) throws IOException { out.write((byte)(0xff & (s >> 8))); out.write((byte)(0xff & s)); } @Override public void writeUTF(String s) throws IOException { throw new UnsupportedOperationException("writeUTF is not supported for fast mode"); } }
923b74775f18642483e4ffac888a3aed67b82146
24,683
java
Java
DevLibUtils/src/main/java/dev/utils/app/wifi/WifiUtils.java
wangjjj/DevUtils
fdf5bb311431d16bb1545ba76e36ca465a3734ba
[ "Apache-2.0" ]
1
2018-12-07T09:38:46.000Z
2018-12-07T09:38:46.000Z
DevLibUtils/src/main/java/dev/utils/app/wifi/WifiUtils.java
wangjjj/DevUtils
fdf5bb311431d16bb1545ba76e36ca465a3734ba
[ "Apache-2.0" ]
null
null
null
DevLibUtils/src/main/java/dev/utils/app/wifi/WifiUtils.java
wangjjj/DevUtils
fdf5bb311431d16bb1545ba76e36ca465a3734ba
[ "Apache-2.0" ]
null
null
null
25.927521
141
0.659199
999,607
package dev.utils.app.wifi; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiConfiguration.KeyMgmt; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.text.TextUtils; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import dev.utils.LogPrintUtils; /** * detail: wifi工具类 * Created by Ttt * <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> */ public final class WifiUtils { // 日志TAG private final static String TAG = WifiUtils.class.getSimpleName(); // ======= wifi管理类对象 ======= /** 定义WifiManager对象 */ private WifiManager mWifiManager; // ======= 常量 ======= /** 没有密码 */ public static final int NOPWD = 0; /** wep加密方式 */ public static final int WEP = 1; /** wpa加密方式 */ public static final int WPA = 2; // ==================================================== /** 构造器(只能进行初始化WifiManager操作,其他靠方法定义) */ public WifiUtils(Context context) { // 初始化WifiManager对象 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); } /** * 获取wifi管理对象 * @return */ public WifiManager getWifiManager(){ return this.mWifiManager; } // ================= wifi 开关、连接状态获取 ================= /** 判断是否打开wifi */ public boolean isOpenWifi(){ return mWifiManager.isWifiEnabled(); } /** 打开WIFI */ public void openWifi() { // 如果没有打开wifi,才进行打开 if (!isOpenWifi()) { mWifiManager.setWifiEnabled(true); } } /** 关闭WIFI */ public void closeWifi() { // 如果已经打开了wifi,才进行关闭 if (isOpenWifi()) { mWifiManager.setWifiEnabled(false); } } /** 自动切换wifi开关状态 */ public void toggleWifiEnabled(){ // 如果打开了,则关闭 // 如果关闭了,则打开 // ================= mWifiManager.setWifiEnabled(!isOpenWifi()); } /** 获取当前WIFI连接状态 */ public int getWifiState() { // WifiManager.WIFI_STATE_ENABLED: // 已打开 // WifiManager.WIFI_STATE_ENABLING: // 正在打开 // WifiManager.WIFI_STATE_DISABLED: // 已关闭 // WifiManager.WIFI_STATE_DISABLING: // 正在关闭 // WifiManager.WIFI_STATE_UNKNOWN: // 未知 return mWifiManager.getWifiState(); } // ================= GET 操作 ================= /** 开始扫描wifi */ public boolean startScan(){ // 开始扫描 return mWifiManager.startScan(); } /** 获取已配置的网络 */ public List<WifiConfiguration> getConfiguration() { return mWifiManager.getConfiguredNetworks(); } /** 获取网络列表 */ public List<ScanResult> getWifiList() { return mWifiManager.getScanResults(); } /** 获取WifiInfo对象 */ public WifiInfo getWifiInfo(){ return mWifiManager.getConnectionInfo(); } /** * 获取MAC地址 * @param wifiInfo * @return */ public String getMacAddress(WifiInfo wifiInfo) { return wifiInfo.getMacAddress(); } /** * 获取接入点的BSSID * @param wifiInfo * @return */ public String getBSSID(WifiInfo wifiInfo) { return wifiInfo.getBSSID(); } /** * 获取IP地址 * @param wifiInfo * @return */ public int getIPAddress(WifiInfo wifiInfo) { return wifiInfo.getIpAddress(); } /** * 获取连接的ID * @param wifiInfo * @return */ public int getNetworkId(WifiInfo wifiInfo) { return wifiInfo.getNetworkId(); } // === /** * 获取SSID * @param wifiInfo wifi信息 * @return */ public static String getSSID(WifiInfo wifiInfo){ try { // 获取SSID,并进行处理 return formatSSID(wifiInfo.getSSID(), false); } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "getSSID"); } return null; } /** * 通过 Context 获取当前连接的ssid * @param context */ public static String getSSID(Context context){ try { // 初始化WifiManager对象 WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); // 获取当前连接的wifi WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); // 获取wifi - SSID return formatSSID(wifiInfo.getSSID(), false); } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "getSSID"); } return null; } // === /** * 判断是否存在\"ssid\",存在则裁剪返回 * @param ssid */ public static String formatSSID(String ssid){ // 自动去掉SSID if(ssid != null && ssid.startsWith("\"") && ssid.endsWith("\"")){ try { // 裁剪连接的ssid,并返回 return ssid.substring(1, ssid.length() - 1); } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "formatSSID"); } } return ssid; } /** * 格式化,处理SSID * @param ssid * @param isHandler true = 添加引号,false = 删除引号 * @return */ public static String formatSSID(String ssid, boolean isHandler){ if(isHandler){ return "\"" + ssid + "\""; } else { return formatSSID(ssid); } } /** * 获取密码(经过处理) * @param pwd 需要处理的密码 * @param isJudge 是否需要判断 * @return */ public String getPassword(String pwd, boolean isJudge){ if (isJudge && isHexWepKey(pwd)) { return pwd; } else { return "\"" + pwd + "\""; } } /** * 判断是否 wep 加密 * @param wepKey * @return */ public static boolean isHexWepKey(String wepKey) { // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?) int len = wepKey.length(); if (len != 10 && len != 26 && len != 58) { return false; } return isHex(wepKey); } /** * 判断是否 十六进制 * @param key * @return */ private static boolean isHex(String key) { for (int i = key.length() - 1;i >= 0;i--) { char c = key.charAt(i); if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) { return false; } } return true; } // ================= 快捷操作 ================= /** * 获取加密类型(int常量) - 判断String * @param type */ public static int getWifiType(String type) { // WPA 是本机的用法 if (type.contains("WPA")) { return WPA; } else if (type.contains("WEP")) { return WEP; } // 默认没有密码 return NOPWD; } /** * 获取加密类型(int常量) - 判断int(String) * @param type */ public static int getWifiTypeInt(String type){ // WPA 是本机的用法 if (type.equals("2")) { return WPA; } else if (type.equals("1")) { return WEP; } // 默认没有密码 return NOPWD; } /** * 获取加密类型(int常量) * @param type */ public static String getWifiType(int type){ switch(type){ case WPA: return "2"; case WEP: return "1"; case NOPWD: return "0"; } return "0"; } /** * 获取加密类型(String) * @param type * @return */ public static String getWifiTypeStr(int type) { switch(type){ case WPA: return "WPA"; case WEP: return "WEP"; default: return ""; } } /** * 判断是否连接为null - unknown ssid * @param ssid * @return */ public static boolean isConnNull(String ssid){ if(ssid == null){ return true; } else if (ssid.indexOf("unknown") != -1){ // <unknown ssid> return true; } return false; } /** * 判断是否连接上Wifi(非连接中) * @param context * @return 返回ssid */ public static String isConnectAphot(Context context){ try { // 连接管理 ConnectivityManager cManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // 连接状态 NetworkInfo.State nState = cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); if((nState == NetworkInfo.State.CONNECTED)){ // 获取连接的ssid return getSSID(context); } } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "isConnectAphot"); } return null; } // ================= Wifi配置操作 ================= /** 默认没有密码 */ static final int SECURITY_NONE = 0; /** WEP加密方式 */ static final int SECURITY_WEP = 1; /** PSK加密方式 */ static final int SECURITY_PSK = 2; /** EAP加密方式 */ static final int SECURITY_EAP = 3; /** * 获取Wifi配置,加密类型 * @param wifiConfig * @return */ public static int getSecurity(WifiConfiguration wifiConfig) { if (wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { return SECURITY_PSK; } if (wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || wifiConfig.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { return SECURITY_EAP; } return (wifiConfig.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE; } /** * 获知Wifi配置,是否属于密码加密类型 * @param wifiConfig * @return */ public static boolean isExsitsPwd(WifiConfiguration wifiConfig){ int wifiSecurity = getSecurity(wifiConfig); // 判断是否加密 return (wifiSecurity != SECURITY_NONE); } /** * 查看以前是否也配置过这个网络 * @param ssid 需要判断的wifi SSID */ public WifiConfiguration isExsits(String ssid){ // 获取wifi 连接过的配置信息 List<WifiConfiguration> listWifiConfigs = getConfiguration(); // 防止为null if(listWifiConfigs == null){ return null; } // 遍历判断是否存在 for(int i = 0, len = listWifiConfigs.size();i < len ;i++){ WifiConfiguration wConfig = listWifiConfigs.get(i); if(wConfig != null){ if (wConfig.SSID.equals("\"" + ssid + "\"")){ return wConfig; } } } return null; } /** * 查看以前是否也配置过这个网络 * @param networkId 网络id */ public WifiConfiguration isExsits(int networkId){ // 获取wifi 连接过的配置信息 List<WifiConfiguration> listWifiConfigs = getConfiguration(); // 防止为null if(listWifiConfigs == null){ return null; } // 遍历判断是否存在 for(int i = 0, len = listWifiConfigs.size();i < len ;i++){ WifiConfiguration wConfig = listWifiConfigs.get(i); if(wConfig != null){ if (wConfig.networkId == networkId){ return wConfig; } } } return null; } // ================= 配置操作 ================= /** * 删除指定的 Wifi(SSID) 配置信息 * @param context * @param ssid * @return 删除结果 */ public static boolean delWifiConfig(Context context, String ssid){ try { // 初始化WifiManager对象 WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); // 获取wifi 连接过的配置信息 List<WifiConfiguration> listWifiConfigs = mWifiManager.getConfiguredNetworks(); // 防止为null if(listWifiConfigs != null){ // 遍历判断是否存在 for(int i = 0, len = listWifiConfigs.size();i < len ;i++){ WifiConfiguration wConfig = listWifiConfigs.get(i); if(wConfig != null){ if (wConfig.SSID.equals("\"" + ssid + "\"")){ // 删除操作 mWifiManager.removeNetwork(wConfig.networkId); } } } // 保存操作 mWifiManager.saveConfiguration(); return true; } } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "delWifiConfig"); } return false; } /** * 快速连接Wifi(不使用静态ip方式) * @param ssid wifi SSID * @param pwd wifi密码 * @param wType 加密类型 */ public WifiConfiguration quickConnWifi(String ssid, String pwd, int wType){ return quickConnWifi(ssid, pwd, wType, false, null); } /** * 快速连接Wifi * @param ssid wifi SSID * @param pwd wifi密码 * @param wType 加密类型 * @param isStatic 是否使用静态ip连接 * @param ip 静态IP地址 * @return 连接成功的 WifiConfiguration */ public WifiConfiguration quickConnWifi(String ssid, String pwd, int wType, boolean isStatic, String ip){ // 步骤 // 1.创建Wifi静态Ip连接配置 // 2.创建正常Wifi连接配置 // 3.查询准备连接的Wifi-SSID 是否存在配置文件,准备进行删除 // 4.查询当前连接的Wifi-SSID 准备进行断开 // 5.同步进行断开,删除操作,并且进行保存 // 6.调用连接方法 // 7.返回连接的配置信息 // ============= // -- try { // 正常的Wifi连接配置 WifiConfiguration connWifiConfig = null; // 如果需要通过静态ip方式连接,则进行设置 if(isStatic && !TextUtils.isEmpty(ip)){ // 创建Wifi静态IP连接配置 WifiConfiguration staticWifiConfig = setStaticWifiConfig(createWifiConfig(ssid, pwd, wType, true), ip); // 如果静态ip方式,配置失败,则初始化正常连接的Wifi配置 if(staticWifiConfig == null){ // 创建正常的配置信息 connWifiConfig = createWifiConfig(ssid, pwd, wType, true); // -- LogPrintUtils.dTag(TAG, "属于正常方式连接(DHCP)"); } else { // 设置静态信息 connWifiConfig = staticWifiConfig; // -- LogPrintUtils.dTag(TAG, "属于静态IP方式连接"); } } else { // 创建正常的配置信息 connWifiConfig = createWifiConfig(ssid, pwd, wType, true); // -- LogPrintUtils.dTag(TAG, "属于正常方式连接(DHCP)"); } // 判断当前准备连接的wifi,是否存在配置文件 WifiConfiguration preWifiConfig = this.isExsits(ssid); // -- if(preWifiConfig != null){ // 存在则删除 boolean isRemove = mWifiManager.removeNetwork(preWifiConfig.networkId); // 打印结果 LogPrintUtils.dTag(TAG, "删除旧的配置信息 - " + preWifiConfig.SSID + ", isRemove: " + isRemove); // 保存配置 mWifiManager.saveConfiguration(); } // -- // 连接网络 int _nId = mWifiManager.addNetwork(connWifiConfig); if(_nId != -1){ try { // 获取当前连接的Wifi对象 WifiInfo wifiInfo = getWifiInfo(); // 获取连接的id int networdId = wifiInfo.getNetworkId(); // 禁用网络 boolean isDisable = mWifiManager.disableNetwork(networdId); // 断开之前的连接 boolean isDisConnect = mWifiManager.disconnect(); // 打印断开连接结果 LogPrintUtils.dTag(TAG, "isDisConnect : " + isDisConnect + ", isDisable : " + isDisable); } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "quickConnWifi - 关闭连接出错:" + _nId); } // 开始连接 boolean isResult = mWifiManager.enableNetwork(_nId, true); // -- if(!isResult){ isResult = mWifiManager.enableNetwork(_nId, true); } // 打印结果 LogPrintUtils.dTag(TAG, "addNetwork(enableNetwork) - result : " + isResult); } else { // 尝试不带引号SSID连接 connWifiConfig.SSID = formatSSID(connWifiConfig.SSID, false); // 连接网络 _nId = mWifiManager.addNetwork(connWifiConfig); if(_nId !=-1){ try { // 获取当前连接的Wifi对象 WifiInfo wifiInfo = getWifiInfo(); // 获取连接的id int networdId = wifiInfo.getNetworkId(); // 禁用网络 boolean isDisable = mWifiManager.disableNetwork(networdId); // 断开之前的连接 boolean isDisConnect = mWifiManager.disconnect(); // 打印断开连接结果 LogPrintUtils.dTag(TAG, "isDisConnect : " + isDisConnect + ", isDisable : " + isDisable); } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "quickConnWifi - 关闭连接出错:" + _nId); } // 开始连接 boolean isResult = mWifiManager.enableNetwork(_nId, true); // -- if(!isResult){ isResult = mWifiManager.enableNetwork(_nId, true); } // 打印结果 LogPrintUtils.dTag(TAG, "addNetwork(enableNetwork) - result : " + isResult); } } // 保存id connWifiConfig.networkId = _nId; // 连接的networkId LogPrintUtils.dTag(TAG, "连接的SSID - networkId : " + _nId); // 返回连接的信息 return connWifiConfig; } catch (Exception e){ LogPrintUtils.eTag(TAG, "quickConnWifi", e); } return null; } /** * 创建Wifi配置信息(无其他操作,单独返回WifiConfig) * @param ssid * @param pwd * @param wType * @param isHandler 是否处理双引号 */ public static WifiConfiguration createWifiConfig(String ssid, String pwd, int wType, boolean isHandler) { try { // 创建一个新的网络配置 WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.allowedAuthAlgorithms.clear(); wifiConfig.allowedGroupCiphers.clear(); wifiConfig.allowedKeyManagement.clear(); wifiConfig.allowedPairwiseCiphers.clear(); wifiConfig.allowedProtocols.clear(); wifiConfig.priority = 0; /** 设置连接的SSID */ if (isHandler) { wifiConfig.SSID = formatSSID(ssid, true); } else { wifiConfig.SSID = ssid; } switch(wType){ case WifiUtils.NOPWD: // 不存在密码 wifiConfig.hiddenSSID = true; wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE); break; case WifiUtils.WEP: // WEP 加密方式 wifiConfig.hiddenSSID = true; if (isHandler) { if (isHexWepKey(pwd)) { wifiConfig.wepKeys[0] = pwd; } else { wifiConfig.wepKeys[0] = "\"" + pwd + "\""; } } else { wifiConfig.wepKeys[0] = pwd; } wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE); wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); // wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); wifiConfig.wepTxKeyIndex = 0; break; case WifiUtils.WPA: // WPA 加密方式 if (isHandler) { wifiConfig.preSharedKey = "\"" + pwd + "\""; } else { wifiConfig.preSharedKey = pwd; } wifiConfig.hiddenSSID = true; wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wifiConfig.allowedKeyManagement.set(KeyMgmt.WPA_PSK); // wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wifiConfig.status = WifiConfiguration.Status.ENABLED; break; } return wifiConfig; } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "createWifiConfig"); } return null; } // ==================== 连接操作 ======================== /** * 移除某个Wifi配置信息 * @param wcg * @return */ public boolean removeWifiConfig(WifiConfiguration wcg){ // 如果等于null则直接返回 if(wcg == null) return false; try { // 删除配置 boolean isResult = mWifiManager.removeNetwork(wcg.networkId); // 保存操作 mWifiManager.saveConfiguration(); // 返回删除结果 return isResult; } catch (Exception e){ LogPrintUtils.eTag(TAG, "removeWifiConfig", e); } return false; } /** * 断开指定ID的网络 * @param netId wifiid */ public void disconnectWifi(int netId) { try { mWifiManager.disableNetwork(netId); mWifiManager.disconnect(); } catch (Exception e){ LogPrintUtils.eTag(TAG, "disconnectWifi", e); } } // ========================== 设置静态ip,域名,等信息 ===================================== /** * 设置静态Wifi信息 * @param wifiConfig Wifi配置信息 * @param ip 静态ip * @return */ private WifiConfiguration setStaticWifiConfig(WifiConfiguration wifiConfig, String ip){ String gateway = null; String dns = null; if(ip != null){ try { InetAddress intetAddress = InetAddress.getByName(ip); int intIp = inetAddressToInt(intetAddress); dns = (intIp & 0xFF) + "." + ((intIp >> 8) & 0xFF) + "." + ((intIp >> 16) & 0xFF) + ".1"; gateway = dns; } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "setStaticWifiConfig"); return null; } } // 暂时不需要设置dns,所以dns参数传入null return setStaticWifiConfig(wifiConfig, ip, gateway, null, 24); } /** * 设置静态Wifi信息 * @param wifiConfig Wifi配置信息 * @param ip 静态ip * @param gateway 网关 * @param dns dns * @param networkPrefixLength 网络前缀长度 * @return */ private WifiConfiguration setStaticWifiConfig(WifiConfiguration wifiConfig, String ip, String gateway, String dns, int networkPrefixLength){ try { if(ip == null || gateway == null){ return null; } // 设置Inet地址 InetAddress intetAddress = InetAddress.getByName(ip); if(Build.VERSION.SDK_INT <= 20){ // 旧的版本,5.0之前 // 设置IP分配方式,静态ip setEnumField(wifiConfig, "STATIC", "ipAssignment"); // 设置不用代理 setEnumField(wifiConfig, "NONE", "proxySettings"); // 设置ip地址 setIpAddress(intetAddress, networkPrefixLength, wifiConfig); // 设置网关 setGateway(InetAddress.getByName(gateway), wifiConfig); if(dns != null){ // 判断是否需要设置域名 // 设置DNS setDNS(InetAddress.getByName(dns), wifiConfig); } } else { // 5.0新版本改变到其他地方 Object obj = getDeclaredField(wifiConfig, "mIpConfiguration"); // 设置IP分配方式,静态ip setEnumField(obj, "STATIC", "ipAssignment"); // 设置不用代理 setEnumField(obj, "NONE", "proxySettings"); // 设置ip地址、网关、DNS setStaticIpConfig(ip, gateway, dns, networkPrefixLength, obj); } return wifiConfig; } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "setStaticWifiConfig"); } return null; } private int inetAddressToInt(InetAddress inetAddr) throws Exception { byte[] addr = inetAddr.getAddress(); if (addr.length != 4) { throw new IllegalArgumentException("Not an IPv4 address"); } return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) | ((addr[1] & 0xff) << 8) | (addr[0] & 0xff); } /** * 设置DNS * @param dns * @param wifiConfig * @throws Exception */ private void setDNS(InetAddress dns, WifiConfiguration wifiConfig) throws Exception { Object linkProperties = getField(wifiConfig, "linkProperties"); if (linkProperties == null) throw new NullPointerException(); ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(linkProperties, "mDnses"); mDnses.clear(); // or add a new dns address , here I just want to replace DNS1 mDnses.add(dns); } /** * 设置网关 * @param gateway * @param wifiConfig * @throws Exception */ private void setGateway(InetAddress gateway, WifiConfiguration wifiConfig) throws Exception { Object linkProperties = getField(wifiConfig, "linkProperties"); if (linkProperties == null) throw new NullPointerException(); Class routeInfoClass = Class.forName("android.net.RouteInfo"); Constructor routeInfoConstructor = routeInfoClass.getConstructor(new Class[] { InetAddress.class }); Object routeInfo = routeInfoConstructor.newInstance(gateway); ArrayList mRoutes = (ArrayList) getDeclaredField(linkProperties, "mRoutes"); mRoutes.clear(); mRoutes.add(routeInfo); } /** * 设置Ip地址 * @param addr ip地址 * @param prefixLength 网络前缀长度 * @param wifiConfig Wifi配置信息 * @throws Exception */ private void setIpAddress(InetAddress addr, int prefixLength, WifiConfiguration wifiConfig) throws Exception { Object linkProperties = getField(wifiConfig, "linkProperties"); if (linkProperties == null) throw new NullPointerException(); Class laClass = Class.forName("android.net.LinkAddress"); Constructor laConstructor = laClass.getConstructor(new Class[] { InetAddress.class, int.class }); Object linkAddress = laConstructor.newInstance(addr, prefixLength); ArrayList mLinkAddresses = (ArrayList) getDeclaredField(linkProperties, "mLinkAddresses"); mLinkAddresses.clear(); mLinkAddresses.add(linkAddress); } /** * 设置Ip地址、网关、DNS(5.0之后) * @param ip 静态ip * @param gateway 网关 * @param dns dns * @param prefixLength 网络前缀长度 * @param obj Wifi配置信息 * @throws Exception */ private void setStaticIpConfig(String ip, String gateway, String dns, int prefixLength, Object obj) throws Exception { // 从WifiConfig -> mIpConfiguration 获取staticIpConfiguration // 获取 staticIpConfiguration 变量 Object staticIpConfigClass = getField(obj, "staticIpConfiguration"); if(staticIpConfigClass == null){ // 创建静态ip配置类 staticIpConfigClass = Class.forName("android.net.StaticIpConfiguration").newInstance(); } // 初始化LinkAddress 并设置ip地址 Class laClass = Class.forName("android.net.LinkAddress"); Constructor laConstructor = laClass.getConstructor(new Class[] { InetAddress.class, int.class }); Object linkAddress = laConstructor.newInstance(InetAddress.getByName(ip), prefixLength); // 设置地址ip地址 ipAddress setValueField(staticIpConfigClass, linkAddress, "ipAddress"); // 设置网关 gateway setValueField(staticIpConfigClass, InetAddress.getByName(gateway), "gateway"); if(dns != null){ // 判断是否需要设置域名 // 设置DNS ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(staticIpConfigClass, "dnsServers"); mDnses.clear(); // or add a new dns address , here I just want to replace DNS1 mDnses.add(InetAddress.getByName(dns)); } // 设置赋值 staticIpConfiguration 属性 setValueField(obj, staticIpConfigClass, "staticIpConfiguration"); } /** * 通过反射获取public字段 * @param obj * @param name * @return * @throws Exception */ private Object getField(Object obj, String name) throws Exception { Field f = obj.getClass().getField(name); Object out = f.get(obj); return out; } /** * 通过反射获取全部字段 * @param obj * @param name * @return * @throws Exception */ private Object getDeclaredField(Object obj, String name) throws Exception { Field f = obj.getClass().getDeclaredField(name); f.setAccessible(true); Object out = f.get(obj); return out; } /** * 通过反射枚举类,进行设置 * @param obj 设置对象 * @param value 设置参数值 * @param name 变量名 * @throws Exception 抛出异常 */ private void setEnumField(Object obj, String value, String name) throws Exception { Field f = obj.getClass().getField(name); f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value)); } /** * 通过反射,进行设置 * @param obj 设置对象 * @param val 设置参数值 * @param name 变量名 * @throws Exception 抛出异常 */ private void setValueField(Object obj, Object val, String name) throws Exception { Field f = obj.getClass().getField(name); f.set(obj, val); } }
923b748296d59d65bdcf5c751b76549d368231da
645
java
Java
java-spring/accounts-command-side-web/src/main/java/net/chrisrichardson/eventstore/javaexamples/banking/web/commandside/accounts/CreateAccountRequest.java
igorborojevic/event-sourcing-examples
c5778b1379309525c878757ca331c3c3c4026b75
[ "Apache-2.0" ]
1
2017-01-18T15:52:32.000Z
2017-01-18T15:52:32.000Z
java-spring/accounts-command-side-web/src/main/java/net/chrisrichardson/eventstore/javaexamples/banking/web/commandside/accounts/CreateAccountRequest.java
piyush-kansal/event-sourcing-examples
e488df3d064e3ebc08ce9dfa965cb9ff93a411a4
[ "Apache-2.0" ]
null
null
null
java-spring/accounts-command-side-web/src/main/java/net/chrisrichardson/eventstore/javaexamples/banking/web/commandside/accounts/CreateAccountRequest.java
piyush-kansal/event-sourcing-examples
e488df3d064e3ebc08ce9dfa965cb9ff93a411a4
[ "Apache-2.0" ]
null
null
null
21.5
85
0.782946
999,608
package net.chrisrichardson.eventstore.javaexamples.banking.web.commandside.accounts; import javax.validation.constraints.NotNull; import javax.validation.constraints.DecimalMin; import java.math.BigDecimal; public class CreateAccountRequest { @NotNull @DecimalMin("0") private BigDecimal initialBalance; public CreateAccountRequest() { } public CreateAccountRequest(BigDecimal initialBalance) { this.initialBalance = initialBalance; } public BigDecimal getInitialBalance() { return initialBalance; } public void setInitialBalance(BigDecimal initialBalance) { this.initialBalance = initialBalance; } }
923b74a9724568e8725eeda01440e194efaaeaae
1,069
java
Java
modules/openmrs/api/src/main/java/org/motechproject/openmrs/security/OpenMRSSession.java
mestatrit/motech-usm.commcare-openmrs
272287ff06a75ce86cf2f9b71199af3cb67b1135
[ "BSD-3-Clause" ]
null
null
null
modules/openmrs/api/src/main/java/org/motechproject/openmrs/security/OpenMRSSession.java
mestatrit/motech-usm.commcare-openmrs
272287ff06a75ce86cf2f9b71199af3cb67b1135
[ "BSD-3-Clause" ]
null
null
null
modules/openmrs/api/src/main/java/org/motechproject/openmrs/security/OpenMRSSession.java
mestatrit/motech-usm.commcare-openmrs
272287ff06a75ce86cf2f9b71199af3cb67b1135
[ "BSD-3-Clause" ]
1
2022-03-27T01:57:32.000Z
2022-03-27T01:57:32.000Z
32.393939
108
0.735267
999,609
package org.motechproject.openmrs.security; import org.motechproject.mrs.security.MRSSecurityUser; import org.openmrs.api.context.Context; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; public class OpenMRSSession { public void open() { Context.openSession(); } public void authenticate() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); MRSSecurityUser principal = (MRSSecurityUser) authentication.getPrincipal(); Context.authenticate(principal.getUsername(), principal.getPassword()); } public void close() { Context.closeSession(); } public static OpenMRSSecurityUser login(String userName, String password) { Context.openSession(); Context.authenticate(userName, password); OpenMRSSecurityUser openMRSUser = new OpenMRSSecurityUser(Context.getAuthenticatedUser(), password); Context.closeSession(); return openMRSUser; } }
923b7522a89eada5ad70976616a02700fef72978
1,861
java
Java
src/main/java/es/upm/miw/apaw_practice/adapters/mongodb/property/persistence/ProprietorPersistenceMongodb.java
helderhernandez/apaw-practice
38fbe250f5ff21f2503ab129e243c2cbecf312d9
[ "MIT" ]
null
null
null
src/main/java/es/upm/miw/apaw_practice/adapters/mongodb/property/persistence/ProprietorPersistenceMongodb.java
helderhernandez/apaw-practice
38fbe250f5ff21f2503ab129e243c2cbecf312d9
[ "MIT" ]
null
null
null
src/main/java/es/upm/miw/apaw_practice/adapters/mongodb/property/persistence/ProprietorPersistenceMongodb.java
helderhernandez/apaw-practice
38fbe250f5ff21f2503ab129e243c2cbecf312d9
[ "MIT" ]
null
null
null
39.595745
100
0.732402
999,610
package es.upm.miw.apaw_practice.adapters.mongodb.property.persistence; import es.upm.miw.apaw_practice.adapters.mongodb.property.daos.ProprietorRepository; import es.upm.miw.apaw_practice.adapters.mongodb.property.entities.ProprietorEntity; import es.upm.miw.apaw_practice.domain.exceptions.NotFoundException; import es.upm.miw.apaw_practice.domain.models.property.Proprietor; import es.upm.miw.apaw_practice.domain.persistence_ports.property.ProprietorPersistence; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.stream.Stream; @Repository("proprietorPersistence") public class ProprietorPersistenceMongodb implements ProprietorPersistence { private final ProprietorRepository proprietorRepository; @Autowired public ProprietorPersistenceMongodb(ProprietorRepository proprietorRepository) { this.proprietorRepository = proprietorRepository; } public Stream<Proprietor> readAll() { return this.proprietorRepository.findAll().stream() .map(proprietorEntity -> proprietorEntity.toProprietor()); } //@Override public Proprietor update(Proprietor proprietor) { ProprietorEntity proprietorEntity = this.proprietorRepository .findByDni(proprietor.getDni()) .orElseThrow(() -> new NotFoundException("Proprietor dni: " + proprietor.getDni())); proprietorEntity.fromProprietor(proprietor); return this.proprietorRepository .save(proprietorEntity) .toProprietor(); } //@Override public Proprietor readByDni(String dni) { return this.proprietorRepository .findByDni(dni) .orElseThrow(() -> new NotFoundException("Student dni: " + dni)) .toProprietor(); } }
923b75f42eb78b7725a3d9a1c6493e62fb8d4643
7,919
java
Java
platforms/android/app/build/generated/source/r/debug/android/support/compat/R.java
richardg7/EBAula-App
7f162c7a33e9b3acbd8182ae82f3cbd50aecea4a
[ "Apache-2.0" ]
null
null
null
platforms/android/app/build/generated/source/r/debug/android/support/compat/R.java
richardg7/EBAula-App
7f162c7a33e9b3acbd8182ae82f3cbd50aecea4a
[ "Apache-2.0" ]
null
null
null
platforms/android/app/build/generated/source/r/debug/android/support/compat/R.java
richardg7/EBAula-App
7f162c7a33e9b3acbd8182ae82f3cbd50aecea4a
[ "Apache-2.0" ]
null
null
null
59.097015
126
0.74719
999,611
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.compat; public final class R { public static final class attr { public static final int font = 0x7f010004; public static final int fontProviderAuthority = 0x7f010005; public static final int fontProviderCerts = 0x7f010006; public static final int fontProviderFetchStrategy = 0x7f010007; public static final int fontProviderFetchTimeout = 0x7f010008; public static final int fontProviderPackage = 0x7f010009; public static final int fontProviderQuery = 0x7f01000a; public static final int fontStyle = 0x7f01000b; public static final int fontWeight = 0x7f01000c; } public static final class bool { public static final int abc_action_bar_embed_tabs = 0x7f020000; } public static final class color { public static final int notification_action_color_filter = 0x7f03000b; public static final int notification_icon_bg_color = 0x7f03000c; public static final int ripple_material_light = 0x7f03000f; public static final int secondary_text_default_material_light = 0x7f030011; } public static final class dimen { public static final int compat_button_inset_horizontal_material = 0x7f040000; public static final int compat_button_inset_vertical_material = 0x7f040001; public static final int compat_button_padding_horizontal_material = 0x7f040002; public static final int compat_button_padding_vertical_material = 0x7f040003; public static final int compat_control_corner_material = 0x7f040004; public static final int notification_action_icon_size = 0x7f040005; public static final int notification_action_text_size = 0x7f040006; public static final int notification_big_circle_margin = 0x7f040007; public static final int notification_content_margin_start = 0x7f040008; public static final int notification_large_icon_height = 0x7f040009; public static final int notification_large_icon_width = 0x7f04000a; public static final int notification_main_column_padding_top = 0x7f04000b; public static final int notification_media_narrow_margin = 0x7f04000c; public static final int notification_right_icon_size = 0x7f04000d; public static final int notification_right_side_padding_top = 0x7f04000e; public static final int notification_small_icon_background_padding = 0x7f04000f; public static final int notification_small_icon_size_as_large = 0x7f040010; public static final int notification_subtext_size = 0x7f040011; public static final int notification_top_pad = 0x7f040012; public static final int notification_top_pad_large_text = 0x7f040013; } public static final class drawable { public static final int notification_action_background = 0x7f050018; public static final int notification_bg = 0x7f050019; public static final int notification_bg_low = 0x7f05001a; public static final int notification_bg_low_normal = 0x7f05001b; public static final int notification_bg_low_pressed = 0x7f05001c; public static final int notification_bg_normal = 0x7f05001d; public static final int notification_bg_normal_pressed = 0x7f05001e; public static final int notification_icon_background = 0x7f05001f; public static final int notification_template_icon_bg = 0x7f050020; public static final int notification_template_icon_low_bg = 0x7f050021; public static final int notification_tile_bg = 0x7f050022; public static final int notify_panel_notification_icon_bg = 0x7f050023; } public static final class id { public static final int action_container = 0x7f060001; public static final int action_divider = 0x7f060002; public static final int action_image = 0x7f060003; public static final int action_text = 0x7f060004; public static final int actions = 0x7f060005; public static final int async = 0x7f060009; public static final int blocking = 0x7f06000b; public static final int chronometer = 0x7f060011; public static final int forever = 0x7f06001a; public static final int icon = 0x7f06001b; public static final int icon_group = 0x7f06001c; public static final int info = 0x7f06001e; public static final int italic = 0x7f06001f; public static final int line1 = 0x7f060022; public static final int line3 = 0x7f060023; public static final int normal = 0x7f060026; public static final int notification_background = 0x7f060027; public static final int notification_main_column = 0x7f060028; public static final int notification_main_column_container = 0x7f060029; public static final int right_icon = 0x7f06002b; public static final int right_side = 0x7f06002c; public static final int tag_transition_group = 0x7f060030; public static final int text = 0x7f060031; public static final int text2 = 0x7f060032; public static final int time = 0x7f060033; public static final int title = 0x7f060034; } public static final class integer { public static final int status_bar_notification_info_maxnum = 0x7f070002; } public static final class layout { public static final int notification_action = 0x7f080000; public static final int notification_action_tombstone = 0x7f080001; public static final int notification_template_custom_big = 0x7f080008; public static final int notification_template_icon_group = 0x7f080009; public static final int notification_template_part_chronometer = 0x7f08000d; public static final int notification_template_part_time = 0x7f08000e; } public static final class string { public static final int status_bar_notification_info_overflow = 0x7f0a0017; } public static final class style { public static final int TextAppearance_Compat_Notification = 0x7f0b0000; public static final int TextAppearance_Compat_Notification_Info = 0x7f0b0001; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0b0003; public static final int TextAppearance_Compat_Notification_Time = 0x7f0b0006; public static final int TextAppearance_Compat_Notification_Title = 0x7f0b0008; public static final int Widget_Compat_NotificationActionContainer = 0x7f0b000a; public static final int Widget_Compat_NotificationActionText = 0x7f0b000b; } public static final class styleable { public static final int[] FontFamily = { 0x7f010005, 0x7f010006, 0x7f010007, 0x7f010008, 0x7f010009, 0x7f01000a }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x01010532, 0x01010533, 0x0101053f, 0x7f010004, 0x7f01000b, 0x7f01000c }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_font = 3; public static final int FontFamilyFont_fontStyle = 4; public static final int FontFamilyFont_fontWeight = 5; } }
923b778ab9ec1e2e6d426590784b0e26004c8556
20,150
java
Java
px-checkout/src/test/java/com/mercadopago/android/px/installments/InstallmentsPresenterTest.java
serguei-ml/px-android
39a671eab63079c1bdd9ff7f53d96b1d3d2a4681
[ "MIT" ]
1
2018-09-12T05:39:00.000Z
2018-09-12T05:39:00.000Z
px-checkout/src/test/java/com/mercadopago/android/px/installments/InstallmentsPresenterTest.java
serguei-ml/px-android
39a671eab63079c1bdd9ff7f53d96b1d3d2a4681
[ "MIT" ]
null
null
null
px-checkout/src/test/java/com/mercadopago/android/px/installments/InstallmentsPresenterTest.java
serguei-ml/px-android
39a671eab63079c1bdd9ff7f53d96b1d3d2a4681
[ "MIT" ]
null
null
null
37.245841
117
0.716873
999,612
package com.mercadopago.android.px.installments; import android.support.annotation.NonNull; import com.mercadopago.android.px.internal.callbacks.OnSelectedCallback; import com.mercadopago.android.px.internal.repository.AmountRepository; import com.mercadopago.android.px.internal.repository.DiscountRepository; import com.mercadopago.android.px.internal.repository.PaymentSettingRepository; import com.mercadopago.android.px.internal.repository.UserSelectionRepository; import com.mercadopago.android.px.internal.util.TextUtil; import com.mercadopago.android.px.mocks.Installments; import com.mercadopago.android.px.mocks.Issuers; import com.mercadopago.android.px.mocks.PayerCosts; import com.mercadopago.android.px.mocks.PaymentMethods; import com.mercadopago.android.px.model.Card; import com.mercadopago.android.px.model.CardInfo; import com.mercadopago.android.px.model.Discount; import com.mercadopago.android.px.model.Installment; import com.mercadopago.android.px.model.Issuer; import com.mercadopago.android.px.model.PayerCost; import com.mercadopago.android.px.model.PaymentMethod; import com.mercadopago.android.px.model.Site; import com.mercadopago.android.px.model.Sites; import com.mercadopago.android.px.model.exceptions.MercadoPagoError; import com.mercadopago.android.px.internal.callbacks.TaggedCallback; import com.mercadopago.android.px.preferences.CheckoutPreference; import com.mercadopago.android.px.preferences.PaymentPreference; import com.mercadopago.android.px.internal.features.InstallmentsPresenter; import com.mercadopago.android.px.internal.features.providers.InstallmentsProvider; import com.mercadopago.android.px.internal.features.InstallmentsActivityView; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class InstallmentsPresenterTest { private MockedView mockedView = new MockedView(); private MockedProvider provider = new MockedProvider(); private InstallmentsPresenter presenter; @Mock private AmountRepository amountRepository; @Mock private PaymentSettingRepository configuration; @Mock private CheckoutPreference checkoutPreference; @Mock private UserSelectionRepository userSelectionRepository; @Mock private DiscountRepository discountRepository; @Before public void setUp() { //Simulation no charge - no discount when(checkoutPreference.getSite()).thenReturn(Sites.ARGENTINA); when(configuration.getCheckoutPreference()).thenReturn(checkoutPreference); when(amountRepository.getAmountToPay()).thenReturn(new BigDecimal(1000)); presenter = new InstallmentsPresenter(amountRepository, configuration, userSelectionRepository, discountRepository); presenter.attachView(mockedView); presenter.attachResourcesProvider(provider); } @Test public void whenPayerCostIsNullThenGetInstallments() { final List<Installment> installments = Installments.getInstallmentsList(); provider.setResponse(installments); final PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); final Issuer issuer = Issuers.getIssuerMLA(); final PaymentPreference paymentPreference = new PaymentPreference(); presenter.setPaymentPreference(paymentPreference); presenter.setCardInfo(getCardInfo()); when(userSelectionRepository.getIssuer()).thenReturn(issuer); when(userSelectionRepository.getPaymentMethod()).thenReturn(paymentMethod); presenter.initialize(); assertTrue(mockedView.headerShown); assertFalse(mockedView.loadingViewShown); assertTrue(mockedView.installmentsShown); } @Test public void whenGetInstallmentsGetEmptyListThenShowError() { final List<Installment> installments = new ArrayList<Installment>(); provider.setResponse(installments); final PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); final Issuer issuer = Issuers.getIssuerMLA(); final PaymentPreference paymentPreference = new PaymentPreference(); presenter.setPaymentPreference(paymentPreference); presenter.setCardInfo(getCardInfo()); when(userSelectionRepository.getIssuer()).thenReturn(issuer); when(userSelectionRepository.getPaymentMethod()).thenReturn(paymentMethod); presenter.initialize(); assertTrue(mockedView.errorShown); assertTrue(provider.noInstallmentsFoundErrorGotten); } @Test public void whenGetInstallmentsGetMoreThanOneElementsThenShowError() { final List<Installment> installments = getThreeInstallmentList(); provider.setResponse(installments); final PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); final Issuer issuer = Issuers.getIssuerMLA(); final PaymentPreference paymentPreference = new PaymentPreference(); presenter.setPaymentPreference(paymentPreference); presenter.setCardInfo(getCardInfo()); when(userSelectionRepository.getIssuer()).thenReturn(issuer); when(userSelectionRepository.getPaymentMethod()).thenReturn(paymentMethod); presenter.initialize(); assertTrue(mockedView.errorShown); assertTrue(provider.multipleInstallmentsErrorGotten); } @Test public void whenPayerCostIsNotNullThenFinishWithPayerCost() { List<PayerCost> payerCosts = PayerCosts.getPayerCostsWithCFT(); PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); Issuer issuer = Issuers.getIssuerMLA(); PaymentPreference paymentPreference = new PaymentPreference(); presenter.setPaymentPreference(paymentPreference); presenter.setCardInfo(getCardInfo()); userSelectionRepository.select(paymentMethod); userSelectionRepository.select(issuer); presenter.setPayerCosts(payerCosts); presenter.initialize(); assertTrue(mockedView.headerShown); assertFalse(mockedView.loadingViewShown); assertTrue(mockedView.installmentsShown); } @Test public void whenInstallmentIsSelectedFinishWithResult() { final List<PayerCost> payerCosts = PayerCosts.getPayerCostsWithCFT(); final PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); final Issuer issuer = Issuers.getIssuerMLA(); final PaymentPreference paymentPreference = new PaymentPreference(); presenter.setPaymentPreference(paymentPreference); presenter.setCardInfo(getCardInfo()); userSelectionRepository.select(paymentMethod); userSelectionRepository.select(issuer); presenter.setPayerCosts(payerCosts); presenter.initialize(); mockedView.simulateInstallmentSelection(0); assertTrue(mockedView.finishWithResult); } @Test public void whenSelectOnInstallmentThenFinishWithPayerCost() { final List<Installment> installments = Installments.getInstallmentsList(); provider.setResponse(installments); final PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); final Issuer issuer = Issuers.getIssuerMLA(); final PaymentPreference paymentPreference = new PaymentPreference(); presenter.setPaymentPreference(paymentPreference); presenter.setCardInfo(getCardInfo()); when(userSelectionRepository.getIssuer()).thenReturn(issuer); when(userSelectionRepository.getPaymentMethod()).thenReturn(paymentMethod); presenter.initialize(); mockedView.simulateInstallmentSelection(0); assertTrue(mockedView.installmentsShown); assertTrue(mockedView.headerShown); assertTrue(mockedView.finishWithResult); assertEquals(installments.get(0).getPayerCosts().get(0), mockedView.selectedPayerCost); } @Test public void whenGetInstallmentFailThenShowError() { MercadoPagoError mercadoPagoError = new MercadoPagoError("Error", true); provider.setResponse(mercadoPagoError); PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); Issuer issuer = Issuers.getIssuerMLA(); PaymentPreference paymentPreference = new PaymentPreference(); presenter.setPaymentPreference(paymentPreference); presenter.setCardInfo(getCardInfo()); when(userSelectionRepository.getIssuer()).thenReturn(issuer); when(userSelectionRepository.getPaymentMethod()).thenReturn(paymentMethod); presenter.initialize(); assertFalse(mockedView.loadingViewShown); assertTrue(mockedView.errorShown); } @Test public void whenRecoverFromFailureThenGetInstallmentsAgain() { MercadoPagoError mercadoPagoError = new MercadoPagoError("Error", true); provider.setResponse(mercadoPagoError); PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); Issuer issuer = Issuers.getIssuerMLA(); PaymentPreference paymentPreference = new PaymentPreference(); presenter.setPaymentPreference(paymentPreference); presenter.setCardInfo(getCardInfo()); when(userSelectionRepository.getIssuer()).thenReturn(issuer); when(userSelectionRepository.getPaymentMethod()).thenReturn(paymentMethod); presenter.initialize(); presenter.recoverFromFailure(); assertFalse(mockedView.loadingViewShown); assertTrue(mockedView.errorShown); assertNotEquals(presenter.getFailureRecovery(), null); } @Test public void whenRecoverFromFailureIsNullThenNotRecoverFromError() { presenter.recoverFromFailure(); assertEquals(presenter.getFailureRecovery(), null); } @Test public void whenPayerCostsSizeIsOneThenFinishWithResult() { final PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); final Issuer issuer = Issuers.getIssuerMLA(); final PaymentPreference paymentPreference = new PaymentPreference(); final List<PayerCost> payerCosts = PayerCosts.getOnePayerCostList(); presenter.setPaymentPreference(paymentPreference); presenter.setCardInfo(getCardInfo()); presenter.setPayerCosts(payerCosts); userSelectionRepository.select(paymentMethod); userSelectionRepository.select(issuer); presenter.initialize(); assertEquals(mockedView.selectedPayerCost, payerCosts.get(0)); assertTrue(mockedView.finishWithResult); } @Test public void whenPayerCostsisEmptyhenShowError() { List<Installment> installments = Installments.getInstallmentsListWithoutPayerCosts(); provider.setResponse(installments); PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); Issuer issuer = Issuers.getIssuerMLA(); PaymentPreference paymentPreference = new PaymentPreference(); presenter.setPaymentPreference(paymentPreference); presenter.setCardInfo(getCardInfo()); when(userSelectionRepository.getIssuer()).thenReturn(issuer); when(userSelectionRepository.getPaymentMethod()).thenReturn(paymentMethod); presenter.initialize(); assertTrue(mockedView.errorShown); assertTrue(provider.noPayerCostFoundErrorGotten); } @Test public void whenPaymentPreferenceHasDefaultPayerCostThenFinishWithResult() { List<PayerCost> payerCosts = PayerCosts.getPayerCostsWithCFT(); PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); Issuer issuer = Issuers.getIssuerMLA(); PaymentPreference paymentPreference = new PaymentPreference(); paymentPreference.setDefaultInstallments(1); presenter.setPaymentPreference(paymentPreference); presenter.setCardInfo(getCardInfo()); presenter.setPayerCosts(payerCosts); userSelectionRepository.select(paymentMethod); userSelectionRepository.select(issuer); presenter.initialize(); assertTrue(mockedView.finishWithResult); assertEquals(mockedView.selectedPayerCost, getPayerCost(payerCosts, paymentPreference.getDefaultInstallments())); } @Test public void whenIsCardInfoAndPaymentMethodAvailableThenIsNotRequiredCardDrawn() { final CardInfo cardInfo = getCardInfo(); final PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); presenter.setCardInfo(cardInfo); when(userSelectionRepository.getPaymentMethod()).thenReturn(paymentMethod); assertTrue(presenter.isRequiredCardDrawn()); } @Test public void whenIsNotPaymentMethodAvailableThenIsNotRequiredCardDrawn() { CardInfo cardInfo = getCardInfo(); presenter.setCardInfo(cardInfo); assertFalse(presenter.isRequiredCardDrawn()); } @Test public void whenIsNotCardInfoAvailableThenIsNotRequiredCardDrawn() { PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); userSelectionRepository.select(paymentMethod); assertFalse(presenter.isRequiredCardDrawn()); } @Test public void whenCardInfoNullThenBinIsNull() { CardInfo cardInfo = null; presenter.setCardInfo(cardInfo); assertTrue(TextUtil.isEmpty(presenter.getBin())); } @Test public void whenMCOThenShowBankInterestsNotCoveredWarning() { PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); Issuer issuer = Issuers.getIssuers().get(0); when(checkoutPreference.getSite()).thenReturn(Sites.COLOMBIA); presenter.setCardInfo(getCardInfo()); when(userSelectionRepository.getIssuer()).thenReturn(issuer); when(userSelectionRepository.getPaymentMethod()).thenReturn(paymentMethod); presenter.initialize(); assertTrue(mockedView.bankInterestsWarningShown); } @Test public void whenNotMCOThenDoNotShowBankInterestsNotCoveredWarning() { PaymentMethod paymentMethod = PaymentMethods.getPaymentMethodOnVisa(); Issuer issuer = Issuers.getIssuers().get(0); presenter.setCardInfo(getCardInfo()); when(userSelectionRepository.getIssuer()).thenReturn(issuer); when(userSelectionRepository.getPaymentMethod()).thenReturn(paymentMethod); presenter.initialize(); assertFalse(mockedView.bankInterestsWarningShown); } private CardInfo getCardInfo() { Card card = new Card(); card.setLastFourDigits("4321"); card.setFirstSixDigits("123456"); return new CardInfo(card); } private List<Installment> getThreeInstallmentList() { List<Installment> installments = new ArrayList<Installment>(); Installment installment = new Installment(); installments.add(installment); installments.add(installment); installments.add(installment); return installments; } private PayerCost getPayerCost(List<PayerCost> payerCosts, Integer defaultInstallments) { PayerCost payerCost = new PayerCost(); for (PayerCost currentPayerCost : payerCosts) { if (defaultInstallments.equals(currentPayerCost.getInstallments())) { payerCost = currentPayerCost; } } return payerCost; } private class MockedProvider implements InstallmentsProvider { private boolean shouldFail; private List<Installment> successfulResponse; private MercadoPagoError failedResponse; private boolean noInstallmentsFoundErrorGotten = false; private boolean noPayerCostFoundErrorGotten = false; private boolean multipleInstallmentsErrorGotten = false; MockedProvider() { successfulResponse = Installments.getInstallmentsList(); failedResponse = new MercadoPagoError("Default mocked error", false); } void setResponse(List<Installment> installments) { shouldFail = false; successfulResponse = installments; } private void setResponse(MercadoPagoError exception) { shouldFail = true; failedResponse = exception; } @Override public void getInstallments(String bin, BigDecimal amount, Long issuerId, String paymentMethodId, Integer differential, TaggedCallback<List<Installment>> taggedCallback) { if (shouldFail) { taggedCallback.onFailure(failedResponse); } else { taggedCallback.onSuccess(successfulResponse); } } @Override public MercadoPagoError getNoInstallmentsFoundError() { this.noInstallmentsFoundErrorGotten = true; return null; } @Override public MercadoPagoError getMultipleInstallmentsFoundForAnIssuerError() { this.multipleInstallmentsErrorGotten = true; return null; } @Override public MercadoPagoError getNoPayerCostFoundError() { this.noPayerCostFoundErrorGotten = true; return null; } } private class MockedView implements InstallmentsActivityView { private boolean installmentsShown = false; private boolean finishWithResult = false; private boolean headerShown = false; private boolean errorShown = false; private boolean loadingViewShown = false; private boolean installmentRecyclerViewShown = false; private PayerCost selectedPayerCost; private OnSelectedCallback<Integer> installmentSelectionCallback; private boolean bankInterestsWarningShown = false; @Override public void showInstallments(List<PayerCost> payerCostList, OnSelectedCallback<Integer> onSelectedCallback) { this.installmentSelectionCallback = onSelectedCallback; this.installmentsShown = true; } @Override public void finishWithResult(PayerCost payerCost) { this.finishWithResult = true; this.selectedPayerCost = payerCost; } @Override public void showLoadingView() { this.loadingViewShown = true; } @Override public void hideLoadingView() { this.loadingViewShown = false; } @Override public void showError(MercadoPagoError error, String requestOrigin) { this.errorShown = true; } @Override public void showHeader() { this.headerShown = true; } @Override public void showInstallmentsRecyclerView() { this.installmentRecyclerViewShown = true; } @Override public void warnAboutBankInterests() { bankInterestsWarningShown = true; } @Override public void showDetailDialog() { // do nothing } @Override public void showDiscountInputDialog() { // do nothing } @Override public void showAmount(@NonNull final DiscountRepository discountRepository, @NonNull final BigDecimal itemsPlusCharges, @NonNull final Site site) { // do nothing } @Override public void onSuccessCodeDiscountCallback(Discount discount) { // do nothing } @Override public void onFailureCodeDiscountCallback() { // do nothing } private void simulateInstallmentSelection(int index) { installmentSelectionCallback.onSelected(index); } } }
923b7884a6fc715b32e25fb5dc421c73951bf6b8
3,487
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/All/DriveConstant.java
edsumpena/SkyStone
dab78c1687547d19171626ec3287ab37082bb4c2
[ "MIT" ]
1
2021-03-08T06:13:03.000Z
2021-03-08T06:13:03.000Z
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/All/DriveConstant.java
edsumpena/SkyStone
dab78c1687547d19171626ec3287ab37082bb4c2
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/All/DriveConstant.java
edsumpena/SkyStone
dab78c1687547d19171626ec3287ab37082bb4c2
[ "MIT" ]
2
2019-11-13T06:29:26.000Z
2020-02-08T20:26:20.000Z
40.546512
141
0.640092
999,613
package org.firstinspires.ftc.teamcode.All; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; public class DriveConstant { public static double WHEEL_ENCODER_COUNTS_PER_REVOLUTION = 383.6; //@TODO Test and find the number of encoder counts for 1 revolution public static double ODOMETRY_ENCODER_COUNTS_PER_REVOLUTION = 1400.0; public static double ODOMETRY_RAD = 2.9; //in cm public static double MECANUM_RAD = 2.0; //in in public static double MOTOR_GEAR_RATIO = 2.0 / 1.0; //@TODO Change the gear ratios [Encoder gear / Wheel gear] 24/40? public static double ODOMETRY_GEAR_RATIO = 1.0 / 1.0; public static String trajectoryString = "Trajectory>>LineTo_Forward:{-34.56,-63.582,0.0},StrafeTo:{-28.578,-22.597,0.0}," + "LineTo_Forward:{45.415,-22.597,0.0},LineTo_Forward:{-7.532,-22.597,0.0},LineTo_Forward:{45.415,-22.597,0.0}," + "StrafeTo:{41.428,-28.578,0.0},LineTo_Reversed:{41.428,-9.526,0.0},SplineTo_Forward:{25.477,-34.56,0.0}," + "SplineTo_Forward:{6.425,-28.578,0.0}||"; public static void writeFile(String filePath, String data) { try { File folder = new File(filePath.substring(0,filePath.lastIndexOf("/") + 1)); folder.mkdirs(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(new File(filePath), true)); outputStreamWriter.write(data); outputStreamWriter.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } } public static void writeSerializedObject(String filePath, Object data) { try { File folder = new File(filePath.substring(0, filePath.lastIndexOf("/") + 1)); new File(filePath).delete(); ObjectOutputStream outputStreamWriter = new ObjectOutputStream(new FileOutputStream(new File(filePath), true)); outputStreamWriter.writeObject(data); outputStreamWriter.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } } public static Object getSerializedObject(String filePath){ Object output = null; try { File folder = new File(filePath.substring(0, filePath.lastIndexOf("/") + 1)); folder.mkdirs(); ObjectInputStream outputStreamReader = new ObjectInputStream(new FileInputStream(new File(filePath))); output = outputStreamReader.readObject(); outputStreamReader.close(); } catch (Exception e) { e.printStackTrace(); } return output; } public static String getString(String filePath){ String output = null; try { File folder = new File(filePath.substring(0, filePath.lastIndexOf("/") + 1)); folder.mkdirs(); ObjectInputStream outputStreamReader = new ObjectInputStream(new FileInputStream(new File(filePath))); output = outputStreamReader.readObject().toString(); outputStreamReader.close(); } catch (Exception e) { e.printStackTrace(); } return output; } }
923b793280674a1b2c9b04e243265ae5ab0d55ef
16,443
java
Java
io.fairyproject.modules/platform.bukkit/bukkit-menu/src/main/java/io/fairyproject/bukkit/menu/Menu.java
LeeGodSRC/fairy
3f40ec5d5569bbe7b336eccae9938b9876847fe0
[ "MIT" ]
20
2021-08-03T23:22:05.000Z
2022-02-13T03:31:30.000Z
io.fairyproject.modules/platform.bukkit/bukkit-menu/src/main/java/io/fairyproject/bukkit/menu/Menu.java
LeeGodSRC/fairy
3f40ec5d5569bbe7b336eccae9938b9876847fe0
[ "MIT" ]
22
2021-08-04T02:45:39.000Z
2022-03-24T16:43:39.000Z
io.fairyproject.modules/platform.bukkit/bukkit-menu/src/main/java/io/fairyproject/bukkit/menu/Menu.java
LeeGodSRC/fairy
3f40ec5d5569bbe7b336eccae9938b9876847fe0
[ "MIT" ]
4
2021-08-03T23:22:23.000Z
2022-03-30T02:22:32.000Z
32.431953
129
0.569178
999,614
/* * MIT License * * Copyright (c) 2021 Imanity * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.fairyproject.bukkit.menu; import com.cryptomorin.xseries.XMaterial; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import lombok.Getter; import lombok.Setter; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import io.fairyproject.bukkit.FairyBukkitPlatform; import io.fairyproject.bukkit.listener.events.Events; import io.fairyproject.bukkit.metadata.Metadata; import io.fairyproject.bukkit.util.BukkitUtil; import io.fairyproject.metadata.MetadataKey; import io.fairyproject.metadata.MetadataMap; import io.fairyproject.util.CC; import io.fairyproject.util.Stacktrace; import io.fairyproject.util.terminable.TerminableConsumer; import io.fairyproject.util.terminable.composite.CompositeTerminable; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; @Getter @Setter public abstract class Menu implements TerminableConsumer { private static final MetadataKey<Menu> METADATA = MetadataKey.create("imanity:menu", Menu.class); private static final Map<Class<? extends Menu>, List<Menu>> MENU_BY_TYPE = new ConcurrentHashMap<>(); private static void addMenu(Menu menu) { List<Menu> list; final Class<? extends Menu> type = menu.getClass(); if (MENU_BY_TYPE.containsKey(type)) { list = MENU_BY_TYPE.get(type); } else { list = new ArrayList<>(); MENU_BY_TYPE.put(type, list); } list.add(menu); } private static void removeMenu(Menu menu) { final Class<? extends Menu> type = menu.getClass(); if (!MENU_BY_TYPE.containsKey(type)) { return; } final List<Menu> list = MENU_BY_TYPE.get(type); list.remove(menu); if (list.isEmpty()) { MENU_BY_TYPE.remove(type); } } public static Menu getMenuByUuid(UUID uuid) { return Metadata.provideForPlayer(uuid).getOrNull(METADATA); } public static <T extends Menu> List<T> getMenusByType(Class<T> type) { List<T> menuList = new ArrayList<>(); for (Menu menu : MENU_BY_TYPE.getOrDefault(type, Collections.emptyList())) { menuList.add(type.cast(menu)); } return menuList; } private Int2ObjectOpenHashMap<Button> buttonsMap = new Int2ObjectOpenHashMap<>(); private final CompositeTerminable compositeTerminable = CompositeTerminable.create(); protected Player player; private Inventory inventory; private boolean opening, rendering, reopening; private long openMillis, lastAccessMillis; private int updateCount; private Button placeholderButton = Button.placeholder(XMaterial.GRAY_STAINED_GLASS_PANE, " "); @NotNull @Override public <T extends AutoCloseable> T bind(@NotNull T terminable) { return this.compositeTerminable.bind(terminable); } protected Menu set(int slot, Button... buttons) { for (int i = 0; i < buttons.length; i++) { this.set(slot + i, buttons[i]); } return this; } protected Menu set(int slot, Button button) { final int limit = this.getSizeLimit(); Preconditions.checkArgument(slot < limit, "slot >= limit(" + limit + ")"); this.buttonsMap.put(slot, button); return this; } protected Menu set(int x, int y, Button... buttons) { for (int i = 0; i < buttons.length; i++) { this.set(getSlot(x, y) + i, buttons[i]); } return this; } protected int findFirstEmpty() { int limit = this.getSizeLimit(); for (int i = 0; i < limit - 1; i++) { if (this.isEmpty(i)) { return i; } } return -1; } protected int findLastEmpty() { int limit = this.getSizeLimit(); for (int i = limit - 1; i > 0; i++) { if (this.isEmpty(i)) { return i; } } return -1; } protected int findFirstEmptyBetween(int minSlot, int maxSlot) { int limit = this.getSizeLimit(); Preconditions.checkArgument(maxSlot < limit, "maxSlot >= limit(" + limit + ")"); Preconditions.checkArgument(minSlot >= 0, "minSlot < 0"); for (int i = minSlot; i < maxSlot; i++) { if (this.isEmpty(i)) { return i; } } return -1; } protected int findLastEmptyBetween(int minSlot, int maxSlot) { int limit = this.getSizeLimit(); Preconditions.checkArgument(maxSlot < limit, "maxSlot >= limit(" + limit + ")"); Preconditions.checkArgument(minSlot >= 0, "minSlot < 0"); for (int i = maxSlot; i < minSlot; i++) { if (this.isEmpty(i)) { return i; } } return -1; } protected List<Integer> findEmptySlots() { List<Integer> result = new ArrayList<>(); int limit = this.getSizeLimit(); for (int i = 0; i < limit; i++) { if (this.isEmpty(i)) { result.add(i); } } return result; } protected List<Integer> findEmptySlotsBetween(int minSlot, int maxSlot) { int limit = this.getSizeLimit(); Preconditions.checkArgument(maxSlot < limit, "maxSlot >= limit(" + limit + ")"); Preconditions.checkArgument(minSlot >= 0, "minSlot < 0"); List<Integer> result = new ArrayList<>(); for (int i = minSlot; i < maxSlot; i++) { if (this.isEmpty(i)) { result.add(i); } } return result; } protected boolean isEmpty(int slot) { return !this.buttonsMap.containsKey(slot); } protected boolean hasItem(int slot) { return !this.isEmpty(slot); } public Menu clear() { this.buttonsMap.clear(); return this; } public void clear(int x, int y) { this.clear(getSlot(x, y)); } public void clear(int slot) { this.buttonsMap.remove(slot); } public Menu clearBetween(int minSlot, int maxSlot) { this.buttonsMap.int2ObjectEntrySet().removeIf(entry -> entry.getIntKey() >= minSlot && entry.getIntKey() <= maxSlot); return this; } public final void open(Player player) { if (this.opening) { throw new IllegalArgumentException("The menu is already opened!"); } this.opening = true; this.openMillis = System.currentTimeMillis(); this.player = player; Metadata.provide(player).put(METADATA, this); Menu.addMenu(this); this.render(true); this.onOpen(player); this.registerListeners(); } public void close() { player.closeInventory(); } public void remove() { if (!this.opening) { return; } if (this.reopening) { return; } this.opening = false; MetadataMap metadataMap = Metadata.provideForPlayer(this.player); Menu existing = metadataMap.getOrNull(METADATA); if (existing == this) { metadataMap.remove(METADATA); } Menu.removeMenu(this); this.compositeTerminable.closeAndReportException(); this.onClose(player); this.player = null; this.buttonsMap.clear(); this.inventory.clear(); } private void registerListeners() { Plugin plugin; try { plugin = JavaPlugin.getProvidingPlugin(this.getClass()); } catch (Throwable ignored) { plugin = FairyBukkitPlatform.PLUGIN; } Events.subscribe(PlayerQuitEvent.class) .priority(EventPriority.HIGH) .filter(event -> event.getPlayer() == this.player) .listen(event -> { Player player = event.getPlayer(); player.closeInventory(); this.remove(); }) .build(plugin) .bindWith(this); Events.subscribe(PlayerDeathEvent.class) .priority(EventPriority.HIGH) .filter(event -> event.getEntity() == this.player) .listen(event -> { Player player = event.getEntity(); player.closeInventory(); this.remove(); }) .build(plugin) .bindWith(this); Events.subscribe(InventoryClickEvent.class) .priority(EventPriority.MONITOR) .filter(event -> event.getInventory().getHolder() != null) .filter(event -> event.getInventory().getHolder().equals(this.player)) .listen(event -> { if (this.player == null) { return; } int slot = event.getSlot(); if (slot != event.getRawSlot()) { if ((event.getClick() == ClickType.SHIFT_LEFT || event.getClick() == ClickType.SHIFT_RIGHT)) { event.setCancelled(true); } return; } if (this.buttonsMap.containsKey(slot)) { Button button = this.buttonsMap.get(slot); boolean cancel = button.shouldCancel(player, slot, event.getClick()); if (!cancel && (event.getClick() == ClickType.SHIFT_LEFT || event.getClick() == ClickType.SHIFT_RIGHT)) { event.setCancelled(true); if (event.getCurrentItem() != null) { player.getInventory().addItem(event.getCurrentItem()); } } else { event.setCancelled(cancel); } button.clicked(player, slot, event.getClick(), event.getHotbarButton()); if (!this.opening) { return; } this.lastAccessMillis = System.currentTimeMillis(); if (event.isCancelled()) { BukkitUtil.delayedUpdateInventory(player); } } else { if ((event.getClick() == ClickType.SHIFT_LEFT || event.getClick() == ClickType.SHIFT_RIGHT)) { event.setCancelled(true); } } }) .build(plugin) .bindWith(this); Events.subscribe(InventoryCloseEvent.class) .priority(EventPriority.HIGH) .filter(event -> event.getInventory().getHolder() != null) .filter(event -> event.getInventory().getHolder().equals(this.player)) .listen(event -> { try { if (this.rerendering) { return; } this.remove(); } catch (Throwable throwable) { Stacktrace.print(throwable); } }) .build(plugin) .bindWith(this); } public final void render() { this.render(false); } private boolean rerendering = false; private void render(boolean firstInitial) { if (this.rendering) { return; } this.lastAccessMillis = System.currentTimeMillis(); Map<Integer, Button> previousButtons = firstInitial ? null : ImmutableMap.copyOf(this.buttonsMap); this.rendering = true; this.draw(firstInitial); this.rendering = false; Inventory inventory = null; int size = this.getSize() == -1 ? this.size(this.buttonsMap) : this.getSize(); String title = CC.translate(this.getTitle()); if (title.length() > 32) { title = title.substring(0, 32); } final InventoryView openInventory = player.getOpenInventory(); String topInventory = openInventory.getTitle(); if (this.inventory != null && title.equals(topInventory) && size == openInventory.getTopInventory().getSize()) { inventory = this.inventory; } boolean recreate = false; if (inventory == null) { inventory = Bukkit.createInventory(player, size, title); recreate = true; } for (final Map.Entry<Integer, Button> buttonEntry : this.buttonsMap.int2ObjectEntrySet()) { int slot = buttonEntry.getKey(); Button button = buttonEntry.getValue(); if (previousButtons == null || previousButtons.get(slot) != button) { inventory.setItem(slot, button.getButtonItem(player)); } } if (previousButtons != null) { for (int slot : previousButtons.keySet()) { if (!this.buttonsMap.containsKey(slot)) { inventory.setItem(slot, null); } } } this.inventory = inventory; if (recreate) { this.rerendering = true; player.closeInventory(); player.openInventory(inventory); this.rerendering = false; } else { player.updateInventory(); } } public abstract void draw(boolean firstInitial); public int size(final Map<Integer, Button> buttons) { int highest = buttons.keySet().stream() .max(Comparator.naturalOrder()) .orElse(0); return (int) (Math.ceil((highest + 1) / 9D) * 9D); } public static int getSlot(final int x, final int y) { return ((9 * y) + x); } public int getSize() { return -1; } public int getSizeLimit() { int size = this.getSize(); if (size == -1) { size = 9 * 6; } return size; } public final <T> List<Button> transformToButtons(Iterable<T> list, Function<T, Button> function) { final ImmutableList.Builder<Button> listBuilder = new ImmutableList.Builder<>(); for (T t : list) { listBuilder.add(function.apply(t)); } return listBuilder.build(); } public abstract String getTitle(); public void onOpen(final Player player) { } public void onClose(final Player player) { } }
923b798a5b0a482b9afd01f0a75e95f42938c6f6
9,315
java
Java
src/main/java/athenarc/imsi/sdl/service/AnalysisService.java
schatzopoulos/SciNeM
ab62c30713281a4ca99af1fc67ad9b512685021c
[ "Apache-2.0" ]
null
null
null
src/main/java/athenarc/imsi/sdl/service/AnalysisService.java
schatzopoulos/SciNeM
ab62c30713281a4ca99af1fc67ad9b512685021c
[ "Apache-2.0" ]
2
2021-05-20T12:13:02.000Z
2022-03-17T22:28:15.000Z
src/main/java/athenarc/imsi/sdl/service/AnalysisService.java
schatzopoulos/SciNeM
ab62c30713281a4ca99af1fc67ad9b512685021c
[ "Apache-2.0" ]
1
2020-09-18T12:21:16.000Z
2020-09-18T12:21:16.000Z
41.7713
202
0.649705
999,615
package athenarc.imsi.sdl.service; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import com.opencsv.CSVParserBuilder; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import org.bson.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import athenarc.imsi.sdl.config.Constants; import athenarc.imsi.sdl.domain.PredefinedMetapath; import athenarc.imsi.sdl.repository.PredefinedMetapathRepository; import athenarc.imsi.sdl.service.util.FileUtil; @Service public class AnalysisService { @Autowired private PredefinedMetapathRepository predefinedMetapathRepository; private final Logger log = LoggerFactory.getLogger(AnalysisService.class); @Async public void submit(String id, ArrayList<String> analyses, List<Document> queries, String primaryEntity, int searchK, int t, int targetId, String dataset, String selectField, int edgesThreshold, double prAlpha, double prTol, int simMinValues, String commAlgorithm, double commThreshold, int commStopCriterion, int commMaxSteps, int commNumOfCommunities, double commRatio) throws java.io.IOException, InterruptedException { // create folder to store results String outputDir = FileUtil.createDir(id); String hdfsOutputDir = Constants.HDFS_BASE_PATH + "/" + id; String outputLog = FileUtil.getLogfile(id); String config = FileUtil.writeConfig(analyses, outputDir, hdfsOutputDir, queries, primaryEntity, searchK, t, targetId, dataset, selectField, edgesThreshold, prAlpha, prTol, simMinValues, commAlgorithm, commThreshold, commStopCriterion, commMaxSteps, commNumOfCommunities, commRatio); ProcessBuilder pb = new ProcessBuilder(); pb.command("/bin/bash", Constants.WORKFLOW_DIR + "analysis/analysis.sh", config); // redirect ouput to logfile File out = new File(outputLog); File err = new File(FileUtil.getErrorLog(id)); pb.redirectOutput(out); pb.redirectError(err); // execute analysis script Process process = pb.start(); int exitCode = process.waitFor(); // write to file that the job has finished FileWriter fileWriter = new FileWriter(outputLog, true); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.print("Exit Code\t" + exitCode); printWriter.close(); log.debug("Analysis task for id: " + id + " exited with code: " + exitCode); } private static void getMeta(Document meta, int totalRecords, int totalPages, int page, String[] headers) { meta.append("totalRecords", totalRecords); meta.append("page", page); meta.append("totalPages", totalPages); meta.append("pageSize", Constants.PAGE_SIZE); Document links = new Document(); links.append("hasNext", (page < totalPages) ? true : false); links.append("hasPrev", (page > 1) ? true : false); meta.append("links", links); meta.append("headers", headers); } public List<Document> getCommunityResults(String analysisFile, Integer page, Document meta) throws IOException { if (page == null) { page = 1; } List<Document> docs = new ArrayList<>(); List<Long> communityPositions = FileUtil.getCommunityPositions(analysisFile); int totalRecords = communityPositions.size(); int totalPages = (int) Math.ceil(((double) totalRecords) / ((double) Constants.PAGE_SIZE)); String[] headers = FileUtil.getHeaders(analysisFile); int firstCommunityIndex = (page - 1) * Constants.PAGE_SIZE; if (firstCommunityIndex < communityPositions.size()) { int communityColumnIndex; for (communityColumnIndex = 0; communityColumnIndex < headers.length; communityColumnIndex++) { if (headers[communityColumnIndex].equals("Community")) break; } boolean reachEnd = communityPositions.size() <= firstCommunityIndex + Constants.PAGE_SIZE; log.debug(reachEnd? "Will reach end":"Will dump 50 entries"); long communityPositionLimit = reachEnd ? -1 : communityPositions.get(firstCommunityIndex + Constants.PAGE_SIZE); RandomAccessFile communityResultsFile = new RandomAccessFile(analysisFile, "r"); // Set<String> communityIds = new HashSet<>(); long currentPosition; String line = null; communityResultsFile.seek(communityPositions.get(firstCommunityIndex)); do { currentPosition = communityResultsFile.getFilePointer(); if ((currentPosition < communityPositionLimit) || reachEnd) { line = communityResultsFile.readLine(); if (line != null) { String[] attributes = line.split("\t"); Document doc = new Document(); for (int i = 0; i < attributes.length; i++) { doc.append(headers[i], attributes[i]); } docs.add(doc); } } } while (((currentPosition < communityPositionLimit) || reachEnd) && (line != null)); } AnalysisService.getMeta(meta, totalRecords, totalPages, page, headers); meta.append("community_counts", totalRecords); return docs; } public List<Document> getResults(String analysisFile, Integer page, Document meta) throws IOException { if (page == null) page = 1; List<Document> docs = new ArrayList<>(); int totalRecords = FileUtil.countLines(analysisFile); int totalPages = FileUtil.totalPages(totalRecords); String[] headers = FileUtil.getHeaders(analysisFile); final int firstRecordNumber = (page - 1) * Constants.PAGE_SIZE + 1; int count = 0; Reader reader = Files.newBufferedReader(Paths.get(analysisFile)); CSVReader csvReader = new CSVReaderBuilder(reader) .withCSVParser(new CSVParserBuilder().withSeparator('\t').build()).withSkipLines(firstRecordNumber) .build(); String[] attributes; while (count < Constants.PAGE_SIZE && ((attributes = csvReader.readNext()) != null)) { // IMPORTANT: the order of the fields is indicated from the headers array in the // metadata section Document doc = new Document(); for (int i = 0; i < attributes.length; i++) { doc.append(headers[i], attributes[i]); } docs.add(doc); count++; } AnalysisService.getMeta(meta, totalRecords, totalPages, page, headers); return docs; } public double getProgress(ArrayList<String> analyses, int stage, float step) { int analysesSize = analyses.size(); // do count combinations Ranking-CD and CD-Ranking as extra analyses in progress if (analyses.contains("Ranking") && analyses.contains("Community Detection")) { analysesSize -= 2; } return (step / 3.0) * (100.0 / (analysesSize + 1)) + (stage - 1) * (100.0 / (analysesSize + 1)); } public Document getCommunityCounts(String detailsFile, List<Document> docs) throws FileNotFoundException, IOException { Document communityCounts = new Document(); Document counts = Document.parse(FileUtil.readJsonFile(detailsFile)); // get number of entities of each community in the results for (Document doc : docs) { System.out.println(doc); String entity = (String) doc.get("Community"); int count = (int) counts.get(entity); communityCounts.append(entity, count); } // add total number of communities communityCounts.append("total", (int) counts.get("total")); return communityCounts; } public void updatePredifinedMetapaths(String dataset, String metapathToUpdate, String key, List<String> entities) { PredefinedMetapath metapath = predefinedMetapathRepository.findFirstByDatasetAndMetapath(dataset, metapathToUpdate); if (metapath != null) { metapath.setTimesUsed(metapath.getTimesUsed() + 1); predefinedMetapathRepository.save(metapath); } else { PredefinedMetapath newMetapath = new PredefinedMetapath(); newMetapath.setDataset(dataset); newMetapath.setKey(key); newMetapath.setMetapath(metapathToUpdate); newMetapath.setEntities(entities); newMetapath.setDescription(""); newMetapath.setTimesUsed(1); newMetapath.setShowit(false); predefinedMetapathRepository.save(newMetapath); } } }
923b7a5eab75b1969ac04d849713f0afca719fda
4,910
java
Java
com/planet_ink/coffee_mud/Abilities/Prayers/Prayer_ProtCurses.java
PeteKeller/CoffeeMud
430081e391df78ae231a02ce8a6e98d4ee8eac75
[ "Apache-2.0" ]
149
2015-01-11T12:55:39.000Z
2022-03-03T16:14:48.000Z
com/planet_ink/coffee_mud/Abilities/Prayers/Prayer_ProtCurses.java
PeteKeller/CoffeeMud
430081e391df78ae231a02ce8a6e98d4ee8eac75
[ "Apache-2.0" ]
42
2015-02-08T03:44:01.000Z
2022-02-10T08:52:43.000Z
com/planet_ink/coffee_mud/Abilities/Prayers/Prayer_ProtCurses.java
PeteKeller/CoffeeMud
430081e391df78ae231a02ce8a6e98d4ee8eac75
[ "Apache-2.0" ]
104
2015-01-21T20:20:55.000Z
2022-03-24T05:01:20.000Z
29.401198
202
0.717515
999,616
package com.planet_ink.coffee_mud.Abilities.Prayers; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2014-2021 Bo Zimmerman 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. */ public class Prayer_ProtCurses extends Prayer { @Override public String ID() { return "Prayer_ProtCurses"; } private final static String localizedName = CMLib.lang().L("Protection Curses"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Protection/Curses)"); @Override public String displayText() { return localizedStaticDisplay; } @Override public int classificationCode() { return Ability.ACODE_PRAYER|Ability.DOMAIN_HOLYPROTECTION; } @Override public int abstractQuality() { return Ability.QUALITY_BENEFICIAL_SELF; } @Override public long flags() { return Ability.FLAG_NEUTRAL; } @Override protected int canAffectCode() { return Ability.CAN_MOBS; } @Override protected int canTargetCode() { return Ability.CAN_MOBS; } @Override public void unInvoke() { // undo the affects of this spell if(!(affected instanceof MOB)) return; final MOB mob=(MOB)affected; super.unInvoke(); if(canBeUninvoked()) mob.tell(L("Your natural defences against curses take over.")); } @Override public void affectCharStats(final MOB affectedMOB, final CharStats affectedStats) { super.affectCharStats(affectedMOB,affectedStats); affectedStats.setStat(CharStats.STAT_SAVE_UNDEAD,affectedStats.getStat(CharStats.STAT_SAVE_UNDEAD)+10); } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!super.okMessage(myHost,msg)) return false; if(!(affected instanceof MOB)) return true; if((msg.target()==affected) &&(msg.tool() instanceof Ability) &&(msg.source()!=affected) &&(msg.targetMinor()==CMMsg.TYP_CAST_SPELL) &&(msg.isTarget(CMMsg.MASK_MALICIOUS)) &&(CMLib.dice().rollPercentage()>50) &&((((Ability)msg.tool()).classificationCode() & Ability.ALL_DOMAINS)==Ability.DOMAIN_CURSING) &&(((Ability)msg.tool()).castingQuality(msg.source(), (MOB)msg.target())==Ability.QUALITY_MALICIOUS)) { msg.source().location().show((MOB)affected,msg.source(),CMMsg.MSG_OK_VISUAL,L("An curse from <T-NAME> against <S-NAME> is magically repelled.")); return false; } return true; } @Override public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(ID())!=null) { failureTell(mob,target,auto,L("<S-NAME> already <S-HAS-HAVE> protection from curses.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> attain(s) a blessed mind and body."):L("^S<S-NAME> @x1 for protection from curses.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 for protection from curses, but nothing happens.",prayWord(mob))); // return whether it worked return success; } }
923b7ab36c1addfc5668dd712c03451423539ff1
1,300
java
Java
src/es/upm/babel/ccjml/samples/readerswriters/java/runenv/Reader.java
rnnalborodo/shared_resources
2fe36c1ecd992b3cb5d79df7bbeff4f01457743f
[ "Unlicense" ]
null
null
null
src/es/upm/babel/ccjml/samples/readerswriters/java/runenv/Reader.java
rnnalborodo/shared_resources
2fe36c1ecd992b3cb5d79df7bbeff4f01457743f
[ "Unlicense" ]
null
null
null
src/es/upm/babel/ccjml/samples/readerswriters/java/runenv/Reader.java
rnnalborodo/shared_resources
2fe36c1ecd992b3cb5d79df7bbeff4f01457743f
[ "Unlicense" ]
null
null
null
24.074074
112
0.688462
999,617
package es.upm.babel.ccjml.samples.readerswriters.java.runenv; import java.util.Calendar; import java.util.logging.Level; import java.util.logging.Logger; import es.upm.babel.ccjml.samples.readerswriters.java.ReadersWriters; import es.upm.babel.ccjml.samples.utils.DataProcessor; import es.upm.babel.cclib.ConcIO; /** * Reader processes ask for permission to read and then read. */ public class Reader extends Thread { private static final java.util.Random random = new java.util.Random(Calendar.getInstance().getTimeInMillis()); /** * Shared resource. */ private final ReadersWriters sharedResource; /** * @param a shared resource to be read from */ public Reader(ReadersWriters a) { sharedResource = a; } /** * Readers ask for permission to read and then read. */ @Override public void run() { int p; while (true) { ConcIO.printfnl("Asking to read "); sharedResource.beforeRead(); ConcIO.printfnl("Granted "); try { Thread.sleep(random.nextInt(1500)); } catch (InterruptedException ex) { Logger.getLogger(DataProcessor.class.getName()).log(Level.SEVERE, null, ex); } finally { } ConcIO.printfnl("Trying to read "); sharedResource.afterRead(); ConcIO.printfnl("read it! "); } } }
923b7b068ab31454264558c6d8bd4a1fd1f32925
7,665
java
Java
src/org/openid4java/message/pape/PapeResponse.java
391328974/openid4java
f1ab66af39488ac1f44e445278c9d420a1597c5e
[ "Apache-2.0" ]
99
2015-07-08T15:38:17.000Z
2020-09-09T20:15:39.000Z
src/org/openid4java/message/pape/PapeResponse.java
391328974/openid4java
f1ab66af39488ac1f44e445278c9d420a1597c5e
[ "Apache-2.0" ]
7
2015-07-08T07:32:38.000Z
2021-09-27T15:36:50.000Z
src/org/openid4java/message/pape/PapeResponse.java
391328974/openid4java
f1ab66af39488ac1f44e445278c9d420a1597c5e
[ "Apache-2.0" ]
62
2015-07-09T11:58:12.000Z
2022-03-30T08:30:01.000Z
29.594595
107
0.608219
999,618
/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.pape; import org.openid4java.message.ParameterList; import org.openid4java.message.MessageException; import org.openid4java.message.Parameter; import org.openid4java.util.InternetDateFormat; import org.openid4java.OpenIDException; import java.util.*; import java.text.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the extension for OpenID Provider Authentication Policy responses. * * @author Marius Scurtescu, Johnny Bufu */ public class PapeResponse extends PapeMessage { private static Log _log = LogFactory.getLog(PapeResponse.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected final static List PAPE_FIELDS = Arrays.asList( new String[] { "auth_policies", "auth_time", }); private static final String AUTH_POLICY_NONE = "http://schemas.openid.net/pape/policies/2007/06/none"; private static InternetDateFormat _dateFormat = new InternetDateFormat(); /** * Constructs a Pape Response with an empty parameter list. */ protected PapeResponse() { set("auth_policies", AUTH_POLICY_NONE); if (DEBUG) _log.debug("Created empty PAPE response."); } /** * Constructs a Pape Response with an empty parameter list. */ public static PapeResponse createPapeResponse() { return new PapeResponse(); } /** * Constructs a Pape Response from a parameter list. * <p> * The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.<extension_alias>." prefix. */ protected PapeResponse(ParameterList params) { super(params); } public static PapeResponse createPapeResponse(ParameterList params) throws MessageException { PapeResponse resp = new PapeResponse(params); resp.validate(); if (DEBUG) _log.debug("Created PAPE response from parameter list:\n" + params); return resp; } /** * Gets the auth_policies parameter value. */ public String getAuthPolicies() { return getParameterValue("auth_policies"); } /** * Sets a new value for the auth_policies parameter. * * The previous value of the parameter will be owerwritten. * * @param policyUris Space separated list of authentication policy * URIs to be set. * @see #addAuthPolicy(String) */ public void setAuthPolicies(String policyUris) { // todo: enforce that policyUri is a valid URI? set("auth_policies", policyUris); } /** * Adds an authentication policy URI to the auth_policies * parameter. * * @param policyUri The authentication policy URI to be set. * @see #setAuthPolicies(String) */ public void addAuthPolicy(String policyUri) { // todo: check that policyUri isn't already in the list? String policies = getAuthPolicies(); if (policies == null || AUTH_POLICY_NONE.equals(policies)) // should never be null setAuthPolicies(policyUri); else setAuthPolicies(policies + " " + policyUri); } /** * Gets a list with the auth_policies. An empty list is * returned if no authentication policies exist. */ public List getAuthPoliciesList() { String policies = getParameterValue("auth_policies"); if (policies == null || AUTH_POLICY_NONE.equals(policies)) // should never be null return new ArrayList(); else return Arrays.asList(policies.split(" ")); } /** * Sets the auth_time parameter. * * @param timestamp The most recent timestamp when the End User has * actively authenticated to the OP in a manner * fitting the asserted policies. */ public void setAuthTime(Date timestamp) { set("auth_time", _dateFormat.format(timestamp)); } /** * Gets the timestamp when the End User has most recentnly authenticated * to the OpenID Provider in a manner fitting the asserted policies. * * @return The verbatim value of the auth_time parameter. * Null is returned if the parameter is not present * in the PapeResponse. * * @see #getAuthDate() */ public String getAuthTime() { return getParameterValue("auth_time"); } /** * Gets the timestamp when the End User has most recentnly authenticated * to the OpenID Provider in a manner fitting the asserted policies. * * @return The value of the auth_time parameter parsed into * a java.util.Date. Null is returned if the parameter * is not present in the PapeResponse, or if the * parameter value is invalid. * * @see #getAuthTime() */ public Date getAuthDate() { String authTime = getParameterValue("auth_time"); if (authTime != null) { try { return _dateFormat.parse(authTime); } catch (ParseException e) { _log.warn("Invalid auth_time: " + authTime + "; returning null."); } } return null; } /** * Checks the validity of the extension. * <p> * Used when constructing a extension from a parameter list. * * @throws MessageException if the PapeResponse is not valid. */ private void validate() throws MessageException { if (! _parameters.hasParameter("auth_policies")) { throw new MessageException( "auth_policies is required in a PAPE response.", OpenIDException.PAPE_ERROR); } String authTime = getAuthTime(); if (authTime != null) { try { _dateFormat.parse(authTime); } catch (ParseException e) { throw new MessageException( "Invalid auth_time in PAPE response: " + authTime, OpenIDException.PAPE_ERROR, e); } } Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { String paramName = ((Parameter) it.next()).getKey(); if (PAPE_FIELDS.contains(paramName) || paramName.startsWith(PapeMessage.AUTH_LEVEL_NS_PREFIX)) continue; if ( paramName.startsWith(AUTH_LEVEL_PREFIX) && (authLevelAliases.values().contains(paramName.substring(AUTH_LEVEL_PREFIX.length())))) continue; throw new MessageException( "Invalid parameter in PAPE response: " + paramName, OpenIDException.PAPE_ERROR); } } public void setCustomAuthLevel(String authLevelTypeUri, String level) { String alias = addAuthLevelExtension(authLevelTypeUri); set(AUTH_LEVEL_PREFIX + alias, level); } public String getCustomAuthLevel(String authLevelTypeUri) { if (hasCustomAuthLevel(authLevelTypeUri)) return getParameterValue(AUTH_LEVEL_PREFIX + getCustomAuthLevelAlias(authLevelTypeUri)); else return null; } }
923b7be411e5a8d32005d05fc37a98ba9b73a0ff
5,717
java
Java
src/main/java/biz/gabrys/lesscss/compiler2/LessVariableOptionsBuilder.java
gabrysbiz/lesscss-compiler
f33cc053d12a044b0ad9587b2afbcf7ca4b02362
[ "BSD-3-Clause" ]
1
2018-07-31T02:26:51.000Z
2018-07-31T02:26:51.000Z
src/main/java/biz/gabrys/lesscss/compiler2/LessVariableOptionsBuilder.java
gabrysbiz/lesscss-compiler
f33cc053d12a044b0ad9587b2afbcf7ca4b02362
[ "BSD-3-Clause" ]
18
2016-04-11T18:32:02.000Z
2018-12-25T12:06:33.000Z
src/main/java/biz/gabrys/lesscss/compiler2/LessVariableOptionsBuilder.java
gabrysbiz/lesscss-compiler
f33cc053d12a044b0ad9587b2afbcf7ca4b02362
[ "BSD-3-Clause" ]
null
null
null
35.509317
196
0.633899
999,619
/* * LessCSS Compiler * http://lesscss-compiler.projects.gabrys.biz/ * * Copyright (c) 2015 Adam Gabrys * * This file is licensed under the BSD 3-Clause (the "License"). * You may not use this file except in compliance with the License. * You may obtain: * - a copy of the License at project page * - a template of the License at https://opensource.org/licenses/BSD-3-Clause */ package biz.gabrys.lesscss.compiler2; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import biz.gabrys.lesscss.compiler2.util.StringUtils; /** * <p> * Creates values of the {@link LessOptions#getGlobalVariables() global} and {@link LessOptions#getModifyVariables() * modify} variables options. The builder allows adding multiple variables with the same name (they are not replaced). * </p> * <p> * Example code: * </p> * * <pre> * Map&lt;String, String&gt; variablesMap = new LinkedHashMap&lt;String, String&gt;(); * variablesMap.put("name1", "value1"); * variablesMap.put("name2", "value2"); * * List&lt;{@link LessVariableOption}&gt; variables = new {@link #LessVariableOptionsBuilder() LessVariableOptionsBuilder}() * .{@link #append(Map) append}(variablesMap) * .{@link #append(CharSequence, CharSequence) append}("name3", "value3") * .{@link #append(LessVariableOption) append}(new {@link LessVariableOption#LessVariableOption(String, String) LessVariableOption}("name2", "value4")) * .{@link #build() build}(); * * System.out.println(variables.get(0)); // name1=value1 * System.out.println(variables.get(1)); // name2=value2 * System.out.println(variables.get(2)); // name3=value3 * System.out.println(variables.get(3)); // name2=value4 * </pre> * * @since 2.0.0 * @see LessOptions */ public class LessVariableOptionsBuilder { private final List<LessVariableOption> variables = new LinkedList<>(); /** * Constructs a new instance. * @since 2.0.0 */ public LessVariableOptionsBuilder() { // do nothing } /** * Appends variables. * @param variables the variables to add (cannot be {@code null}). * @return {@code this} builder. * @throws IllegalArgumentException if the variables is {@code null} or at least one key or value is blank. * @since 2.0.0 */ public LessVariableOptionsBuilder append(final Map<? extends CharSequence, ? extends CharSequence> variables) { if (variables == null) { throw new IllegalArgumentException("Variables cannot be null"); } for (final Entry<? extends CharSequence, ? extends CharSequence> variable : variables.entrySet()) { append(variable.getKey(), variable.getValue()); } return this; } /** * Appends a variable with specified name and value. * @param name the variable name (cannot be blank). * @param value the variable name (cannot be blank). * @return {@code this} builder. * @throws IllegalArgumentException if key or value is blank. * @since 2.0.0 */ public LessVariableOptionsBuilder append(final CharSequence name, final CharSequence value) { getVariables().add(new LessVariableOption(StringUtils.toStringIfNotNull(name), StringUtils.toStringIfNotNull(value))); return this; } /** * Appends variables. * @param variables the variables to add (cannot be {@code null}). * @return {@code this} builder. * @throws IllegalArgumentException if the variables or any contained variable is {@code null}. * @since 2.0.0 */ public LessVariableOptionsBuilder append(final Iterable<? extends LessVariableOption> variables) { if (variables == null) { throw new IllegalArgumentException("Variables cannot be null"); } for (final LessVariableOption variable : variables) { append(variable); } return this; } /** * Appends variables. * @param variables the variables to add (cannot be {@code null}). * @return {@code this} builder. * @throws IllegalArgumentException if the variables or any contained variable is {@code null}. * @since 2.0.0 */ public LessVariableOptionsBuilder append(final LessVariableOption... variables) { if (variables == null) { throw new IllegalArgumentException("Variables cannot be null"); } for (final LessVariableOption variable : variables) { append(variable); } return this; } /** * Appends a variable. * @param variable the variable to add (cannot be {@code null}). * @return {@code this} builder. * @throws IllegalArgumentException if the variable is {@code null}. * @since 2.0.0 */ public LessVariableOptionsBuilder append(final LessVariableOption variable) { if (variable == null) { throw new IllegalArgumentException("Variable cannot be null"); } getVariables().add(variable); return this; } /** * Builds a new list with all appended variables. * @return the new list with all appended variables. * @since 2.0.0 */ public List<LessVariableOption> build() { return new ArrayList<>(getVariables()); } /** * Returns an internal state of the builder. * @return the internal state. * @since 2.0.0 */ protected List<LessVariableOption> getVariables() { return variables; } }
923b7c093e8649a39d12ffa57b194a921489954c
2,104
java
Java
src/main/java/com/github/phylogeny/boundtotems/item/ItemBoundTotemTeleporting.java
Phylogeny/BoundTotems
5103d8ba60f82537f870feec2c6d6c453d00a192
[ "Unlicense" ]
1
2021-12-08T00:02:30.000Z
2021-12-08T00:02:30.000Z
src/main/java/com/github/phylogeny/boundtotems/item/ItemBoundTotemTeleporting.java
Phylogeny/BoundTotems
5103d8ba60f82537f870feec2c6d6c453d00a192
[ "Unlicense" ]
4
2020-05-28T00:55:51.000Z
2020-10-02T01:30:08.000Z
src/main/java/com/github/phylogeny/boundtotems/item/ItemBoundTotemTeleporting.java
Phylogeny/BoundTotems
5103d8ba60f82537f870feec2c6d6c453d00a192
[ "Unlicense" ]
2
2021-12-08T00:02:44.000Z
2021-12-10T09:24:24.000Z
44.765957
116
0.756654
999,620
package com.github.phylogeny.boundtotems.item; import com.github.phylogeny.boundtotems.util.EntityUtil; import com.github.phylogeny.boundtotems.util.NBTUtil; import net.minecraft.network.chat.Component; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; import javax.annotation.Nullable; import java.util.List; public class ItemBoundTotemTeleporting extends ItemBoundTotem { public ItemBoundTotemTeleporting(Properties properties) { super(properties); } @Override public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) { ItemStack stack = player.getItemInHand(hand); InteractionResult result = player.isCrouching() ? InteractionResult.SUCCESS : InteractionResult.PASS; if (!world.isClientSide && result == InteractionResult.SUCCESS) { LivingEntity entity = EntityUtil.rayTraceEntities(world, player, LivingEntity.class); NBTUtil.setBoundLocation(stack, entity != null ? entity : player); } return new InteractionResultHolder<>(result, stack); } @Override public void inventoryTick(ItemStack stack, Level world, Entity entity, int itemSlot, boolean isSelected) { super.inventoryTick(stack, world, entity, itemSlot, isSelected); if (!world.isClientSide && !NBTUtil.hasBoundLocation(stack.getTag()) && entity instanceof LivingEntity) NBTUtil.setBoundLocation(stack, (LivingEntity) entity); } @Override public void appendHoverText(ItemStack stack, @Nullable Level world, List<Component> tooltip, TooltipFlag flag) { super.appendHoverText(stack, world, tooltip, flag); NBTUtil.addBoundLocationInformation(stack, tooltip, flag.isAdvanced()); } }
923b7c6cb065920edba6e036e9b9ace2ed30c5eb
2,485
java
Java
dc-ssh/src/main/java/com/dc/ssh/client/exec/support/CommandFormatter.java
divinecloud/DivineCloud
638fdab7493dd8a1ca8650dabd2a8b8165d1bf34
[ "Apache-2.0" ]
null
null
null
dc-ssh/src/main/java/com/dc/ssh/client/exec/support/CommandFormatter.java
divinecloud/DivineCloud
638fdab7493dd8a1ca8650dabd2a8b8165d1bf34
[ "Apache-2.0" ]
null
null
null
dc-ssh/src/main/java/com/dc/ssh/client/exec/support/CommandFormatter.java
divinecloud/DivineCloud
638fdab7493dd8a1ca8650dabd2a8b8165d1bf34
[ "Apache-2.0" ]
null
null
null
33.133333
124
0.618109
999,621
/* * * * Copyright (C) 2014 Divine Cloud 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.dc.ssh.client.exec.support; import com.dc.ssh.client.SshException; import com.dc.ssh.client.exec.cmd.SingleSshCommand; import com.dc.ssh.client.exec.cmd.script.BaseScriptCommand; import com.dc.ssh.client.exec.cmd.script.ScriptLanguage; import com.dc.ssh.client.support.RunAsAdminSupport; public class CommandFormatter { public static String generateDefaultFileName(ScriptLanguage language, String executionId) { String extension; switch(language) { case Shell: extension = ".sh"; break; case Ruby: extension = ".rb"; break; case Perl: extension = ".pl"; break; case Python: extension = ".py"; break; case Groovy: extension = ".groovy"; break; default: extension = ".txt"; } return executionId + extension; } public static String formatCommand(SingleSshCommand command) { return RunAsAdminSupport.conditionallyAddSuperUser(command.getCommand(), command.runAsUser(), command.runAsAdmin()); } public static String formatCommand(BaseScriptCommand command, String destination) throws SshException { String commandString; String program = command.getInvokingProgram(); if("bash".equals(program)) { program = "bash -e"; } if(command.getArguments() != null) { commandString = program + " " + destination + " " + command.getArguments(); } else { commandString = program + " " + destination; } return RunAsAdminSupport.conditionallyAddSuperUser(commandString, command.runAsUser(), command.runAsAdmin()); } }
923b7c8bd5341445cdb7162aea0b90800f8c4f4e
2,704
java
Java
eventstorm-sql-apt/src/main/java/eu/eventstorm/sql/apt/PojoMapperFactoryGenerator.java
eventstorm-projects/eventstorm
800018ea7ca82fa5bfdf0012cce1ed3e2eb1c1c1
[ "Apache-2.0" ]
null
null
null
eventstorm-sql-apt/src/main/java/eu/eventstorm/sql/apt/PojoMapperFactoryGenerator.java
eventstorm-projects/eventstorm
800018ea7ca82fa5bfdf0012cce1ed3e2eb1c1c1
[ "Apache-2.0" ]
4
2020-06-05T14:50:29.000Z
2022-02-17T11:34:21.000Z
eventstorm-sql-apt/src/main/java/eu/eventstorm/sql/apt/PojoMapperFactoryGenerator.java
eventstorm-projects/eventstorm
800018ea7ca82fa5bfdf0012cce1ed3e2eb1c1c1
[ "Apache-2.0" ]
2
2021-03-15T13:13:58.000Z
2022-02-02T13:42:51.000Z
32.698795
132
0.662859
999,622
package eu.eventstorm.sql.apt; import static eu.eventstorm.sql.apt.Helper.hasAutoIncrementPK; import static eu.eventstorm.sql.apt.Helper.toUpperCase; import static eu.eventstorm.sql.apt.Helper.writeGenerated; import static eu.eventstorm.sql.apt.Helper.writeNewLine; import static eu.eventstorm.sql.apt.Helper.writePackage; import java.io.IOException; import java.io.Writer; import java.util.List; import javax.annotation.processing.ProcessingEnvironment; import javax.tools.JavaFileObject; import eu.eventstorm.sql.apt.log.Logger; import eu.eventstorm.sql.apt.log.LoggerFactory; import eu.eventstorm.sql.apt.model.PojoDescriptor; import eu.eventstorm.sql.jdbc.Mapper; import eu.eventstorm.sql.jdbc.MapperWithAutoIncrement; /** * @author <a href="mailto:efpyi@example.com">Jacques Militello</a> */ final class PojoMapperFactoryGenerator implements Generator { private final Logger logger; PojoMapperFactoryGenerator() { logger = LoggerFactory.getInstance().getLogger(PojoMapperFactoryGenerator.class); } public void generate(ProcessingEnvironment env, SourceCode sourceCode) { sourceCode.forEachByPackage((pack, descriptors) -> { try { create(env, pack, descriptors); } catch (Exception cause) { logger.error("PojoMapperFactoryGenerator -> IOException for [" + pack + "] -> [" + cause.getMessage() + "]", cause); } }); } private void create(ProcessingEnvironment env, String pack, List<PojoDescriptor> descriptors) throws IOException { JavaFileObject object = env.getFiler().createSourceFile(pack + ".Mappers"); Writer writer = object.openWriter(); writePackage(writer, pack); writeGenerated(writer, PojoMapperFactoryGenerator.class.getName()); writer.write("public final class Mappers {"); writeNewLine(writer); for (PojoDescriptor desc : descriptors) { writeNewLine(writer); writer.write(" public static final "); if (hasAutoIncrementPK(desc)) { writer.write(MapperWithAutoIncrement.class.getName()); } else { writer.write(Mapper.class.getName()); } writer.write("<"); writer.write(desc.element().toString()); writer.write("> "); writer.write(toUpperCase(desc.element().getSimpleName().toString())); writer.write(" = new "); writer.write(desc.element().getSimpleName().toString()); writer.write("Mapper();"); writeNewLine(writer); } writeNewLine(writer); writer.write('}'); writer.close(); } }
923b7cbf4912cf3e0d5d79ded17630cd989a68ad
1,049
java
Java
experiments/subjects/math_10/symexe/src/test/org/apache/commons/math3/linear/SparseRealMatrix.java
yannicnoller/hydiff
4df7df1d2f00bf28d6fb2e2ed7a14103084c39f3
[ "MIT" ]
19
2020-05-24T11:55:24.000Z
2022-03-29T08:16:36.000Z
experiments/subjects/math_10/symexe/src/test/org/apache/commons/math3/linear/SparseRealMatrix.java
newthis/hydiff
dd4fe909fb733fdea9f60ce3729a215322c4371a
[ "MIT" ]
1
2022-01-03T11:48:08.000Z
2022-01-04T01:07:39.000Z
experiments/subjects/math_10/symexe/src/test/org/apache/commons/math3/linear/SparseRealMatrix.java
newthis/hydiff
dd4fe909fb733fdea9f60ce3729a215322c4371a
[ "MIT" ]
4
2020-05-24T11:55:26.000Z
2021-03-24T02:20:08.000Z
34.966667
94
0.750238
999,623
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package test.org.apache.commons.math3.linear; /** * Marker interface for {@link RealMatrix} implementations that require sparse backing storage * * @version $Id$ * @since 2.0 * */ public interface SparseRealMatrix extends RealMatrix { }
923b7d75b5fee5ce476c756766fc4fbfcf608d06
5,451
java
Java
JEasyCrypto/src/easycrypto/EasyCryptoAPI.java
aasalo/JEasyCrypto
b5c77aa7d6fb19d835e2f9e9418274863f80be0b
[ "BSD-3-Clause" ]
null
null
null
JEasyCrypto/src/easycrypto/EasyCryptoAPI.java
aasalo/JEasyCrypto
b5c77aa7d6fb19d835e2f9e9418274863f80be0b
[ "BSD-3-Clause" ]
null
null
null
JEasyCrypto/src/easycrypto/EasyCryptoAPI.java
aasalo/JEasyCrypto
b5c77aa7d6fb19d835e2f9e9418274863f80be0b
[ "BSD-3-Clause" ]
null
null
null
33.237805
127
0.691616
999,624
package easycrypto; /** @brief This class is the public interface to the crypting library. The library supports multiple encrypting methods and also decrypts the encrypted text back to plain text.<br /> All the methods in this class are static, so there is no need to instantiate the class. Implementation creates necessary internal objects which do the actual encrypting and decrypting.<br /> Usage: -# Query encryption methods you can use by calling methods(). Resulting string lists the methods separated by comma.</li> -# Encrypt by calling encrypt() using one of the methods returned by methods()</li> -# Decrypt by calling decrypt() using the same method which was used in encrypt()</li> @author Antti Juustila @version 1.0.0 */ public class EasyCryptoAPI { private static final String currentVersion = "1.0.0"; public enum ResultCode { ESuccess, /*!< Text was successfully en/decrypted. */ EError, /*!< There was an error with en/decryption. */ ENotSupported /*!< The method of en/decription is not supported by the library */ } public static class Result { private ResultCode code = ResultCode.ENotSupported; private String result = null; public Result(ResultCode c, String r) { code = c; result = r; } public ResultCode resultCode() { return code; } public String result() { return result; } } /** Encrypts the given plain text and stores it to the parameter to be used by the caller. @param toEncrypt Text to encrypt. @param toStoreTo A string to store the encrypted text to. @param m The method of encryption. @returns Returns success code of the encryption. See Result enum for details. */ public static Result encrypt(final String toEncrypt, final String method, final String key) { try { if (method.equalsIgnoreCase("reverse")) { CryptoMethod theImpl = new ReverseMethod(); if (theImpl.requiresKey() && key.isEmpty()) { return new Result(ResultCode.EError, "Error: encryption key is empty!"); } return theImpl.encrypt(toEncrypt); } else if (method.equalsIgnoreCase("matrix")) { CryptoMethod theImpl = new MatrixMethod(); if (theImpl.requiresKey() && key.isEmpty()) { return new Result(ResultCode.EError, "Error: encryption key is empty!"); } return theImpl.encrypt(toEncrypt); } else if (method.equalsIgnoreCase("cyr")) { CryptoMethod theImpl = new CyrMethod(); if (theImpl.requiresKey() && key.isEmpty()) { return new Result(ResultCode.EError, "Error: encryption key is empty!"); } return theImpl.encrypt(toEncrypt); } else if (method.equalsIgnoreCase("rot13")){ CryptoMethod theImpl = new Rot13Method(); if (theImpl.requiresKey() && key.isEmpty()) { return new Result(ResultCode.EError, "Error: encryption key is empty!"); } return theImpl.encrypt(toEncrypt); } } catch (Exception e) { return new Result(ResultCode.EError, e.getMessage()); } return new Result(ResultCode.ENotSupported, "Error: Method not supported!"); } /** Decrypts the given encrypted text and stores it to the parameter to be used by the caller. @param toDecrypt Text to decrypt. @param toStoreTo A string to store the derypted plain text to. @param m The method of decryption. @returns Returns success code of the decryption. See Result enum for details. */ public static Result decrypt(final String toDecrypt, final String method, final String key) { try { if (method.equalsIgnoreCase("reverse")) { CryptoMethod theImpl = new ReverseMethod(); if (theImpl.requiresKey() && key.isEmpty()) { return new Result(ResultCode.EError, "Error: encryption key is empty!"); } return theImpl.decrypt(toDecrypt); } else if (method.equalsIgnoreCase("matrix")) { CryptoMethod theImpl = new MatrixMethod(); if (theImpl.requiresKey() && key.isEmpty()) { return new Result(ResultCode.EError, "Error: encryption key is empty!"); } return theImpl.decrypt(toDecrypt); } else if (method.equalsIgnoreCase("cyr")) { CryptoMethod theImpl = new CyrMethod(); if (theImpl.requiresKey() && key.isEmpty()) { return new Result(ResultCode.EError, "Error: encryption key is empty!"); } return theImpl.decrypt(toDecrypt); }else if (method.equalsIgnoreCase("rot13")){ CryptoMethod theImpl = new Rot13Method(); return theImpl.decrypt(toDecrypt); } } catch (Exception e) { e.printStackTrace(); return new Result(ResultCode.EError, e.getMessage()); } return new Result(ResultCode.ENotSupported, "Error: Method not supported!"); } /** To query the version of the library. @returns The library version number in the form "1.0.0". */ public static String version() { return currentVersion; } /** To query the supported en/decryption methods of the library. Method returns the supported method names separated by comma. @returns The supported methods in the form "matrix,reverse". */ public static String methods() { String methods = ""; CryptoMethod method = null; try { method = new ReverseMethod(); methods = method.method(); methods += ","; method = new MatrixMethod(); methods += method.method(); method = new CyrMethod(); methods += "," + method.method(); method = new Rot13Method(); methods += "," + method.method(); } catch (Exception e) { // .... } finally { method = null; } return methods; } }
923b7ea5a3d025972b82d400f494e3d9179e2c0b
3,316
java
Java
fmxl/Regla.java
adgaol/thelastjob
4158a64e0587a98feade50eb2c83fd60c461d8d0
[ "Apache-2.0" ]
null
null
null
fmxl/Regla.java
adgaol/thelastjob
4158a64e0587a98feade50eb2c83fd60c461d8d0
[ "Apache-2.0" ]
null
null
null
fmxl/Regla.java
adgaol/thelastjob
4158a64e0587a98feade50eb2c83fd60c461d8d0
[ "Apache-2.0" ]
null
null
null
19.391813
122
0.584439
999,625
package fmxl; import java.util.ArrayList; import java.util.List; /* * 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. */ /** * * @author chema */ public class Regla { private String valor; private List<Simbolo> regla; private String id; private int tam; private List<AccionSemantica> acciones; boolean accionesInsertadas = false; //boolean para almacenar si podemos visualizar la acción semántica en la gramática List<String> valorAtributos;//el valor de los atributos de la acción semántica /** * inicialite the array of symbols */ public Regla() { this.regla = new ArrayList<>(); } /** * * @return the symbols of the rule */ public List<Simbolo> getRegla() { return regla; } /** * * @param regla * the symbols of the rule */ public void setRegla(List<Simbolo> regla) { this.regla = regla; } /** * add a symbol to the rule * @param s * symbol to add */ public void añadir(Simbolo s){ this.regla.add(s); } /** * * @return id of the rule */ public String getId() { return id; } /** * * @param id * id of the rule */ public void setId(String id) { this.id = id; } /** * * @return the value of the rule */ public String getValor() { return valor; } /** * * @param valor * the value of the rule */ public void setValor(String valor) { this.valor = valor; } /** * * @return the size of the rule */ public int getTam() { return tam; } /** * * @param tam * the size of the rule */ public void setTam(int tam) { this.tam = tam; } /** * * @return the string "valor //id//value of the attributes of the semantic action " */ @Override public String toString(){ StringBuilder sb= new StringBuilder(); int i=0; for(String v:valorAtributos){ if(valorAtributos.size()-1==i) sb.append(v); else sb.append(v+"//"); i++; } return valor + " //"+id+"//"+sb.toString(); } /** * * @return semantics actions */ public List<AccionSemantica> getAcciones() { return acciones; } /** * * @param acciones * semantics actions */ public void setAcciones(List<AccionSemantica> acciones) { this.acciones = acciones; } /** * * @return if the semantic action is inserted */ public boolean isAccionesInsertadas() { return accionesInsertadas; } /** * * @param accionesInsertadas * if the semantic action is inserted */ public void setAccionesInsertadas(boolean accionesInsertadas) { this.accionesInsertadas = accionesInsertadas; } /** * * @return value of the attributes of the semantics actions */ public List<String> getValorAtributos() { return valorAtributos; } /** * * @param valorAtributos * value of the attributes of the semantics actions */ public void setValorAtributos(List<String> valorAtributos) { this.valorAtributos = valorAtributos; } }
923b7ee49c009d9a9cbe47ca9eb70e86fe124c47
2,165
java
Java
java/305/Number of Islands II.java
charlienzw/LeetCode
a1c4135d4fb596c7c825b5ba7334e7ef381b1542
[ "MIT" ]
null
null
null
java/305/Number of Islands II.java
charlienzw/LeetCode
a1c4135d4fb596c7c825b5ba7334e7ef381b1542
[ "MIT" ]
null
null
null
java/305/Number of Islands II.java
charlienzw/LeetCode
a1c4135d4fb596c7c825b5ba7334e7ef381b1542
[ "MIT" ]
1
2019-04-01T17:43:52.000Z
2019-04-01T17:43:52.000Z
29.256757
235
0.352887
999,626
//Time: O(klog(mn)) Space: O(mn) class Solution { class UF { private int[] parent; private int[] rank; private int count = 0; public UF(int n) { parent = new int[n + 1]; rank = new int[n + 1]; for(int i = 0; i <= n; i ++) { parent[i] = i; rank[i] = 1; } count = n; } public int find(int u) { while(parent[u] != u) { parent[u] = parent[parent[u]]; u = parent[u]; } return u; } public boolean union(int u, int v) { int pu = find(u); int pv = find(v); if(pu == pv) return false; if(rank[pu] < rank[pv]) { parent[pv] = pu; } else if(rank[pu] > rank[pv]) { parent[pu] = pv; } else { parent[pu] = pv; rank[pu]++; } count --; return true; } public int size() { return count; } } public List<Integer> numIslands2(int m, int n, int[][] positions) { List<Integer> res = new ArrayList<>(); UF uf = new UF(m * n); int[] map = new int[m * n]; int[][] dir = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; for(int i = 0; i < positions.length; i++) { for(int d = 0; d < 4; d++) { if(positions[i][0] + dir[d][0] >= 0 && positions[i][0] + dir[d][0] < m && positions[i][1] + dir[d][1] >= 0 && positions[i][1] + dir[d][1] < n && map[(positions[i][0] + dir[d][0]) * n + positions[i][1] + dir[d][1]] == 1) { uf.union(positions[i][0] * n + positions[i][1], (positions[i][0] + dir[d][0]) * n + positions[i][1] + dir[d][1]); } map[positions[i][0] * n + positions[i][1]] = 1; } res.add(uf.size() - (m * n - i - 1)); } return res; } }
923b8141767844b221dc8e1482b650357dda4f7f
5,985
java
Java
sample/src/main/java/com/github/florent37/materialviewpager/worldmovies/adapter/TrendsGalleryRecycleViewAdapter.java
SIMPLYBOYS/WorldMoviesPro
6480d73b342548ffb26172fcf60497666466faa5
[ "Apache-2.0" ]
1
2018-01-31T03:54:49.000Z
2018-01-31T03:54:49.000Z
sample/src/main/java/com/github/florent37/materialviewpager/worldmovies/adapter/TrendsGalleryRecycleViewAdapter.java
SIMPLYBOYS/WorldMoviesPro
6480d73b342548ffb26172fcf60497666466faa5
[ "Apache-2.0" ]
null
null
null
sample/src/main/java/com/github/florent37/materialviewpager/worldmovies/adapter/TrendsGalleryRecycleViewAdapter.java
SIMPLYBOYS/WorldMoviesPro
6480d73b342548ffb26172fcf60497666466faa5
[ "Apache-2.0" ]
null
null
null
35
126
0.628237
999,627
package com.github.florent37.materialviewpager.worldmovies.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ProgressBar; import com.github.florent37.materialviewpager.worldmovies.R; import com.github.florent37.materialviewpager.worldmovies.framework.ImageTrasformation; import com.github.florent37.materialviewpager.worldmovies.model.TrendsObject; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by aaron on 2016/6/19. */ public class TrendsGalleryRecycleViewAdapter extends RecyclerView.Adapter<TrendsGalleryRecycleViewAdapter.GalleryItemHolder> { private ArrayList<TrendsObject.GalleryItem> mItems; private AdapterView.OnItemClickListener mOnItemClickListener; private int mPlaceholderSize = 0; //default value private ProgressBar mProgressBar; public boolean inAlbum; public TrendsGalleryRecycleViewAdapter(TrendsObject trendsObject, boolean album) { mItems = new ArrayList<TrendsObject.GalleryItem>(); inAlbum = album; } /* * A common adapter modification or reset mechanism. As with LearderBoardListAdapter, * calling notifyDataSetChanged() will trigger the RecyclerView to update * the view. However, this method will not trigger any of the RecyclerView * animation features. */ public void setItemCount(int count) { mItems.clear(); // mItems.addAll(generateDummyData(count)); notifyDataSetChanged(); } /* * Inserting a new item at the head of the list. This uses a specialized * RecyclerView method, notifyItemInserted(), to trigger any enabled item * animations in addition to updating the view. */ public void addItem(int position, TrendsObject.GalleryItem Item) { if (position > mItems.size()) return; mItems.add(position, Item); notifyItemInserted(position); } /* * Inserting a new item at the head of the list. This uses a specialized * RecyclerView method, notifyItemRemoved(), to trigger any enabled item * animations in addition to updating the view. */ public void removeItem(int position) { if (position >= mItems.size()) return; mItems.remove(position); notifyItemRemoved(position); } @Override public GalleryItemHolder onCreateViewHolder(ViewGroup container, int viewType) { LayoutInflater inflater = LayoutInflater.from(container.getContext()); View root = null; if (inAlbum) { root = inflater.inflate(R.layout.album_pic, container, false); } else { root = inflater.inflate(R.layout.gallery_pic, container, false); } mProgressBar = (ProgressBar)root.findViewById(android.R.id.progress); return new GalleryItemHolder(root, this); } @Override public void onBindViewHolder(GalleryItemHolder itemHolder, int position) { TrendsObject.GalleryItem item = mItems.get(position - mPlaceholderSize); if (item!= null) { final String Url = item.getUrl(); if (!Url.isEmpty()) { mProgressBar.setVisibility(View.VISIBLE); itemHolder.bind(itemHolder, item, mProgressBar); } } } @Override public int getItemCount() { return mItems.size(); } public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) { mOnItemClickListener = onItemClickListener; } private void onItemHolderClick(GalleryItemHolder itemHolder) { if (mOnItemClickListener != null) { mOnItemClickListener.onItemClick(null, itemHolder.pictureView, itemHolder.getAdapterPosition(), itemHolder.getItemId()); } } public class GalleryItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TrendsGalleryRecycleViewAdapter mAdapter; private ImageView pictureView; public GalleryItemHolder(View itemView, TrendsGalleryRecycleViewAdapter adapter) { super(itemView); itemView.setOnClickListener(this); mAdapter = adapter; pictureView = (ImageView) itemView.findViewById(R.id.picture); } public void bind(GalleryItemHolder itemHolder, TrendsObject.GalleryItem item, final ProgressBar mProgressBar) { if (inAlbum) { Picasso.with(pictureView.getContext()).load(item.getUrl()).placeholder(R.drawable.placeholder) .transform(ImageTrasformation.getTransformation(itemHolder.pictureView)) .into(pictureView, new Callback() { @Override public void onSuccess() { mProgressBar.setVisibility(View.GONE); } @Override public void onError() { } }); } else { Picasso.with(pictureView.getContext()).load(item.getUrl()).placeholder(R.drawable.placeholder) .fit() .centerCrop() .into(pictureView, new Callback() { @Override public void onSuccess() { mProgressBar.setVisibility(View.GONE); } @Override public void onError() { } }); } } @Override public void onClick(View v) { mAdapter.onItemHolderClick(this); } } }
923b839198a2458a638e19eef2606ad3110d2ea7
197
java
Java
src/main/java/in/ramakant/rpg/domain/exception/NotImplementedYetException.java
rbadolia/rpg-console
5b2bd0fa92e4a64c30c3c1da42b5a2b670d37aa4
[ "MIT" ]
null
null
null
src/main/java/in/ramakant/rpg/domain/exception/NotImplementedYetException.java
rbadolia/rpg-console
5b2bd0fa92e4a64c30c3c1da42b5a2b670d37aa4
[ "MIT" ]
null
null
null
src/main/java/in/ramakant/rpg/domain/exception/NotImplementedYetException.java
rbadolia/rpg-console
5b2bd0fa92e4a64c30c3c1da42b5a2b670d37aa4
[ "MIT" ]
1
2018-10-27T07:30:23.000Z
2018-10-27T07:30:23.000Z
32.833333
79
0.84264
999,628
package in.ramakant.rpg.domain.exception; public class NotImplementedYetException extends UnsupportedOperationException { private static final long serialVersionUID = -8481081981975263094L; }
923b83c4dd26f9b5d4ce27d5cdf3ffca652c8bdb
8,077
java
Java
service-domain-implementations/current-account/src/main/java/com/redhat/mercury/service/currentaccount/model/CRCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis.java
snandakumar87/customer-eligibility-example
ce2bf09d8ed7893a88b503523dace6700b05bd66
[ "Apache-2.0" ]
null
null
null
service-domain-implementations/current-account/src/main/java/com/redhat/mercury/service/currentaccount/model/CRCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis.java
snandakumar87/customer-eligibility-example
ce2bf09d8ed7893a88b503523dace6700b05bd66
[ "Apache-2.0" ]
null
null
null
service-domain-implementations/current-account/src/main/java/com/redhat/mercury/service/currentaccount/model/CRCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis.java
snandakumar87/customer-eligibility-example
ce2bf09d8ed7893a88b503523dace6700b05bd66
[ "Apache-2.0" ]
null
null
null
61.189394
340
0.851059
999,629
package com.redhat.mercury.service.currentaccount.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; /** * CRCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2020-05-08T15:54:56.097-04:00[America/New_York]") public class CRCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis { @JsonProperty("currentAccountFulfillmentArrangementInstanceAnalysisData") private String currentAccountFulfillmentArrangementInstanceAnalysisData; @JsonProperty("currentAccountFulfillmentArrangementInstanceAnalysisReportType") private String currentAccountFulfillmentArrangementInstanceAnalysisReportType; @JsonProperty("currentAccountFulfillmentArrangementInstanceAnalysisReport") private Object currentAccountFulfillmentArrangementInstanceAnalysisReport; public CRCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis currentAccountFulfillmentArrangementInstanceAnalysisData(String currentAccountFulfillmentArrangementInstanceAnalysisData) { this.currentAccountFulfillmentArrangementInstanceAnalysisData = currentAccountFulfillmentArrangementInstanceAnalysisData; return this; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The inputs and results of the instance analysis that can be on-going, periodic and actual and projected * @return currentAccountFulfillmentArrangementInstanceAnalysisData */ @ApiModelProperty(value = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The inputs and results of the instance analysis that can be on-going, periodic and actual and projected ") public String getCurrentAccountFulfillmentArrangementInstanceAnalysisData() { return currentAccountFulfillmentArrangementInstanceAnalysisData; } public void setCurrentAccountFulfillmentArrangementInstanceAnalysisData(String currentAccountFulfillmentArrangementInstanceAnalysisData) { this.currentAccountFulfillmentArrangementInstanceAnalysisData = currentAccountFulfillmentArrangementInstanceAnalysisData; } public CRCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis currentAccountFulfillmentArrangementInstanceAnalysisReportType(String currentAccountFulfillmentArrangementInstanceAnalysisReportType) { this.currentAccountFulfillmentArrangementInstanceAnalysisReportType = currentAccountFulfillmentArrangementInstanceAnalysisReportType; return this; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external performance analysis report available * @return currentAccountFulfillmentArrangementInstanceAnalysisReportType */ @ApiModelProperty(value = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external performance analysis report available ") public String getCurrentAccountFulfillmentArrangementInstanceAnalysisReportType() { return currentAccountFulfillmentArrangementInstanceAnalysisReportType; } public void setCurrentAccountFulfillmentArrangementInstanceAnalysisReportType(String currentAccountFulfillmentArrangementInstanceAnalysisReportType) { this.currentAccountFulfillmentArrangementInstanceAnalysisReportType = currentAccountFulfillmentArrangementInstanceAnalysisReportType; } public CRCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis currentAccountFulfillmentArrangementInstanceAnalysisReport(Object currentAccountFulfillmentArrangementInstanceAnalysisReport) { this.currentAccountFulfillmentArrangementInstanceAnalysisReport = currentAccountFulfillmentArrangementInstanceAnalysisReport; return this; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The external analysis report in any suitable form including selection filters where appropriate * @return currentAccountFulfillmentArrangementInstanceAnalysisReport */ @ApiModelProperty(value = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The external analysis report in any suitable form including selection filters where appropriate ") @Valid public Object getCurrentAccountFulfillmentArrangementInstanceAnalysisReport() { return currentAccountFulfillmentArrangementInstanceAnalysisReport; } public void setCurrentAccountFulfillmentArrangementInstanceAnalysisReport(Object currentAccountFulfillmentArrangementInstanceAnalysisReport) { this.currentAccountFulfillmentArrangementInstanceAnalysisReport = currentAccountFulfillmentArrangementInstanceAnalysisReport; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CRCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis crCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis = (CRCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis) o; return Objects.equals(this.currentAccountFulfillmentArrangementInstanceAnalysisData, crCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis.currentAccountFulfillmentArrangementInstanceAnalysisData) && Objects.equals(this.currentAccountFulfillmentArrangementInstanceAnalysisReportType, crCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis.currentAccountFulfillmentArrangementInstanceAnalysisReportType) && Objects.equals(this.currentAccountFulfillmentArrangementInstanceAnalysisReport, crCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis.currentAccountFulfillmentArrangementInstanceAnalysisReport); } @Override public int hashCode() { return Objects.hash(currentAccountFulfillmentArrangementInstanceAnalysisData, currentAccountFulfillmentArrangementInstanceAnalysisReportType, currentAccountFulfillmentArrangementInstanceAnalysisReport); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CRCurrentAccountFulfillmentArrangementRetrieveOutputModelCurrentAccountFulfillmentArrangementInstanceAnalysis {\n"); sb.append(" currentAccountFulfillmentArrangementInstanceAnalysisData: ").append(toIndentedString(currentAccountFulfillmentArrangementInstanceAnalysisData)).append("\n"); sb.append(" currentAccountFulfillmentArrangementInstanceAnalysisReportType: ").append(toIndentedString(currentAccountFulfillmentArrangementInstanceAnalysisReportType)).append("\n"); sb.append(" currentAccountFulfillmentArrangementInstanceAnalysisReport: ").append(toIndentedString(currentAccountFulfillmentArrangementInstanceAnalysisReport)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
923b843b6bef7508ba067dbaa04b771cc3ac0621
775
java
Java
OnlineBank/Spring/online-bank/src/main/java/edu/prahlad/casestudy/onlinebank/entity/SavingsTransaction.java
MukeshKumarP/CaseStudy
6e937ce27f6f19da826e07dfe097e1fdb7a819bb
[ "MIT" ]
null
null
null
OnlineBank/Spring/online-bank/src/main/java/edu/prahlad/casestudy/onlinebank/entity/SavingsTransaction.java
MukeshKumarP/CaseStudy
6e937ce27f6f19da826e07dfe097e1fdb7a819bb
[ "MIT" ]
19
2021-09-02T13:00:22.000Z
2022-03-02T09:18:49.000Z
OnlineBank/Spring/online-bank/src/main/java/edu/prahlad/casestudy/onlinebank/entity/SavingsTransaction.java
MukeshKumarP/CaseStudy
6e937ce27f6f19da826e07dfe097e1fdb7a819bb
[ "MIT" ]
1
2021-01-30T09:55:59.000Z
2021-01-30T09:55:59.000Z
23.484848
95
0.771613
999,630
package edu.prahlad.casestudy.onlinebank.entity; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.springframework.stereotype.Service; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; @Entity @Getter @Setter @ToString @SequenceGenerator(name ="savingsTransactionId_Seq") public class SavingsTransaction { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "savingsTransactionId_Seq") private Long id; private Date date; private String description; private String type; private String status; private double amount; private BigDecimal availableBalance; @ManyToOne @JoinColumn(name = "savings_account_id") private SavingsAccount savingsAccount; }
923b853721035b5b1e5d124cd5eaca5bbfedbf43
2,320
java
Java
src/main/java/net/superblaubeere27/clientbase/modules/modules/movement/Fly.java
Lehoooo/GatoClient
cd82e968816c93808c232a28cc799068d709d3c2
[ "MIT" ]
null
null
null
src/main/java/net/superblaubeere27/clientbase/modules/modules/movement/Fly.java
Lehoooo/GatoClient
cd82e968816c93808c232a28cc799068d709d3c2
[ "MIT" ]
null
null
null
src/main/java/net/superblaubeere27/clientbase/modules/modules/movement/Fly.java
Lehoooo/GatoClient
cd82e968816c93808c232a28cc799068d709d3c2
[ "MIT" ]
null
null
null
44.615385
463
0.733621
999,631
/* * Copyright (c) 2018 superblaubeere27 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package net.superblaubeere27.clientbase.modules.modules.movement; import com.darkmagician6.eventapi.EventTarget; import net.superblaubeere27.clientbase.events.MotionUpdateEvent; import net.superblaubeere27.clientbase.modules.Module; import net.superblaubeere27.clientbase.modules.ModuleCategory; import net.superblaubeere27.clientbase.valuesystem.ModeValue; public class Fly extends Module { private ModeValue modeValue = new ModeValue("Mode:", "Vanilla", "Vanilla", "Hypixel"); public Fly() { super("Fly", "idk", ModuleCategory.MOVEMENT); } public boolean ShouldFly = false; public void onEnable() { ShouldFly = true; } @EventTarget private void onMove(MotionUpdateEvent event) { if (ShouldFly == true) { mc.thePlayer.capabilities.isFlying = true; } else { if (mc.thePlayer.capabilities.isCreativeMode == false) { mc.thePlayer.capabilities.isFlying = false; mc.thePlayer.capabilities.allowFlying = false; } else if (mc.thePlayer.capabilities.isCreativeMode == true) { mc.thePlayer.capabilities.allowFlying = true; } } } public void onDisable() { ShouldFly = false; } }
923b85d752086e5e3fd1ad35f16f0c449ad49f1f
1,617
java
Java
src/main/java/de/psdev/stabbedandroid/StabbedApplication.java
PSDev/stabbed-android
bc210e79cf5c639df0b4a1fd65420682c786740f
[ "Apache-2.0" ]
7
2015-01-08T14:47:20.000Z
2021-11-11T22:30:43.000Z
src/main/java/de/psdev/stabbedandroid/StabbedApplication.java
PSDev/stabbed-android
bc210e79cf5c639df0b4a1fd65420682c786740f
[ "Apache-2.0" ]
null
null
null
src/main/java/de/psdev/stabbedandroid/StabbedApplication.java
PSDev/stabbed-android
bc210e79cf5c639df0b4a1fd65420682c786740f
[ "Apache-2.0" ]
1
2018-01-17T11:21:05.000Z
2018-01-17T11:21:05.000Z
29.944444
100
0.715523
999,632
/* * Copyright 2013 Philip Schiffer * * 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 de.psdev.stabbedandroid; import android.app.Application; import dagger.ObjectGraph; import java.util.List; public abstract class StabbedApplication extends Application implements StabbedContext { private ObjectGraph mApplicationGraph; @Override public void onCreate() { super.onCreate(); // Create the application graph mApplicationGraph = ObjectGraph.create(getModules().toArray()); // Inject ourselves so subclasses will have dependencies fulfilled when this method returns. inject(this); } /** * A list of modules to use for the application graph. Subclasses can override this method to * provide additional modules provided they call {@code super.getModules()}. */ protected abstract List<Object> getModules(); @Override public void inject(final Object object) { mApplicationGraph.inject(object); } @Override public ObjectGraph getObjectGraph() { return mApplicationGraph; } }
923b86b505977b26f7eb42b1919ece772439ac0e
4,364
java
Java
app/src/main/java/app/meat/view/base/BaseFragment.java
fedka27/meatApp
ffa37b9d48ee4a3cf477c8c44e9caeb1c593ae54
[ "Apache-2.0" ]
null
null
null
app/src/main/java/app/meat/view/base/BaseFragment.java
fedka27/meatApp
ffa37b9d48ee4a3cf477c8c44e9caeb1c593ae54
[ "Apache-2.0" ]
null
null
null
app/src/main/java/app/meat/view/base/BaseFragment.java
fedka27/meatApp
ffa37b9d48ee4a3cf477c8c44e9caeb1c593ae54
[ "Apache-2.0" ]
null
null
null
34.912
100
0.62626
999,633
package app.meat.view.base; import android.content.Context; import android.os.Bundle; import android.support.annotation.DrawableRes; import android.support.annotation.IdRes; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.widget.FrameLayout; import app.meat.util.NotificationUtil; import butterknife.ButterKnife; public abstract class BaseFragment extends Fragment { protected NotificationUtil notificationUtil; private FragmentManager fragmentManager; private Fragment progressFragment; @Override public void onAttach(Context context) { super.onAttach(context); fragmentManager = getActivity().getSupportFragmentManager(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); notificationUtil = new NotificationUtil(getContext(), view); } protected void replaceFragment(@IdRes int containerId, FragmentManager fragmentManager, BaseFragment fragment, boolean addToBackStack) { showFragment(containerId, fragmentManager, fragment, addToBackStack); } protected void replaceFragment(@IdRes int containerId, BaseFragment fragment, boolean addToBackStack) { showFragment(containerId, fragmentManager, fragment, addToBackStack); } protected void replaceFragment(@IdRes int containerId, FragmentManager fragmentManager, BaseFragment fragment) { showFragment(containerId, fragmentManager, fragment, false); } private void showFragment(@IdRes int containerId, FragmentManager fragmentManager, BaseFragment fragment, boolean addToBackStack) { try { ((FrameLayout) getActivity().findViewById(containerId)).removeAllViews(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(containerId, fragment, fragment.getClass().getSimpleName()); if (addToBackStack) { fragmentTransaction.addToBackStack(null); } fragmentTransaction.commit(); this.fragmentManager.executePendingTransactions(); } catch (Exception e) { e.printStackTrace(); } } public void showBaseProgress() { if (progressFragment != null && progressFragment.isVisible()) { return; } progressFragment = fragmentManager.findFragmentByTag("progress"); try { if (progressFragment == null) { progressFragment = new ProgressFragment(); } if (progressFragment.isAdded()) { hideBaseProgress(); } fragmentManager.beginTransaction() .add(getId(), progressFragment, "progress") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commitAllowingStateLoss(); } catch (Exception e) { e.printStackTrace(); hideBaseProgress(); } } public void hideBaseProgress() { if (progressFragment != null) { fragmentManager.beginTransaction() .remove(progressFragment) .commitAllowingStateLoss(); } } protected void setBackground(@DrawableRes int background) { getActivity().getWindow().setBackgroundDrawableResource(background); } @Override public void onPause() { super.onPause(); hideBaseProgress(); } }
923b86ca2d3624a946d58083d840ff0079bdb5f6
177
java
Java
athing-aliyun/athing-aliyun-qatest/src/test/java/com/github/ompc/athing/aliyun/qatest/puppet/component/PersonThingCom.java
xiaoxiao-quick/athing
d894618df13404ffeae72a04ee6d89dfa8bf7736
[ "MIT" ]
null
null
null
athing-aliyun/athing-aliyun-qatest/src/test/java/com/github/ompc/athing/aliyun/qatest/puppet/component/PersonThingCom.java
xiaoxiao-quick/athing
d894618df13404ffeae72a04ee6d89dfa8bf7736
[ "MIT" ]
null
null
null
athing-aliyun/athing-aliyun-qatest/src/test/java/com/github/ompc/athing/aliyun/qatest/puppet/component/PersonThingCom.java
xiaoxiao-quick/athing
d894618df13404ffeae72a04ee6d89dfa8bf7736
[ "MIT" ]
null
null
null
25.285714
62
0.830508
999,634
package com.github.ompc.athing.aliyun.qatest.puppet.component; import com.github.ompc.athing.standard.component.ThingCom; public interface PersonThingCom extends ThingCom { }
923b87da5f1a8f4eee0bafc868949c31569fbf3a
8,867
java
Java
install/pims-web/src/presentation/org/pimslims/utils/ExecRunner.java
chrishmorris/PiMS
cdcc1a5b17b6753a11081bf7163f77596831916c
[ "BSD-2-Clause" ]
null
null
null
install/pims-web/src/presentation/org/pimslims/utils/ExecRunner.java
chrishmorris/PiMS
cdcc1a5b17b6753a11081bf7163f77596831916c
[ "BSD-2-Clause" ]
null
null
null
install/pims-web/src/presentation/org/pimslims/utils/ExecRunner.java
chrishmorris/PiMS
cdcc1a5b17b6753a11081bf7163f77596831916c
[ "BSD-2-Clause" ]
null
null
null
38.219828
112
0.560054
999,635
package org.pimslims.utils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; // import org.apache.commons.logging.Log; // import org.apache.commons.logging.LogFactory; /** * The class allows to run an external executable program from java. Sets an input stream for the executable * program, records an output stream and errors of the program and returns outputstream as a byte array; * * @author Ekaterina Pilicheva * @since 31.03.2006 */ public class ExecRunner { // TODO remove private Log log = LogFactory.getLog(Class.class); // executable command and its arguments String[] commands; /** * public constructor for ExecRunner * * @param command - an array of Strings, starts from an absolute path to the *.exe file to be run, * followed by other command line arguments * @throws ExecRunnerException */ public ExecRunner(final String[] command) { assert !(command == null || command.length < 1); this.commands = command; }// End of ExecRunner /** * the method sets input stream for the executable program, runs executable program in a new created * proccess, logs errors stream info coming out of the program exe, returns output from the executable * program as an array of bytes * * @param inputToDot - InputStream for executable program * @return output after from executable progra * @throws ExecRunnerException */ public byte[] runCommand() throws ExecRunnerException.BadPathException { byte[] res; ProcessBuilder pb = null; Process process = null; InputStream errorFromDotStream = null; InputStream fromDotStream = null; OutputStream toDotStream = null; try { // create and start process pb = new ProcessBuilder(this.commands); process = pb.start(); // get error stream and results stream from process errorFromDotStream = process.getErrorStream(); fromDotStream = process.getInputStream(); // create and start new threads to deal with error and results from // the process final HelperThread errorThread = new HelperThread(errorFromDotStream, "ERROR"); final HelperThread fromDotThread = new HelperThread(fromDotStream, "OUTPUT"); errorThread.start(); fromDotThread.start(); // attach input data to the process toDotStream = process.getOutputStream(); toDotStream.flush(); toDotStream.close(); final int exitCode = process.waitFor(); errorThread.join(1000); fromDotThread.join(1000); // log all error messages from error stream and exceptions from // output stream, // but do not throw an exception final StringBuffer errorMessage = new StringBuffer(); final byte[] errorBuf = errorThread.getResult(); IOException ioexception = null; int i = 0; if (errorBuf != null && errorBuf.length > 0) { while (i < errorBuf.length) { errorMessage.append((char) errorBuf[i]); i++; } // TODO log.warn(errorMessage.toString()); } if ((ioexception = fromDotThread.getProblem()) != null) { errorMessage.append(ioexception.getMessage()); } if (errorMessage.length() > 0) { // TODO log.warn(errorMessage, ioexception); } // Only throw exception if exit code is not 0 if (exitCode != 0) { errorMessage.append(errorThread.getResult()); throw new RuntimeException(errorMessage.toString()); } // get results from the process output thread res = fromDotThread.getResult(); } catch (final IOException ioe) { final String message = ioe.getMessage(); if (message.startsWith("CreateProcess: ") && message.endsWith("error=3")) { throw new ExecRunnerException.BadPathException(message, ioe); } throw new RuntimeException(ioe.getMessage(), ioe); } catch (final InterruptedException ie) { throw new RuntimeException(ie.getMessage(), ie); } return res; }// End of runCommand public byte[] runCommand(final InputStream inputToDot) throws ExecRunnerException.BadPathException { // check input stream is not null //System.out.println("ExecRunner.runCommand"); assert null != inputToDot; byte[] res; ProcessBuilder pb = null; Process process = null; InputStream errorFromDotStream = null; InputStream fromDotStream = null; OutputStream toDotStream = null; try { // create and start process final StringBuffer sb = new StringBuffer(); for (int i = 0; i < this.commands.length; i++) { sb.append(this.commands[i] + " "); } //System.out.println("ExecRunner.runCommand [" + sb.substring(0, sb.length() - 1) + "]"); pb = new ProcessBuilder(this.commands); process = pb.start(); // get error stream and results stream from process errorFromDotStream = process.getErrorStream(); fromDotStream = process.getInputStream(); // create and start new threads to deal with error and results from // the process final HelperThread errorThread = new HelperThread(errorFromDotStream, "ERROR"); final HelperThread fromDotThread = new HelperThread(fromDotStream, "OUTPUT"); errorThread.start(); fromDotThread.start(); // attach input data to the process toDotStream = process.getOutputStream(); int c; while ((c = inputToDot.read()) != -1) { toDotStream.write(c); } toDotStream.flush(); toDotStream.close(); final int exitCode = process.waitFor(); errorThread.join(1000); fromDotThread.join(1000); // log all error messages from error stream and exceptions from // output stream, // but do not throw an exception final StringBuffer errorMessage = new StringBuffer(); final byte[] errorBuf = errorThread.getResult(); IOException ioexception = null; int i = 0; if (errorBuf != null && errorBuf.length > 0) { while (i < errorBuf.length) { errorMessage.append((char) errorBuf[i]); i++; } // TODO log.warn(errorMessage.toString()); } if ((ioexception = fromDotThread.getProblem()) != null) { errorMessage.append(ioexception.getMessage()); } if (errorMessage.length() > 0) { // TODO log.warn(errorMessage, ioexception); } // Only throw exception if exit code is not 0 if (exitCode != 0) { //System.out.println("ExecRunner.runCommand exitCode [" + exitCode + "]"); errorMessage.append(errorThread.getResult()); throw new java.lang.AssertionError("dot failed: " + errorMessage.toString()); } // get results from the process output thread res = fromDotThread.getResult(); } catch (final IOException ioe) { // TODO print process.getErrorStream() final String message = ioe.getMessage(); System.out.println("IOException [" + message + "]"); ioe.printStackTrace(); if (message.startsWith("CreateProcess: ") && message.endsWith("error=3")) { throw new ExecRunnerException.BadPathException(message, ioe); } throw new RuntimeException("Cant run: " + this.commands[0] + " because: " + ioe.getMessage(), ioe); } catch (final InterruptedException ie) { throw new RuntimeException(ie.getMessage(), ie); } finally { try { if (inputToDot != null) { inputToDot.close(); } } catch (final IOException e) { // do nothing } } return res; }// End of runCommand }
923b88b70cb71a44e1d2b222dbc3e1ca020f5047
1,155
java
Java
app/src/main/java/de/binhacken/app/FBMS.java
BinHacken/android_app
84a3a424d62ece1250fdbaf15a62f8e9b3741c66
[ "MIT" ]
null
null
null
app/src/main/java/de/binhacken/app/FBMS.java
BinHacken/android_app
84a3a424d62ece1250fdbaf15a62f8e9b3741c66
[ "MIT" ]
null
null
null
app/src/main/java/de/binhacken/app/FBMS.java
BinHacken/android_app
84a3a424d62ece1250fdbaf15a62f8e9b3741c66
[ "MIT" ]
null
null
null
30.394737
91
0.697835
999,636
package de.binhacken.app; import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import androidx.core.app.NotificationCompat; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import static android.content.ContentValues.TAG; public class FBMS extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage){ Log.i("PVL", "MESSAGE RECEIVED!!"); if (remoteMessage.getNotification().getBody() != null) { Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getNotification().getBody()); } else { Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getData().get("message")); } } @Override public void onNewToken(String token) { Log.d(TAG, "Refreshed token: " + token); // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // Instance ID token to your app server. } }
923b88cc52944e98c99db8ceadd70fc9fbdd7f49
400
java
Java
src/homework/homework1/homework5/AsciiCodeConverter.java
AlexandruBaris/datatypes
22dd4499766a21378402babb184c9f5f9a771c99
[ "MIT" ]
null
null
null
src/homework/homework1/homework5/AsciiCodeConverter.java
AlexandruBaris/datatypes
22dd4499766a21378402babb184c9f5f9a771c99
[ "MIT" ]
null
null
null
src/homework/homework1/homework5/AsciiCodeConverter.java
AlexandruBaris/datatypes
22dd4499766a21378402babb184c9f5f9a771c99
[ "MIT" ]
null
null
null
30.769231
100
0.6675
999,637
package homework.homework1.homework5; import java.util.Scanner; public class AsciiCodeConverter { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an ASCII code: "); byte asciiCode = scanner.nextByte(); System.out.println("The character for ASCII code " + asciiCode + " is " + (char) asciiCode); } }
923b8952dd7f3ab946b4ed67ad22edbf42f3885a
1,438
java
Java
src/controller/ManagePeople.java
Hashadhi/Student-Attendance-System
eaf2ea0baca617955882ea6f6e18a01c962e93f9
[ "MIT" ]
null
null
null
src/controller/ManagePeople.java
Hashadhi/Student-Attendance-System
eaf2ea0baca617955882ea6f6e18a01c962e93f9
[ "MIT" ]
null
null
null
src/controller/ManagePeople.java
Hashadhi/Student-Attendance-System
eaf2ea0baca617955882ea6f6e18a01c962e93f9
[ "MIT" ]
null
null
null
29.958333
90
0.658554
999,638
package controller; import db.DBConnection; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.ToggleGroup; import javafx.stage.Stage; import java.io.IOException; import java.sql.Connection; public class ManagePeople { public Label lblGreeting; public RadioButton rdoManageAdminsUsers; public ToggleGroup ManagePeople; public RadioButton rdoManageStudents; public Button btnGo; public void btnGo_OnAction(ActionEvent actionEvent) { String path = "/view/ManageStudents.fxml"; String target = "Students"; if (rdoManageAdminsUsers.isSelected()) { path = "/view/ManageUsersAndAdmins.fxml"; target = "Admins/Users"; } try { Stage stage = (Stage) btnGo.getScene().getWindow(); stage.setScene(new Scene(FXMLLoader.load(this.getClass().getResource(path)))); stage.setTitle("Student Attendance System: Manage " + target); Platform.runLater(()->{ stage.centerOnScreen(); stage.sizeToScene(); }); stage.setResizable(false); stage.show(); } catch (IOException e) { e.printStackTrace(); } } }
923b896bb1ed0a2b06fb6dc521afa75ba7547fa4
30,299
java
Java
src/com/prupe/mcpatcher/ModList.java
ammoore00/BTWPatcher
1aa45839b2cd029143809edfa60ec59e5ef75f80
[ "MIT" ]
1
2021-12-24T22:40:02.000Z
2021-12-24T22:40:02.000Z
src/com/prupe/mcpatcher/ModList.java
ammoore00/BTWPatcher
1aa45839b2cd029143809edfa60ec59e5ef75f80
[ "MIT" ]
8
2020-05-05T23:47:10.000Z
2021-04-19T03:23:24.000Z
src/com/prupe/mcpatcher/ModList.java
ammoore00/BTWPatcher
1aa45839b2cd029143809edfa60ec59e5ef75f80
[ "MIT" ]
null
null
null
36.548854
163
0.532295
999,639
package com.prupe.mcpatcher; import com.google.gson.JsonObject; import com.prupe.mcpatcher.launcher.version.Library; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipFile; class ModList { static LegacyVersionList legacyVersionList; private final MinecraftVersion version; private final Map<String, BuiltInMod> builtInMods = new LinkedHashMap<String, BuiltInMod>(); private final List<Mod> modsByIndex = new ArrayList<Mod>(); private final Map<String, Mod> modsByName = new HashMap<String, Mod>(); private boolean needReorder; private boolean applied; private class ModDependencyException extends Exception { ModDependencyException(String s) { super(s); } } private static class BuiltInMod { final String name; final Class<? extends Mod> modClass; final ClassLoader loader; boolean internal; boolean experimental; BuiltInMod(LegacyVersionList.Mod entry, ClassLoader loader) throws ClassNotFoundException { this(entry.name, entry.className, loader); setInternal(entry.isInternal()); setExperimental(entry.isExperimental()); } BuiltInMod(String name, String className, ClassLoader loader) throws ClassNotFoundException { this(name, loader.loadClass(className).asSubclass(Mod.class), loader); } BuiltInMod(String name, Class<? extends Mod> modClass, ClassLoader loader) { this.name = name; this.modClass = modClass; this.loader = loader; } BuiltInMod setInternal(boolean internal) { this.internal = internal; return this; } BuiltInMod setExperimental(boolean experimental) { this.experimental = experimental; return this; } } ModList(MinecraftVersion version) throws PatcherException, IOException, ClassNotFoundException { this.version = version; register(new BuiltInMod(MCPatcherUtils.BASE_MOD, BaseMod.class, ClassLoader.getSystemClassLoader()).setInternal(true)); boolean found = false; if (version.compareTo("13w18a") < 0) { if (legacyVersionList == null) { legacyVersionList = getLegacyVersionList(); } if (legacyVersionList != null) { for (LegacyVersionList.Version entry : legacyVersionList.find(MCPatcher.API_VERSION)) { if (version.compareTo(entry.maxMinecraftVersion) <= 0) { ClassLoader loader = getLegacyClassLoader(entry); for (LegacyVersionList.Mod mod : entry.mods) { register(new BuiltInMod(mod, loader)); } found = true; break; } } } } if (!found) { ClassLoader loader; if (Util.devDir == null) { loader = new JarClassLoader("/mods4.jar"); } else { File local = new File(Util.devDir, "out/artifacts/mods4/mods4.jar"); loader = new URLClassLoader(new URL[]{local.toURI().toURL()}); } register(new BuiltInMod(MCPatcherUtils.TEXTURE_PACK_API_MOD, "com.prupe.mcpatcher.mal.TexturePackAPIMod", loader).setInternal(true)); register(new BuiltInMod(MCPatcherUtils.TESSELLATOR_API_MOD, "com.prupe.mcpatcher.mal.TessellatorAPIMod", loader).setInternal(true)); register(new BuiltInMod(MCPatcherUtils.TILESHEET_API_MOD, "com.prupe.mcpatcher.mal.TilesheetAPIMod", loader).setInternal(true)); register(new BuiltInMod(MCPatcherUtils.NBT_API_MOD, "com.prupe.mcpatcher.mal.NBTAPIMod", loader).setInternal(true)); register(new BuiltInMod(MCPatcherUtils.BLOCK_API_MOD, "com.prupe.mcpatcher.mal.BlockAPIMod", loader).setInternal(true)); register(new BuiltInMod(MCPatcherUtils.ITEM_API_MOD, "com.prupe.mcpatcher.mal.ItemAPIMod", loader).setInternal(true)); register(new BuiltInMod(MCPatcherUtils.BIOME_API_MOD, "com.prupe.mcpatcher.mal.BiomeAPIMod", loader).setInternal(true)); boolean is18 = version.compareTo("14w25a") >= 0; register(new BuiltInMod(MCPatcherUtils.EXTENDED_HD, "com.prupe.mcpatcher.mod.ExtendedHD", loader)); register(new BuiltInMod(MCPatcherUtils.RANDOM_MOBS, "com.prupe.mcpatcher.mod.RandomMobs", loader)); register(new BuiltInMod(MCPatcherUtils.CUSTOM_COLORS, "com.prupe.mcpatcher.mod.cc.CustomColors", loader)); if (!is18) { register(new BuiltInMod(MCPatcherUtils.CONNECTED_TEXTURES, "com.prupe.mcpatcher.mod.ConnectedTextures", loader)); register(new BuiltInMod(MCPatcherUtils.BETTER_GLASS, "com.prupe.mcpatcher.mod.BetterGlass", loader)); } register(new BuiltInMod(MCPatcherUtils.BETTER_SKIES, "com.prupe.mcpatcher.mod.BetterSkies", loader)); if (is18) { register(new BuiltInMod(MCPatcherUtils.CUSTOM_TEXTURES_MODELS, "com.prupe.mcpatcher.mod.CustomTexturesModels", loader)); } else { register(new BuiltInMod(MCPatcherUtils.CUSTOM_ITEM_TEXTURES, "com.prupe.mcpatcher.mod.CustomItemTextures", loader)); } } loadBuiltInMods(true); } private static LegacyVersionList getLegacyVersionList() throws PatcherException { LegacyVersionList list; for (File dir : new File[]{Util.devDir, new File("."), new File("..")}) { if (dir != null) { File local = new File(dir, "../mcpatcher-legacy/" + LegacyVersionList.VERSIONS_JSON); if (Util.checkSignature(local, Util.JSON_SIGNATURE)) { list = JsonUtils.parseJson(local, LegacyVersionList.class); if (list != null) { return list; } } } } File local = MCPatcherUtils.getMinecraftPath(LegacyVersionList.VERSIONS_JSON); Util.fetchURL(LegacyVersionList.VERSIONS_URL, local, true, Util.LONG_TIMEOUT, Util.JSON_SIGNATURE); list = JsonUtils.parseJson(local, LegacyVersionList.class); local.delete(); return list; } private static ClassLoader getLegacyClassLoader(LegacyVersionList.Version version) throws MalformedURLException, PatcherException { File local; for (File dir : new File[]{Util.devDir, new File("."), new File("..")}) { if (dir != null) { local = new File(dir, "../mcpatcher-legacy/out/artifacts/" + version.id + version.getResource()); if (Util.checkSignature(local, Util.JAR_SIGNATURE)) { return new URLClassLoader(new URL[]{local.toURI().toURL()}); } } } Library library = new Library("com.prupe.mcpatcher:mcpatcher-legacy:" + version.libraryVersion, LegacyVersionList.DEFAULT_BASE_URL); local = library.getPath(MCPatcherUtils.getMinecraftPath("libraries")); boolean forceRemote = false; if (local.isFile() && !MCPatcherUtils.isNullOrEmpty(version.md5)) { String currentMD5 = Util.computeMD5(local); if (!version.md5.equals(currentMD5)) { forceRemote = true; } } local.getParentFile().mkdirs(); Util.fetchURL(version.getURL(), local, forceRemote, Util.LONG_TIMEOUT, Util.JAR_SIGNATURE); return new URLClassLoader(new URL[]{local.toURI().toURL()}); } private void register(BuiltInMod builtInMod) { try { Method preInit = builtInMod.modClass.getDeclaredMethod("preInitialize"); preInit.invoke(null); } catch (NoSuchMethodException e) { // nothing } catch (Throwable e) { e.printStackTrace(); } builtInMods.put(builtInMod.name, builtInMod); } void close() { for (Mod mod : modsByIndex) { mod.close(); } } void loadBuiltInMods(boolean internal) { for (BuiltInMod builtInMod : builtInMods.values()) { if (!modsByName.containsKey(builtInMod.name) && (MCPatcher.experimentalMods || !builtInMod.experimental) && internal == builtInMod.internal) { addNoReplace(newModInstance(builtInMod)); needReorder = true; } } if (needReorder) { while (needReorder) { needReorder = reorderBuiltinMods(); } refreshInternalMods(); } } void loadCustomMods(File directory) { if (directory.isDirectory()) { for (File f : directory.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isFile() && pathname.getName().endsWith(".jar"); } })) { try { loadCustomModsFromJar(f); } catch (Throwable e) { Logger.log(Logger.LOG_JAR, "Error loading mods from %s", f.getPath()); Logger.log(e); } } } } private void loadCustomModsFromJar(File file) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException { Logger.log(Logger.LOG_JAR, "Opening %s", file.getPath()); final JarFile jar = new JarFile(file); URLClassLoader loader = new URLClassLoader(new URL[]{file.toURI().toURL()}, getClass().getClassLoader()); for (JarEntry entry : Collections.list(jar.entries())) { if (!entry.isDirectory() && MinecraftJar.isClassFile(entry.getName())) { Mod mod = loadCustomMod(loader, ClassMap.filenameToClassName(entry.getName())); if (addNoReplace(mod)) { Logger.log(Logger.LOG_MOD, "new %s()", mod.getClass().getName()); mod.customJar = file; } } } } private Mod loadCustomMod(File file, String className) { try { URLClassLoader loader = new URLClassLoader(new URL[]{file.toURI().toURL()}, getClass().getClassLoader()); return loadCustomMod(loader, className); } catch (Throwable e) { Logger.log(e); } return null; } private Mod loadCustomMod(URLClassLoader loader, String className) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException { Class<?> cl = null; try { cl = loader.loadClass(className); } catch (NoClassDefFoundError e) { Logger.log(Logger.LOG_MOD, "WARNING: skipping %s: %s", className, e.toString()); } if (cl != null && !cl.isInterface() && Mod.class.isAssignableFrom(cl)) { int flags = cl.getModifiers(); if (!Modifier.isAbstract(flags) && Modifier.isPublic(flags)) { try { Mod.currentClassLoader = loader; return newModInstance(cl.asSubclass(Mod.class)); } finally { Mod.currentClassLoader = null; } } } return null; } void loadImpliedMods(ProfileManager profileManager, UserInterface ui) throws Exception { Library forgeLibrary = profileManager.getForgeLibrary(); if (forgeLibrary != null && !hasModSubclass(ForgeAdapter.class)) { ForgeAdapter forgeMod = new ForgeAdapter(ui, forgeLibrary); forgeMod.setEnabled(true); addFirstBuiltin(forgeMod); } } boolean hasModSubclass(Class<? extends Mod> modClass) { for (Mod mod : getAll()) { if (modClass.isAssignableFrom(mod.getClass())) { return true; } } return false; } List<Mod> getAll() { return modsByIndex; } List<Mod> getVisible() { List<Mod> visibleMods = new ArrayList<Mod>(); for (Mod mod : modsByIndex) { if (!mod.internal || MCPatcher.showInternal) { visibleMods.add(mod); } } return visibleMods; } ArrayList<Mod> getSelected() { ArrayList<Mod> list = new ArrayList<Mod>(); for (Mod mod : modsByIndex) { if (mod.okToApply() && mod.isEnabled()) { list.add(mod); } } return list; } HashMap<String, String> getReverseMap() { HashMap<String, String> map = new HashMap<String, String>(); for (Mod mod : modsByIndex) { for (Map.Entry<String, String> entry : mod.getClassMap().getReverseClassMap().entrySet()) { map.put(entry.getKey(), entry.getValue()); } } return map; } Mod get(String name) { return modsByName.get(name); } Mod get(int index) { return modsByIndex.get(index); } int size() { return modsByIndex.size(); } void enableValidMods(boolean enableAll) { for (int i = modsByIndex.size() - 1; i >= 0; i--) { Mod mod = modsByIndex.get(i); boolean enabled = mod.okToApply(); if (enabled) { if (enableAll) { selectMod(mod, true); } } else { selectMod(mod, false); } } } void disableAll() { for (int i = modsByIndex.size() - 1; i >= 0; i--) { Mod mod = modsByIndex.get(i); selectMod(mod, false); } } boolean isApplied() { return applied; } void setApplied(boolean applied) { this.applied = applied; } void remove(Mod mod) { String name = mod.getName(); for (int i = 0; i < modsByIndex.size(); i++) { if (modsByIndex.get(i) == mod) { modsByIndex.remove(i); modsByName.remove(name); } } mod.close(); } int addFirst(Mod mod) { String name = mod.getName(); Mod oldMod = modsByName.get(name); if (oldMod != null) { remove(oldMod); } modsByIndex.add(0, mod); modsByName.put(name, mod); return indexOfVisible(mod); } int addFirstBuiltin(Mod mod) { String name = mod.getName(); Mod oldMod = modsByName.get(name); if (oldMod != null) { remove(oldMod); } int i; for (i = 0; i < modsByIndex.size(); i++) { oldMod = modsByIndex.get(i); if (!(oldMod instanceof ExternalMod) && indexOfVisible(oldMod) >= 0) { break; } } modsByIndex.add(i, mod); modsByName.put(name, mod); return indexOfVisible(mod); } int addLast(Mod mod) { String name = mod.getName(); Mod oldMod = modsByName.get(name); if (oldMod != null) { remove(oldMod); } modsByIndex.add(mod); modsByName.put(name, mod); return indexOfVisible(mod); } int moveUp(int index, boolean toTop) { return move(index, -1, toTop); } int moveDown(int index, boolean toBottom) { return move(index, 1, toBottom); } private int move(int index, int direction, boolean allTheWay) { List<Mod> visibleMods = getVisible(); int newIndex; if (!allTheWay) { newIndex = index + direction; } else if (direction < 0) { newIndex = 0; } else { newIndex = visibleMods.size() - 1; } if (index >= 0 && index < visibleMods.size() && newIndex >= 0 && newIndex < visibleMods.size() && newIndex != index) { List<Mod> mods = visibleMods.subList(Math.min(index, newIndex), Math.max(index, newIndex) + 1); for (int i = 0; i < modsByIndex.size(); i++) { for (int j = 0; j < mods.size(); j++) { if (modsByIndex.get(i) == mods.get(j)) { modsByIndex.set(i, mods.get((j + direction + mods.size()) % mods.size())); break; } } } index = newIndex; } return index; } int replace(Mod oldMod, Mod newMod) { int index = indexOf(oldMod); if (index >= 0 && oldMod.getName().equals(newMod.getName())) { modsByIndex.set(index, newMod); modsByName.put(newMod.getName(), newMod); oldMod.close(); return indexOfVisible(newMod); } else { remove(oldMod); return addFirst(newMod); } } private boolean addNoReplace(Mod mod) { if (mod == null) { return false; } String name = mod.getName(); if (modsByName.containsKey(name)) { Logger.log(Logger.LOG_MOD, "WARNING: duplicate mod %s ignored", name); return false; } modsByName.put(name, mod); modsByIndex.add(mod); mod.setEnabled(mod.defaultEnabled); mod.loadOptions(); return true; } int indexOf(Mod mod) { for (int i = 0; i < modsByIndex.size(); i++) { if (mod == modsByIndex.get(i)) { return i; } } return -1; } int indexOfVisible(Mod mod) { List<Mod> visible = getVisible(); for (int i = 0; i < visible.size(); i++) { if (mod == visible.get(i)) { return i; } } return -1; } void selectMod(Mod mod, boolean enable) { HashMap<Mod, Boolean> changes = new HashMap<Mod, Boolean>(); try { if (enable) { enableMod(changes, mod, false); } else { disableMod(changes, mod, false); } } catch (ModDependencyException e) { Logger.log(e); } for (Map.Entry<Mod, Boolean> entry : changes.entrySet()) { mod = entry.getKey(); mod.setEnabled(entry.getValue()); } refreshInternalMods(); } private boolean reorderBuiltinMods() { List<String> builtIns = new ArrayList<String>(); builtIns.addAll(builtInMods.keySet()); for (int i = 0; i < modsByIndex.size(); i++) { Mod mod1 = modsByIndex.get(i); int index1 = builtIns.indexOf(mod1.getName()); if (index1 >= 0) { for (int j = i + 1; j < modsByIndex.size(); j++) { Mod mod2 = modsByIndex.get(j); int index2 = builtIns.indexOf(mod2.getName()); if (index2 >= 0 && index1 > index2) { modsByIndex.set(i, mod2); modsByIndex.set(j, mod1); return true; } } } } return false; } void refreshInternalMods() { outer: while (true) { for (int i = 0; i < modsByIndex.size() - 1; i++) { Mod mod1 = modsByIndex.get(i); Mod mod2 = modsByIndex.get(i + 1); if (mod1.internal && !mod2.internal && !dependsOn(mod2, mod1)) { modsByIndex.set(i, mod2); modsByIndex.set(i + 1, mod1); continue outer; } } break; } if (!MCPatcher.showInternal) { for (Mod mod : modsByIndex) { if (mod.internal) { mod.setEnabled(false); } } } HashMap<Mod, Boolean> changes = new HashMap<Mod, Boolean>(); for (Mod mod : modsByIndex) { try { if (mod.internal) { // nothing } else if (mod.isEnabled()) { enableMod(changes, mod, false); } else { disableMod(changes, mod, false); } } catch (ModDependencyException e) { Logger.log(e); } } for (Map.Entry<Mod, Boolean> entry : changes.entrySet()) { Mod mod = entry.getKey(); mod.setEnabled(entry.getValue()); } } private boolean dependsOn(Mod mod1, Mod mod2) { if (mod1 == null || mod2 == null) { return false; } if (mod1 == mod2) { return true; } for (Mod.Dependency dep : mod1.dependencies) { if (dep.required && !dep.name.equals(mod1.getName()) && dependsOn(modsByName.get(dep.name), mod2)) { return true; } } return false; } private void enableMod(HashMap<Mod, Boolean> inst, Mod mod, boolean recursive) throws ModDependencyException { if (mod == null) { return; } //Logger.log(Logger.LOG_MOD, "%senabling %s", (recursive ? " " : ""), mod.getName()); if (!mod.okToApply()) { throw new ModDependencyException(mod.getName() + " cannot be applied"); } if (inst.containsKey(mod)) { if (!inst.get(mod)) { throw new ModDependencyException(mod.getName() + " is both conflicting and required"); } return; } else { inst.put(mod, true); } for (Mod.Dependency dep : mod.dependencies) { Mod dmod = modsByName.get(dep.name); if (dep.required) { if (dmod == null) { throw new ModDependencyException("dependent mod " + dep.name + " not available"); } else { enableMod(inst, dmod, true); } } else { disableMod(inst, dmod, true); } } for (Mod dmod : modsByIndex) { if (dmod != mod) { for (Mod.Dependency dep : dmod.dependencies) { if (dep.name.equals(mod.getName()) && !dep.required) { disableMod(inst, dmod, true); } } } } } private void disableMod(HashMap<Mod, Boolean> inst, Mod mod, boolean recursive) throws ModDependencyException { if (mod == null) { return; } //Logger.log(Logger.LOG_MOD, "%sdisabling %s", (recursive ? " " : ""), mod.getName()); if (inst.containsKey(mod)) { if (inst.get(mod)) { throw new ModDependencyException(mod.getName() + " is both conflicting and required"); } return; } else { inst.put(mod, false); } for (Mod dmod : modsByIndex) { if (dmod != mod) { for (Mod.Dependency dep : dmod.dependencies) { if (dep.name.equals(mod.getName()) && dep.required) { disableMod(inst, dmod, true); } } } } } void loadSavedMods() { Config config = Config.getInstance(); List<String> invalidEntries = new ArrayList<String>(); needReorder = false; for (Map.Entry<String, Config.ModEntry> entry : config.getSelectedVersion().mods.entrySet()) { String name = entry.getKey(); Config.ModEntry modEntry = entry.getValue(); String type = modEntry.type; boolean enabled = modEntry.enabled; Mod mod = null; if (name == null || type == null) { // nothing } else if (type.equals(Config.VAL_BUILTIN)) { BuiltInMod builtInMod = builtInMods.get(name); if (builtInMod == null) { needReorder = true; } else if (MCPatcher.experimentalMods || !builtInMod.experimental) { mod = newModInstance(builtInMod); } } else if (type.equals(Config.VAL_EXTERNAL_ZIP)) { String path = modEntry.path; List<Config.FileEntry> files = modEntry.files; if (path != null && files != null) { File file = new File(path); if (file.isFile()) { Map<String, String> fileMap = new LinkedHashMap<String, String>(); for (Config.FileEntry entry1 : files) { fileMap.put(entry1.to, entry1.from); } try { mod = new ExternalMod(new ZipFile(file), fileMap); } catch (IOException e) { Logger.log(e); } } } } else if (type.equals(Config.VAL_EXTERNAL_JAR)) { String path = modEntry.path; String className = modEntry.className; if (path != null && className != null) { File file = new File(path); if (file.exists()) { mod = loadCustomMod(file, className); if (mod != null) { mod.customJar = file; } } } } if (mod == null) { invalidEntries.add(name); } else { addNoReplace(mod); mod.setEnabled(enabled); } } for (String name : invalidEntries) { config.getSelectedVersion().mods.remove(name); } refreshInternalMods(); } private void updateModElement(Mod mod, Config.ModEntry modEntry) { modEntry.enabled = mod.okToApply() && mod.isEnabled(); if (mod instanceof ExternalMod) { ExternalMod extmod = (ExternalMod) mod; modEntry.type = Config.VAL_EXTERNAL_ZIP; modEntry.path = extmod.zipFile.getName(); modEntry.className = null; List<Config.FileEntry> files = new ArrayList<Config.FileEntry>(); files.clear(); for (Map.Entry<String, String> entry : extmod.fileMap.entrySet()) { files.add(new Config.FileEntry(entry.getValue(), entry.getKey())); } modEntry.files = files; } else if (mod.customJar == null) { modEntry.type = Config.VAL_BUILTIN; modEntry.path = null; modEntry.className = null; modEntry.files = null; } else { modEntry.type = Config.VAL_EXTERNAL_JAR; modEntry.path = mod.customJar.getPath(); modEntry.className = mod.getClass().getCanonicalName(); modEntry.files = null; } } void updateProperties() { Config.VersionEntry versionEntry = Config.getInstance().getSelectedVersion(); Map<String, Config.ModEntry> oldEntries = new HashMap<String, Config.ModEntry>(); oldEntries.putAll(versionEntry.mods); versionEntry.mods.clear(); for (Mod mod : modsByIndex) { if (mod.internal) { continue; } Config.ModEntry modEntry = oldEntries.get(mod.getName()); if (modEntry == null) { modEntry = new Config.ModEntry(); } updateModElement(mod, modEntry); versionEntry.mods.put(mod.getName(), modEntry); } } private Mod newModInstance(Class<? extends Mod> modClass) { Mod mod; try { mod = modClass.getDeclaredConstructor().newInstance(); } catch (Throwable e) { e.printStackTrace(); return null; } try { Method supportsVersion = modClass.getDeclaredMethod("supportsVersion", MinecraftVersion.class); if (supportsVersion.getReturnType() == Boolean.TYPE && Modifier.isStatic(supportsVersion.getModifiers())) { boolean b = (Boolean) supportsVersion.invoke(null, version); if (!b) { return null; } } } catch (NoSuchMethodException e) { // nothing } catch (Throwable e) { e.printStackTrace(); return null; } return mod; } private Mod newModInstance(BuiltInMod builtInMod) { try { Mod.currentClassLoader = builtInMod.loader; Mod mod = newModInstance(builtInMod.modClass); if (mod != null) { mod.internal = builtInMod.internal; mod.experimental = builtInMod.experimental; } return mod; } finally { Mod.currentClassLoader = null; } } JsonObject getOverrideVersionJson() { JsonObject json = null; for (Mod mod : getSelected()) { JsonObject json1 = mod.getOverrideVersionJson(); if (json1 != null) { json = json1; } } return json; } String getExtraJavaArguments() { List<String> cmdLine = new ArrayList<String>(); for (Mod mod : getSelected()) { mod.addExtraJavaArguments(cmdLine); } StringBuilder sb = new StringBuilder(); for (String s : cmdLine) { if (sb.length() > 0) { sb.append(' '); } sb.append(s); } return sb.toString(); } List<Library> getExtraLibraries() { List<Library> list = new ArrayList<Library>(); for (Mod mod : getSelected()) { mod.addExtraLibraries(list); } return list; } }
923b89ab552bfa3e821f9962276d454a4d453911
3,675
java
Java
src/main/java/com/cloudmersive/client/model/NsfwResult.java
Cloudmersive/Cloudmersive.APIClient.Java.Android
5d90113399e4e47bc5e68cfd70f0152641c86a09
[ "Apache-2.0" ]
null
null
null
src/main/java/com/cloudmersive/client/model/NsfwResult.java
Cloudmersive/Cloudmersive.APIClient.Java.Android
5d90113399e4e47bc5e68cfd70f0152641c86a09
[ "Apache-2.0" ]
null
null
null
src/main/java/com/cloudmersive/client/model/NsfwResult.java
Cloudmersive/Cloudmersive.APIClient.Java.Android
5d90113399e4e47bc5e68cfd70f0152641c86a09
[ "Apache-2.0" ]
null
null
null
36.75
237
0.715102
999,640
/** * imageapi * Image Recognition and Processing APIs let you use Machine Learning to recognize and process images, and also perform useful image modification operations. * * OpenAPI spec version: v1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.cloudmersive.client.model; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; /** * Result of an NSFW classification **/ @ApiModel(description = "Result of an NSFW classification") public class NsfwResult { @SerializedName("Successful") private Boolean successful = null; @SerializedName("Score") private Double score = null; @SerializedName("ClassificationOutcome") private String classificationOutcome = null; /** * True if the classification was successfully run, false otherwise **/ @ApiModelProperty(value = "True if the classification was successfully run, false otherwise") public Boolean getSuccessful() { return successful; } public void setSuccessful(Boolean successful) { this.successful = successful; } /** * Score between 0.0 and 1.0. Scores of 0.0-0.2 represent high probability safe content, while scores 0.8-1.0 represent high probability unsafe content. Content between 0.2 and 0.8 is of increasing raciness. **/ @ApiModelProperty(value = "Score between 0.0 and 1.0. Scores of 0.0-0.2 represent high probability safe content, while scores 0.8-1.0 represent high probability unsafe content. Content between 0.2 and 0.8 is of increasing raciness.") public Double getScore() { return score; } public void setScore(Double score) { this.score = score; } /** * Classification result into four categories: SafeContent_HighProbability, UnsafeContent_HighProbability, RacyContent, SafeContent_ModerateProbability **/ @ApiModelProperty(value = "Classification result into four categories: SafeContent_HighProbability, UnsafeContent_HighProbability, RacyContent, SafeContent_ModerateProbability") public String getClassificationOutcome() { return classificationOutcome; } public void setClassificationOutcome(String classificationOutcome) { this.classificationOutcome = classificationOutcome; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NsfwResult nsfwResult = (NsfwResult) o; return (this.successful == null ? nsfwResult.successful == null : this.successful.equals(nsfwResult.successful)) && (this.score == null ? nsfwResult.score == null : this.score.equals(nsfwResult.score)) && (this.classificationOutcome == null ? nsfwResult.classificationOutcome == null : this.classificationOutcome.equals(nsfwResult.classificationOutcome)); } @Override public int hashCode() { int result = 17; result = 31 * result + (this.successful == null ? 0: this.successful.hashCode()); result = 31 * result + (this.score == null ? 0: this.score.hashCode()); result = 31 * result + (this.classificationOutcome == null ? 0: this.classificationOutcome.hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class NsfwResult {\n"); sb.append(" successful: ").append(successful).append("\n"); sb.append(" score: ").append(score).append("\n"); sb.append(" classificationOutcome: ").append(classificationOutcome).append("\n"); sb.append("}\n"); return sb.toString(); } }
923b8a1d31bab04d7fd0d314aa312ff5b1a57257
1,716
java
Java
spring-core/src/main/java/org/springframework/core/serializer/DefaultSerializer.java
JiangHao-1/spring-analysis
8c7a5cd11cd7c53c24106d0b19c67e516fc701e2
[ "Apache-2.0" ]
49,076
2015-01-01T07:23:26.000Z
2022-03-31T23:57:00.000Z
spring-core/src/main/java/org/springframework/core/serializer/DefaultSerializer.java
JiangHao-1/spring-analysis
8c7a5cd11cd7c53c24106d0b19c67e516fc701e2
[ "Apache-2.0" ]
7,918
2015-01-06T17:17:21.000Z
2022-03-31T20:10:05.000Z
spring-core/src/main/java/org/springframework/core/serializer/DefaultSerializer.java
JiangHao-1/spring-analysis
8c7a5cd11cd7c53c24106d0b19c67e516fc701e2
[ "Apache-2.0" ]
37,778
2015-01-01T08:25:16.000Z
2022-03-31T17:25:08.000Z
33.647059
104
0.748834
999,641
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.serializer; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; /** * A {@link Serializer} implementation that writes an object to an output stream * using Java serialization. * * @author Gary Russell * @author Mark Fisher * @since 3.0.5 */ public class DefaultSerializer implements Serializer<Object> { /** * Writes the source object to an output stream using Java serialization. * The source object must implement {@link Serializable}. * @see ObjectOutputStream#writeObject(Object) */ @Override public void serialize(Object object, OutputStream outputStream) throws IOException { if (!(object instanceof Serializable)) { throw new IllegalArgumentException(getClass().getSimpleName() + " requires a Serializable payload " + "but received an object of type [" + object.getClass().getName() + "]"); } ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(object); objectOutputStream.flush(); } }
923b8a2c11ce9ec45e18c788cb9fa2093f19a9e9
589
java
Java
src/main/java/xyz/gnarbot/gnar/commands/executors/test/TestCommand.java
xXMicroRaptorXx/Micro
72138514c6df06dde04c8e59d3744d3765200c5d
[ "MIT" ]
null
null
null
src/main/java/xyz/gnarbot/gnar/commands/executors/test/TestCommand.java
xXMicroRaptorXx/Micro
72138514c6df06dde04c8e59d3744d3765200c5d
[ "MIT" ]
null
null
null
src/main/java/xyz/gnarbot/gnar/commands/executors/test/TestCommand.java
xXMicroRaptorXx/Micro
72138514c6df06dde04c8e59d3744d3765200c5d
[ "MIT" ]
null
null
null
28.047619
57
0.721562
999,642
package xyz.gnarbot.gnar.commands.executors.test; import net.dv8tion.jda.core.Permission; import xyz.gnarbot.gnar.commands.Category; import xyz.gnarbot.gnar.commands.Command; import xyz.gnarbot.gnar.commands.CommandExecutor; import xyz.gnarbot.gnar.utils.Context; @Command( aliases = "wow", administrator = true, category = Category.NONE, permissions = Permission.ADMINISTRATOR ) public class TestCommand extends CommandExecutor { @Override public void execute(Context context, String[] args) { context.send().text("wow").queue(); } }
923b8a99fe28fa3ed13a2ea67c064a0cf01edc7b
8,119
java
Java
reformcloud2-executor-api/src/main/java/systems/reformcloud/reformcloud2/executor/api/common/network/NetworkUtil.java
zLvkas/reformcloud2
9142f6806fce926e613a8c259d5831ada74e9bde
[ "Apache-2.0" ]
null
null
null
reformcloud2-executor-api/src/main/java/systems/reformcloud/reformcloud2/executor/api/common/network/NetworkUtil.java
zLvkas/reformcloud2
9142f6806fce926e613a8c259d5831ada74e9bde
[ "Apache-2.0" ]
null
null
null
reformcloud2-executor-api/src/main/java/systems/reformcloud/reformcloud2/executor/api/common/network/NetworkUtil.java
zLvkas/reformcloud2
9142f6806fce926e613a8c259d5831ada74e9bde
[ "Apache-2.0" ]
null
null
null
39.033654
241
0.651681
999,643
package systems.reformcloud.reformcloud2.executor.api.common.network; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollServerSocketChannel; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.MultithreadEventExecutorGroup; import systems.reformcloud.reformcloud2.executor.api.common.base.Conditions; import systems.reformcloud.reformcloud2.executor.api.common.configuration.JsonConfiguration; import systems.reformcloud.reformcloud2.executor.api.common.language.LanguageManager; import systems.reformcloud.reformcloud2.executor.api.common.network.channel.NetworkChannelReader; import systems.reformcloud.reformcloud2.executor.api.common.network.channel.PacketSender; import systems.reformcloud.reformcloud2.executor.api.common.network.channel.defaults.DefaultPacketSender; import systems.reformcloud.reformcloud2.executor.api.common.network.channel.manager.DefaultChannelManager; import systems.reformcloud.reformcloud2.executor.api.common.network.packet.DefaultPacket; import systems.reformcloud.reformcloud2.executor.api.common.network.packet.Packet; import systems.reformcloud.reformcloud2.executor.api.common.network.packet.handler.PacketHandler; import javax.annotation.Nonnull; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.function.BiFunction; import java.util.function.Consumer; public final class NetworkUtil { /* ============================= */ public static final int NODE_TO_NODE_BUS = 20000; public static final int NODE_TO_NODE_QUERY_BUS = 25000; public static final int CONTROLLER_INFORMATION_BUS = 2000; public static final int EVENT_BUS = 3000; public static final int CONTROLLER_QUERY_BUS = 4000; public static final int PLAYER_INFORMATION_BUS = 5000; public static final int EXTERNAL_BUS = 50000; /* ============================ */ public static final Executor EXECUTOR = Executors.newCachedThreadPool(); public static final Consumer<ChannelHandlerContext> DEFAULT_AUTH_FAILURE_HANDLER = context -> context.channel().writeAndFlush(new DefaultPacket(-511, new JsonConfiguration().add("access", false))).syncUninterruptibly().channel().close(); public static final BiFunction<String, ChannelHandlerContext, PacketSender> DEFAULT_SUCCESS_HANDLER = (s, context) -> { PacketSender packetSender = new DefaultPacketSender(context.channel()); packetSender.setName(s); return packetSender; }; private static final boolean EPOLL = Epoll.isAvailable(); private static final ThreadFactory THREAD_FACTORY = new DefaultThreadFactory(MultithreadEventExecutorGroup.class, true, Thread.MIN_PRIORITY); public static EventLoopGroup eventLoopGroup() { if (!Boolean.getBoolean("reformcloud.disable.native")) { if (EPOLL) { return new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors(), THREAD_FACTORY); } } return new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), THREAD_FACTORY); } public static Class<? extends ServerSocketChannel> serverSocketChannel() { if (!Boolean.getBoolean("reformcloud.disable.native")) { if (EPOLL) { return EpollServerSocketChannel.class; } } return NioServerSocketChannel.class; } public static Class<? extends SocketChannel> socketChannel() { if (!Boolean.getBoolean("reformcloud.disable.native")) { if (EPOLL) { return EpollSocketChannel.class; } } return NioSocketChannel.class; } public static synchronized ByteBuf write(ByteBuf byteBuf, int value) { do { byte temp = (byte) (value & 0b01111111); value >>>= 7; if (value != 0) { temp |= 0b10000000; } byteBuf.writeByte(temp); } while (value != 0); return byteBuf; } public static synchronized int read(ByteBuf byteBuf) { int numRead = 0; int result = 0; byte read; do { read = byteBuf.readByte(); int value = (read & 0b01111111); result |= (value << (7 * numRead)); numRead++; if (numRead > 5) { throw new RuntimeException("VarInt is too big"); } } while ((read & 0b10000000) != 0); return result; } public static synchronized ByteBuf write(ByteBuf byteBuf, String s) { byte[] bytes = s.getBytes(StandardCharsets.UTF_8); write(byteBuf, bytes.length); byteBuf.writeBytes(bytes); return byteBuf; } public static synchronized String readString(ByteBuf byteBuf) { int size = read(byteBuf); byte[] bytes = new byte[size]; byteBuf.readBytes(bytes, 0, size); return new String(bytes, StandardCharsets.UTF_8); } public static NetworkChannelReader newReader(PacketHandler packetHandler, Consumer<PacketSender> consumer) { return new NetworkChannelReader() { private PacketSender sender; @Nonnull @Override public PacketHandler getPacketHandler() { return packetHandler; } @Nonnull @Override public PacketSender sender() { return sender; } @Override public void setSender(PacketSender sender) { Conditions.isTrue(this.sender == null); this.sender = sender; DefaultChannelManager.INSTANCE.registerChannel(sender); } @Override public void channelActive(ChannelHandlerContext context) { if (sender == null) { String address = ((InetSocketAddress) context.channel().remoteAddress()).getAddress().getHostAddress(); System.out.println(LanguageManager.get("network-channel-connected", address)); } } @Override public void channelInactive(ChannelHandlerContext context) { if (sender != null) { DefaultChannelManager.INSTANCE.unregisterChannel(sender); consumer.accept(sender); System.out.println(LanguageManager.get("network-channel-disconnected", sender.getName())); } } @Override public void read(ChannelHandlerContext context, Packet packet) { NetworkUtil.EXECUTOR.execute(() -> { if (packet.queryUniqueID() != null && getPacketHandler().getQueryHandler().hasWaitingQuery(packet.queryUniqueID())) { getPacketHandler().getQueryHandler().getWaitingQuery(packet.queryUniqueID()).complete(packet); } else { getPacketHandler().getNetworkHandlers(packet.packetID()).forEach(networkHandler -> networkHandler.handlePacket(sender, packet, out -> { if (packet.queryUniqueID() != null) { out.setQueryID(packet.queryUniqueID()); sender.sendPacket(out); } })); } }); } }; } private NetworkUtil() { throw new UnsupportedOperationException(); } }
923b8d1344d392036134245d22b9bff521e4570a
292
java
Java
src/main/java/jpuppeteer/cdp/client/entity/emulation/SetScrollbarsHiddenRequest.java
sunshinex/jpuppeteer
b423248ad8b35db84d0d4839c4ae097f62da684f
[ "Apache-2.0" ]
29
2019-12-02T10:28:40.000Z
2022-02-28T17:29:36.000Z
src/main/java/jpuppeteer/cdp/client/entity/emulation/SetScrollbarsHiddenRequest.java
sunshinex/jpuppeteer
b423248ad8b35db84d0d4839c4ae097f62da684f
[ "Apache-2.0" ]
1
2020-05-15T01:49:45.000Z
2020-05-15T01:49:45.000Z
src/main/java/jpuppeteer/cdp/client/entity/emulation/SetScrollbarsHiddenRequest.java
sunshinex/jpuppeteer
b423248ad8b35db84d0d4839c4ae097f62da684f
[ "Apache-2.0" ]
6
2020-03-02T06:49:10.000Z
2022-02-11T06:29:54.000Z
18.25
55
0.684932
999,644
package jpuppeteer.cdp.client.entity.emulation; /** */ public class SetScrollbarsHiddenRequest { /** * Whether scrollbars should be always hidden. */ public final Boolean hidden; public SetScrollbarsHiddenRequest(Boolean hidden) { this.hidden = hidden; } }
923b8d3a519b627223c7ed8251e4da1f9bf3e1a2
570
java
Java
src/dyhelper/com/util/MapUtils.java
ModWU/DYHelper2
c3dc9ee55c61f1c6c5f6c32585a3a70b74ab7197
[ "Apache-2.0" ]
null
null
null
src/dyhelper/com/util/MapUtils.java
ModWU/DYHelper2
c3dc9ee55c61f1c6c5f6c32585a3a70b74ab7197
[ "Apache-2.0" ]
null
null
null
src/dyhelper/com/util/MapUtils.java
ModWU/DYHelper2
c3dc9ee55c61f1c6c5f6c32585a3a70b74ab7197
[ "Apache-2.0" ]
null
null
null
27.142857
93
0.62807
999,645
package dyhelper.com.util; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; public class MapUtils { public static Map<String, String> sortMapByKey(Map<String, String> oriMap) { if (oriMap == null || oriMap.isEmpty()) { return null; } Map<String, String> sortedMap = new TreeMap<String, String>(new Comparator<String>() { public int compare(String key1, String key2) { return key1.compareTo(key2); }}); sortedMap.putAll(oriMap); return sortedMap; } }
923b8d803b258302ecfaaf6431bd10e14fbbd3eb
3,440
java
Java
src/ChatServer/JdbcOdbc.java
utkarshporwal24/Java-Review
339464716f29e5010a7fabc6911a6f418f3a1660
[ "MIT" ]
null
null
null
src/ChatServer/JdbcOdbc.java
utkarshporwal24/Java-Review
339464716f29e5010a7fabc6911a6f418f3a1660
[ "MIT" ]
null
null
null
src/ChatServer/JdbcOdbc.java
utkarshporwal24/Java-Review
339464716f29e5010a7fabc6911a6f418f3a1660
[ "MIT" ]
null
null
null
37.391304
108
0.592151
999,646
package ChatServer; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import oracle.jdbc.OraclePreparedStatement; import oracle.jdbc.OracleResultSet; /* * 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. */ /** * * @author ZISHAN */ public class JdbcOdbc { private Connection con; OraclePreparedStatement pst=null; OracleResultSet rs=null; public JdbcOdbc(){ try{ Class.forName("oracle.jdbc.OracleDriver"); con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "sanu786"); }catch(ClassNotFoundException | SQLException ex){ System.out.println(ex); } } public boolean authentiction(String userName , String password) throws SQLException{ String sql="select * from Login where username='"+userName+"'and password='"+password+"' "; System.out.println("Authentiction of DB userName"+userName+"8"); pst = (OraclePreparedStatement) con.prepareStatement(sql); //pst.setString(1, userName); rs=(OracleResultSet) pst.executeQuery(); // if(rs.next()) // System.out.println("Data Base Responce "+rs.getString(1)+" "); return rs.next(); } public boolean isUserExist(String user){ String sql="select * from Login where username='"+user+"'"; try { pst = (OraclePreparedStatement) con.prepareStatement(sql); rs=(OracleResultSet) pst.executeQuery(); return rs.next(); } catch (SQLException ex) { Logger.getLogger(JdbcOdbc.class.getName()).log(Level.SEVERE, null, ex); } return false; } public boolean createUser(String msg){ String details[]=msg.split(" ")[1].split(","); try { String sql="insert into Registration values(?,?,?,?,?,?)"; String loginSql="insert into Login values(?,?)"; pst = (OraclePreparedStatement) con.prepareStatement(sql); pst.setString(1, details[0]); pst.setString(2, details[1]); pst.setString(3, details[2]); pst.setString(4, details[3]); pst.setString(5, details[4]); pst.setString(6, details[5]); pst.executeUpdate(); pst = (OraclePreparedStatement) con.prepareStatement(loginSql); pst.setString(1, details[3]); pst.setString(2, details[4]); pst.executeUpdate(); return true; } catch (SQLException ex) { Logger.getLogger(JdbcOdbc.class.getName()).log(Level.SEVERE, null, ex); } return false; } public String getPassword(String user){ String sql="select * from Login where username='"+user+"'"; try { pst = (OraclePreparedStatement) con.prepareStatement(sql); rs=(OracleResultSet) pst.executeQuery(); if( rs.next()); return rs.getString(2); } catch (SQLException ex) { Logger.getLogger(JdbcOdbc.class.getName()).log(Level.SEVERE, null, ex); } return null; } }
923b8e2d9c42b232a6d3730773c4c3b335ccabce
1,833
java
Java
app/src/main/java/razerdp/demo/popup/AutoLocatedPopup.java
zhonghehuangpu/BasePopup
2f1ef638f18fd6e05b5dc769c613f20be20b54b5
[ "Apache-2.0" ]
4
2019-10-08T02:09:36.000Z
2019-12-26T08:46:39.000Z
app/src/main/java/razerdp/demo/popup/AutoLocatedPopup.java
1hanliang/BasePopup
148a84c0859f4d983a1a8ec377ab165b1ff02452
[ "Apache-2.0" ]
null
null
null
app/src/main/java/razerdp/demo/popup/AutoLocatedPopup.java
1hanliang/BasePopup
148a84c0859f4d983a1a8ec377ab165b1ff02452
[ "Apache-2.0" ]
1
2019-11-22T16:26:50.000Z
2019-11-22T16:26:50.000Z
24.118421
87
0.626296
999,647
package razerdp.demo.popup; import android.content.Context; import android.view.View; import android.view.animation.Animation; import razerdp.basepopup.BasePopupWindow; import razerdp.basepopup.R; import razerdp.demo.utils.ToastUtils; /** * Created by 大灯泡 on 2016/11/23. * <p> * 自动定位的popup,空间不足显示在上面 */ public class AutoLocatedPopup extends BasePopupWindow implements View.OnClickListener { public AutoLocatedPopup(Context context) { super(context); setAutoLocatePopup(true); bindEvent(); } @Override protected Animation onCreateShowAnimation() { return getDefaultAlphaAnimation(); } @Override protected Animation onCreateDismissAnimation() { return getDefaultAlphaAnimation(false); } @Override public View onCreateContentView() { return createPopupById(R.layout.popup_menu); } private void bindEvent() { findViewById(R.id.tx_1).setOnClickListener(this); findViewById(R.id.tx_2).setOnClickListener(this); findViewById(R.id.tx_3).setOnClickListener(this); } @Override public void onAnchorTop() { ToastUtils.ToastMessage(getContext(), "显示在上方(下方位置不足)"); } @Override public void onAnchorBottom() { ToastUtils.ToastMessage(getContext(), "显示在下方(上位置不足)"); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tx_1: ToastUtils.ToastMessage(getContext(), "click tx_1"); break; case R.id.tx_2: ToastUtils.ToastMessage(getContext(), "click tx_2"); break; case R.id.tx_3: ToastUtils.ToastMessage(getContext(), "click tx_3"); break; default: break; } } }
923b8f2139663d46225b997dccde8a477da4b5fa
2,178
java
Java
clouddriver-cloudfoundry/src/test/java/com/netflix/spinnaker/clouddriver/cloudfoundry/deploy/ops/AbstractCloudFoundryAtomicOperationTest.java
sidmuls/clouddriver
c2de4b416bf15afbd09640013724e7f7b069ce09
[ "Apache-2.0" ]
382
2015-11-16T17:54:23.000Z
2022-03-24T05:35:37.000Z
clouddriver-cloudfoundry/src/test/java/com/netflix/spinnaker/clouddriver/cloudfoundry/deploy/ops/AbstractCloudFoundryAtomicOperationTest.java
sidmuls/clouddriver
c2de4b416bf15afbd09640013724e7f7b069ce09
[ "Apache-2.0" ]
2,541
2015-11-17T11:22:10.000Z
2022-03-28T22:30:12.000Z
clouddriver-cloudfoundry/src/test/java/com/netflix/spinnaker/clouddriver/cloudfoundry/deploy/ops/AbstractCloudFoundryAtomicOperationTest.java
sidmuls/clouddriver
c2de4b416bf15afbd09640013724e7f7b069ce09
[ "Apache-2.0" ]
1,229
2015-11-16T19:22:35.000Z
2022-03-28T18:32:40.000Z
36.3
97
0.743802
999,648
/* * Copyright 2018 Pivotal, 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.netflix.spinnaker.clouddriver.cloudfoundry.deploy.ops; import static java.util.Collections.emptyList; import com.netflix.spinnaker.clouddriver.cloudfoundry.client.*; import com.netflix.spinnaker.clouddriver.data.task.DefaultTask; import com.netflix.spinnaker.clouddriver.data.task.Status; import com.netflix.spinnaker.clouddriver.data.task.Task; import com.netflix.spinnaker.clouddriver.data.task.TaskRepository; import com.netflix.spinnaker.clouddriver.orchestration.AtomicOperation; import java.util.Collections; import java.util.Optional; import org.assertj.core.api.Condition; class AbstractCloudFoundryAtomicOperationTest { final CloudFoundryClient client; AbstractCloudFoundryAtomicOperationTest() { client = new MockCloudFoundryClient(); } Task runOperation(AtomicOperation<?> op) { Task task = new DefaultTask("test"); TaskRepository.threadLocalTask.set(task); try { Optional.ofNullable(op.operate(emptyList())) .ifPresent(o -> task.addResultObjects(Collections.singletonList(o))); } catch (CloudFoundryApiException e) { task.addResultObjects(Collections.singletonList(Collections.singletonMap("EXCEPTION", e))); } return task; } static Condition<? super Status> status(String desc) { return new Condition<>( status -> status.getStatus().equals(desc), "description = '" + desc + "'"); } static Condition<? super Status> statusStartsWith(String desc) { return new Condition<>( status -> status.getStatus().startsWith(desc), "description = '" + desc + "'"); } }
923b901a7480b12a59bed8e17327ea7f77aa3026
2,077
java
Java
app/src/main/java/org/webrtc/RtpReceiver.java
hexstia/ScreenShareRTC-master
30ce46fb7b977dee0c163fd7a0ab00dc47e4e7c3
[ "Apache-2.0" ]
null
null
null
app/src/main/java/org/webrtc/RtpReceiver.java
hexstia/ScreenShareRTC-master
30ce46fb7b977dee0c163fd7a0ab00dc47e4e7c3
[ "Apache-2.0" ]
null
null
null
app/src/main/java/org/webrtc/RtpReceiver.java
hexstia/ScreenShareRTC-master
30ce46fb7b977dee0c163fd7a0ab00dc47e4e7c3
[ "Apache-2.0" ]
1
2020-10-16T09:42:54.000Z
2020-10-16T09:42:54.000Z
28.452055
87
0.707752
999,649
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package org.webrtc; import org.webrtc.MediaStreamTrack.MediaType; public class RtpReceiver { final long nativeRtpReceiver; private long nativeObserver; private MediaStreamTrack cachedTrack; public RtpReceiver(long nativeRtpReceiver) { this.nativeRtpReceiver = nativeRtpReceiver; long track = nativeGetTrack(nativeRtpReceiver); this.cachedTrack = new MediaStreamTrack(track); } public MediaStreamTrack track() { return this.cachedTrack; } public boolean setParameters(RtpParameters parameters) { return nativeSetParameters(this.nativeRtpReceiver, parameters); } public RtpParameters getParameters() { return nativeGetParameters(this.nativeRtpReceiver); } public String id() { return nativeId(this.nativeRtpReceiver); } public void dispose() { this.cachedTrack.dispose(); if (this.nativeObserver != 0L) { nativeUnsetObserver(this.nativeRtpReceiver, this.nativeObserver); this.nativeObserver = 0L; } free(this.nativeRtpReceiver); } public void SetObserver(RtpReceiver.Observer observer) { if (this.nativeObserver != 0L) { nativeUnsetObserver(this.nativeRtpReceiver, this.nativeObserver); } this.nativeObserver = nativeSetObserver(this.nativeRtpReceiver, observer); } private static native long nativeGetTrack(long var0); private static native boolean nativeSetParameters(long var0, RtpParameters var2); private static native RtpParameters nativeGetParameters(long var0); private static native String nativeId(long var0); private static native void free(long var0); private static native long nativeSetObserver(long var0, RtpReceiver.Observer var2); private static native long nativeUnsetObserver(long var0, long var2); public interface Observer { void onFirstPacketReceived(MediaType var1); } }
923b90bd91abe40822238ec13194abc0f3d1ed90
4,617
java
Java
SP_MAPS/src/comun/Galeria.java
7Mendez/SistemasPuntosVenta
68bb0f6725d0f74dc67957224f421b82769e7074
[ "MIT" ]
null
null
null
SP_MAPS/src/comun/Galeria.java
7Mendez/SistemasPuntosVenta
68bb0f6725d0f74dc67957224f421b82769e7074
[ "MIT" ]
null
null
null
SP_MAPS/src/comun/Galeria.java
7Mendez/SistemasPuntosVenta
68bb0f6725d0f74dc67957224f421b82769e7074
[ "MIT" ]
null
null
null
25.508287
107
0.508989
999,650
package comun; import java.util.Calendar; /** * <p>Title : Persona</p> * <p>Description : Clase para el control de la informaci&oacute;n de una persona</p> * <p>Copyright : Copyright (c) 2004</p> * <p>Company : Universidad Tecnol&oacute;gica de Tabasco</p> * @author Octavio Elias Sanchez Aquino * @version 1.0 */ public class Galeria implements IGrabable { protected int cveEvento; protected int consecutivo; protected String ruta; protected String comentario; private boolean _existe; /** * Constructor por defecto de la clase */ public Galeria() { limpiar(); } /** * M&eacute;todo para limpiar los miembros de la clase */ public void limpiar() { _existe = false; } public String getRuta() { return ruta; } public int getConsecutivo() { int sigue=0; Resultados rsMaximo=UtilDB.ejecutaConsulta("Select Max(Consecutivo) + 1 maximo " + "From Galeria " + "Where Cve_Evento=" + cveEvento); while (rsMaximo.next()) { sigue=rsMaximo.getInt("maximo"); } if (sigue==0) { sigue=1; } return sigue; } public int getCveFoto() { int sigue=0; Resultados rsMaximo=UtilDB.ejecutaConsulta("Select Max(Cve_Foto) + 1 maximo From Galeria"); while (rsMaximo.next()) { sigue=rsMaximo.getInt("maximo"); } if (sigue==0) { sigue=1; } return sigue; } public String getComentario(){ return this.comentario; } public int getEvento(){ return cveEvento; } public void setComentario(String xcomentario){ this.comentario = xcomentario; } public ErrorSistema grabar() { ErrorSistema err = new ErrorSistema(); err = validar(); if ( err.getNumeroError() == 0 ) { if ( !_existe ) { String sql = "Insert into Galeria ( Cve_Evento, Ruta, Comentario, Consecutivo, Cve_Foto) " + "Values (" + String.valueOf(cveEvento) + "," + Utilerias.CadenaEncomillada(ruta) + "," + Utilerias.CadenaEncomillada(comentario) + "," + String.valueOf(getConsecutivo()) + "," + String.valueOf(getCveFoto()) + ")"; err = UtilDB.ejecutaSQL(sql); } else { String sql = "Insert into Galeria (Cve_Evento, Ruta, Comentario, Consecutivo, Cve_Foto) " + "Values (" + String.valueOf(cveEvento) + "," + Utilerias.CadenaEncomillada(ruta) + "," + Utilerias.CadenaEncomillada(comentario) + "," + String.valueOf(getConsecutivo()) + "," + String.valueOf(getCveFoto()) + ")"; err = UtilDB.ejecutaSQL(sql); } } return err; } /** * Valida la informaci&oacute;n contenida en el objeto * @return La condici&oacute;n de error */ private ErrorSistema validar() { ErrorSistema err = new ErrorSistema(); return err; } /** * Borra al registro de la de datos, * no aplicable para este objeto * @return La condici&oacute;n de error */ public ErrorSistema borrar() { // No se debe de borrar un registro de persona ErrorSistema err = new ErrorSistema(); err.setCadenaError("No se puede borrar la informaci�n de una persona"); err.setNumeroError(-1); return err; } /** * Carga la informaci&oacuten de la de datos al objeto */ public void cargar() { } /** * Carga la informaci&oacute;n de un objeto Resultados al objeto Persona * @param res Objeto resultados */ public void cargar(Resultados res) { } /** * Indica si la persona existe ya en la de datos o no * @return La condici&oacute;n de existencia */ public boolean existe() { return _existe; } public void setRuta(String xRuta) { ruta = xRuta; } public void setEvento(int xEvento) { cveEvento = xEvento; } }
923b91387b518e658289b3d60b930e9259a5b2ba
367
java
Java
joolun-wx/joolun-common/src/main/java/com/joolun/common/exception/file/FileException.java
supermanvv/JooLun-wx
aeaaa4678a55b48bb3db7c851cb0d4def4f4a39d
[ "MIT" ]
1,544
2020-03-21T12:31:07.000Z
2022-03-29T10:27:06.000Z
joolun-wx/joolun-common/src/main/java/com/joolun/common/exception/file/FileException.java
supermanvv/JooLun-wx
aeaaa4678a55b48bb3db7c851cb0d4def4f4a39d
[ "MIT" ]
2
2021-03-09T14:24:14.000Z
2021-03-22T06:09:51.000Z
joolun-wx/joolun-common/src/main/java/com/joolun/common/exception/file/FileException.java
supermanvv/JooLun-wx
aeaaa4678a55b48bb3db7c851cb0d4def4f4a39d
[ "MIT" ]
83
2020-04-19T11:37:35.000Z
2022-03-31T03:01:03.000Z
18.35
53
0.653951
999,651
package com.joolun.common.exception.file; import com.joolun.common.exception.BaseException; /** * 文件信息异常类 * * @author ruoyi */ public class FileException extends BaseException { private static final long serialVersionUID = 1L; public FileException(String code, Object[] args) { super("file", code, args, null); } }
923b91e4703af2f31e6805fc91014acdd59d390d
3,758
java
Java
superuser/src/main/java/com/topjohnwu/superuser/internal/DataInputImpl.java
xVERSUSx/libsu
984376e83b5d8e9adfde419c0bab6bb841fa84c9
[ "Apache-2.0" ]
1
2018-08-07T05:46:24.000Z
2018-08-07T05:46:24.000Z
superuser/src/main/java/com/topjohnwu/superuser/internal/DataInputImpl.java
xVERSUSx/libsu
984376e83b5d8e9adfde419c0bab6bb841fa84c9
[ "Apache-2.0" ]
null
null
null
superuser/src/main/java/com/topjohnwu/superuser/internal/DataInputImpl.java
xVERSUSx/libsu
984376e83b5d8e9adfde419c0bab6bb841fa84c9
[ "Apache-2.0" ]
null
null
null
27.837037
81
0.571048
999,652
/* * Copyright 2018 John "topjohnwu" Wu * * 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.topjohnwu.superuser.internal; import android.support.annotation.NonNull; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStreamReader; interface DataInputImpl extends DataInput { @Override default void readFully(@NonNull byte[] b) throws IOException { readFully(b, 0, b.length); } @Override default boolean readBoolean() throws IOException { return readByte() != 0; } @Override default byte readByte() throws IOException { byte[] b = new byte[1]; readFully(b); return b[0]; } @Override default int readUnsignedByte() throws IOException { return readByte() & 0xFF; } @Override default short readShort() throws IOException { byte[] b = new byte[2]; readFully(b); return (short)((b[0] << 8) + (b[1] << 0)); } @Override default int readUnsignedShort() throws IOException { byte[] b = new byte[2]; readFully(b); return (b[0] << 8) + (b[1] << 0); } @Override default char readChar() throws IOException { return (char) readUnsignedShort(); } @Override default int readInt() throws IOException { byte[] b = new byte[4]; readFully(b); return ((b[0] << 24) + (b[1] << 16) + (b[2] << 8) + (b[3] << 0)); } @Override default long readLong() throws IOException { byte[] b = new byte[8]; readFully(b); return (((long)b[0] << 56) + ((long)(b[1] & 255) << 48) + ((long)(b[2] & 255) << 40) + ((long)(b[3] & 255) << 32) + ((long)(b[4] & 255) << 24) + ((b[5] & 255) << 16) + ((b[6] & 255) << 8) + ((b[7] & 255) << 0)); } @Override default float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } @Override default double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } @Override default String readLine() throws IOException { int b; ByteArrayOutputStream buf = new ByteArrayOutputStream(); try { while (true) { b = readUnsignedByte(); buf.write(b); if (b == '\n') break; } } catch (EOFException ignored) { if (buf.size() == 0) return null; } return new BufferedReader(new InputStreamReader(new ByteArrayInputStream( buf.toByteArray()))).readLine(); } @NonNull @Override default String readUTF() throws IOException { int len = readUnsignedShort(); byte[] b = new byte[len + 2]; b[0] = (byte)(len >>> 8); b[1] = (byte)(len >>> 0); readFully(b, 2, len); return new DataInputStream(new ByteArrayInputStream(b)).readUTF(); } }
923b93979d1bbb05500e57f685556da103365984
1,479
java
Java
components/camel-braintree/src/generated/java/org/apache/camel/component/braintree/internal/BraintreeApiName.java
alta404/camel
c5af90cdd56acae38f1400dfdab5f1fad7872018
[ "Apache-2.0" ]
1
2020-09-11T07:20:25.000Z
2020-09-11T07:20:25.000Z
components/camel-braintree/src/generated/java/org/apache/camel/component/braintree/internal/BraintreeApiName.java
alta404/camel
c5af90cdd56acae38f1400dfdab5f1fad7872018
[ "Apache-2.0" ]
8
2020-08-15T18:26:18.000Z
2020-08-30T06:49:36.000Z
components/camel-braintree/src/generated/java/org/apache/camel/component/braintree/internal/BraintreeApiName.java
alta404/camel
c5af90cdd56acae38f1400dfdab5f1fad7872018
[ "Apache-2.0" ]
1
2020-12-25T05:56:04.000Z
2020-12-25T05:56:04.000Z
20.830986
92
0.664638
999,653
/* * Camel ApiName Enumeration generated by camel-api-component-maven-plugin */ package org.apache.camel.component.braintree.internal; import org.apache.camel.support.component.ApiName; /** * Camel {@link ApiName} Enumeration for Component Braintree */ public enum BraintreeApiName implements ApiName { ADDON("addOn"), ADDRESS("address"), CLIENTTOKEN("clientToken"), CREDITCARDVERIFICATION("creditCardVerification"), CUSTOMER("customer"), DISCOUNT("discount"), DISPUTE("dispute"), DOCUMENTUPLOAD("documentUpload"), MERCHANTACCOUNT("merchantAccount"), PAYMENTMETHOD("paymentMethod"), PAYMENTMETHODNONCE("paymentMethodNonce"), PLAN("plan"), REPORT("report"), SETTLEMENTBATCHSUMMARY("settlementBatchSummary"), SUBSCRIPTION("subscription"), TRANSACTION("transaction"), WEBHOOKNOTIFICATION("webhookNotification"); private static final BraintreeApiName[] VALUES = values(); private final String name; private BraintreeApiName(String name) { this.name = name; } @Override public String getName() { return name; } public static BraintreeApiName fromValue(String value) throws IllegalArgumentException { for (int i = 0; i < VALUES.length; i++) { if (VALUES[i].name.equals(value)) { return VALUES[i]; } } throw new IllegalArgumentException("Invalid value " + value); } }
923b93a31376c2b658776cf60e69b591cc7fbb4b
5,597
java
Java
app/src/main/java/be/henallux/ig3/smartcity/elbatapp/ui/bookings/BookingsListViewModel.java
AurelieBodart/Smartcity-ELBAT-Android-App
20fda6d37bba3bc853aba695372706911f1e36e7
[ "MIT" ]
null
null
null
app/src/main/java/be/henallux/ig3/smartcity/elbatapp/ui/bookings/BookingsListViewModel.java
AurelieBodart/Smartcity-ELBAT-Android-App
20fda6d37bba3bc853aba695372706911f1e36e7
[ "MIT" ]
16
2021-08-19T05:12:37.000Z
2022-02-24T05:15:25.000Z
app/src/main/java/be/henallux/ig3/smartcity/elbatapp/ui/bookings/BookingsListViewModel.java
AurelieBodart/Smartcity-ELBAT-Android-App
20fda6d37bba3bc853aba695372706911f1e36e7
[ "MIT" ]
null
null
null
39.695035
172
0.692693
999,654
package be.henallux.ig3.smartcity.elbatapp.ui.bookings; import android.app.Application; import android.content.Context; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.auth0.android.jwt.Claim; import com.auth0.android.jwt.JWT; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import java.util.Objects; import be.henallux.ig3.smartcity.elbatapp.data.model.NetworkError; import be.henallux.ig3.smartcity.elbatapp.data.model.Reservation; import be.henallux.ig3.smartcity.elbatapp.data.model.User; import be.henallux.ig3.smartcity.elbatapp.repositories.web.ELBATWebService; import be.henallux.ig3.smartcity.elbatapp.repositories.web.RetrofitConfigurationService; import be.henallux.ig3.smartcity.elbatapp.repositories.web.dto.ReservationDto; import be.henallux.ig3.smartcity.elbatapp.service.mappers.CancelMapper; import be.henallux.ig3.smartcity.elbatapp.service.mappers.ReservationMapper; import be.henallux.ig3.smartcity.elbatapp.utils.errors.NoConnectivityException; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class BookingsListViewModel extends AndroidViewModel { private MutableLiveData<List<Reservation>> _bookings = new MutableLiveData<>(); private LiveData<List<Reservation>> bookings = _bookings; private MutableLiveData<List<Reservation>> _canceledBookings = new MutableLiveData<>(); private LiveData<List<Reservation>> canceledBookings = _canceledBookings; private MutableLiveData<Reservation> _bookingChosen = new MutableLiveData<>(); private LiveData<Reservation> bookingChosen = _bookingChosen; private MutableLiveData<NetworkError> _error = new MutableLiveData<>(); private LiveData<NetworkError> error = _error; private MutableLiveData<Integer> _statutCode = new MutableLiveData<>(); private LiveData<Integer> statutCode = _statutCode; private ELBATWebService webService; private ReservationMapper reservationMapper; private CancelMapper cancelMapper; private String token; private Integer userId; public BookingsListViewModel(Application application) { super(application); this.webService = RetrofitConfigurationService.getInstance(getApplication()).getELBATWebService(); this.reservationMapper = ReservationMapper.getInstance(); this.cancelMapper = CancelMapper.getInstance(); token = getApplication() .getSharedPreferences("JSONWEBTOKEN", Context.MODE_PRIVATE) .getString("JSONWEBTOKEN", ""); JWT jwt = new JWT(token); Claim userData = jwt.getClaim("userData"); userId = Objects.requireNonNull(userData.asObject(User.class)).getId(); _error.setValue(null); } public LiveData<List<Reservation>> getBookings() { return bookings; } public LiveData<List<Reservation>> getCanceledBookings() { return canceledBookings; } public LiveData<Reservation> getBookingChosen() { return bookingChosen; } public void setBookingChosen(Reservation bookingChosen) { _bookingChosen.setValue(bookingChosen); } public LiveData<NetworkError> getError() { return error; } public LiveData<Integer> getStatutCode() { return statutCode; } public void loadBookings(){ webService.getReservations("Bearer " + token, userId).enqueue(new Callback<List<ReservationDto>>() { @Override public void onResponse(@NotNull Call<List<ReservationDto>> call, @NotNull Response<List<ReservationDto>> response) { if(response.isSuccessful()){ List<Reservation> bookingsToCome = new ArrayList<>(); List<Reservation> canceledBookings = new ArrayList<>(); GregorianCalendar now = new GregorianCalendar(); for (Reservation booking : reservationMapper.mapToReservations(response.body())) { if(now.compareTo(booking.getDateTimeReserved()) > 0 || booking.getCancelled()) canceledBookings.add(booking); else bookingsToCome.add(booking); } _bookings.setValue(bookingsToCome); _canceledBookings.setValue(canceledBookings); } _statutCode.setValue(response.code()); _error.setValue(null); } @Override public void onFailure(@NotNull Call<List<ReservationDto>> call, @NotNull Throwable t) { _error.setValue(t instanceof NoConnectivityException ? NetworkError.NO_CONNECTION : NetworkError.TECHNICAL_ERROR); } }); } public void cancelBooking(){ webService.cancelReservations("Bearer " + token, cancelMapper.mapToCancelDto(userId, bookingChosen.getValue().getDateTimeReserved())).enqueue(new Callback<Void>() { @Override public void onResponse(@NotNull Call<Void> call, @NotNull Response<Void> response) { _statutCode.setValue(response.code()); _error.setValue(null); } @Override public void onFailure(@NotNull Call<Void> call, @NotNull Throwable t) { _error.setValue(t instanceof NoConnectivityException ? NetworkError.NO_CONNECTION : NetworkError.TECHNICAL_ERROR); } }); } }
923b949e80c091fc7fad40461531d593eb8ad1b5
2,503
java
Java
unused/mine/packages/org.cakelab.blender.fileviewer-src-0.0.10/src-dna/org/blender/dna/NodeInputInt.java
sirivus/studioonline
536cb4f3f8a8640821a47c0bdbef3877fe2e6f7a
[ "MIT" ]
null
null
null
unused/mine/packages/org.cakelab.blender.fileviewer-src-0.0.10/src-dna/org/blender/dna/NodeInputInt.java
sirivus/studioonline
536cb4f3f8a8640821a47c0bdbef3877fe2e6f7a
[ "MIT" ]
null
null
null
unused/mine/packages/org.cakelab.blender.fileviewer-src-0.0.10/src-dna/org/blender/dna/NodeInputInt.java
sirivus/studioonline
536cb4f3f8a8640821a47c0bdbef3877fe2e6f7a
[ "MIT" ]
null
null
null
26.347368
115
0.701159
999,655
package org.blender.dna; import java.io.IOException; import org.cakelab.blender.io.block.Block; import org.cakelab.blender.io.block.BlockTable; import org.cakelab.blender.nio.CFacade; import org.cakelab.blender.nio.CMetaData; import org.cakelab.blender.nio.CPointer; /** * Generated facet for DNA struct type 'NodeInputInt'. * * <h3>Class Documentation</h3> * */ @CMetaData(size32=4, size64=4) public class NodeInputInt extends CFacade { /** * This is the sdna index of the struct NodeInputInt. * <p> * It is required when allocating a new block to store data for NodeInputInt. * </p> * @see {@link org.cakelab.blender.io.dna.internal.StructDNA} * @see {@link org.cakelab.blender.io.block.BlockTable#allocate} */ public static final int __DNA__SDNA_INDEX = 494; /** * Field descriptor (offset) for struct member 'integer'. * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * NodeInputInt nodeinputint = ...; * CPointer&lt;Object&gt; p = nodeinputint.__dna__addressof(NodeInputInt.__DNA__FIELD__integer); * CPointer&lt;Integer&gt; p_integer = p.cast(new Class[]{Integer.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'integer'</li> * <li>Signature: 'int'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__integer = new long[]{0, 0}; public NodeInputInt(long __address, Block __block, BlockTable __blockTable) { super(__address, __block, __blockTable); } protected NodeInputInt(NodeInputInt that) { super(that.__io__address, that.__io__block, that.__io__blockTable); } /** * Get method for struct member 'integer'. * @see #__DNA__FIELD__integer */ public int getInteger() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readInt(__io__address + 0); } else { return __io__block.readInt(__io__address + 0); } } /** * Set method for struct member 'integer'. * @see #__DNA__FIELD__integer */ public void setInteger(int integer) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeInt(__io__address + 0, integer); } else { __io__block.writeInt(__io__address + 0, integer); } } /** * Instantiates a pointer on this instance. */ public CPointer<NodeInputInt> __io__addressof() { return new CPointer<NodeInputInt>(__io__address, new Class[]{NodeInputInt.class}, __io__block, __io__blockTable); } }
923b95c96814551a8638d27fb9666646e2948327
213
java
Java
src/main/java/net/splatcraft/api/client/keybind/ChangeSquidFormKeyBehavior.java
splatcraft/splatcraft-fabric
05fd177d3ce1846f13df913e55574319ae3f5742
[ "MIT" ]
3
2021-11-30T17:22:33.000Z
2021-12-27T17:39:39.000Z
src/main/java/net/splatcraft/api/client/keybind/ChangeSquidFormKeyBehavior.java
splatcraft/splatcraft-fabric
05fd177d3ce1846f13df913e55574319ae3f5742
[ "MIT" ]
6
2021-12-23T23:51:31.000Z
2022-02-26T10:47:09.000Z
src/main/java/net/splatcraft/api/client/keybind/ChangeSquidFormKeyBehavior.java
splatcraft/splatcraft-fabric
05fd177d3ce1846f13df913e55574319ae3f5742
[ "MIT" ]
1
2021-12-27T06:46:51.000Z
2021-12-27T06:46:51.000Z
21.3
43
0.769953
999,656
package net.splatcraft.api.client.keybind; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @Environment(EnvType.CLIENT) public enum ChangeSquidFormKeyBehavior { HOLD, TOGGLE }
923b9650eda5cb810c2f45d37b0f1e5691833723
1,297
java
Java
overthere/src/main/java/com/xebialabs/overthere/cifs/winrm/connector/LaxJdkHttpConnector.java
gschueler/overthere
abe4939b41c2619d86521cc97e12f889d096411f
[ "Apache-2.0" ]
null
null
null
overthere/src/main/java/com/xebialabs/overthere/cifs/winrm/connector/LaxJdkHttpConnector.java
gschueler/overthere
abe4939b41c2619d86521cc97e12f889d096411f
[ "Apache-2.0" ]
null
null
null
overthere/src/main/java/com/xebialabs/overthere/cifs/winrm/connector/LaxJdkHttpConnector.java
gschueler/overthere
abe4939b41c2619d86521cc97e12f889d096411f
[ "Apache-2.0" ]
null
null
null
30.880952
96
0.769468
999,657
/* License added by: GRADLE-LICENSE-PLUGIN * * Copyright 2008-2012 XebiaLabs * * 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.xebialabs.overthere.cifs.winrm.connector; import com.xebialabs.overthere.cifs.winrm.TokenGenerator; import javax.net.ssl.HttpsURLConnection; import java.net.URL; /** * Lax HTTPS Connection */ public class LaxJdkHttpConnector extends JdkHttpConnector { static { // FIXME: Every HTTP connection opened after this static initializer is called will be "lazy". HttpsURLConnection.setDefaultHostnameVerifier(new LaxHostnameVerifier()); HttpsURLConnection.setDefaultSSLSocketFactory(new LaxSSLSocketFactory()); } public LaxJdkHttpConnector(URL targetURL, TokenGenerator tokenGenerator) { super(targetURL, tokenGenerator); } }
923b972802e93f779dcc61def9195b2e6a0400e4
908
java
Java
src/mstb/Tools.java
kleinsimon/MicroStructureToolBox
d0a9418a575c841113d25cad4b5932b1554cd24d
[ "MIT" ]
null
null
null
src/mstb/Tools.java
kleinsimon/MicroStructureToolBox
d0a9418a575c841113d25cad4b5932b1554cd24d
[ "MIT" ]
1
2021-02-24T15:55:48.000Z
2021-02-24T15:55:48.000Z
src/mstb/Tools.java
kleinsimon/MicroStructureToolBox
d0a9418a575c841113d25cad4b5932b1554cd24d
[ "MIT" ]
null
null
null
21.619048
69
0.622247
999,658
package mstb; import java.awt.Color; import java.lang.reflect.Field; final public class Tools { public static int getRoundedInt(Double from) { //Long rnd = Math.round(from); //return Math.toIntExact(rnd); return (int) (from + 0.5); } public static String BooleanToString(boolean[] bools) { String ret = ""; for (boolean b : bools) ret += (b == true) ? "1" : "0"; return ret; } public static boolean[] StringToBoolean(String str, int outLength) { boolean[] ret = new boolean[outLength]; if (str == null) return ret; if (str.length() == outLength) { for (int i = 0; i < str.length(); i++) { ret[i] = (str.charAt(i) == '1') ? true : false; } } return ret; } public static Color getColorByName(String Cname) { try { Field field = Color.class.getField(Cname); return (Color)field.get(null); } catch (Exception e) { return Color.RED; } } }
923b97bfe929900a4baf0484c2aca8ed46f1cff0
1,800
java
Java
wicket-core/src/test/java/org/apache/wicket/resource/ApplicationStringResourceLoaderTest.java
chimerast/wicket
02305741273ded4b8de8f3fb6280475e4f68930b
[ "Apache-2.0" ]
1
2022-02-14T13:17:19.000Z
2022-02-14T13:17:19.000Z
wicket-core/src/test/java/org/apache/wicket/resource/ApplicationStringResourceLoaderTest.java
chimerast/wicket
02305741273ded4b8de8f3fb6280475e4f68930b
[ "Apache-2.0" ]
null
null
null
wicket-core/src/test/java/org/apache/wicket/resource/ApplicationStringResourceLoaderTest.java
chimerast/wicket
02305741273ded4b8de8f3fb6280475e4f68930b
[ "Apache-2.0" ]
1
2020-01-20T14:20:30.000Z
2020-01-20T14:20:30.000Z
32.142857
93
0.761111
999,659
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.resource; import java.util.Locale; import org.apache.wicket.resource.loader.ClassStringResourceLoader; import org.apache.wicket.resource.loader.IStringResourceLoader; import org.junit.Test; /** * Tests for the <code>ApplicationStringResourceLoader</code> class. * * @author Chris Turner */ public class ApplicationStringResourceLoaderTest extends StringResourceLoaderTestBase { /** * Return the loader instance * * @return The loader instance to test */ @Override protected IStringResourceLoader createLoader() { return new ClassStringResourceLoader(tester.getApplication().getClass()); } /** * @see org.apache.wicket.resource.StringResourceLoaderTestBase#testLoaderUnknownResources() */ @Override @Test public void loaderUnknownResources() { assertNull( "Unknown resource should return null", createLoader().loadStringResource(component.getClass(), "test.string.that.does.not.exist", Locale.getDefault(), null, null)); } }
923b97e6b8ec07aef1102bf758d06b5efbe08b4d
6,459
java
Java
src/test/java/seedu/address/model/ModelManagerTest.java
chowyiyin/main
e8bab323a301b605400bb83ade04efd53303341c
[ "MIT" ]
null
null
null
src/test/java/seedu/address/model/ModelManagerTest.java
chowyiyin/main
e8bab323a301b605400bb83ade04efd53303341c
[ "MIT" ]
null
null
null
src/test/java/seedu/address/model/ModelManagerTest.java
chowyiyin/main
e8bab323a301b605400bb83ade04efd53303341c
[ "MIT" ]
null
null
null
40.36875
112
0.73804
999,660
package seedu.address.model; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.model.Model.PREDICATE_SHOW_ALL_PERSONS; import static seedu.address.testutil.Assert.assertThrows; import static seedu.address.testutil.TypicalPersons.ALICE; import static seedu.address.testutil.TypicalPersons.BENSON; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import org.junit.jupiter.api.Test; import javafx.collections.ObservableMap; import seedu.address.commons.core.GuiSettings; import seedu.address.model.person.NameContainsKeywordsPredicate; import seedu.address.testutil.AddressBookBuilder; import seedu.address.testutil.TypicalAddressBook; import seedu.address.testutil.TypicalPersons; public class ModelManagerTest { private ModelManager modelManager = new ModelManager(); @Test public void constructor() { assertEquals(new UserPrefs(), modelManager.getUserPrefs()); assertEquals(new GuiSettings(), modelManager.getGuiSettings()); assertEquals(new AddressBook(), new AddressBook(modelManager.getAddressBook())); } @Test public void setUserPrefs_nullUserPrefs_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> modelManager.setUserPrefs(null)); } @Test public void setUserPrefs_validUserPrefs_copiesUserPrefs() { UserPrefs userPrefs = new UserPrefs(); userPrefs.setAddressBookFilePath(Paths.get("address/book/file/path")); userPrefs.setGuiSettings(new GuiSettings(1, 2, 3, 4)); modelManager.setUserPrefs(userPrefs); assertEquals(userPrefs, modelManager.getUserPrefs()); // Modifying userPrefs should not modify modelManager's userPrefs UserPrefs oldUserPrefs = new UserPrefs(userPrefs); userPrefs.setAddressBookFilePath(Paths.get("new/address/book/file/path")); assertEquals(oldUserPrefs, modelManager.getUserPrefs()); } @Test public void setGuiSettings_nullGuiSettings_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> modelManager.setGuiSettings(null)); } @Test public void setGuiSettings_validGuiSettings_setsGuiSettings() { GuiSettings guiSettings = new GuiSettings(1, 2, 3, 4); modelManager.setGuiSettings(guiSettings); assertEquals(guiSettings, modelManager.getGuiSettings()); } @Test public void setAddressBookFilePath_nullPath_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> modelManager.setAddressBookFilePath(null)); } @Test public void setAddressBookFilePath_validPath_setsAddressBookFilePath() { Path path = Paths.get("address/book/file/path"); modelManager.setAddressBookFilePath(path); assertEquals(path, modelManager.getAddressBookFilePath()); } @Test public void hasPerson_nullPerson_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> modelManager.hasPerson(null)); } @Test public void hasPerson_personNotInAddressBook_returnsFalse() { assertFalse(modelManager.hasPerson(ALICE)); } @Test public void hasPerson_personInAddressBook_returnsTrue() { modelManager.addPerson(ALICE); assertTrue(modelManager.hasPerson(ALICE)); } @Test public void getFilteredPersonList_modifyList_throwsUnsupportedOperationException() { assertThrows(UnsupportedOperationException.class, () -> modelManager.getFilteredPersonList().remove(0)); } @Test public void getPolicyPopularityBreakdown_typicalAddressBook_returnsTrue() { modelManager.setAddressBook(TypicalAddressBook.getTypicalAddressBook()); ObservableMap<String, Integer> result = modelManager.getPolicyPopularityBreakdown(); ObservableMap<String, Integer> expected = TypicalPersons.getTypicalPolicyPopularityBreakdown(); assertEquals(result, expected); } @Test public void getAgeGroupBreakdown() { modelManager.setAddressBook(TypicalAddressBook.getTypicalAddressBook()); ObservableMap<String, Integer> result = modelManager.getAgeGroupBreakdown(); ObservableMap<String, Integer> expected = TypicalPersons.getAgeGroupBreakdown(); assertEquals(result, expected); } @Test public void getGenderBreakdown() { modelManager.setAddressBook(TypicalAddressBook.getTypicalAddressBook()); ObservableMap<String, Integer> result = modelManager.getGenderBreakdown(); ObservableMap<String, Integer> expected = TypicalPersons.getGenderBreakdown(); assertEquals(result, expected); } @Test public void equals() { AddressBook addressBook = new AddressBookBuilder().withPerson(ALICE).withPerson(BENSON).build(); AddressBook differentAddressBook = new AddressBook(); UserPrefs userPrefs = new UserPrefs(); // same values -> returns true modelManager = new ModelManager(addressBook, userPrefs); ModelManager modelManagerCopy = new ModelManager(addressBook, userPrefs); assertTrue(modelManager.equals(modelManagerCopy)); // same object -> returns true assertTrue(modelManager.equals(modelManager)); // null -> returns false assertFalse(modelManager.equals(null)); // different types -> returns false assertFalse(modelManager.equals(5)); // different addressBook -> returns false assertFalse(modelManager.equals(new ModelManager(differentAddressBook, userPrefs))); // different filteredList -> returns false String[] keywords = ALICE.getName().fullName.split("\\s+"); modelManager.updateFilteredPersonList(new NameContainsKeywordsPredicate(Arrays.asList(keywords))); assertFalse(modelManager.equals(new ModelManager(addressBook, userPrefs))); // resets modelManager to initial state for upcoming tests modelManager.updateFilteredPersonList(PREDICATE_SHOW_ALL_PERSONS); // different userPrefs -> returns false UserPrefs differentUserPrefs = new UserPrefs(); differentUserPrefs.setAddressBookFilePath(Paths.get("differentFilePath")); assertFalse(modelManager.equals(new ModelManager(addressBook, differentUserPrefs))); } }
923b9d4b3270b960f4303e93f29b439f807dd35f
2,176
java
Java
quickstart-openejb/ejb/src/main/java/org/jeecqrs/example/openejb/domain/model/order/Order.java
JEEventStore/JEECQRS-Quickstart-Sample
574b621c24cdeac38a8ed51a83951bf6773aa873
[ "MIT" ]
6
2015-02-23T23:39:01.000Z
2018-01-29T16:33:56.000Z
quickstart-openejb/ejb/src/main/java/org/jeecqrs/example/openejb/domain/model/order/Order.java
JEEventStore/JEECQRS-Examples
574b621c24cdeac38a8ed51a83951bf6773aa873
[ "MIT" ]
2
2015-08-11T23:22:05.000Z
2015-08-17T09:29:11.000Z
quickstart-openejb/ejb/src/main/java/org/jeecqrs/example/openejb/domain/model/order/Order.java
JEEventStore/JEECQRS-Examples
574b621c24cdeac38a8ed51a83951bf6773aa873
[ "MIT" ]
4
2015-07-17T15:25:46.000Z
2016-12-03T01:55:03.000Z
26.536585
102
0.65579
999,661
package org.jeecqrs.example.openejb.domain.model.order; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jeecqrs.common.domain.model.AbstractEventSourcedAggregateRoot; import org.joda.time.DateTime; public final class Order extends AbstractEventSourcedAggregateRoot<Order, OrderId> { private OrderId orderId; private DateTime orderDate; private Orderer orderer; private final Map<OrderLineId, OrderLine> orderLines = new HashMap<>(); private DateTime shippedAt = null; private String cancelReason = null; protected Order(OrderId orderId, DateTime orderDate, String orderer, List<OrderLine> orderLines) { this.apply(new OrderPlaced(orderId, orderDate, new Orderer(orderer), orderLines)); } @Override public OrderId id() { return this.orderId; } public DateTime orderDate() { return orderDate; } public Orderer orderer() { return orderer; } public BigDecimal orderTotals() { BigDecimal sum = BigDecimal.ZERO; for (OrderLine ol : orderLines.values()) { BigDecimal quantity = new BigDecimal(ol.quantity()); sum = sum.add(ol.pricePerItem().multiply(quantity)); } return sum; } public void ship() { this.apply(new OrderShipped(orderId, new DateTime())); } public void cancel(String reason) { this.apply(new OrderCanceled(orderId, reason)); } public DateTime shippedAt() { return this.shippedAt; } public String cancelReason() { return this.cancelReason; } protected void when(OrderPlaced event) { this.orderId = event.orderId(); this.orderDate = event.orderDate(); this.orderer = event.orderer(); for (OrderLine ol : event.orderLines()) this.orderLines.put(ol.id(), ol); } protected void when(OrderShipped event) { this.shippedAt = event.shippingDate(); } protected void when(OrderCanceled event) { this.cancelReason = event.reason(); } // required for repository private Order() { } }
923b9e798136aea87dec018c5f66d51510561152
3,962
java
Java
install/tools/src/org/pimslims/command/DataUpdate/DataFixerList.java
chrishmorris/PiMS
cdcc1a5b17b6753a11081bf7163f77596831916c
[ "BSD-2-Clause" ]
null
null
null
install/tools/src/org/pimslims/command/DataUpdate/DataFixerList.java
chrishmorris/PiMS
cdcc1a5b17b6753a11081bf7163f77596831916c
[ "BSD-2-Clause" ]
null
null
null
install/tools/src/org/pimslims/command/DataUpdate/DataFixerList.java
chrishmorris/PiMS
cdcc1a5b17b6753a11081bf7163f77596831916c
[ "BSD-2-Clause" ]
null
null
null
37.377358
105
0.573195
999,662
/** * current-pims-web org.pimslims.command.DataUpdate DataFixerList.java * * @author bl67 * @date 17 Dec 2007 * * Protein Information Management System * @version: 1.3 * * Copyright (c) 2007 bl67 * * */ package org.pimslims.command.DataUpdate; import java.io.File; import java.io.FileNotFoundException; import java.util.LinkedList; import java.util.List; import org.pimslims.dao.AbstractModel; import org.pimslims.dao.ModelImpl; import org.pimslims.dao.WritableVersion; import org.pimslims.exception.AbortedException; import org.pimslims.exception.AccessException; import org.pimslims.exception.ConstraintException; /** * DataFixerList * */ public class DataFixerList { protected static final List<IDataFixer> getDataFixers() { final List<IDataFixer> dataFixers = new LinkedList<IDataFixer>(); dataFixers.add(new OrganismsFixer()); return dataFixers; } private static AbstractModel model; public static void main(final String[] args) throws FileNotFoundException { if (args.length != 1) { DataFixerList.model = ModelImpl.getModel(); } else { DataFixerList.initModel(args[0]); } int currentFixer = 1; final int totoalFixer = DataFixerList.getDataFixers().size(); for (final IDataFixer fixer : DataFixerList.getDataFixers()) { System.out.println("\n---------Fixer " + currentFixer + " of " + totoalFixer + " -----------------------------------"); currentFixer++; System.out.println(fixer.getClass().getSimpleName() + ": " + fixer.getDescription() + "\n"); final WritableVersion wv = DataFixerList.model.getWritableVersion(org.pimslims.access.Access.ADMINISTRATOR); try { final Boolean result = fixer.fixData(wv); if (result != null && result) { System.out.println(fixer.getClass().getSimpleName() + " did not find any problem!"); } wv.commit(); } catch (final ConstraintException e) { e.printStackTrace(); System.out.println(fixer.getClass().getSimpleName() + " failed due to " + e.getLocalizedMessage()); } catch (final AccessException e) { e.printStackTrace(); System.out.println(fixer.getClass().getSimpleName() + " failed due to " + e.getLocalizedMessage()); } catch (final AbortedException e) { e.printStackTrace(); System.out.println(fixer.getClass().getSimpleName() + " failed due to " + e.getLocalizedMessage()); } finally { if (!wv.isCompleted()) { wv.abort(); System.out.println("Transaction(s) aborted!"); } } System.out.println(fixer.getClass().getSimpleName() + " has finished!"); } System.out.println("-------------All Fixers have been finished!---------------------------"); } /** * @param string * @throws FileNotFoundException */ private static void initModel(final String propertyFileName) throws FileNotFoundException { //start from propertyFile if provided System.out.println("loading DB connection info from: " + propertyFileName); final File properties = new java.io.File(propertyFileName); if (!properties.exists()) { System.out.println("file does NOT exist:" + propertyFileName); } else if (!properties.isFile()) { System.out.println("please give a file NOT a directory: " + propertyFileName); } DataFixerList.model = org.pimslims.dao.ModelImpl.getModel(properties); } }
923b9e9acceb043a97e7783712c9f394a1bef957
16,116
java
Java
src/main/java/com/demshape/factorization/model/Factorization.java
ozgurdemir/item-item-factorization
3b18dafe7ad0687243910c77788c3650d0fe63e1
[ "MIT" ]
2
2017-12-19T09:14:55.000Z
2018-01-12T15:06:40.000Z
src/main/java/com/demshape/factorization/model/Factorization.java
ozgurdemir/item-item-factorization
3b18dafe7ad0687243910c77788c3650d0fe63e1
[ "MIT" ]
null
null
null
src/main/java/com/demshape/factorization/model/Factorization.java
ozgurdemir/item-item-factorization
3b18dafe7ad0687243910c77788c3650d0fe63e1
[ "MIT" ]
null
null
null
37.742389
231
0.619447
999,663
package com.demshape.factorization.model; import com.demshape.factorization.dataset.DatasetInterface; import com.demshape.factorization.datastructure.DataPoint; import com.demshape.factorization.datastructure.SparseVector; import com.demshape.factorization.lossfunction.LossFunctionInterface; import com.demshape.factorization.metric.LossAverager; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jblas.FloatMatrix; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadLocalRandom; import static com.demshape.factorization.tools.GlobalConstants.HASH_MAP_LOAD_FACTOR; import static com.demshape.factorization.tools.GlobalConstants.hashSize; public class Factorization { private static final Logger logger = LogManager.getLogger(Factorization.class); /** * number of features */ public int dimensions; /** * initial learn rate for sgd */ public float learnRate; /** * regularization factor for the bias */ public float lambda1; /** * regularization factor for the latent features */ public float lambda2; /** * number of learn iterations */ public int iterations; /** * number of negative samples */ public int negatives; /** * loss function to be used for training */ public LossFunctionInterface lossFunction; /** * wheather a regreassion should be used instead of a classification */ public boolean regression; /** * table size used for negative sampling */ public int tableSize; /** * minimum count after which no weighting is applied to individual samples */ public int minCount; /** * smoothing parameter for negative sampling */ public double alpha; /** * bins used to calculate loss */ public int[] bins; // internal data structures public FloatMatrix biases; public FloatMatrix[] latentVectors; public float[] gradientLengths; public int[] samplingTable; public int[] itemCount; public int[] contextCount; public Factorization() { } public Factorization(int dimensions, float learnRate, float lambda1, float lambda2, int iterations, int negatives, LossFunctionInterface lossFunction, boolean regression, int tableSize, int minCount, double alpha, int[] bins) { this.dimensions = dimensions; this.learnRate = learnRate; this.lambda1 = lambda1; this.lambda2 = lambda2; this.iterations = iterations; this.negatives = negatives; this.lossFunction = lossFunction; this.regression = regression; this.tableSize = tableSize; this.minCount = minCount; this.alpha = alpha; this.bins = bins; } public void train(DatasetInterface trainset, SparseVector[] optionalFeatures, int numFeatures) throws InterruptedException, ExecutionException { initParameters(numFeatures, dimensions); initLearnRates(numFeatures); count(numFeatures, trainset); if (negatives > 0) initSamplingTable(contextCount, alpha, tableSize); for (int iteration = 1; iteration <= iterations; ++iteration) { logger.info(String.format("Iteration %d start...", iteration)); trainset.parallelStream().map(dataPoint -> { LossAverager lossAverager = new LossAverager(bins); final int itemOccurrence = itemCount[dataPoint.itemId]; // positive data points float measured = 1.0f; float weight = dataPoint.rating; if (regression) { measured = (float) Math.log(1.0 + dataPoint.rating); weight = weight(dataPoint.rating); } SparseVector sparseVector = dataPoint.toSparseVector(optionalFeatures[dataPoint.itemId]); float loss = trainStep(sparseVector, measured, weight); lossAverager.add(loss, itemOccurrence); // negative sampling int numSamples = negatives; for (int i = 0; i < negatives; i++) { int negativeContext = sample(); if (dataPoint.contextId == negativeContext) { --numSamples; continue; } dataPoint.contextId = negativeContext; measured = -1.0f; weight = dataPoint.rating / numSamples; if (regression) { measured = 0.0f; // log(1.0 + 0) weight = weight(1.0f); } sparseVector = dataPoint.toSparseVector(optionalFeatures[dataPoint.itemId]); loss = trainStep(sparseVector, measured, weight); lossAverager.add(loss, itemOccurrence); } return lossAverager; }).reduce((a, b) -> a.add(b)).ifPresent(iterationLoss -> logger.info("train loss: " + iterationLoss)); } } public float trainStep(SparseVector sparseVector, float measured, float weight) { final float predicted = predict(sparseVector); final float error = weight * lossFunction.gDeriv(predicted, measured); // pre compute sum of vectors to speed up computation final FloatMatrix vectorSum = FloatMatrix.zeros(latentVectors[0].length); for (SparseVector.SparseEntry entry : sparseVector) vectorSum.addi(latentVectors[entry.key].mul(entry.value)); // gradient updates for (SparseVector.SparseEntry entryA : sparseVector) { int key = entryA.key; float value = entryA.value; FloatMatrix vector = latentVectors[key]; // quadratic term final FloatMatrix gradientA = vectorSum.mul(value).subi(vector.mul(value * value)); gradientA.muli(error).addi(vector.mul(lambda2)); float individualLearnRate = updateLearnRate(key, gradientA); vector.subi(gradientA.muli(learnRate * individualLearnRate)); // linear term float current = biases.get(key); float linearGradient = value * error + lambda1 * current; biases.put(key, current - learnRate * individualLearnRate * linearGradient); } // note that reported loss does not contain regularization term return weight * lossFunction.g(predicted, measured); } public float predict(SparseVector sparseVector) { float predicted = 0.0f; for (int i = 0; i < sparseVector.size(); ++i) { // linear term SparseVector.SparseEntry entryA = sparseVector.get(i); int keyA = entryA.key; float valueA = entryA.value; FloatMatrix vectorA = latentVectors[keyA]; predicted += valueA * biases.get(keyA); // quadratic term // XXX(od): do not include quadratic features for (int j = i + 1; j < sparseVector.size(); ++j) { SparseVector.SparseEntry entryB = sparseVector.get(j); int keyB = entryB.key; float valueB = entryB.value; FloatMatrix vectorB = latentVectors[keyB]; predicted += valueA * valueB * vectorA.dot(vectorB); } } return predicted; } /** * Predict loss on a data set e.g. test set * @param dataset Input data set * @param optionalFeatures optional features of the data set * @return Binned losses */ public LossAverager predict(DatasetInterface dataset, SparseVector[] optionalFeatures) { return dataset.parallelStream().map(dataPoint -> { LossAverager lossAverager = new LossAverager(bins); SparseVector sparseVector = dataPoint.toSparseVector(optionalFeatures[dataPoint.itemId]); float predicted = predict(sparseVector); int itemOccurrence = itemCount[dataPoint.itemId]; float measured = 1.0f; float weight = dataPoint.rating; if (regression) { measured = (float) Math.log(1.0f + dataPoint.rating); weight = weight(dataPoint.rating); } float loss = weight * lossFunction.g(predicted, measured); lossAverager.add(loss, itemOccurrence); // negative samples int numSamples = negatives; for (int i = 0; i < negatives; i++) { int negativeContext = sample(); if (dataPoint.contextId == negativeContext) { --numSamples; continue; } dataPoint.contextId = negativeContext; measured = -1.0f; weight = dataPoint.rating / numSamples; if (regression) { measured = 0.0f; // log(1.0 + 0) weight = weight(1.0f); } sparseVector = dataPoint.toSparseVector(optionalFeatures[dataPoint.itemId]); loss = weight * lossFunction.g(predict(sparseVector), measured); lossAverager.add(loss, itemOccurrence); } return lossAverager; }).reduce((a, b) -> a.add(b)).get(); } /** * Updates sum of gradient length and returns updated learn rate * @param id id of item * @param gradient current gradient * @return updated learn rate */ public float updateLearnRate(int id, FloatMatrix gradient) { gradientLengths[id] += gradientLength(gradient); return learnRate(gradientLengths[id]); } public float gradientLength(FloatMatrix gradient) { return gradient.dot(gradient) / (float) gradient.length; } /** * Returns AdaGrad learn rate * @param gradientLength current gradient length * @return AdaGrad learn rate */ public float learnRate(float gradientLength) { return (float) (1.0 / Math.sqrt(gradientLength)); } /** * Weight based on number of co-occurrences * @param score Score of pair * @return weight based on score */ public float weight(float score) { if (score <= minCount) return (float) Math.pow(score / minCount, alpha); return 1.0f; } /** * Init context, item and feature latent vectors with a normal distribution and * set biases to 0. * @param numFeatures number of additional features * @param dimensions number of latent factors */ public void initParameters(int numFeatures, int dimensions) { logger.info("initializing parameters..."); biases = FloatMatrix.zeros(numFeatures); latentVectors = new FloatMatrix[numFeatures]; for (int i = 0; i < numFeatures; ++i) latentVectors[i] = gaussVector(dimensions).divi(dimensions); } public void initLearnRates(int numFeatures) { logger.info("initializing learn rates..."); gradientLengths = new float[numFeatures]; } /** * Number of item occurrences in the train set. Used to build up the sample table and bin the results. * Note that the result array is not dense. Context and item indices will be * filled in with zeros. * @param numFeatures number of features * @param dataset the train set */ public void count(int numFeatures, DatasetInterface dataset) { logger.info("counting item occurrence..."); itemCount = new int[numFeatures]; contextCount = new int[numFeatures]; for (DataPoint dataPoint : dataset) { contextCount[dataPoint.contextId]++; itemCount[dataPoint.itemId]++; } } /** * Creates a sampling table for a given distribution. * Example for size = 3 and distribution = 1 to 10, 2 to 20 will result in int[] = {1, 2, 2} * Hence, a uniform sampling over this samplingTable will result in a distribution similar to the given * one. * @param itemCount an array which holds the item occurrences * @param alpha smoothing parameter * @param tableSize sampling table size */ public void initSamplingTable(int[] itemCount, double alpha, int tableSize) { logger.info("initializing sampling table..."); samplingTable = new int[tableSize]; double sum = 0.0; for (int itemId = 0; itemId < itemCount.length; ++itemId) sum += Math.pow(itemCount[itemId], alpha); int tableIndex = 0; double cumulative = 0.0; for (int itemId = 0; itemId < itemCount.length; ++itemId) { if (itemCount[itemId] > 0) { cumulative += Math.pow(itemCount[itemId], alpha) / sum; while (cumulative > (tableIndex / (double) tableSize) && tableIndex < tableSize) samplingTable[tableIndex++] = itemId; } } } /** * Samples a negative item according to samplingTable distribution * @return id of sampled item */ public int sample() { return samplingTable[ThreadLocalRandom.current().nextInt(tableSize)]; } /** * Returns a vector initialized with a gaussian distribution * mean = 1, std = 1 * @param dimensions number of dimensions * @return Normalized vector */ public FloatMatrix gaussVector(int dimensions) { return FloatMatrix.randn(dimensions); } /** * Given a dense mapping returns feature latent vectors * @param map mapping from initial to dense ids * @return mapping from original id to latent vectors */ public Map<Integer, FloatMatrix> vectors(Map<Integer, Integer> map) { Map<Integer, FloatMatrix> vectors = new HashMap<>(hashSize(map.size()), HASH_MAP_LOAD_FACTOR); map.forEach((id, mappedId) -> vectors.put(id, vector(mappedId))); return vectors; } public FloatMatrix vector(int mappedId) { return latentVectors[mappedId]; } /** * Returns context / item latent vectors summed up with feature latent vectors * @param map mapping from original to dense ids * @param featureMap embeddings of additional features * @param unmappedFeatures unmapped features * @return context / item latent vectors summed up with feature latent vectors */ public Map<Integer, FloatMatrix> featureVectors(Map<Integer, Integer> map, Map<Integer, Integer> featureMap, Map<Integer, SparseVector> unmappedFeatures) { Map<Integer, FloatMatrix> vectors = new HashMap<>(hashSize(map.size()), HASH_MAP_LOAD_FACTOR); map.forEach((id, mappedId) -> { FloatMatrix summedVector = vector(mappedId).dup(); unmappedFeatures.getOrDefault(id, new SparseVector(0)).forEach((unmappedFeature) -> summedVector.addi(vector(featureMap.get(unmappedFeature.key)).mul(unmappedFeature.value))); vectors.put(id, summedVector); }); return vectors; } /** * Returns embeddings of additional features * @param featureMap embeddings of additional features * @param unmappedFeatures unmapped features * @return embeddings of additional features */ public Map<Integer, FloatMatrix> featureVectors(Map<Integer, Integer> featureMap, Map<Integer, SparseVector> unmappedFeatures) { Map<Integer, FloatMatrix> vectors = new HashMap<>(hashSize(unmappedFeatures.size()), HASH_MAP_LOAD_FACTOR); unmappedFeatures.forEach((id, sparseVector) -> { FloatMatrix summedVector = FloatMatrix.zeros(dimensions); sparseVector.forEach((unmappedFeature) -> summedVector.addi(vector(featureMap.get(unmappedFeature.key)).mul(unmappedFeature.value))); vectors.put(id, summedVector); }); return vectors; } }