blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
daf3e57079c1e7123cd3cbdfc5681c9e501a3b86
225bd2dc2179d10ec57ccd9f4da8ecb1ef119057
/app/src/main/java/com/louisgeek/myarch/image/picasso/PicassoImageLoader.java
f7b89898351b261223baaff8d213660ed45cfa1c
[]
no_license
louisgeek/MyArch
0676e5fa7a387ff037bd572798c13184a61c6209
e1e4767ffea519671f6610309daac2c444d21ee0
refs/heads/master
2020-03-14T12:09:43.767820
2018-05-06T16:36:54
2018-05-06T16:36:54
131,605,632
0
0
null
null
null
null
UTF-8
Java
false
false
645
java
package com.louisgeek.myarch.image.picasso; import android.widget.ImageView; import com.louisgeek.myarch.image.IImageLoader; import com.squareup.picasso.Picasso; import java.io.File; public class PicassoImageLoader implements IImageLoader { @Override public void load(ImageView imageView, int imageResId) { Picasso.get().load(imageResId).into(imageView); } @Override public void load(ImageView imageView, File imageFile) { Picasso.get().load(imageFile).into(imageView); } @Override public void load(ImageView imageView, String url) { Picasso.get().load(url).into(imageView); } }
[ "louisgeek@qq.com" ]
louisgeek@qq.com
c971187554c9423014250611d0850555b3518297
5eba6cc6555dc9830d4d1e44713a4eb050d99b82
/2.JavaCore/src/com/javarush/task/task15/task1504/Solution.java
9b4f309288d12cac913b938bff4a44c4824b825e
[]
no_license
sashashtmv/JavaRushTasks
761b7d3fe0dbb5413e8b0f6c161735c54369d189
5acd46eed5b0a4f131b0b509c6364582ec2f20b5
refs/heads/master
2020-03-28T14:40:42.276808
2019-01-11T17:30:03
2019-01-11T17:30:03
148,511,125
0
0
null
null
null
null
UTF-8
Java
false
false
1,825
java
package com.javarush.task.task15.task1504; import java.util.LinkedList; import java.util.List; /* ООП - книги */ public class Solution { public static void main(String[] args) { List<Book> books = new LinkedList<Book>(); books.add(new MarkTwainBook("Tom Sawyer")); books.add(new AgathaChristieBook("Hercule Poirot")); System.out.println(books); } abstract static class Book { private String author; public Book(String author) { this.author = author; } public abstract Book getBook(); public abstract String getTitle(); private String getOutputByBookType() { String agathaChristieOutput = author + ", " + getBook().getTitle() + " is a detective"; String markTwainOutput = getBook().getTitle() + " book was written by " + author; String output = "output"; if(author == "Mark Twain") output = markTwainOutput; if (author == "Agatha Christie") output = agathaChristieOutput;//Add your code here return output; } public String toString() { return getOutputByBookType(); } } public static class MarkTwainBook extends Book{ String title; public MarkTwainBook(String title){ super("Mark Twain"); this.title=title; } public MarkTwainBook getBook(){return this;} public String getTitle(){return title;} } public static class AgathaChristieBook extends Book{ String title; public AgathaChristieBook(String title){ super("Agatha Christie"); this.title=title; } public AgathaChristieBook getBook(){return this;} public String getTitle(){return title;} } }
[ "sasha-shtmv@rambler.ru" ]
sasha-shtmv@rambler.ru
cbc9f8271e5a8daf9c55c5bf072895b99bb2b308
1d9f7acb46ddc71a0ea14ec13c0d2129d1928e4c
/src/main/java/com/bjdvt/wx/config/WebSecurityConfig.java
be6f1b4f6ecd4508b6061aad84ef93766426418d
[]
no_license
dantegarden/wxService
1216e475a8f59c0db8bccc96b701a0df2b45984c
ed8a6bc9447002ee14c88795a546670f59b9822f
refs/heads/master
2020-04-25T07:53:39.038211
2019-02-26T03:15:10
2019-02-26T03:15:10
172,627,634
0
0
null
null
null
null
UTF-8
Java
false
false
2,499
java
package com.bjdvt.wx.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import com.bjdvt.wx.filter.HTTPBearerAuthorizeAttribute; /** * SpringSecurity的配置 * 通过SpringSecurity的配置,将JWTLoginFilter,JWTAuthenticationFilter组合在一起 * @author zhaoxinguo on 2017/9/13. */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { /** * 需要放行的URL */ private static final String[] AUTH_WHITELIST = { // -- register url "/**", "/img/**", "/user/getWxSessionKey/**", "/user/login/**", "/image/getImage/**" // other public endpoints of your API may be appended to this array }; // 设置 HTTP 验证规则 @Override protected void configure(HttpSecurity http) throws Exception { LogoutConfigurer<HttpSecurity> httpSecurityLogoutConfigurer = http.cors().and().csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() .antMatchers(AUTH_WHITELIST).permitAll() .anyRequest().authenticated() // 所有请求需要身份认证 .and() .addFilter(new HTTPBearerAuthorizeAttribute(authenticationManager())) .logout(); } }
[ "lijing@bjdvt.com" ]
lijing@bjdvt.com
f1a29ba94ad301a5e16c1b8aa0087ab39198086f
03e248ec503e9b82bc230a90bf2e7af6f1e3d72e
/src/main/java/com/example/demo/Repository/RepoParticipacion.java
c3dad15597e822f4f7e926507f1ceda81a5907e2
[]
no_license
alex0vlz22/backendProyectoFinalAndroid2
6ada66af1d57ce6f15ce5cf7fbb9dfb78e9b085f
7cef7756e888e73ff113747664aa9a527653e49b
refs/heads/main
2023-01-20T04:52:59.880527
2020-11-26T04:53:52
2020-11-26T04:53:52
308,458,754
1
0
null
null
null
null
UTF-8
Java
false
false
1,052
java
package com.example.demo.Repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.example.demo.Entity.Estudiante; import com.example.demo.Entity.Participacion; public interface RepoParticipacion extends JpaRepository<Participacion, Integer>{ Participacion findByDescripcion(String descripcion); Participacion findById(int id); List<Participacion> findAllByIdForo(int idForo); List<Participacion> findByIdParticipante(int idParticipante); List<Participacion> findAll(); @Query("Select p from Participacion p where p.idParticipante= ?1 and p.idForo=?2") public List<Participacion> buscarParticipacionesPorParticipanteYForo(int idParticipante, int idForo); /* @Query("select * from (select * from (Select distinct idEstudiante from participacion p where p.idForo= ?1) e join Estudiantes est where e.idEstudiante= est.id) minus select * from estudiantes estud") public List<Estudiante> contarFaltantes(int idForo); */ }
[ "edwardlopez625@gmail.com" ]
edwardlopez625@gmail.com
a7b92e1d6789a0287a3bc5e1dcefc3fd6ab7a480
80addf939aac0e118067574d9358dbfcdb794ac6
/TMS/firstlesson (6)/firstlesson/src/by/tms/test/B.java
79aa140d974c23d386fab3f7afb454750b0fbc1c
[]
no_license
GH-Slav/myJava
80526cf0f56303b978fcc2f2559dc0210172feb9
3f9e04b1be8f856e5d8b23e7f8eac105186f5f4c
refs/heads/master
2021-05-18T11:34:03.138190
2020-03-30T06:52:27
2020-03-30T06:52:27
251,228,167
0
0
null
null
null
null
UTF-8
Java
false
false
115
java
package by.tms.test; public class B extends A { public void run() { System.out.println("B"); } }
[ "59572751+GH-Slav@users.noreply.github.com" ]
59572751+GH-Slav@users.noreply.github.com
dd1df99e3ea74a6c93c16f0e26843b25adf3eec2
318fa11192599f2fe82b0b2d2b4cb3217191e657
/Dazaza/app/src/main/java/com/dazaza/model/ModelInfoImage.java
936908b8988f3911a5e573c3eab89d42fcaf6eb2
[]
no_license
cacard/DazazaAndroid
6bfac2c64f0a0551b581ceaa30f422e40e3b2d03
378969f4a8cb7d76470bbddc594181cd2f96d9f1
refs/heads/master
2021-01-20T02:17:12.058300
2015-09-23T03:40:07
2015-09-23T03:40:07
41,336,980
0
0
null
null
null
null
UTF-8
Java
false
false
2,383
java
package com.dazaza.model; import android.os.Parcel; import android.os.Parcelable; import java.io.Serializable; import java.util.Date; /** * Created by cunqingli on 2015/9/11. */ public class ModelInfoImage implements Serializable, Parcelable { private static final long serialVersionUID = 7870149986186215424L; private int infoid; private Date posttime; private String note; private String path; private int id; private String imgUrl; public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } public int getInfoid() { return infoid; } public void setInfoid(int infoid) { this.infoid = infoid; } public Date getPosttime() { return posttime; } public void setPosttime(Date posttime) { this.posttime = posttime; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.infoid); dest.writeLong(posttime != null ? posttime.getTime() : -1); dest.writeString(this.note); dest.writeString(this.path); dest.writeInt(this.id); dest.writeString(this.imgUrl); } public ModelInfoImage() { } protected ModelInfoImage(Parcel in) { this.infoid = in.readInt(); long tmpPosttime = in.readLong(); this.posttime = tmpPosttime == -1 ? null : new Date(tmpPosttime); this.note = in.readString(); this.path = in.readString(); this.id = in.readInt(); this.imgUrl = in.readString(); } public static final Creator<ModelInfoImage> CREATOR = new Creator<ModelInfoImage>() { public ModelInfoImage createFromParcel(Parcel source) { return new ModelInfoImage(source); } public ModelInfoImage[] newArray(int size) { return new ModelInfoImage[size]; } }; }
[ "cacard@126.com" ]
cacard@126.com
73b5989ef29f42cad0233c648b94fad63dd26396
485c4fb77a6a3e8773ac98cb4bbf4915ecd82a0a
/app/src/main/java/com/example/geomob2/Videos.java
54d9ccc64f6a17428386f2a27a4b8bacb531a822
[]
no_license
RekkasImene/ProjetMob
8b2c6af68b7b74d026110e2e37024b1f75dbc745
596fba3d24fa48a28d7c2c5826b06cff1a438a53
refs/heads/master
2022-11-15T12:07:16.739505
2020-06-30T12:38:45
2020-06-30T12:38:45
276,091,348
0
0
null
null
null
null
UTF-8
Java
false
false
849
java
package com.example.geomob2; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "Videos") public class Videos { public Videos(String title,String video) { this.title = title; this.video = video; } @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(name = "title") private String title; @ColumnInfo(name = "video") private String video; public int getId() { return id; } public String getTitle() { return title; } public String getVideo() { return video; } public void setTitle(String title) { this.title = title; } public void setVideo(String name) { this.video = name; } public void setId(int name) { this.id = name; } }
[ "you@example.com" ]
you@example.com
49dc67a0f06d3a7d4b22e3110bc5a944adcc8f0c
f0e43a48af9597aac948a59f6385354ef0bea42a
/commons-validator-1.4.0-org/src/main/java/org/apache/commons/validator/util/ValidatorUtils.java
fbb63ca519ced03ec1a728c9f51bee197309b71f
[ "Apache-2.0" ]
permissive
jonkiky/reg-ex
7135f185fc1a23dd491cf4b261c3322242da9b24
fa6455f42a31f7c79542557a1735547cded44c74
refs/heads/master
2023-06-26T13:40:53.166400
2021-07-27T14:46:52
2021-07-27T14:46:52
390,018,174
0
0
null
null
null
null
UTF-8
Java
false
false
6,622
java
/* * 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.commons.validator.util; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.FastHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.validator.Arg; import org.apache.commons.validator.Msg; import org.apache.commons.validator.Var; /** * Basic utility methods. * <p> * The use of FastHashMap is deprecated and will be replaced in a future * release. * </p> * * @version $Revision: 1227703 $ $Date: 2012-01-05 18:15:19 +0100 (Thu, 05 Jan 2012) $ */ public class ValidatorUtils { /** * <p>Replace part of a <code>String</code> with another value.</p> * * @param value <code>String</code> to perform the replacement on. * @param key The name of the constant. * @param replaceValue The value of the constant. * * @return The modified value. */ public static String replace(String value, String key, String replaceValue) { if (value == null || key == null || replaceValue == null) { return value; } int pos = value.indexOf(key); if (pos < 0) { return value; } int length = value.length(); int start = pos; int end = pos + key.length(); if (length == key.length()) { value = replaceValue; } else if (end == length) { value = value.substring(0, start) + replaceValue; } else { value = value.substring(0, start) + replaceValue + replace(value.substring(end), key, replaceValue); } return value; } /** * Convenience method for getting a value from a bean property as a * <code>String</code>. If the property is a <code>String[]</code> or * <code>Collection</code> and it is empty, an empty <code>String</code> * "" is returned. Otherwise, property.toString() is returned. This method * may return <code>null</code> if there was an error retrieving the * property. * * @param bean The bean object. * @param property The name of the property to access. * * @return The value of the property. */ public static String getValueAsString(Object bean, String property) { Object value = null; try { value = PropertyUtils.getProperty(bean, property); } catch(IllegalAccessException e) { Log log = LogFactory.getLog(ValidatorUtils.class); log.error(e.getMessage(), e); } catch(InvocationTargetException e) { Log log = LogFactory.getLog(ValidatorUtils.class); log.error(e.getMessage(), e); } catch(NoSuchMethodException e) { Log log = LogFactory.getLog(ValidatorUtils.class); log.error(e.getMessage(), e); } if (value == null) { return null; } if (value instanceof String[]) { return ((String[]) value).length > 0 ? value.toString() : ""; } else if (value instanceof Collection) { return ((Collection) value).isEmpty() ? "" : value.toString(); } else { return value.toString(); } } /** * Makes a deep copy of a <code>FastHashMap</code> if the values * are <code>Msg</code>, <code>Arg</code>, * or <code>Var</code>. Otherwise it is a shallow copy. * * @param map <code>FastHashMap</code> to copy. * @return FastHashMap A copy of the <code>FastHashMap</code> that was * passed in. * @deprecated This method is not part of Validator's public API. Validator * will use it internally until FastHashMap references are removed. Use * copyMap() instead. */ public static FastHashMap copyFastHashMap(FastHashMap map) { FastHashMap results = new FastHashMap(); Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Entry entry = (Entry) i.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); if (value instanceof Msg) { results.put(key, ((Msg) value).clone()); } else if (value instanceof Arg) { results.put(key, ((Arg) value).clone()); } else if (value instanceof Var) { results.put(key, ((Var) value).clone()); } else { results.put(key, value); } } results.setFast(true); return results; } /** * Makes a deep copy of a <code>Map</code> if the values are * <code>Msg</code>, <code>Arg</code>, or <code>Var</code>. Otherwise, * it is a shallow copy. * * @param map The source Map to copy. * * @return A copy of the <code>Map</code> that was passed in. */ public static Map copyMap(Map map) { Map results = new HashMap(); Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Entry entry = (Entry) i.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); if (value instanceof Msg) { results.put(key, ((Msg) value).clone()); } else if (value instanceof Arg) { results.put(key, ((Arg) value).clone()); } else if (value instanceof Var) { results.put(key, ((Var) value).clone()); } else { results.put(key, value); } } return results; } }
[ "jonkiky@gmail.com" ]
jonkiky@gmail.com
3a578e9cc15a77c4ab464600608c78f40f3239c0
b0da88db8a4bd9c708f69dfbff1a4761cfaedccc
/grails-app/domain/edu/erling/barber/Client.java
db37edf5dfb53b35961539e636c0cbd76d264ac6
[]
no_license
erlingmendoza9901/BarberShopService
aa09ebbb8d9fc4f666a91d08cc07c10e1c5e13f9
b066ef95aed0773fbf7910cfadc104525cd89596
refs/heads/master
2020-08-28T15:34:37.712322
2019-11-02T14:29:05
2019-11-02T14:29:05
217,741,604
0
0
null
null
null
null
UTF-8
Java
false
false
52
java
package edu.erling.barber; public class Client { }
[ "hanielmendoza9901@gmail.com" ]
hanielmendoza9901@gmail.com
6408becd2edeef14d70dd3e87991788951481bfb
3919fe98c7e79519acf8ad5fc699c1251048d09d
/business_service/src/main/java/com/demo/business/BusinessApplication.java
857491e3beb4943541b83f4cdf975ca943e44fb6
[]
no_license
xiao-Ray/fescar_demo
52f9103e3397b2f3c8b520b344ece25d5831e7b2
84db4511cc2066c7c894940c86e177d1326cee1a
refs/heads/master
2022-12-21T21:35:51.242879
2020-03-23T04:19:45
2020-03-23T04:19:45
217,083,859
0
0
null
null
null
null
UTF-8
Java
false
false
842
java
package com.demo.business; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) //使用自定义数据源,排除默认加载的数据源 @EnableEurekaClient @EnableFeignClients @ComponentScan(basePackages = {"com.demo.*"}) public class BusinessApplication { public static void main(String[] args) { SpringApplication.run(BusinessApplication.class,args); } }
[ "1083903857@qq.com" ]
1083903857@qq.com
eaeba86521fb576928c2a24fa992561a38374e7b
1c57b89119ee5cf69d9ae8254b9ce474d8d638bb
/test_code/pinyougou-content-web/src/main/java/com/pinyougou/content/controller/FreightTemplateController.java
93d8f6ddf26dbb384aba161ee729fbb1234403aa
[]
no_license
itDaiFei/pyg
b254bc6c4ada4a4d3b0391ad41a63fdb8769f8a8
806e31d650a52170e73c7eb55c737c26befe6ab9
refs/heads/master
2022-12-21T11:45:04.892961
2019-07-13T02:10:02
2019-07-13T02:10:02
196,668,561
0
0
null
2022-12-16T04:25:04
2019-07-13T02:21:46
JavaScript
UTF-8
Java
false
false
2,542
java
package com.pinyougou.content.controller; import java.util.List; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.dubbo.config.annotation.Reference; import com.pinyougou.pojo.TbFreightTemplate; import com.pinyougou.content.service.FreightTemplateService; import entity.PageResult; import entity.Result; /** * controller * @author Administrator * */ @RestController @RequestMapping("/freightTemplate") public class FreightTemplateController { @Reference private FreightTemplateService freightTemplateService; /** * 返回全部列表 * @return */ @RequestMapping("/findAll") public List<TbFreightTemplate> findAll(){ return freightTemplateService.findAll(); } /** * 返回全部列表 * @return */ @RequestMapping("/findPage") public PageResult findPage(int page,int rows){ return freightTemplateService.findPage(page, rows); } /** * 增加 * @param freightTemplate * @return */ @RequestMapping("/add") public Result add(@RequestBody TbFreightTemplate freightTemplate){ try { freightTemplateService.add(freightTemplate); return new Result(true, "增加成功"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "增加失败"); } } /** * 修改 * @param freightTemplate * @return */ @RequestMapping("/update") public Result update(@RequestBody TbFreightTemplate freightTemplate){ try { freightTemplateService.update(freightTemplate); return new Result(true, "修改成功"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "修改失败"); } } /** * 获取实体 * @param id * @return */ @RequestMapping("/findOne") public TbFreightTemplate findOne(Long id){ return freightTemplateService.findOne(id); } /** * 批量删除 * @param ids * @return */ @RequestMapping("/delete") public Result delete(Long [] ids){ try { freightTemplateService.delete(ids); return new Result(true, "删除成功"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "删除失败"); } } /** * 查询+分页 * @param brand * @param page * @param rows * @return */ @RequestMapping("/search") public PageResult search(@RequestBody TbFreightTemplate freightTemplate, int page, int rows ){ return freightTemplateService.findPage(freightTemplate, page, rows); } }
[ "1157633159@qq.com" ]
1157633159@qq.com
904ea170657be7d45d07883529b87f720ea04b5e
02f6a5cab220a683539dadd6ef676985b7dbf2e7
/src/main/java/be/feesboek/business/DialogDataBoundary.java
4c3e389d95ac299312d4f3215c86a60256854163
[]
no_license
DimitriDewaele/FeesBoekWar
7f4883c4517315b4e7757990a25a03fa98c76dec
f13d560bbc1c5b333ca7af4c672400cb3eaab56a
refs/heads/master
2021-05-16T03:07:41.457607
2019-03-05T10:17:30
2019-03-05T10:17:30
30,183,640
0
0
null
null
null
null
UTF-8
Java
false
false
2,987
java
package be.feesboek.business; import be.feesboek.models.PersonVO; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Named; import javax.enterprise.context.SessionScoped; /** * * @author dimitridw */ @Named @SessionScoped public class DialogDataBoundary implements Serializable { private static final long serialVersionUID = 1L; private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(DialogDataBoundary.class); private List<PersonVO> persons; /** * Creates a new instance of DialogDataBean */ public DialogDataBoundary() { } @PostConstruct public void initialize() { persons = new ArrayList<>(); persons.add(new PersonVO(1, "Jean", "Pol", "receptionist", new Date(74, 10, 10))); persons.add(new PersonVO(2, "Jef", "Snijders", "guardener", new Date(71, 10, 10))); persons.add(new PersonVO(3, "Piet", "Peters", "truck driver", new Date(64, 10, 10))); persons.add(new PersonVO(4, "Peet", "Polders", "professor", new Date(54, 10, 10))); persons.add(new PersonVO(5, "Nell", "Van Den Walle", "student", new Date(12, 10, 10))); persons.add(new PersonVO(6, "Nady", "Van Toren", "cleaning", new Date(98, 10, 10))); persons.add(new PersonVO(7, "Jenny", "De Koster", "police", new Date(45, 10, 10))); persons.add(new PersonVO(8, "Malena", "Zetterman", "air traffic controler", new Date(71, 10, 10))); persons.add(new PersonVO(9, "Medina", "Zegers", "test engineer", new Date(85, 10, 10))); persons.add(new PersonVO(10, "Horaire", "Safrina", "manager", new Date(47, 10, 10))); } public List<PersonVO> findAll() { return persons; } public PersonVO getById(Integer id) { PersonVO local = null; for (Iterator iter = persons.listIterator(); iter.hasNext();) { PersonVO temp = (PersonVO) iter.next(); if (id.equals(temp.getId())) { LOGGER.debug("The person is: {}", temp); local = temp; break; } } return local; } public int maxId() { return persons.size(); } public void remove(Integer id) { PersonVO local = getById(id); if (local != null) { LOGGER.debug("Remove person: {}", local); persons.remove(local); } } public void add(PersonVO person) { persons.add(person); } public void edit(PersonVO person) { PersonVO local = getById(person.getId()); local = person; } /** * @return the persons */ public List<PersonVO> getPersons() { return persons; } /** * @param persons the persons to set */ public void setPersons(List<PersonVO> persons) { this.persons = persons; } }
[ "dimitri.dewaele@mips.be" ]
dimitri.dewaele@mips.be
6b2837cd2b4070708b531c2a843d0d26f74cdd75
d5e6d45697bc1aba8b56d803a562af92ea00e728
/zhuoyue-parent/zhuoyue-common/src/main/java/entity/Result.java
fd6bde7ded15fddf38acae1461ec06fd40cfbc8f
[]
no_license
Cnlomou/zykj-forum
a3a4e0bf6171579f121a3fd74482637001ec0534
53036e6bc78aa24125b678b4eaeaa02a0cb63a71
refs/heads/master
2022-07-14T08:31:22.566015
2020-05-15T06:51:59
2020-05-15T06:51:59
264,075,760
0
0
null
null
null
null
UTF-8
Java
false
false
1,792
java
package entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel public class Result<T> { @ApiModelProperty(value = "是否成功,true:成功;false:失败", required = true) private boolean flag; @ApiModelProperty(value = "状态码,20000成功,20001失败,") private Integer code; @ApiModelProperty(value = "提示信息") private String message; @ApiModelProperty(value = "逻辑数据") private T data; public Result() { } public Result(boolean flag, Integer code, String message, T data) { this.flag = flag; this.code = code; this.message = message; this.data = data; } public Result(boolean flag, Integer code, String message) { this.flag = flag; this.code = code; this.message = message; } public Result(boolean flag, Integer code, T data) { this.flag = flag; this.code = code; this.data = data; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } @Override public String toString() { return "Result{" + "flag=" + flag + ", code=" + code + ", message='" + message + '\'' + ", data=" + data + '}'; } }
[ "1246269795@qq.com" ]
1246269795@qq.com
64c549e3a9c03acf163270f3059634fbfd45ae3a
7d10f058988eb3a824341937069348e04801f741
/src/main/java/com/methodpark/cmpe/code/isp_refactored/ITextFromFileLoader.java
61e10fd7ebe58bf454a56d8a8a2b95bf82cd759a
[]
no_license
schwenk85/CMPE-Code-Day1
2e4b49f0c7d1f4bf04f66bf6fc03cd5cfb1ea4b8
fa79579e896eb2bdddba76909e67e1bc83c28700
refs/heads/master
2020-12-03T01:48:34.496179
2017-04-12T13:13:42
2017-04-12T13:13:42
95,869,899
0
0
null
2017-06-30T08:59:02
2017-06-30T08:59:02
null
UTF-8
Java
false
false
162
java
package com.methodpark.cmpe.code.isp_refactored; // this is not used here public interface ITextFromFileLoader { public String loadFile(String filename); }
[ "markus.reinhardt@methodpark.de" ]
markus.reinhardt@methodpark.de
2f2452792afbb7ec09150b60d6661135fbcffa05
ab69b7ac519c4ec6a5969666dca3c1d585afef47
/MyApplication/app/src/main/java/com/example/user/myapplication/Game/SixDiceGame.java
08204eb010f1bd0faca727a6f7e7cc532b08e866
[]
no_license
Acrylone/AndroidProgram
2a5c4b6d3cde0ff935257614cbc7501a6986b2b0
9704ecf8179069a71eab698b149e917a835ca32a
refs/heads/master
2020-06-13T23:13:44.919620
2017-07-20T13:32:06
2017-07-20T13:32:06
75,533,294
1
0
null
null
null
null
UTF-8
Java
false
false
30,424
java
package com.example.user.myapplication.Game; import android.content.Intent; import android.graphics.Typeface; import android.media.MediaPlayer; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.example.user.myapplication.EndGame; import com.example.user.myapplication.InterstitialGoogle; import com.example.user.myapplication.Menu.Navigation.Rules.Rules; import com.example.user.myapplication.R; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import java.util.ArrayList; import java.util.List; public class SixDiceGame extends AppCompatActivity implements View.OnClickListener { private static final int NUM_OF_THROWING_MAX = 19; private static final int NUM_OF_DICE = 6; private static final int NUM_OF_ALLOWED_THROWS = 3; private static int COUNTDOWN = NUM_OF_ALLOWED_THROWS -1; private int alreadyThrown; private boolean bonusGone = false; private boolean isBonus = false; public boolean onTheGame = false; protected boolean isAbleToClickScoreButton; private int num_of_launches = 0; private DieImageButton[] dice; //Array for the dice private List<ScoreButton> scoreButtons; //Array list of the ScoreButton private List<ScoreButton> scoreButtonsLeft; //Array list of the ScoreButton private CalculateDiceFive calculateDiceFive; //Call the class relevant private ProgressBar progressBar; int clickcount = 0; //Counter for how many times clicking on the desactive Button -> message private int counterTotal = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.six_dice_game); //******//ProgressBar function********************************************************************** progressBar = (ProgressBar) findViewById(R.id.progressbarsixdice); progressBar.setMax(133); //////////////////////////////////////////////////////////////////////////////////////////////////// // // Load an ad into the AdMob banner view. // AdView adView = (AdView) findViewById(R.id.adView); // AdRequest adRequest = new AdRequest.Builder() // .setRequestAgent("android_studio:ad_template").build(); // adView.loadAd(adRequest); final AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); mAdView.setAdListener(new AdListener() { @Override public void onAdLoaded() { super.onAdLoaded(); mAdView.setVisibility(View.VISIBLE); } }); ////////OnClickListener for the scoreNumbers//////////////////////////////////////////////////////// final Button pen_one = (Button) findViewById(R.id.SCORE_ONE); pen_one.setOnClickListener(this); final Button pen_two = (Button) findViewById(R.id.SCORE_TWO); pen_two.setOnClickListener(this); final Button pen_three = (Button) findViewById(R.id.SCORE_THREE); pen_three.setOnClickListener(this); final Button pen_four = (Button) findViewById(R.id.SCORE_FOUR); pen_four.setOnClickListener(this); final Button pen_five = (Button) findViewById(R.id.SCORE_FIVE); pen_five.setOnClickListener(this); final Button pen_six = (Button) findViewById(R.id.SCORE_SIX); pen_six.setOnClickListener(this); final Button pen_pair = (Button) findViewById(R.id.PAIR); pen_pair.setOnClickListener(this); final Button pen_2pairs = (Button) findViewById(R.id.TWOPAIRS); pen_2pairs.setOnClickListener(this); final Button pen_3pairs = (Button) findViewById(R.id.THREEOFKIND); pen_3pairs.setOnClickListener(this); final Button pen_4pairs = (Button) findViewById(R.id.FOUROFKIND); pen_4pairs.setOnClickListener(this); final Button pen_lowS = (Button) findViewById(R.id.STRAIGHTLOW); pen_lowS.setOnClickListener(this); final Button pen_highS = (Button) findViewById(R.id.STRAIGHTHIGH); pen_highS.setOnClickListener(this); // final Button pen_full = (Button) findViewById(R.id.FULLHOUSE); // pen_full.setOnClickListener(this); final Button pen_threeandthree = (Button) findViewById(R.id.THREEANDTHREE); pen_threeandthree.setOnClickListener(this); final Button pen_fourandtwo = (Button) findViewById(R.id.FOURANDTWO); pen_fourandtwo.setOnClickListener(this); final Button pen_chance = (Button) findViewById(R.id.CHANCE); pen_chance.setOnClickListener(this); final Button pen_yatzy = (Button) findViewById(R.id.YATZY); pen_yatzy.setOnClickListener(this); //////////////////////////////////////////////////////////////////////////////////////////////////// alreadyThrown = 0; //Create array with 6 cells - and adapt each cell with the appropriate die dice = new DieImageButton[NUM_OF_DICE]; dice[0] = (DieImageButton) findViewById(R.id.diceOne); dice[1] = (DieImageButton) findViewById(R.id.diceTwo); dice[2] = (DieImageButton) findViewById(R.id.diceThree); dice[3] = (DieImageButton) findViewById(R.id.diceFour); dice[4] = (DieImageButton) findViewById(R.id.diceFive); dice[5] = (DieImageButton) findViewById(R.id.diceSix); //************************************************************************************************** //Loop to active/de-active the dice for (DieImageButton dib : dice) { dib.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toggleActivation(view); onTheGame = true; } }); } //Reset all the dice initializeDice(); calculateDiceFive = new CalculateDiceSix(dice); //******//Launch animation fireworks Yatzy//**************************UNDER CONSTRUCTION************ final LayoutInflater inflater = getLayoutInflater(); final View layout = inflater.inflate(R.layout.animation_yatzy, (ViewGroup) findViewById(R.id.animation_custom_container)); final MediaPlayer mplayer = MediaPlayer.create(this, R.raw.great_sound); final Button activeAnimationYatzY = (Button) this.findViewById(R.id.YATZY); activeAnimationYatzY.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { clickScoreButton(activeAnimationYatzY); progressBar.setProgress(progressBar.getProgress() + 7); if (Integer.valueOf(activeAnimationYatzY.getText().toString()).equals(CalculateDiceSix.YATZY_ARCADE_POINTS)) { mplayer.start(); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } } }); //******//Sound Dice Rolling//********************************************************************** final MediaPlayer mp = MediaPlayer.create(this, R.raw.shake_dice); final Button play_button = (Button) this.findViewById(R.id.rollingdice); play_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mp.start(); throwDice(play_button); } }); //************************************************************************************************** //******// Floating Button Help//******************************************************************* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.helpbonus); fab.setImageResource(R.drawable.ic_help_24dp); fab.setOnClickListener(new View.OnClickListener() { LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.help_bonus, (ViewGroup) findViewById(R.id.help_bonus_container)); @Override public void onClick(View view) { Intent i = new Intent(getApplicationContext(), Rules.class); startActivity(i); } }); //************************************************************************************************** //************************************************************************************************** //************************************************************************************************** //******//Array List Of All the ScoreButtons//****************************************************** scoreButtons = new ArrayList<>(); scoreButtons.add((ScoreButton) findViewById(R.id.SCORE_ONE)); scoreButtons.add((ScoreButton) findViewById(R.id.SCORE_TWO)); scoreButtons.add((ScoreButton) findViewById(R.id.SCORE_THREE)); scoreButtons.add((ScoreButton) findViewById(R.id.SCORE_FOUR)); scoreButtons.add((ScoreButton) findViewById(R.id.SCORE_FIVE)); scoreButtons.add((ScoreButton) findViewById(R.id.SCORE_SIX)); scoreButtons.add((ScoreButton) findViewById(R.id.SCORE_TOTAL)); scoreButtons.add((ScoreButton) findViewById(R.id.SCORE_BONUS)); scoreButtons.add((ScoreButton) findViewById(R.id.PAIR)); scoreButtons.add((ScoreButton) findViewById(R.id.TWOPAIRS)); scoreButtons.add((ScoreButton) findViewById(R.id.THREEPAIRS)); scoreButtons.add((ScoreButton) findViewById(R.id.THREEOFKIND)); scoreButtons.add((ScoreButton) findViewById(R.id.FOUROFKIND)); scoreButtons.add((ScoreButton) findViewById(R.id.FIVEOFKIND)); scoreButtons.add((ScoreButton) findViewById(R.id.STRAIGHTLOW)); scoreButtons.add((ScoreButton) findViewById(R.id.STRAIGHTHIGH)); scoreButtons.add((ScoreButton) findViewById(R.id.STRAIGHTFULL)); // scoreButtons.add((ScoreButton) findViewById(R.id.FULLHOUSE)); scoreButtons.add((ScoreButton) findViewById(R.id.THREEANDTHREE)); scoreButtons.add((ScoreButton) findViewById(R.id.FOURANDTWO)); scoreButtons.add((ScoreButton) findViewById(R.id.CHANCE)); scoreButtons.add((ScoreButton) findViewById(R.id.YATZY)); scoreButtonsLeft = new ArrayList<>(); scoreButtonsLeft.add((ScoreButton) findViewById(R.id.SCORE_ONE)); scoreButtonsLeft.add((ScoreButton) findViewById(R.id.SCORE_TWO)); scoreButtonsLeft.add((ScoreButton) findViewById(R.id.SCORE_THREE)); scoreButtonsLeft.add((ScoreButton) findViewById(R.id.SCORE_FOUR)); scoreButtonsLeft.add((ScoreButton) findViewById(R.id.SCORE_FIVE)); scoreButtonsLeft.add((ScoreButton) findViewById(R.id.SCORE_SIX)); } //*****End of OnCreate****************************************************************************** //************************************************************************************************** //************************************************************************************************** //*****On Click Void to make sound on Score Button************************************************** @Override public void onClick(View v) { final MediaPlayer mp = MediaPlayer.create(this, R.raw.pen); final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.pen2); final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.pen3); final MediaPlayer mp4 = MediaPlayer.create(this, R.raw.pen4); final MediaPlayer mp5 = MediaPlayer.create(this, R.raw.pen5); final MediaPlayer mp6 = MediaPlayer.create(this, R.raw.pen6); switch (v.getId()) { case R.id.SCORE_ONE: mp.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.SCORE_TWO: mp2.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.SCORE_THREE: mp3.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.SCORE_FOUR: mp4.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.SCORE_FIVE: mp5.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.SCORE_SIX: mp6.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.PAIR: mp.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.TWOPAIRS: mp2.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.THREEPAIRS: mp2.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.THREEOFKIND: mp3.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.FOUROFKIND: mp4.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.FIVEOFKIND: mp4.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.STRAIGHTLOW: mp5.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.STRAIGHTHIGH: mp6.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.STRAIGHTFULL: mp6.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.THREEANDTHREE: mp6.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; case R.id.FOURANDTWO: mp6.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; // case R.id.FULLHOUSE: // mp2.start(); // progressBar.setProgress(progressBar.getProgress() + 7); // clickScoreButton(v); // break; case R.id.CHANCE: mp3.start(); progressBar.setProgress(progressBar.getProgress() + 7); clickScoreButton(v); break; default: break; } } //*****Initialize the dice, active them and update the image dice corresponding********************* public void initializeDice() { for (int i = 0; i < NUM_OF_DICE; i++) { dice[i].setValue(i + 1); dice[i].setIsActive(true); } } //************************************************************************************************** //*****Update the cell with the relevant ScoreNumber************************************************ public void updateScores() { //Find all score options for (int i = 0; i < scoreButtons.size(); i++) { if (scoreButtons.get(i).isEnabled()) { switch (scoreButtons.get(i).getId()) { case R.id.SCORE_ONE: showScore1(scoreButtons.get(i)); break; case R.id.SCORE_TWO: showScore2(scoreButtons.get(i)); break; case R.id.SCORE_THREE: showScore3(scoreButtons.get(i)); break; case R.id.SCORE_FOUR: showScore4(scoreButtons.get(i)); break; case R.id.SCORE_FIVE: showScore5(scoreButtons.get(i)); break; case R.id.SCORE_SIX: showScore6(scoreButtons.get(i)); break; case R.id.PAIR: showScorePair(scoreButtons.get(i)); break; case R.id.TWOPAIRS: clickScoreButtonTwoPairs(scoreButtons.get(i)); break; case R.id.THREEPAIRS: clickScoreButtonThreePairs(scoreButtons.get(i)); break; case R.id.THREEOFKIND: showScoreThreeOfKind(scoreButtons.get(i)); break; case R.id.FOUROFKIND: showScoreFourOfKind(scoreButtons.get(i)); break; case R.id.FIVEOFKIND: showScoreFiveOfKind(scoreButtons.get(i)); break; case R.id.STRAIGHTLOW: showScoreStraightLow(scoreButtons.get(i)); break; case R.id.STRAIGHTHIGH: showScoreStraightHigh(scoreButtons.get(i)); break; case R.id.STRAIGHTFULL: showScoreStraightFull(scoreButtons.get(i)); break; //// case R.id.FULLHOUSE: // showScoreFullHouse(scoreButtons.get(i)); //// break; case R.id.THREEANDTHREE: showScoreThreeAndThree(scoreButtons.get(i)); break; case R.id.FOURANDTWO: showScoreFourAndTwo(scoreButtons.get(i)); break; case R.id.CHANCE: showScoreChance(scoreButtons.get(i)); break; case R.id.YATZY: showScoreYatzy(scoreButtons.get(i)); break; case R.id.SCORE_BONUS: showScoreBonus(scoreButtons.get(i)); break; case R.id.SCORE_TOTAL: showScoreTotal(scoreButtons.get(i)); break; } } } // for (int i = 0; i < scoreButtons.size(); i++) { // if (scoreButtons.get(i).getId() == R.id.SCORE_TOTAL) { // showScoreTotal(scoreButtons.get(i)); // } // } } //*****Update the image in center of the game Yatzy************************************************* //*****from blue cold to red fire in function of proximity to make YatzY**************************** // public void updateYatzyAnimation(View view) { //TODO UNDER CONSTRUCTION // int num = 0; // GifTextView blueyatzy = (GifTextView) findViewById(R.id.yatzybleu); // GifTextView orangeyatzy = (GifTextView) findViewById(R.id.yatzyorange); // GifTextView redoyatzy = (GifTextView) findViewById(R.id.yatzyredo); // GifTextView redyatzy = (GifTextView) findViewById(R.id.yatzyfeu); // GifTextView fireyatzy = (GifTextView) findViewById(R.id.yatzyenflamme); // // calculateDiceFive.findHighestNRepititions(1); // blueyatzy.setVisibility(View.VISIBLE); // // calculateDiceFive.findHighestNRepititions(2); // blueyatzy.setVisibility(View.GONE); // orangeyatzy.setVisibility(View.VISIBLE); // // calculateDiceFive.findHighestNRepititions(3); // orangeyatzy.setVisibility(View.GONE); // redoyatzy.setVisibility(View.VISIBLE); // // calculateDiceFive.findHighestNRepititions(4); // redoyatzy.setVisibility(View.GONE); // redyatzy.setVisibility(View.VISIBLE); // // calculateDiceFive.findHighestNRepititions(5); // redyatzy.setVisibility(View.GONE); // fireyatzy.setVisibility(View.VISIBLE); // } //*****Function to active update and limit the rolling dice and showing result dice***************** public void throwDice(View view) { isAbleToClickScoreButton = true; //**Make a countdown 3-2-1 for the number of launch of dice************** TextView tx = (TextView) findViewById(R.id.countdown); Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/DIGITALDREAM.ttf"); tx.setTypeface(custom_font); tx.setText("" + COUNTDOWN); COUNTDOWN--; if (alreadyThrown < NUM_OF_ALLOWED_THROWS) { switch (view.getId()) { case R.id.rollingdice: for (int i = 0; i < dice.length; i++) { if (dice[i].isActive()) { dice[i].throwSelfDie(); } } break; } updateScores(); // updateYatzyAnimation(view); alreadyThrown++; //*****At the end of 3 throwing, deactive the button*********************************************** if (alreadyThrown == NUM_OF_ALLOWED_THROWS) { Button activeButton = (Button) findViewById(R.id.rollingdice); activeButton.setEnabled(false); Button desactiveButton = (Button) findViewById(R.id.rollingdiceoff); desactiveButton.setEnabled(true); } } } //Make a toast message if the player click too many times in the inactive Button "Rolling Dice" public void count(View view) { // Button desactiveButton = (Button) findViewById(R.id.rollingdiceoff); // DieImageButton dice = (DieImageButton) findViewById(R.id.diceOne); clickcount++; if (clickcount > 4 && clickcount < 8) { Toast.makeText(this, "Please click on one of the available boxes", Toast.LENGTH_SHORT).show(); } } //*****Make active and visible the dice during launching******************************************** public void toggleActivation(View view) { if (alreadyThrown != 0 && alreadyThrown != NUM_OF_ALLOWED_THROWS) { ((DieImageButton) view).toggleActivation(); } } //*****Classes of Dice Scores*********************************************************************** public void showScore1(ScoreButton view) { view.turnVisible(calculateDiceFive.calculateScoreRepetition(1)); } public void showScore2(ScoreButton view) { view.turnVisible(calculateDiceFive.calculateScoreRepetition(2)); } public void showScore3(ScoreButton view) { view.turnVisible(calculateDiceFive.calculateScoreRepetition(3)); } public void showScore4(ScoreButton view) { view.turnVisible(calculateDiceFive.calculateScoreRepetition(4)); } public void showScore5(ScoreButton view) { view.turnVisible(calculateDiceFive.calculateScoreRepetition(5)); } public void showScore6(ScoreButton view) { view.turnVisible(calculateDiceFive.calculateScoreRepetition(6)); } public void showScorePair(ScoreButton view) { view.turnVisible(calculateDiceFive.findHighestNRepititions(2)); } public void clickScoreButtonTwoPairs(ScoreButton view) { view.turnVisible(calculateDiceFive.findTwoPairs()); } public void clickScoreButtonThreePairs(ScoreButton view) { view.turnVisible(((CalculateDiceSix) calculateDiceFive).findThreePairs()); } public void showScoreThreeOfKind(ScoreButton view) { view.turnVisible(calculateDiceFive.findHighestNRepititions(3)); } public void showScoreFourOfKind(ScoreButton view) { view.turnVisible(calculateDiceFive.findHighestNRepititions(4)); } public void showScoreFiveOfKind(ScoreButton view) { view.turnVisible(calculateDiceFive.findHighestNRepititions(5)); } public void showScoreStraightLow(ScoreButton view) { view.turnVisible((calculateDiceFive).findStraight(1,5)); } public void showScoreStraightHigh(ScoreButton view) { view.turnVisible(( calculateDiceFive).findStraight(2, 6)); } public void showScoreStraightFull(ScoreButton view) { view.turnVisible(calculateDiceFive.findStraight(1, 6)); } // public void showScoreFullHouse(ScoreButton view) { // view.turnVisible(calculateDiceFive.findfullHouse()); // } public void showScoreThreeAndThree(ScoreButton view) { view.turnVisible(((CalculateDiceSix) calculateDiceFive).findthreeandthree()); } public void showScoreFourAndTwo(ScoreButton view) { view.turnVisible(((CalculateDiceSix) calculateDiceFive).findfourandtwo()); } public void showScoreChance(ScoreButton view) { view.turnVisible(((CalculateDiceSix) calculateDiceFive).findChanceArcade()); } public void showScoreYatzy(ScoreButton view) { view.turnVisible(((CalculateDiceSix) calculateDiceFive).findYatzyArcade()); } public void showScoreTotal(ScoreButton view) { int scoreTotal = 0; for (ScoreButton sb : scoreButtons) { String s = ""; if (!sb.isEnabled()) try { s = sb.getText().toString(); } catch (NumberFormatException e) { } if (s != "") { scoreTotal += Integer.valueOf(s); } } view.turnVisible(scoreTotal); } public void showScoreBonus(ScoreButton view) { int scoreTotal = 0; int scoreBonus = -84; for (ScoreButton sb : scoreButtonsLeft) { String s = ""; if (!sb.isEnabled()) { try { s = sb.getText().toString(); scoreBonus -= scoreTotal; } catch (NumberFormatException e) { } if (s != "") { scoreTotal += Integer.valueOf(s); scoreBonus += scoreTotal; if (scoreBonus >= 0 && !bonusGone) { final LayoutInflater inflater = getLayoutInflater(); final View layout = inflater.inflate(R.layout.animation_bonus, (ViewGroup) findViewById(R.id.animation_custom_container)); final MediaPlayer mplayer = MediaPlayer.create(this, R.raw.cheer); mplayer.start(); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); char plus = '+'; isBonus = true; bonusGone = true; scoreBonus = 50; view.setEnabled(false); } } } view.turnVisible(scoreBonus); } showScoreTotal((ScoreButton) findViewById(R.id.SCORE_TOTAL)); } //************************************************************************************************** //*****Class of operations when the player clicked on one of the cell of scores ******************** public void clickScoreButton(View view) { if (alreadyThrown == 0) { return; } //Make cell selected disable view.setEnabled(false); //Reset the number of throws alreadyThrown = 0; //Reset the number of click on the desactive Button clickcount = 0; //Reset the countdown COUNTDOWN = NUM_OF_ALLOWED_THROWS -1; num_of_launches++; if (num_of_launches == NUM_OF_THROWING_MAX) { //update the next activity with the score String finalScoreStr = ((ScoreButton)findViewById(R.id.SCORE_TOTAL)).getText().toString(); EndGame.scoreTotal = Integer.valueOf(finalScoreStr); startActivity(new Intent(this, EndGame.class)); } //******//Reactive the deactive Button image (grey rolling dice) to the active Button image******** Button activeButton = (Button) findViewById(R.id.rollingdice); activeButton.setEnabled(true); Button desactiveButton = (Button) findViewById(R.id.rollingdiceoff); desactiveButton.setEnabled(false); //************************************************************************************************** initializeDice(); //Do automatically dice Throw throwDice(activeButton); } } //***End of the Activity****************************************************************************
[ "Acrylone@gmail.com" ]
Acrylone@gmail.com
cf4ef773c0673795b43f05537f947a442480da0e
3b20f8b16f605b3d4dd3e0db64c8a35450b74600
/midp2/src/net/jxta/impl/rendezvous/RendezVousServiceImpl.java
1809a020958dae95e558a7e62f0a789ff5483d41
[]
no_license
pengpengli/jxta-jxme
817630c98618e108a58b8de1c83ee30694d5349e
4b51effef78c0808e92bcafa4e5c0052eceb93ff
refs/heads/master
2021-06-03T05:27:49.319097
2009-07-10T17:16:48
2009-07-10T17:16:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
71,195
java
/* * Copyright (c) 2001-2008 Sun Microsystems, Inc. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Sun Microsystems, Inc. for Project JXTA." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact Project JXTA at http://www.jxta.org. * * 5. Products derived from this software may not be called "JXTA", * nor may "JXTA" appear in their name, without prior written * permission of Sun. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SUN MICROSYSTEMS OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ========================================================= * * This software consists of voluntary contributions made by many * individuals on behalf of Project JXTA. For more * information on Project JXTA, please see * <http://www.jxta.org/>. * * This license is based on the BSD license adopted by the Apache Foundation. * * $Id: $ */ package net.jxta.impl.rendezvous; import com.sun.java.util.collections.*; import net.jxta.discovery.DiscoveryService; import net.jxta.document.*; import net.jxta.endpoint.*; import net.jxta.id.ID; import net.jxta.id.UUID.UUID; import net.jxta.id.UUID.UUIDFactory; import net.jxta.impl.protocol.RdvConfigAdv; import net.jxta.impl.util.TimeUtils; import net.jxta.impl.util.TimerThreadNamer; import net.jxta.peer.PeerID; import net.jxta.peergroup.PeerGroup; import net.jxta.peergroup.PeerGroupID; import net.jxta.protocol.*; import net.jxta.rendezvous.RendezVousService; import net.jxta.rendezvous.RendezVousStatus; import net.jxta.rendezvous.RendezvousEvent; import net.jxta.rendezvous.RendezvousListener; import net.jxta.service.Service; import net.jxta.util.java.net.URI; import org.apache.log4j.Logger; import org.apache.log4j.Priority; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.NoSuchElementException; import java.util.Random; import java.util.Vector; /** * A JXTA {@link net.jxta.rendezvous.RendezvousService} implementation which * implements the standard JXTA Rendezvous Protocol (RVP). * * @see net.jxta.rendezvous.RendezvousService * @see <a href="http://spec.jxta.org/nonav/v1.0/docbook/JXTAProtocols.html#proto-rvp" * target="_blank">JXTA Protocols Specification : Rendezvous Protocol</a> */ public class RendezVousServiceImpl implements RendezVousService, EndpointListener { private final static long MONITOR_INTERVAL = 15 * TimeUtils.AMINUTE; private final static long ADDEVENT_DELAY = 3 * TimeUtils.ASECOND; private final static long CHALLENGE_TIMEOUT = 90 * TimeUtils.ASECOND; private final static long REQUEST_LEASE = 20 * TimeUtils.AMINUTE; /** * Description of the Field */ public final static String ConnectRequest = "Connect"; /** * Description of the Field */ public final static String ConnectedLeaseReply = "ConnectedLease"; /** * Description of the Field */ public final static String ConnectedPeerReply = "ConnectedPeer"; /** * Description of the Field */ public final static String ConnectedRdvAdvReply = "RdvAdvReply"; // 5 Minutes private final static double DEMOTION_FACTOR = 0.05; private final static long DEMOTION_MIN_CLIENT_COUNT = 3; private final static long DEMOTION_MIN_PEERVIEW_COUNT = 5; /** * Description of the Field */ public final static String DisconnectRequest = "Disconnect"; /** * Description of the Field */ protected transient String HEADER_NAME; private transient long LEASE_MARGIN = 5 * TimeUtils.AMINUTE; /** * Log4J Logger */ private final static transient Logger LOG = Logger.getInstance(RendezVousServiceImpl.class.getName()); /** * Description of the Field */ protected final static int MAX_ADHOC_TTL = 2; /** * Description of the Field */ protected final static int MAX_INFRA_TTL = 2; /** * Description of the Field */ protected final static int MAX_MSGIDS = 100; /** * Number of rendezvous we will try to connect to. */ private final static int MAX_RDV_CONNECTIONS = 1; /** * Description of the Field */ protected final static String MESSAGE_NAMESPACE_NAME = "jxta"; /** * Description of the Field */ protected String PropPName; /** * Description of the Field */ protected final static String PropSName = "JxtaPropagate"; /** * Description of the Field */ public final static String RdvAdvReply = "RdvAdv"; private PeerGroup advGroup = null; private ID assignedID = null; private boolean autoRendezvous = false; private PeerAdvertisement cachedPeerAdv = null; private XMLDocument cachedPeerAdvDoc = null; private int cachedPeerAdvModCount = -1; private EdgeProtocolListener edgeProtocolListener = null; private RdvConfigAdv.RendezVousConfiguration config = RdvConfigAdv.RendezVousConfiguration.EDGE; private int defaultTTL = MAX_ADHOC_TTL; /** * <p/> * <p/> * <p/> * <ul> * <li> Keys are {@link net.jxta.peer.PeerID}.</li> * <li> Values are {@link Long} containing the time at which * the rendezvous disconnected.</li> * </ul> */ private final Set disconnectedRendezVous = Collections.synchronizedSet(new HashSet()); /** * Description of the Field */ public EndpointService endpoint = null; // 5 Minutes private transient final Set eventListeners = Collections.synchronizedSet(new HashSet()); private transient PeerGroup group = null; private transient ModuleImplAdvertisement implAdvertisement = null; private transient long maxChoiceDelay = ADDEVENT_DELAY; private transient int messagesReceived; /** * Once choice delay has reached zero, any ADD event could trigger a * attempt at connecting to one of the rdvs. If these events come in bursts * while we're not yet connected, we might end-up doing many parallel * attempts, which is a waste of bandwidth. Instead we refrain from doing * more than one attempt every ADDEVENT_DELAY */ private transient long monitorNotBefore = -1; /** * This the time in absolute milliseconds at which the monitor is scheduled * to start.The monitor will not be scheduled at all until there is at * least one item in the peerview. The more items in the peerview, the * earlier we start. Once there are at least rdvConfig.minHappyPeerView * items it guaranteed that we start immediately because the start date is * in the past. */ private transient long monitorStartAt = -1; private transient final List msgIds = new ArrayList(MAX_MSGIDS); /** * Description of the Field */ protected transient String pName; /** * Description of the Field */ protected transient String pParam; private transient final Map propListeners = new HashMap(); /** * <p/> * <p/> * <p/> * <ul> * <li> Keys are {@link net.jxta.peer.ID}.</li> * <li> Values are {@link RdvConnection}.</li> * <p/> * </ul> */ private transient final Map rendezVous = Collections.synchronizedMap(new HashMap()); /** * The peer view for this peer group. */ private EndpointAddress seedAddr = null; private PeerID seedPeerID = null; private PeerAdvertisement seedPeerAdvertisement = null; private RdvAdvertisement seedRdv = null; private transient final Timer timer = new Timer(); /** * {@inheritDoc} * * @param listener The feature to be added to the Listener attribute */ public final void addListener(RendezvousListener listener) { eventListeners.add(listener); } /** * Checks if a message id has been recorded * * @param id message to record. * @return Description of the Return Value * @result true if message was added otherwise (duplicate) false. */ public boolean addMsgId(UUID id) { synchronized (msgIds) { if (isMsgIdRecorded(id)) { // Already there. Nothing to do return false; } if (msgIds.size() < MAX_MSGIDS) { msgIds.add(id); } else { msgIds.set((messagesReceived % MAX_MSGIDS), id); } messagesReceived++; } if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Added Message ID : " + id); } return true; } /** * {@inheritDoc} * * @param name The feature to be added to the PropagateListener * attribute * @param listener The feature to be added to the PropagateListener * attribute * @return Description of the Return Value */ public synchronized boolean addPropagateListener(String name, EndpointListener listener) { // FIXME: jice@jxta.org - 20040726 - The naming of PropagateListener is inconsistent with that of EndpointListener. It is // not a major issue but is ugly since messages are always addressed with the EndpointListener convention. The only way to // fix it is to deprecate addPropagateListener in favor of a two argument version and wait for applications to adapt. Only // once that transition is over, will we be able to know where the separator has to be. if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Adding listener (" + listener + ") for name= " + name); } // Take the optimistic stance. Since we're synchronized, replace the current one, and if we find there was one and it's // not the same, put things back as they were. EndpointListener current = (EndpointListener) propListeners.put(name, listener); if ((current != null) && (current != listener)) { propListeners.put(name, current); return false; } return true; } /** * {@inheritDoc} * * @param serviceName The feature to be added to the PropagateListener * attribute * @param serviceParam The feature to be added to the PropagateListener * attribute * @param listener The feature to be added to the PropagateListener * attribute * @return Description of the Return Value */ public boolean addPropagateListener(String serviceName, String serviceParam, EndpointListener listener) { // Until the old API is killed, the new API behaves like the old one (so that name // collisions are still detected if both APIs are in use). return addPropagateListener(serviceName + serviceParam, listener); } /** * Add a rendezvous to our collection of rendezvous peers. * * @param padv PeerAdvertisement for the rendezvous peer. * @param lease The duration of the lease in relative milliseconds. */ private void addRdv(PeerAdvertisement padv, long lease) { int eventType; RdvConnection rdvConnection; RouteAdvertisement route = extractRouteAdv(padv); synchronized (rendezVous) { rdvConnection = (RdvConnection) rendezVous.get(padv.getPeerID()); if (null == rdvConnection) { rdvConnection = new RdvConnection(group, this, createRdvAdvertisement(padv.getPeerID(), padv.getPeerGroupID(), (String) (route.getDest().getEndpointAddresses().next()))); rendezVous.put(padv.getPeerID(), rdvConnection); disconnectedRendezVous.remove(padv.getPeerID()); eventType = RendezvousEvent.RDVCONNECT; } else { eventType = RendezvousEvent.RDVRECONNECT; } } rdvConnection.connect(route, lease, Math.min(LEASE_MARGIN, (lease / 2))); generateEvent(eventType, padv.getPeerID()); } /** * {@inheritDoc} * * @param peer Description of the Parameter * @param delay Description of the Parameter */ public void challengeRendezVous(ID peer, long delay) { challengeRendezVous(peer, delay); } /** * {@inheritDoc} * * @param msg Description of the Parameter * @return Description of the Return Value */ protected RendezVousPropagateMessage checkPropHeader(Message msg) { RendezVousPropagateMessage propHdr; try { propHdr = getPropHeader(msg); if (null == propHdr) { // No header. Discard the message if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Discarding " + msg + " -- missing propagate header."); } return null; } } catch (Exception failure) { // Bad header. Discard the message if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Discarding " + msg + " -- bad propagate header.", failure); } return null; } // Look at the Propagate header if any and check for loops. // Do not remove it; we do not have to change it yet, and we have // do look at it at different places and looking costs less on // incoming elements than on outgoing. // TTL detection. A message arriving with TTL <= 0 should not even // have been sent. Kill it. if (propHdr.getTTL() <= 0) { // This message is dead on arrival. Drop it. if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Discarding " + msg + "(" + propHdr.getMsgId() + ") -- dead on arrival (TTl=" + propHdr.getTTL() + ")."); } return null; } if (!addMsgId(propHdr.getMsgId())) { // We already received this message - discard if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Discarding " + msg + "(" + propHdr.getMsgId() + ") -- feedback."); } return null; } // Loop detection if (propHdr.isVisited(group.getPeerID().toURI())) { // Loop is detected - discard. if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Discarding " + msg + "(" + propHdr.getMsgId() + ") -- loopback."); } return null; } // Message is valid return propHdr; } /** * Connects to a random rendezvous from the peer view. private void connectToRandomRdv() { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Periodic rendezvous connect attempt for " + group.getPeerGroupID()); } List currentView = new ArrayList(Arrays.asList(rpv.getView().toArray())); Collections.shuffle(currentView); while (!currentView.isEmpty()) { PeerViewElement pve = (PeerViewElement) currentView.remove(0); RdvAdvertisement radv = pve.getRdvAdvertisement(); if (null == radv) { continue; } if (null != getPeerConnection(radv.getPeerID())) { continue; } try { newLeaseRequest(radv); break; } catch (IOException ez) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("rdv connection failed.", ez); } } } } */ /** * Connects to a random rendezvous from the peer view. */ private void connectToRdv() { if (LOG.isEnabledFor(Priority.DEBUG)) { } LOG.debug("Periodic rendezvous connect attempt for Group :" + group.getPeerGroupName()); if (null == seedAddr) { LOG.debug("No seed address for Group :" + group.getPeerGroupName()); return; } //Messenger cachedMessenger = endpoint.getMessengerImmediate(seedAddr, null); try { // if (cachedMessenger != null) newLeaseRequest(cachedMessenger); RdvConnection rdvConnection = null; if (! rendezVous.containsKey(seedPeerID)) { seedRdv = createRdvAdvertisement(seedPeerID, group.getPeerGroupID(), seedAddr.toString()); rdvConnection = new RdvConnection(group, this, seedRdv); rdvConnection.connect(seedRdv.getRouteAdv(), REQUEST_LEASE, Math.min(LEASE_MARGIN, (REQUEST_LEASE / 2))); rendezVous.put(seedPeerID, rdvConnection); } Messenger cachedMessenger = rdvConnection.getCachedMessenger(); newLeaseRequest(cachedMessenger); } catch (Exception ez) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("rdv connection failed.", ez); } } } /** * Description of the Method * * @param padv Description of the Parameter * @param name Description of the Parameter * @return Description of the Return Value */ private static RdvAdvertisement createRdvAdvertisement(PeerID pid, PeerGroupID gid, String addr) { try { // FIX ME: 10/19/2002 lomax@jxta.org. We need to properly set up the service ID. Unfortunately // this current implementation of the PeerView takes a String as a service name and not its ID. // Since currently, there is only PeerView per group (all peerviews share the same "service", this // is not a problem, but that will have to be fixed eventually. // create a new RdvAdvertisement RdvAdvertisement rdv = (RdvAdvertisement) AdvertisementFactory.newAdvertisement(RdvAdvertisement.getAdvertisementType()); rdv.setPeerID(pid); rdv.setGroupID(gid); rdv.setName("RDV seed"); RouteAdvertisement ra = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); ra.setDestPeerID(pid); AccessPointAdvertisement ap = (AccessPointAdvertisement) AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); ap.addEndpointAddress(addr); ra.setDest(ap); // Insert it into the RdvAdvertisement. rdv.setRouteAdv(ra); return rdv; } catch (Exception ez) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Cannot create Local RdvAdvertisement: ", ez); } return null; } } /** * Force the peerview to use the given peer as a seed peer and force the * edge rendezvous provider (if we're edge) to chose a rendezvous as soon * as there is one (likely but not necessarily the one given). * * @param addr The addres of the seed peer (raw or peer id based) * @param routeHint Description of the Parameter * @throws IOException if it failed immediately. */ private void connectToRendezVous(EndpointAddress addr, RouteAdvertisement routeHint) throws IOException { // BT nothing implemented yet } /** * {@inheritDoc} */ public void connectToRendezVous(PeerAdvertisement adv) throws IOException { EndpointAddress addr = new EndpointAddress("jxta", adv.getPeerID().getUniqueValue().toString(), null, null); connectToRendezVous(addr, extractRouteAdv(adv)); } /** * {@inheritDoc} */ public void connectToRendezVous(EndpointAddress addr) throws IOException { connectToRendezVous(addr, null); } /** * Description of the Method * * @return Description of the Return Value */ public UUID createMsgId() { return UUIDFactory.newSeqUUID(); } /** * {@inheritDoc} * * @param peerId Description of the Parameter */ public void disconnectFromRendezVous(ID peerId) { removeRdv((PeerID) peerId, false); } /** * Description of the Method * * @param adv Description of the Parameter * @return Description of the Return Value */ public final static RouteAdvertisement extractRouteAdv(PeerAdvertisement adv) { try { // Get its EndpointService advertisement XMLElement endpParam = (XMLElement) adv.getServiceParam(PeerGroup.endpointClassID); if (endpParam == null) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("No Endpoint Params"); } return null; } // get the Route Advertisement element Enumeration paramChilds = endpParam.getChildren(RouteAdvertisement.getAdvertisementType()); XMLElement param; if (paramChilds.hasMoreElements()) { param = (XMLElement) paramChilds.nextElement(); } else { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("No Route Adv in Peer Adv"); } return null; } // build the new route RouteAdvertisement route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement((XMLElement) param); route.setDestPeerID(adv.getPeerID()); return route; } catch (Exception e) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("failed to extract radv", e); } } return null; } /** * {@inheritDoc} * * @throws Throwable Description of the Exception */ protected void finalize() throws Throwable { stopApp(); } /** * Creates a rendezvous event and sends it to all registered listeners. * * @param type Description of the Parameter * @param regarding Description of the Parameter */ public final void generateEvent(int type, ID regarding) { Iterator eachListener = Arrays.asList(eventListeners.toArray()).iterator(); RendezvousEvent event = new RendezvousEvent(getInterface(), type, regarding); if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Calling listeners for " + event); } while (eachListener.hasNext()) { RendezvousListener aListener = (RendezvousListener) eachListener.next(); try { aListener.rendezvousEvent(event); } catch (Throwable ignored) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Uncaught Throwable in listener (" + aListener + ")", ignored); } } } } /** * Gets the assignedID attribute of the RendezVousServiceImpl object * * @return The assignedID value */ public ID getAssignedID() { return assignedID; } /** * {@inheritDoc} * * @return The connectedPeerIDs value */ public Vector getConnectedPeerIDs() { return new Vector(); } /** * {@inheritDoc} */ public Enumeration getConnectedPeers() { return getEmptyEnum(); } /** * {@inheritDoc} */ public Enumeration getConnectedRendezVous() { return Collections.enumeration(Arrays.asList(rendezVous.keySet().toArray())); } /** * {@inheritDoc} */ public Enumeration getDisconnectedRendezVous() { List result = Arrays.asList(disconnectedRendezVous.toArray()); if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug(result.size() + " rendezvous disconnections."); } return Collections.enumeration(result); } /** * Gets the emptyEnum attribute of the RendezVousServiceImpl object * * @return The emptyEnum value */ private static Enumeration getEmptyEnum() { return Collections.enumeration(Collections.EMPTY_LIST); } /** * {@inheritDoc} */ public Advertisement getImplAdvertisement() { return implAdvertisement; } /** * {@inheritDoc} */ public Service getInterface() { return this; } /** * Gets the listener attribute of the RendezVousServiceImpl object * * @param str Description of the Parameter * @return The listener value */ public synchronized EndpointListener getListener(String str) { return (EndpointListener) propListeners.get(str); } /** * {@inheritDoc} */ public Vector getLocalWalkView() { Vector tmp = new Vector(); if (null != seedRdv) { tmp.addElement(seedRdv); } return tmp; } /** * Gets the peerAdvertisementDoc attribute of the RendezVousServiceImpl * object * * @return The peerAdvertisementDoc value */ protected XMLDocument getPeerAdvertisementDoc() { PeerAdvertisement newPadv = null; synchronized (this) { newPadv = group.getPeerAdvertisement(); int newModCount = newPadv.getModCount(); if ((cachedPeerAdv != newPadv) || (cachedPeerAdvModCount != newModCount)) { cachedPeerAdv = newPadv; cachedPeerAdvModCount = newModCount; } else { newPadv = null; } if (null != newPadv) { cachedPeerAdvDoc = (XMLDocument) cachedPeerAdv.getDocument(MimeMediaType.XMLUTF8); } } return cachedPeerAdvDoc; } /** * @inheritDoc */ public PeerConnection getPeerConnection(PeerID id) { return (PeerConnection) rendezVous.get(id); } /** * @inheritDoc */ protected PeerConnection[] getPeerConnections() { Collection c = rendezVous.values(); return (PeerConnection[]) c.toArray(new PeerConnection[c.size()]); } /** * Get propagate header from the message. * * @param msg The source message. * @return The message's propagate header if any, otherwise null. */ protected RendezVousPropagateMessage getPropHeader(Message msg) { MessageElement elem = msg.getMessageElement(MESSAGE_NAMESPACE_NAME, HEADER_NAME); if (elem == null) { return null; } try { StructuredDocument asDoc = StructuredDocumentFactory.newStructuredDocument(elem.getMimeType(), elem.getStream()); return new RendezVousPropagateMessage(asDoc); } catch (IOException failed) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Could not get prop header of " + msg, failed); } IllegalArgumentException failure = new IllegalArgumentException("Could not get prop header of " + msg); throw failure; } } /** * @inheritDoc */ public RendezVousStatus getRendezVousStatus() { return RendezVousStatus.EDGE; } /** * {@inheritDoc} <p/> * <p/> * <b>Note</b> : it is permissible to pass null as the impl parameter when * this instance is not being loaded via the module framework. */ public synchronized void init(PeerGroup group, ID assignedID, Advertisement impl) { this.group = group; this.assignedID = assignedID; this.implAdvertisement = (ModuleImplAdvertisement) impl; PropPName = group.getPeerGroupID().getUniqueValue().toString(); HEADER_NAME = RendezVousPropagateMessage.Name + PropPName; pParam = group.getPeerGroupID().getUniqueValue().toString(); pName = assignedID.toString(); timer.schedule(new TimerThreadNamer("RendezVousServiceImpl Timer for " + group.getPeerGroupID()), 0); advGroup = group.getParentGroup(); if ((null == advGroup) || PeerGroupID.worldPeerGroupID.equals(advGroup.getPeerGroupID())) { // For historical reasons, we publish in our own group rather than // the parent if our parent is the world group. advGroup = group; } ConfigParams confAdv = (ConfigParams) group.getConfigAdvertisement(); // Get the config. If we do not have a config, we're done; we just keep // the defaults (edge peer/no auto-rdv) if (confAdv != null) { Advertisement adv = null; try { XMLDocument configDoc = (XMLDocument) confAdv.getServiceParam(getAssignedID()); if (null != configDoc) { // XXX 20041027 backwards compatibility configDoc.addAttribute("type", RdvConfigAdv.getAdvertisementType()); adv = AdvertisementFactory.newAdvertisement(configDoc); } } catch (NoSuchElementException failed) { } if (adv instanceof RdvConfigAdv) { RdvConfigAdv rdvConfigAdv = (RdvConfigAdv) adv; config = rdvConfigAdv.getConfiguration(); autoRendezvous = rdvConfigAdv.getAutoRendezvousCheckInterval() > 0; //rdv_watchdog_interval = rdvConfigAdv.getAutoRendezvousCheckInterval(); seedPeerID = rdvConfigAdv.getSeedRendezvousID()[0]; seedAddr = new EndpointAddress(rdvConfigAdv.getSeedRendezvous()[0]); System.out.println("Seeding RDV Peer " + seedPeerID); System.out.println("Seeding RDV Addr " + seedAddr); } } if (PeerGroupID.worldPeerGroupID.equals(group.getPeerGroupID())) { config = RdvConfigAdv.RendezVousConfiguration.AD_HOC; } if (LOG.isEnabledFor(Priority.INFO)) { StringBuffer configInfo = new StringBuffer("Configuring RendezVous Service : " + assignedID); if (implAdvertisement != null) { configInfo.append("\n\tImplementation :"); configInfo.append("\n\t\tModule Spec ID: " + implAdvertisement.getModuleSpecID()); configInfo.append("\n\t\tImpl Description : " + implAdvertisement.getDescription()); configInfo.append("\n\t\tImpl URI : " + implAdvertisement.getUri()); configInfo.append("\n\t\tImpl Code : " + implAdvertisement.getCode()); } configInfo.append("\n\tGroup Params :"); configInfo.append("\n\t\tGroup : " + group.getPeerGroupName()); configInfo.append("\n\t\tGroup ID : " + group.getPeerGroupID()); configInfo.append("\n\t\tPeer ID : " + group.getPeerID()); configInfo.append("\n\tConfiguration :"); if (null != advGroup) { configInfo.append("\n\t\tAdvertising group : " + advGroup.getPeerGroupName() + " [" + advGroup.getPeerGroupID() + "]"); } else { configInfo.append("\n\t\tAdvertising group : (none)"); } configInfo.append("\n\t\tRendezVous : " + config); configInfo.append("\n\t\tAuto RendezVous : " + autoRendezvous); //configInfo.append("\n\t\tAuto-RendezVous Reconfig Interval : " + rdv_watchdog_interval); LOG.info(configInfo); } } /** * Gets the rendezvousConnected attribute of the RendezVousServiceImpl * object * * @return true if connected to a rendezvous, false otherwise */ public boolean isConnectedToRendezVous() { return !rendezVous.isEmpty(); } /** * Gets the msgIdRecorded attribute of the RendezVousServiceImpl object * * @param id Description of the Parameter * @return The msgIdRecorded value */ public boolean isMsgIdRecorded(UUID id) { boolean found; synchronized (msgIds) { found = msgIds.contains(id); } if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug(id + " = " + found); } return found; } /** * {@inheritDoc} */ public boolean isRendezVous() { RendezVousStatus currentStatus = getRendezVousStatus(); return (RendezVousStatus.AUTO_RENDEZVOUS == currentStatus) || (RendezVousStatus.RENDEZVOUS == currentStatus); } /** * Convenience method for constructing an endpoint address from an id * * @param destPeer peer id * @param serv the service name (if any) * @param parm the service param (if any) * @return Description of the Return Value */ protected final static EndpointAddress mkAddress(String destPeer, String serv, String parm) { ID asID = ID.create(URI.create(destPeer)); return mkAddress(asID, serv, parm); } /** * Convenience method for constructing an endpoint address from an id * * @param destPeer peer id * @param serv the service name (if any) * @param parm the service param (if any) * @return Description of the Return Value */ protected final static EndpointAddress mkAddress(ID destPeer, String serv, String parm) { EndpointAddress addr = new EndpointAddress(MESSAGE_NAMESPACE_NAME, destPeer.getUniqueValue().toString(), serv, parm); return addr; } /** * Attempt to connect to a rendezvous we have not previously connected to. * * @param radv Rendezvous advertisement for the Rdv we want to * connect to. * @throws IOException Description of the Exception */ private void newLeaseRequest(Messenger messenger) throws IOException { if (null == messenger) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Could not get messenger for seed RDV"); } throw new IOException("Could not connect to seed RDV"); } Message msg = new Message(); // The request simply includes the local peer advertisement. msg.replaceMessageElement("jxta", new TextDocumentMessageElement(ConnectRequest, getPeerAdvertisementDoc(), null)); messenger.sendMessage(msg, pName, pParam); } /** * Adds a propagation header to the given message with the given default * TTL. Also adds this peer to the path recorded in the message. * * @param serviceName Description of the Parameter * @param serviceParam Description of the Parameter * @param ttl Description of the Parameter * @return Description of the Returned Value */ private RendezVousPropagateMessage newPropHeader(String serviceName, String serviceParam, int ttl) { RendezVousPropagateMessage propHdr = new RendezVousPropagateMessage(); propHdr.setTTL(ttl); propHdr.setDestSName(serviceName); propHdr.setDestSParam(serviceParam); UUID msgID = createMsgId(); propHdr.setMsgId(msgID); addMsgId(msgID); // Add this peer to the path. propHdr.addVisited(group.getPeerID().toURI()); return propHdr; } /** * Process a connected replay * * @param msg Description of Parameter */ protected void processConnectedReply(Message msg) { if (LOG.isEnabledFor(Priority.DEBUG)) { } LOG.debug("Processing a Rendezvous connect reply"); // get the Peer Advertisement of the RDV. MessageElement elem = msg.getMessageElement("jxta", ConnectedRdvAdvReply); if (null == elem) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Missing rendezvous peer advertisement"); } return; } InputStream is = null; PeerAdvertisement padv = null; try { is = elem.getStream(); padv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(elem.getMimeType(), is); seedPeerAdvertisement = padv; // This is not our own peer adv so we must not keep it // longer than its expiration time. DiscoveryService discovery = group.getDiscoveryService(); if (null != discovery) { discovery.publish(padv, DiscoveryService.DEFAULT_EXPIRATION, DiscoveryService.DEFAULT_EXPIRATION); } } catch (Exception e) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("failed to publish Rendezvous Advertisement", e); } } finally { if (null != is) { try { is.close(); } catch (IOException ignored) { ; } } is = null; } if (null == padv) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("missing rendezvous peer advertisement"); } return; } long lease; try { MessageElement el = msg.getMessageElement("jxta", ConnectedLeaseReply); if (el == null) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("missing lease"); } return; } lease = Long.parseLong(el.toString()); if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Got a lease for :" + lease); } } catch (Exception e) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Parse lease failed with ", e); } return; } ID pId; MessageElement el = msg.getMessageElement("jxta", ConnectedPeerReply); if (el == null) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("missing rdv peer"); } return; } pId = ID.create(URI.create(el.toString())); if (null == pId) { return; } String rdvName = padv.getName(); if (null == padv.getName()) { rdvName = pId.toString(); } if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("RDV Connect Response : peer=" + rdvName + " lease=" + lease + "ms"); } if (lease <= 0) { removeRdv(pId, false); } else { // BT if (rendezVous.containsKey(pId) // || ((rendezVous.size() < MAX_RDV_CONNECTIONS))) { addRdv(padv, lease); //} else { // if (LOG.isEnabledFor(Priority.DEBUG)) { // XXX bondolo 20040423 perhaps we should send a disconnect here. // LOG.debug("Ignoring lease offer from " + rdvName); // } } } /** * Handle a disconnection request from a remote peer. * * @param msg Description of Parameter */ protected void processDisconnectRequest(Message msg) { try { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Processing a disconnect request"); } MessageElement elem = msg.getMessageElement("jxta", DisconnectRequest); if (null != elem) { InputStream is = elem.getStream(); PeerAdvertisement adv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(elem.getMimeType(), is); RdvConnection rdvConnection = (RdvConnection) rendezVous.get(adv.getPeerID()); if (null != rdvConnection) { rdvConnection.setConnected(false); removeRdv(adv.getPeerID(), true); } else { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Ignoring disconnect request from " + adv.getPeerID()); } } } } catch (Exception failure) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Failure processing disconnect request", failure); } } } /** * {@inheritDoc} */ public void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { //MessageUtil.printMessageStats(msg, true); RendezVousPropagateMessage propHdr = checkPropHeader(msg); if (null != propHdr) { // Get the destination real destination of the message String sName = propHdr.getDestSName(); String sParam = propHdr.getDestSParam(); if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Processing " + msg + "(" + propHdr.getMsgId() + ") for " + sName + "/" + sParam + " from " + srcAddr); } // Check if we have a local listener for this message processReceivedMessage(msg, propHdr, srcAddr, new EndpointAddress(dstAddr, sName, sParam)); } } protected void processReceivedMessage(Message msg, RendezVousPropagateMessage propHdr, EndpointAddress srcAddr, EndpointAddress dstAddr) { EndpointListener listener = getListener(dstAddr.getServiceName() + dstAddr.getServiceParameter()); if (listener != null) { // We have a local listener for this message. // Deliver it. if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Calling local listener for [" + dstAddr.getServiceName() + dstAddr.getServiceParameter() + "] with " + msg + " (" + propHdr.getMsgId() + ")"); } try { listener.processIncomingMessage(msg, srcAddr, dstAddr); } catch (Throwable ignored) { if (LOG.isEnabledFor(Priority.ERROR)) { LOG.error("Uncaught Throwable during callback of (" + listener + ") to " + dstAddr, ignored); } } } else if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("No listener for [" + dstAddr.getServiceName() + dstAddr.getServiceParameter() + "] with " + msg + " (" + propHdr.getMsgId() + ")"); } } /** * Receive and publish a Rendezvous Peer Advertisement. * * @param msg Message containing the Rendezvous Peer Advertisement */ protected void processRdvAdvReply(Message msg) { try { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Processing a rendezvous reply"); } MessageElement elem = msg.getMessageElement("jxta", RdvAdvReply); if (null != elem) { PeerAdvertisement adv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(elem.getMimeType(), elem.getStream()); DiscoveryService discovery = group.getDiscoveryService(); if (null != discovery) { discovery.publish(adv, DiscoveryService.DEFAULT_EXPIRATION, DiscoveryService.DEFAULT_EXPIRATION); } } } catch (Exception failed) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Publish Rdv Adv failed", failed); } } connectToRdv(); } /** * {@inheritDoc} */ public void propagate(Message msg, String serviceName, String serviceParam, int ttl) throws IOException { ttl = Math.min(ttl, defaultTTL); RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, ttl); if (null != propHdr) { sendToEachConnection(msg, propHdr); sendToNetwork(msg, propHdr); } else { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Declining to propagate " + msg + " (No prop header)"); } } } /** * {@inheritDoc} */ public void propagate(Enumeration destPeerIDs, Message msg, String serviceName, String serviceParam, int ttl) throws IOException { propagate(destPeerIDs, msg, serviceName, serviceParam, ttl); } /** * {@inheritDoc} */ public void propagateInGroup(Message msg, String serviceName, String serviceParam, int ttl) throws IOException { ttl = Math.min(ttl, defaultTTL); RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, ttl); if (null != propHdr) { sendToEachConnection(msg, propHdr); } else { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Declining to propagate " + msg + " (No prop header)"); } } } /** * {@inheritDoc} */ public void propagateToNeighbors(Message msg, String serviceName, String serviceParam, int ttl) throws IOException { ttl = Math.min(defaultTTL, ttl); RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, ttl); if (null != propHdr) { try { sendToNetwork(msg, propHdr); } catch (IOException failed) { throw failed; } } } /** * {@inheritDoc} */ public final boolean removeListener(RendezvousListener listener) { return eventListeners.remove(listener); } /** * {@inheritDoc} */ public synchronized EndpointListener removePropagateListener(String name, EndpointListener listener) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Removing listener (" + listener + ") for name= " + name); } // Take the optimistic stance. Since we're synchronized, remove it, and if we find the invoker is cheating. Put it back. EndpointListener current = (EndpointListener) propListeners.remove(name); if ((current != null) && (current != listener)) { propListeners.put(name, current); return null; } return current; } /** * {@inheritDoc} */ public EndpointListener removePropagateListener(String serviceName, String serviceParam, EndpointListener listener) { // Until the old API is killed, the new API behaves like the old one (so that name // collisions are still detected if both APIs are in use). return removePropagateListener(serviceName + serviceParam, listener); } /** * Remove the specified rendezvous from our collection of rendezvous. * * @param rdvid the id of the rendezvous to remove. * @param requested Description of the Parameter private void removeRdv(ID rdvid, boolean requested) { if (LOG.isEnabledFor(Priority.INFO)) { LOG.info("Disconnect from RDV " + rdvid); } PeerConnection rdvConnection; synchronized (this) { rdvConnection = (PeerConnection) rendezVous.remove(rdvid); // let's add it to the list of disconnected rendezvous if (null != rdvConnection) { disconnectedRendezVous.add(rdvid); } } if (null != rdvConnection) { if (rdvConnection.isConnected()) { rdvConnection.setConnected(false); //(rdvConnection); } } * Remove the rendezvous we are disconnecting from the peerview as well. * This prevents us from immediately reconnecting to it. generateEvent(requested ? RendezvousEvent.RDVDISCONNECT : RendezvousEvent.RDVFAILED, rdvid); } */ /** * {@inheritDoc} */ protected void repropagate(Message msg, RendezVousPropagateMessage propHdr, String serviceName, String serviceParam) { try { propHdr = updatePropHeader(msg, propHdr, serviceName, serviceParam, defaultTTL); if (null != propHdr) { sendToEachConnection(msg, propHdr); sendToNetwork(msg, propHdr); } else { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Declining to repropagate " + msg + " (No prop header)"); } } } catch (Exception ez1) { // Not much we can do if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Could not repropagate " + msg, ez1); } } } /** * Sends a disconnect message to the specified peer. * * @param peerid Description of the Parameter * @param padv Description of the Parameter */ protected void sendDisconnect(PeerID peerid, PeerAdvertisement padv) { Message msg = new Message(); // The request simply includes the local peer advertisement. try { msg.replaceMessageElement("jxta", new TextDocumentMessageElement(DisconnectRequest, getPeerAdvertisementDoc(), null)); EndpointAddress addr = mkAddress(peerid, null, null); RouteAdvertisement hint = null; if (null != padv) { hint = RendezVousServiceImpl.extractRouteAdv(padv); } Messenger messenger = endpoint.getMessenger(addr, hint); if (null == messenger) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Could not get messenger for " + peerid); } return; } messenger.sendMessage(msg, pName, pParam); } catch (Exception e) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("sendDisconnect failed", e); } } } /** * Sends a disconnect message to the specified peer. * * @param pConn Description of the Parameter */ protected void sendDisconnect(PeerConnection pConn) { Message msg = new Message(); // The request simply includes the local peer advertisement. try { msg.replaceMessageElement("jxta", new TextDocumentMessageElement(DisconnectRequest, getPeerAdvertisementDoc(), null)); pConn.sendMessage(msg, pName, pParam); } catch (Exception e) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("sendDisconnect failed", e); } } } /** * Sends a disconnect message to the specified peer. * * @param pConn Description of the Parameter protected void sendDisconnect(PeerConnection pConn) { Message msg = new Message(); // The request simply includes the local peer advertisement. try { msg.replaceMessageElement("jxta", new TextDocumentMessageElement(DisconnectRequest, getPeerAdvertisementDoc(), null)); pConn.sendMessage(msg, pName, pParam); } catch (Exception e) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("sendDisconnect failed", e); } } } */ /** * Description of the Method * * @param pConn Description of the Parameter * @throws IOException Description of the Exception */ private void sendLeaseRequest(RdvConnection pConn) throws IOException { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Sending Lease request to " + pConn); } Message msg = new Message(); // The request simply includes the local peer advertisement. msg.replaceMessageElement("jxta", new TextDocumentMessageElement(ConnectRequest, getPeerAdvertisementDoc(), null)); pConn.sendMessage(msg, pName, pParam); } /** * Sends to all connected peers. <p/> * <p/> * Note: The original msg is not modified and may be reused upon return. * * @param msg is the message to propagate. * @param propHdr Description of the Parameter * @return Description of the Return Value */ protected int sendToEachConnection(Message msg, RendezVousPropagateMessage propHdr) { int sentToPeers = 0; List peers = Arrays.asList(getPeerConnections()); Iterator eachClient = peers.iterator(); if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Sending to rendezvous connection :" + peers.size()); } while (eachClient.hasNext()) { PeerConnection pConn = (PeerConnection) eachClient.next(); // Check if this rendezvous has already processed this propagated message. if (!pConn.isConnected()) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Skipping " + pConn + " for " + msg + "(" + propHdr.getMsgId() + ") -- disconnected."); } // next! continue; } if (propHdr.isVisited(pConn.getPeerID().toURI())) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Skipping " + pConn + " for " + msg + "(" + propHdr.getMsgId() + ") -- already visited."); } // next! continue; } if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Sending " + msg + "(" + propHdr.getMsgId() + ") to " + pConn); } if (pConn.sendMessage((Message) msg.clone(), PropSName, PropPName)) { sentToPeers++; } } if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Sent " + msg + "(" + propHdr.getMsgId() + ") to " + sentToPeers + " of " + peers.size() + " peers."); } return sentToPeers; } /** * Propagates on all endpoint protocols. <p/> * <p/> * Note: The original msg is not modified and may be reused upon return. * * @param msg is the message to propagate. * @param propHdr Description of the Parameter * @throws IOException Description of the Exception */ protected void sendToNetwork(Message msg, RendezVousPropagateMessage propHdr) throws IOException { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("Endpoint propagating " + msg + " (" + propHdr.getMsgId() + ")"); } endpoint.propagate((Message) msg.clone(), PropSName, PropPName); } /** * (@inheritDoc} */ public boolean setAutoStart(boolean auto) { return false; } /** * (@inheritDoc} */ public synchronized boolean setAutoStart(boolean auto, long period) { return false; } /** * {@inheritDoc} */ public void setChoiceDelay(long delay) { monitorStartAt = TimeUtils.toAbsoluteTimeMillis(delay); } /** * {@inheritDoc} */ public int startApp(String[] arg) { endpoint = group.getEndpointService(); if (null == endpoint) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Stalled until there is an endpoint service"); } return START_AGAIN_STALLED; } Service needed = group.getMembershipService(); try { // This must stay despite the call to addPropagateListener below. // The somewhat equivalent call done inside addPropagateListener // may be removed in the future and this here would remain the only // case were both a propagate listener and an endpoint listener are connected. if (!endpoint.addIncomingMessageListener(this, PropSName, PropPName)) { if (LOG.isEnabledFor(Priority.ERROR)) { LOG.error("Cannot register the propagation listener (already registered)"); } } addPropagateListener(PropSName + PropPName, this); } catch (Exception ez1) { // Not much we can do here. if (LOG.isEnabledFor(Priority.ERROR)) { LOG.error("Failed registering the propagation listener", ez1); } } /* if (null == needed) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Stalled until there is a membership service"); } return START_AGAIN_STALLED; } */ // Create the PeerView instance if (!PeerGroupID.worldPeerGroupID.equals(group.getPeerGroupID())) { timer.schedule(new MonitorTask(), 0, MONITOR_INTERVAL); } edgeProtocolListener = new EdgeProtocolListener(this); endpoint.addIncomingMessageListener(edgeProtocolListener, pName, null); generateEvent(RendezvousEvent.BECAMEEDGE, group.getPeerID()); if (LOG.isEnabledFor(Priority.INFO)) { LOG.info("Rendezvous Serivce started"); } return 0; } /** * {@inheritDoc} * * @throws will always throw a runtime exception as it is not a supported * operation */ public void startRendezVous() { throw new RuntimeException("Operation not supported"); } /** * {@inheritDoc} */ public synchronized void stopApp() { EndpointListener shouldbehandler = endpoint.removeIncomingMessageListener(pName, null); if (shouldbehandler != edgeProtocolListener) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Unregistered listener was not as expected." + shouldbehandler + " != " + this); } } shouldbehandler = endpoint.removeIncomingMessageListener(PropSName, PropPName); if (shouldbehandler != this) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Unregistered listener was not as expected." + shouldbehandler + " != " + this); } } Iterator eachListener = propListeners.keySet().iterator(); while (eachListener.hasNext()) { String aListener = (String) eachListener.next(); try { endpoint.removeIncomingMessageListener(aListener, null); } catch (Exception ignored) { } eachListener.remove(); } propListeners.clear(); timer.cancel(); msgIds.clear(); eventListeners.clear(); if (LOG.isEnabledFor(Priority.INFO)) { LOG.info("Rendezvous Serivce stopped"); } } /** * {@inheritDoc} */ public void stopRendezVous() { } /** * Remove the specified rendezvous from our collection of rendezvous. * * @param rdvid the id of the rendezvous to remove. * @param requested Description of the Parameter */ private void removeRdv(ID rdvid, boolean requested) { if (LOG.isEnabledFor(Priority.INFO)) { LOG.info("Disconnect from RDV " + rdvid); } PeerConnection rdvConnection; synchronized (this) { rdvConnection = (PeerConnection) rendezVous.remove(rdvid); // let's add it to the list of disconnected rendezvous if (null != rdvConnection) { disconnectedRendezVous.add(rdvid); } } if (null != rdvConnection) { if (rdvConnection.isConnected()) { rdvConnection.setConnected(false); sendDisconnect(rdvConnection); } } /* * Remove the rendezvous we are disconnecting from the peerview as well. * This prevents us from immediately reconnecting to it. */ generateEvent(requested ? RendezvousEvent.RDVDISCONNECT : RendezvousEvent.RDVFAILED, rdvid); } /** * Description of the Method * * @param msg propagated message * @param propHdr header element * @param serviceName service name * @param serviceParam service param * @param ttl time to live * @return RendezVous Propagate Message */ protected RendezVousPropagateMessage updatePropHeader(Message msg, RendezVousPropagateMessage propHdr, String serviceName, String serviceParam, int ttl) { boolean newHeader = false; if (null == propHdr) { propHdr = newPropHeader(serviceName, serviceParam, ttl); newHeader = true; } else { if (null == updatePropHeader(propHdr, ttl)) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("TTL expired for " + msg + " (" + propHdr.getMsgId() + ") ttl=" + propHdr.getTTL()); } return null; } } XMLDocument propHdrDoc = (XMLDocument) propHdr.getDocument(MimeMediaType.XMLUTF8); MessageElement elem = new TextDocumentMessageElement(HEADER_NAME, propHdrDoc, null); if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug((newHeader ? "Added" : "Updated") + " prop header for " + msg + " (" + propHdr.getMsgId() + ") ttl=" + propHdr.getTTL()); } msg.replaceMessageElement(MESSAGE_NAMESPACE_NAME, elem); return propHdr; } /** * Updates the propagation header of the message. Also adds this peer to * the path recorded in the message. Returns true if the message should be * repropagated, false otherwise. * * @param propHdr The propHdr for the message. * @param maxTTL The maximum TTL which will be allowed. * @return The updated propagate header if the message should be * repropagated otherwise null. */ private RendezVousPropagateMessage updatePropHeader(RendezVousPropagateMessage propHdr, int maxTTL) { int msgTTL = propHdr.getTTL(); URI me = group.getPeerID().toURI(); int useTTL = msgTTL; if (!propHdr.isVisited(me)) { // only reduce TTL if message has not previously visited us. useTTL--; } // ensure TTL does not exceed maxTTL useTTL = Math.min(useTTL, maxTTL); propHdr.setTTL(useTTL); // Add this peer to the path. propHdr.addVisited(me); // If message came in with TTL one or less, it was last trip. It can not go any further. return (useTTL <= 0) ? null : propHdr; } /** * {@inheritDoc} */ public void walk(Message msg, String serviceName, String serviceParam, int ttl) throws IOException { propagate(msg, serviceName, serviceParam, defaultTTL); } /** * {@inheritDoc} */ public void walk(Vector destPeerIDs, Message msg, String serviceName, String serviceParam, int defaultTTL) throws IOException { walk(destPeerIDs, msg, serviceName, serviceParam, defaultTTL); } /** * A timer task for monitoring our active rendezvous connections <p/> * <p/> * Checks leases, challenges when peer adv has changed, initiates lease * renewals, starts new lease requests. */ private class MonitorTask extends TimerTask { /** * @inheritDoc */ public void run() { try { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("[" + group.getPeerGroupID() + "] Periodic rendezvous check"); } LOG.debug("[" + group.getPeerGroupID() + "] Periodic rendezvous check"); Iterator eachRendezvous = Arrays.asList(rendezVous.values().toArray()).iterator(); while (eachRendezvous.hasNext()) { RdvConnection pConn = (RdvConnection) eachRendezvous.next(); try { if (!pConn.isConnected()) { if (LOG.isEnabledFor(Priority.INFO)) { LOG.debug("[" + group.getPeerGroupID() + "] Lease expired. Disconnected from " + pConn); } removeRdv(pConn.getPeerID(), false); continue; } if (pConn.peerAdvertisementHasChanged()) { // Pretend that our lease is expiring, so that we do not rest // until we have proven that we still have an rdv. if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("[" + group.getPeerGroupID() + "] Local PeerAdvertisement changed. Challenging " + pConn); } challengeRendezVous(pConn.getPeerID(), CHALLENGE_TIMEOUT); continue; } if (TimeUtils.toRelativeTimeMillis(pConn.getRenewal()) <= 0) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("[" + group.getPeerGroupID() + "] Attempting lease renewal for " + pConn); } sendLeaseRequest(pConn); } } catch (Exception e) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("[" + group.getPeerGroupID() + "] Failure while checking " + pConn, e); } } } // Not enough Rdvs? Try finding more. if (rendezVous.size() < MAX_RDV_CONNECTIONS) { connectToRdv(); } } catch (Throwable t) { if (LOG.isEnabledFor(Priority.WARN)) { LOG.warn("Uncaught throwable in thread :" + Thread.currentThread().getName(), t); } } } } /** * Listener for * <p/> * <assignedID>/<group-unique> */ private class EdgeProtocolListener implements EndpointListener { RendezVousServiceImpl rdvService; EdgeProtocolListener(RendezVousServiceImpl rdvService) { this.rdvService = rdvService; } /** * {@inheritDoc} */ public void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { if (LOG.isEnabledFor(Priority.DEBUG)) { LOG.debug("[" + group.getPeerGroupID() + "] processing " + msg); } if ((msg.getMessageElement("jxta", ConnectedPeerReply) != null) || (msg.getMessageElement("jxta", ConnectedRdvAdvReply) != null)) { rdvService.processConnectedReply(msg); } if (msg.getMessageElement("jxta", RdvAdvReply) != null) { rdvService.processRdvAdvReply(msg); } if (msg.getMessageElement("jxta", DisconnectRequest) != null) { rdvService.processDisconnectRequest(msg); } } } }
[ "Mohamed.Abdelaziz@Sun.COM" ]
Mohamed.Abdelaziz@Sun.COM
511fcfc725b876d23873e7a58b73df7f6f5fc27e
78dba16b47e9cca848baabb24de62877d78a82d0
/KCK/Makiety/src/zadanie1/Main.java
3549b9e46d3e9b22418504781ce98e63deb0f70e
[]
no_license
MSedkowski/java
21ca9d2bff112823629e7e2e78669e980bb71f29
e58639050d1ed113a047d0edaf84fe7ead0425f6
refs/heads/master
2021-01-22T21:53:45.675332
2018-02-09T19:20:56
2018-02-09T19:20:56
85,487,323
0
1
null
2017-04-28T05:37:20
2017-03-19T15:32:30
Java
UTF-8
Java
false
false
3,256
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package zadanie1; import javafx.scene.layout.VBox; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.control.ToggleButton; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Border; import javafx.scene.layout.BorderStroke; import javafx.scene.layout.BorderStrokeStyle; import javafx.scene.layout.BorderWidths; import javafx.scene.layout.CornerRadii; import javafx.scene.paint.Color; import javafx.stage.Stage; /** * * @author Mateusz */ public class Main extends Application { @Override public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("Insert File"); btn.setPrefSize(120, 30); btn.setAlignment(Pos.CENTER); Button btn1 = new Button(); btn1.setText("Clear Text"); btn1.setPrefSize(120, 30); btn1.setAlignment(Pos.CENTER); ToggleButton btn2 = new ToggleButton(); btn2.setText("Run Utility"); btn2.setDisable(true); btn2.setPrefSize(120, 30); btn2.setAlignment(Pos.CENTER); Button btn3 = new Button(); btn3.setText("Save File"); btn3.setPrefSize(120, 30); btn3.setAlignment(Pos.CENTER); Button btn4 = new Button(); btn4.setText("Help"); btn4.setPrefSize(120, 30); btn4.setAlignment(Pos.CENTER); Button btn5 = new Button(); btn5.setText("About"); btn5.setPrefSize(120, 30); btn5.setAlignment(Pos.CENTER); Button btn6 = new Button(); btn6.setText("Exit"); btn6.setPrefSize(120, 30); btn6.setAlignment(Pos.CENTER); VBox box = new VBox(); box.getChildren().addAll(btn,btn1,btn2,btn3,btn4,btn5,btn6); box.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT))); box.setPadding(new Insets(5)); TextArea area = new TextArea(); area.setPrefWidth(260); area.appendText("Pole Tekstowe"); area.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT))); area.setPadding(new Insets(5)); AnchorPane root = new AnchorPane(); AnchorPane.setTopAnchor(box, 0.0); AnchorPane.setLeftAnchor(box, 0.0); AnchorPane.setBottomAnchor(box, 0.0); AnchorPane.setTopAnchor(area, 0.0); AnchorPane.setRightAnchor(area, 0.0); AnchorPane.setBottomAnchor(area, 0.0); root.getChildren().addAll(box,area); Scene scene = new Scene(root, 400, 300); primaryStage.setTitle("Text/File IO Utility"); primaryStage.setScene(scene); primaryStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
[ "mateusz.sedkowski@gmail.com" ]
mateusz.sedkowski@gmail.com
96d29ac1ab694f08c074ecda0237406c6e1a6f7e
9d4e77f0595910e54296caec84883e133bd8f750
/src/BonusMilesService.java
b37239d9db847fca2bec5d040ba236f4a17c9153
[]
no_license
Shliskenstickin/dz_java2.2_1
f047a5819f9c788106b38b737158b8ef3e8294a0
c075c81e2838f70de0e29019c0b24124de8682ab
refs/heads/master
2023-03-13T02:54:40.084154
2021-03-06T11:33:41
2021-03-06T11:33:41
345,077,184
0
0
null
null
null
null
UTF-8
Java
false
false
198
java
public class BonusMilesService { public static int calculate(int price){ int bonusCoefficient = 20; int bonusMiles = price / bonusCoefficient; return bonusMiles; } }
[ "deathwalker@mail.ru" ]
deathwalker@mail.ru
4c20ff33d5a0d96e2a8dd8d9fb9dff0599c1d218
9650ae3628fb46056c990aaf6c48e8c350b0b5f6
/src/main/java/Anomaly/SortFile.java
66e74566ea9216cb05cec11dbbe701f8ee0b8eb3
[]
no_license
machinelearning147/CoinWorks
47b06beb58e92ba01f1f39c3afdfaafa2c2cfa9e
d84b87115ebd2cc66a8c221df4091ad5f49e92cd
refs/heads/master
2023-03-06T04:13:34.318690
2021-02-10T00:14:36
2021-02-10T00:14:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,720
java
package Anomaly; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; public class SortFile { private static final Logger logger = LoggerFactory.getLogger(SortFile.class); public static void main(String args[]) throws IOException { String dataDir = args[0]; String outDir = args[1]; String line = ""; FileUtils.cleanDirectory(new File(outDir)); SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm,a"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); splitIntoDays(dataDir, "inputs", outDir); splitIntoDays(dataDir, "outputs", outDir); } private static void splitIntoDays(String dataDir, String type, String outDir) throws IOException { String line; for (int year = 2009; year < 2018; year++) { for (int month = 1; month <= 12; month++) { logger.info(year + "\t" + month); HashMap<Integer, List<String>> con = new HashMap<>(); String fPath = dataDir + type + year + "_" + month + ".txt"; if (!new File(fPath).exists()) continue; BufferedReader br = new BufferedReader(new FileReader(fPath)); while ((line = br.readLine()) != null) { String arr[] = line.split("\t"); long txTime = Long.parseLong(arr[0]) * 1000; Date date = new Date(txTime); Calendar cal = Calendar.getInstance(); cal.setTime(date); int day = cal.get(Calendar.DAY_OF_YEAR); if (!con.containsKey(day)) { con.put(day, new ArrayList<String>()); } con.get(day).add(line); if (con.get(day).size() > 5000) { writeContent(type, year, con, day, outDir); con.get(day).clear(); } } br.close(); for (int day : con.keySet()) { if (con.get(day).size() > 0) { writeContent(type, year, con, day, outDir); } } } } } private static void writeContent(String type, int year, HashMap<Integer, List<String>> con, int day, String outDir) throws IOException { BufferedWriter wr = new BufferedWriter(new FileWriter(outDir + type + year + "Day" + day + ".txt", true)); for (String s : con.get(day)) { wr.append(s + "\r\n"); } wr.close(); } }
[ "cuneytgurcan@yahoo.com" ]
cuneytgurcan@yahoo.com
4299df7689610e61ec1a37831466faeedfe1fde5
5fdd9cf2d33fee48d343cf0d2fa37f2a40c0b372
/online_edu_permission/src/main/java/com/atguigu/security/utils/MyPasswordEncoder.java
55273d92e1ab05704e1569cc328337aa996d52a7
[]
no_license
hahagioi998/online_edu_parent
4c88d6eab54388e2c602dc620c69a3984a4fe798
51e9bab41404aa273450cc989cb03cb70200921b
refs/heads/master
2023-05-12T23:59:07.369124
2020-05-11T11:18:57
2020-05-11T11:18:57
485,859,282
1
0
null
null
null
null
UTF-8
Java
false
false
613
java
package com.atguigu.security.utils; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; @Component public class MyPasswordEncoder implements PasswordEncoder { public MyPasswordEncoder() { this(-1); } public MyPasswordEncoder(int strength) { } public String encode(CharSequence rawPassword) { return MD5.encrypt(rawPassword.toString()); } public boolean matches(CharSequence rawPassword, String encodedPassword) { return encodedPassword.equals(MD5.encrypt(rawPassword.toString())); } }
[ "18235757166@163.com" ]
18235757166@163.com
6f915642c2ad6fb72752d470ee8b39435e177583
3d5ca8d4791bc88b6cbf1e6b73efc11293a6ab2a
/server/src/main/java/server/electronics/product/domain/dto/promotion/PostPromotionDto.java
77f199f6bf7be06c5de958f596e4c404e8285f32
[]
no_license
vbertie/shop-app
ceb4bb11a797ececca2bd7ff6547071314a6e171
c4e07e264506dfeed86e0c5c9bac11d607a7013f
refs/heads/master
2023-01-05T08:06:09.060851
2019-10-08T08:40:29
2019-10-08T08:40:29
148,149,199
3
2
null
2023-01-04T12:23:37
2018-09-10T12:07:04
TypeScript
UTF-8
Java
false
false
729
java
package server.electronics.product.domain.dto.promotion; import lombok.*; import javax.validation.constraints.*; import java.io.Serializable; @Getter @Builder @AllArgsConstructor @EqualsAndHashCode public class PostPromotionDto implements Serializable { @Null private final Long id; private Long productId; @NotNull @Size(min = 1, max = 40) private String promotionName; @NotNull @Max(100) @Pattern(regexp="([0-9]+)") private String percentageReduction; private Boolean isActive; public PostPromotionDto(){ this.id = null; this.productId = null; this.promotionName = ""; this.percentageReduction = ""; this.isActive = null; } }
[ "Bartlomiej.Sulima@sapiens.com" ]
Bartlomiej.Sulima@sapiens.com
0339fa8d80da0844a3267f6545e80f8c57bf54f6
49b4cb79c910a17525b59d4b497a09fa28a9e3a8
/parserValidCheck/src/main/java/com/ke/css/cimp/fwb/fwb7/Rule_CHARGEABLE_WEIGHT.java
43fb7d68ea22e3bfdaf1bf134a27dd1eadeb8b38
[]
no_license
ganzijo/koreanair
a7d750b62cec2647bfb2bed4ca1bf8648d9a447d
e980fb11bc4b8defae62c9d88e5c70a659bef436
refs/heads/master
2021-04-26T22:04:17.478461
2018-03-06T05:59:32
2018-03-06T05:59:32
124,018,887
0
0
null
null
null
null
UTF-8
Java
false
false
2,304
java
package com.ke.css.cimp.fwb.fwb7; /* ----------------------------------------------------------------------------- * Rule_CHARGEABLE_WEIGHT.java * ----------------------------------------------------------------------------- * * Producer : com.parse2.aparse.Parser 2.5 * Produced : Tue Mar 06 10:38:08 KST 2018 * * ----------------------------------------------------------------------------- */ import java.util.ArrayList; final public class Rule_CHARGEABLE_WEIGHT extends Rule { public Rule_CHARGEABLE_WEIGHT(String spelling, ArrayList<Rule> rules) { super(spelling, rules); } public Object accept(Visitor visitor) { return visitor.visit(this); } public static Rule_CHARGEABLE_WEIGHT parse(ParserContext context) { context.push("CHARGEABLE_WEIGHT"); boolean parsed = true; int s0 = context.index; ParserAlternative a0 = new ParserAlternative(s0); ArrayList<ParserAlternative> as1 = new ArrayList<ParserAlternative>(); parsed = false; { int s1 = context.index; ParserAlternative a1 = new ParserAlternative(s1); parsed = true; if (parsed) { boolean f1 = true; @SuppressWarnings("unused") int c1 = 0; for (int i1 = 0; i1 < 7 && f1; i1++) { Rule rule = Rule_Typ_Decimal.parse(context); if ((f1 = rule != null)) { a1.add(rule, context.index); c1++; } } parsed = true; } if (parsed) { as1.add(a1); } context.index = s1; } ParserAlternative b = ParserAlternative.getBest(as1); parsed = b != null; if (parsed) { a0.add(b.rules, b.end); context.index = b.end; } Rule rule = null; if (parsed) { rule = new Rule_CHARGEABLE_WEIGHT(context.text.substring(a0.start, a0.end), a0.rules); } else { context.index = s0; } context.pop("CHARGEABLE_WEIGHT", parsed); return (Rule_CHARGEABLE_WEIGHT)rule; } } /* ----------------------------------------------------------------------------- * eof * ----------------------------------------------------------------------------- */
[ "wrjo@wrjo-PC" ]
wrjo@wrjo-PC
5d4506b0ca92dc4b1db9a37a7d53180b8121630f
f5348c5c05eb3b80224ac33dfb42d7341723e1f9
/src/main/java/com/bookish/bookish/controllers/UserController.java
2e0df91631e879fec8787cdf6f12d7f448dc9e58
[]
no_license
mikeharrison4/book-ish
3b79b0fde0e507bbf76a5ced94064f69aac63ae5
46190211c0228c9d6c20a8e77841235ea1fab87b
refs/heads/master
2022-12-30T18:42:01.063357
2020-10-21T11:23:06
2020-10-21T11:23:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,207
java
package com.bookish.bookish.controllers; import com.bookish.bookish.models.User; import com.bookish.bookish.models.UserOrder; import com.bookish.bookish.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/api/users") public class UserController { private final UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; } @GetMapping public List<User> getAllUsers() { return userService.getAllUsers(); } @GetMapping("{userId}") public User getUserWithUserId(@PathVariable("userId") String userId) { return userService.getUserWithUserId(userId); }; @GetMapping(path = "{userId}/orders") public List<UserOrder> getAllOrdersForUser(@PathVariable("userId") String userId) { return userService.getAllOrdersForUser(userId); } }
[ "mike.harrison@aexp.com" ]
mike.harrison@aexp.com
b1883248f6dda2e04fbee380613064ab69c97211
c6796ff5fe58186ed291391863dc3ec37fa5295c
/mybatis/mybatis04_crud_annotation/test/com/mybatis/test/MybatisTest.java
4d3c28826823b54657174e77920b8d96a4f1701c
[]
no_license
jsjchai/mybatis_study
0da7524a781595896ab75ebc9db19292522a15d1
f5e3a12f268266cfe150aa01f6385db9a94a3f87
refs/heads/master
2021-01-10T09:26:00.786326
2016-03-30T10:34:38
2016-03-30T10:34:38
55,054,448
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
2,019
java
package com.mybatis.test; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import com.mybatis.db.UserMapper; import com.mybatis.model.User; public class MybatisTest { SqlSessionFactory sqlSessionFactory; @Before public void initFactory() throws IOException { String resource = "sqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testGetUserById(){ SqlSession session=sqlSessionFactory.openSession(); UserMapper mapper= session.getMapper(UserMapper.class); User user=mapper.getUserById(2); session.close(); System.out.println(user); } @Test public void testAdd(){ SqlSession session=sqlSessionFactory.openSession(); UserMapper mapper= session.getMapper(UserMapper.class); User user=new User(); user.setName("ÀîËÄ"); user.setAge(21); user.setAddress("ÉϺ£"); mapper.add(user); session.commit(); session.close(); } @Test public void testUpdate(){ SqlSession session=sqlSessionFactory.openSession(); UserMapper mapper= session.getMapper(UserMapper.class); User user =mapper.getUserById(3); user.setAge(25); mapper.update(user); session.commit(); session.close(); } @Test public void testDelete(){ SqlSession session=sqlSessionFactory.openSession(); UserMapper mapper= session.getMapper(UserMapper.class); mapper.delete(3); session.commit(); session.close(); } @Test public void testFindAll(){ SqlSession session=sqlSessionFactory.openSession(); UserMapper mapper= session.getMapper(UserMapper.class); List<User> userList=mapper.findAll(); for(User user:userList){ System.out.println(user); } session.close(); } }
[ "jsjchai@163.com" ]
jsjchai@163.com
5777f3da945e5f15a2862fd38f936496d29f8b4b
4d7b13efe2b9050b500529b763f4ec28cecf5a15
/src/main/java/com/jacoblucas/adventofcode2020/utils/Pair.java
111f2f5f637c45330f3a20f18d67b6dad5a03b1e
[]
no_license
jacob-lucas/adventofcode-2020
d87cfa3f7837f1cb8779739febad5874e68110ac
ec242589bb3225ea971cd5feaf6bae96c5f5ce1d
refs/heads/main
2023-02-04T13:16:49.128333
2020-12-23T16:26:19
2020-12-23T16:26:19
313,669,355
0
0
null
null
null
null
UTF-8
Java
false
false
243
java
package com.jacoblucas.adventofcode2020.utils; import org.immutables.value.Value; @Value.Immutable @Value.Style(allParameters = true) public abstract class Pair<T, U> { public abstract T getFirst(); public abstract U getSecond(); }
[ "jacob.lucas@gmail.com" ]
jacob.lucas@gmail.com
b9e1b9be35377e816ff7cca48e9a751c005e54cd
60c7d8b2e8ae1d547f6cfc52b81d2eade1faf31d
/reportProject/st-js-stjs-3.3.0/generator-plugin-java8/src/test/java/org/stjs/generator/plugin/java8/writer/lambda/Lambda1.java
8240add1fa1be42b1eed316c8db17200903ecff5
[ "Apache-2.0" ]
permissive
dovanduy/Riddle_artifact
851725d9ac1b73b43b82b06ff678312519e88941
5371ee83161f750892d4f7720f50043e89b56c87
refs/heads/master
2021-05-18T10:00:54.221815
2019-01-27T10:10:01
2019-01-27T10:10:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
264
java
package org.stjs.generator.plugin.java8.writer.lambda; import org.stjs.javascript.functions.Function1; public class Lambda1 { public static void method(Function1<Integer, Integer> f) { } public static void main(String[] args) { method((x) -> x + 1); } }
[ "liuzhenwei_sx@qiyi.com" ]
liuzhenwei_sx@qiyi.com
3de678cbbaa91ad633a91a631b2c06cd367e95ce
0e3240e1bee9caff6cbb84443524609b4a93da4c
/app/src/main/java/com/avinashdavid/trivialtrivia/web/services/WiseService.java
e58e6f89ac6aa6df4aaa63852c498b4fdfc53254
[]
no_license
Aawesh/TrivialTrivia
8a54f05f174998894721e173e9299752ab3f2358
7a26eb9f0e971713b3cdd08b19bbd3ebc38065ad
refs/heads/master
2020-06-01T19:30:42.435180
2019-06-08T15:32:48
2019-06-08T15:32:48
190,901,215
0
0
null
2019-06-08T15:03:33
2019-06-08T15:03:32
null
UTF-8
Java
false
false
705
java
package com.avinashdavid.trivialtrivia.web.services; import com.avinashdavid.trivialtrivia.web.data.Login; import com.avinashdavid.trivialtrivia.web.data.Questions; import com.avinashdavid.trivialtrivia.web.data.Registration; import com.avinashdavid.trivialtrivia.web.data.Score; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; public interface WiseService { @GET("/questions") Call<Questions> getQuestions(); @POST("/login") Call<Boolean> login(@Body Login login); @POST("/quizresult") Call<Void> quizResult(@Body Score login); @POST("/register") Call<Boolean> register(@Body Registration registration); }
[ "shrestha.aawesh@gmail.com" ]
shrestha.aawesh@gmail.com
4aa6caf41510b16d7c6555b9d6e679a77fe94adf
8aad4ce72f667828a2207af26a3d42dd2b82d6d6
/src/com/ehinfo/hr/common/utils/echarts/series/MarkPoint.java
5d687ab09ab602d5d5e71655ea055c59ab3db981
[]
no_license
zhangxuanchen8/zbkfz
9333298644d2d4324094fd65992af92e6e7db5b0
63237c793941ff9149aaff2c99875d940c6d5314
refs/heads/master
2020-06-18T17:08:48.758895
2019-07-11T10:47:05
2019-07-11T10:47:05
196,375,643
0
0
null
null
null
null
UTF-8
Java
false
false
6,853
java
/* * The MIT License (MIT) * * Copyright (c) 2014-2015 * * 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 com.ehinfo.hr.common.utils.echarts.series; import com.ehinfo.hr.common.utils.echarts.AbstractData; import com.ehinfo.hr.common.utils.echarts.style.ItemStyle; /** * Description: MarkPoint * * */ public class MarkPoint extends AbstractData<MarkPoint> { /** * 标注类型 * * @see com.ehinfo.hr.common.utils.echarts.series.Series#symbol */ private Object symbol; /** * 标注大小 * * @see com.ehinfo.hr.common.utils.echarts.series.Series#symbolSize */ private Object symbolSize; /** * 标注图形旋转角度 * * @see com.ehinfo.hr.common.utils.echarts.series.Series#symbolRoate */ private Object symbolRoate; /** * 是否启动大规模标注模式 */ private Boolean large; /** * 标注图形炫光特效 * * @see com.ehinfo.hr.common.utils.echarts.series.Effect */ private Effect effect; /** * 标注图形样式属性 * * @see com.ehinfo.hr.common.utils.echarts.series.Series#itemStyle */ private ItemStyle itemStyle; /** * 地图特有,标注图形定位坐标 * * @see com.ehinfo.hr.common.utils.echarts.series.Map#geoCoord */ private GeoCoord geoCoord; /** * 设置effect值 * * @param effect */ public MarkPoint effect(Effect effect) { this.effect = effect; return this; } /** * 设置itemStyle值 * * @param itemStyle */ public MarkPoint itemStyle(ItemStyle itemStyle) { this.itemStyle = itemStyle; return this; } /** * 获取symbol值 */ public Object symbol() { return this.symbol; } /** * 设置symbol值 * * @param symbol */ public MarkPoint symbol(Object symbol) { this.symbol = symbol; return this; } /** * 获取symbolSize值 */ public Object symbolSize() { return this.symbolSize; } /** * 设置symbolSize值 * * @param symbolSize */ public MarkPoint symbolSize(Object symbolSize) { this.symbolSize = symbolSize; return this; } /** * 获取symbolRoate值 */ public Object symbolRoate() { return this.symbolRoate; } /** * 设置symbolRoate值 * * @param symbolRoate */ public MarkPoint symbolRoate(Object symbolRoate) { this.symbolRoate = symbolRoate; return this; } /** * 获取large值 */ public Boolean large() { return this.large; } /** * 设置large值 * * @param large */ public MarkPoint large(Boolean large) { this.large = large; return this; } /** * 标注图形炫光特效 * * @see com.ehinfo.hr.common.utils.echarts.series.Effect */ public Effect effect() { if (this.effect == null) { this.effect = new Effect(); } return this.effect; } /** * 标线图形样式属性 * * @see com.ehinfo.hr.common.utils.echarts.style.ItemStyle * @see com.ehinfo.hr.common.utils.echarts.series.Series#itemStyle */ public ItemStyle itemStyle() { if (this.itemStyle == null) { this.itemStyle = new ItemStyle(); } return this.itemStyle; } /** * 获取geoCoord值 */ public GeoCoord geoCoord() { if (this.geoCoord == null) { this.geoCoord = new GeoCoord(); } return this.geoCoord; } /** * 设置name,x,y值 * * @param name * @param x * @param y */ public MarkPoint geoCoord(String name, String x, String y) { this.geoCoord().put(name, x, y); return this; } /** * 获取itemStyle值 */ public ItemStyle getItemStyle() { return itemStyle; } /** * 设置itemStyle值 * * @param itemStyle */ public void setItemStyle(ItemStyle itemStyle) { this.itemStyle = itemStyle; } /** * 获取effect值 */ public Effect getEffect() { return effect; } /** * 设置effect值 * * @param effect */ public void setEffect(Effect effect) { this.effect = effect; } /** * 获取symbol值 */ public Object getSymbol() { return symbol; } /** * 设置symbol值 * * @param symbol */ public void setSymbol(Object symbol) { this.symbol = symbol; } /** * 获取symbolSize值 */ public Object getSymbolSize() { return symbolSize; } /** * 设置symbolSize值 * * @param symbolSize */ public void setSymbolSize(Object symbolSize) { this.symbolSize = symbolSize; } /** * 获取symbolRoate值 */ public Object getSymbolRoate() { return symbolRoate; } /** * 设置symbolRoate值 * * @param symbolRoate */ public void setSymbolRoate(Object symbolRoate) { this.symbolRoate = symbolRoate; } /** * 获取large值 */ public Boolean getLarge() { return large; } /** * 设置large值 * * @param large */ public void setLarge(Boolean large) { this.large = large; } /** * 获取geoCoord值 */ public GeoCoord getGeoCoord() { return geoCoord; } /** * 设置geoCoord值 * * @param geoCoord */ public void setGeoCoord(GeoCoord geoCoord) { this.geoCoord = geoCoord; } }
[ "937997183@qq.com" ]
937997183@qq.com
e81e99f6667c7aa8c40899f55d0bacbaceba62a0
4dea4f3f03f6266777e99507ea20c79ee5ce9310
/src/main/java/org/ocelot/tunes4j/effects/events/EffectEvent.java
c134f3723b50314c7a1a74c7cf0d82f17e23de3f
[]
no_license
hugomf/tunes4j
14c8180753e668962deb5c8e33f09b87600262c4
cb13771b2a22ddfea3a266ddb3dfc1958e9df4de
refs/heads/master
2023-04-06T12:19:41.784981
2023-03-23T15:28:25
2023-03-23T15:28:25
124,839,183
0
0
null
null
null
null
UTF-8
Java
false
false
486
java
package org.ocelot.tunes4j.effects.events; import java.util.EventObject; public class EffectEvent extends EventObject { private static final long serialVersionUID = 1L; private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public EffectEvent(Object source) { super(source); } public EffectEvent(Object source,String message) { super(source); this.message = message; } }
[ "hugomartinezf@gmail.com" ]
hugomartinezf@gmail.com
f855c80d420d9e704eeac8b5fe73a34b65a28603
31e7857c0c4d70d44af0888e12c9ff5eb6d788bb
/src/main/java/common/utils/JsonMaps.java
f0bcdafd8fd0bdfffb89fc12e1df80bd377ec4c8
[]
no_license
hbcztutu/MerManage
53a5ae28cfbec7f69ff3be49b7455b615c8510f4
5c3335e6eedd5e906040177c02a6640039c619b6
refs/heads/master
2021-01-13T08:58:41.994485
2016-09-25T10:56:55
2016-09-25T10:56:55
69,158,964
0
0
null
null
null
null
UTF-8
Java
false
false
9,484
java
package common.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonMaps { /** * 将json对象转换成Map * * @param jsonObject * json对象 * @return Map对象 */ public static Map<String, String> toMap(JSONObject jsonObject) { Map<String, String> result = new HashMap<String, String>(); @SuppressWarnings("unchecked") Iterator<String> iterator = jsonObject.keys(); String key = null; String value = null; while (iterator.hasNext()) { key = iterator.next(); value = jsonObject.getString(key); result.put(key, value); } return result; } public static Map<String, Object> parseJSON2Map(String jsonStr) { Map<String, Object> map = new HashMap<String, Object>(); // �?��层解�? JSONObject json = JSONObject.fromObject(jsonStr); @SuppressWarnings("unused") List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (Object k : json.keySet()) { Object v = json.get(k); // 如果内层还是数组的话,继续解�? if (v instanceof JSONArray) { // List<Map<String, Object>> list = new // ArrayList<Map<String,Object>>(); @SuppressWarnings("unchecked") Iterator<JSONObject> it = ((JSONArray) v).iterator(); while (it.hasNext()) { JSONObject json2 = it.next(); map.putAll(parseJSON2Map(json2.toString())); // list.add(parseJSON2Map(json2.toString())); } // map.put(k.toString(), list); } else { map.put(k.toString(), v); } } return map; } public static Map<String, String> parseJSON2Map2(String jsonStr) { Map<String, String> map = new HashMap<String, String>(); // JSONObject json = JSONObject.fromObject(jsonStr); @SuppressWarnings("unused") List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (Object k : json.keySet()) { Object v = json.get(k); // 如果内层还是数组的话,继续解�? if (v instanceof JSONArray) { // List<Map<String, Object>> list = new // ArrayList<Map<String,Object>>(); @SuppressWarnings("unchecked") Iterator<JSONObject> it = ((JSONArray) v).iterator(); while (it.hasNext()) { JSONObject json2 = it.next(); map.putAll(parseJSON2Map2(json2.toString())); // list.add(parseJSON2Map(json2.toString())); } // map.put(k.toString(), list); } else { map.put(k.toString(), (String) v); } } return map; } // map转json @SuppressWarnings("static-access") public static JSONObject toJSON(Map<String, String> map) { return new JSONObject().fromObject(map); } // map转json @SuppressWarnings("static-access") public static JSONObject toJSONs(Map<String, Map<String, String>> map) { return new JSONObject().fromObject(map); } public static Map<String, Map<String, String>> parseTxtMap(String txtStr) { Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>(); // String jsonStr=txtStr.substring(16, txtStr.length()); JSONObject jsonObject = JSONObject.fromObject(txtStr); // 第一层json @SuppressWarnings("unchecked") Iterator<String> iterator = jsonObject.keys(); String key = null; String value = null; while (iterator.hasNext()) { key = iterator.next(); value = jsonObject.getString(key); map.put(key, parseJSON2Map2(value)); // �?层json } return map; } public static String asciiToString(String s) {// ASCII转换为字符串 StringBuffer sbu = new StringBuffer(); sbu.append((char) Integer.parseInt(String.valueOf(s))); System.out.println(sbu.toString()); return sbu.toString(); } public static String StringToAscii(String s) {// 字符串转换为ASCII char[] ss = s.toCharArray(); StringBuffer sbu = new StringBuffer(); for (int i = 0; i < ss.length; i++) { String aa = String.valueOf((int) ss[i]); sbu.append(aa); } System.out.println(sbu.toString()); return sbu.toString(); } public static Map<String, Map<String, String>> parseTxtMaps(String txtStr) { Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>(); JSONObject jsonObject = JSONObject.fromObject(txtStr); // ��һ��json @SuppressWarnings("unchecked") Iterator<String> iterator = jsonObject.keys(); String key = null; String value = null; while (iterator.hasNext()) { key = iterator.next(); value = jsonObject.getString(key); map.put(key, parseJSON2Map2(value)); // �ڶ���json } Map<String, String> head = map.get("head"); Map<String, String> txn = map.get("txn"); head.put("txnType", txn.get("txnType")); txn.remove("txnType"); // head.put("version", txn.get("version")); // txn.remove("version"); // head.put("txnDate", txn.get("txnDate")); // txn.remove("txnDate"); // head.put("txnTime", txn.get("txnTime")); // txn.remove("txnTime"); // head.put("errCode", txn.get("errCode")); // txn.remove("errCode"); // head.put("errDisp", txn.get("errDisp")); // txn.remove("errDisp"); return map; } public static void StringToMap(String ss) { Map<String, String> map = new HashMap<String, String>(); String length = ss.substring(0, 8); map.put("length", length); int len = Integer.valueOf(asciiToString(length)); if (len == ss.length() - 8) { map.put("reqType", asciiToString(ss.substring(8, 9))); map.put("reqChannel", asciiToString(ss.substring(9, 25))); map.put("resChannel", asciiToString(ss.substring(25, 41))); map.put("messageType", asciiToString(ss.substring(41, 42))); map.put("mac", asciiToString(ss.substring(ss.length() - 8, ss.length()))); @SuppressWarnings("unused") String jsonString = asciiToString(ss.substring(42, ss.length() - 8)); } } // public static String asciiToStrings(String text) { // StringBuilder builder = new StringBuilder(); // for (int i = 0; i < text.length(); i++) { // if (text.charAt(i) == '1' && i < text.length() - 2) { // int code = Integer.parseInt(text.substring(i, i + 3)); // builder.append((char) code); // i += 2; // } else if (i < text.length() - 1) { // int code = Integer.parseInt(text.substring(i, i + 2)); // builder.append((char) code); // i += 1; // } // } // System.out.println(builder.toString()); // return builder.toString(); // } public static void main(String[] args) {} /** * * @Title: parseMapToJson * @Description: 将Map转换为Json * @author yang_df * @since 2014年8月25日 * @param map * @return */ public static String parseMapToJson(Map<String, Object> map) { String json = null; JSONObject jsonObject = JSONObject.fromObject(map); json = jsonObject.toString(); return json; } // txn转map @SuppressWarnings("unchecked") public static List<Map<String, String>> parseTxnMap(String txtStr) { @SuppressWarnings("unused") Map<String, List<Map<String, String>>> map = new HashMap<String, List<Map<String, String>>>(); // String jsonStr=txtStr.substring(16, txtStr.length()); JSONObject jsonObject = JSONObject.fromObject(txtStr); // Iterator<String> iterator = jsonObject.keys(); String key = null; @SuppressWarnings("unused") String value = null; @SuppressWarnings("rawtypes") List l = null; while (iterator.hasNext()) { key = iterator.next(); value = jsonObject.getString(key); if (key.equals("txn")) { // map.put(key, jsontolist(jsonObject.getString(key))); l = jsontolist(jsonObject.getString(key)); } } return l; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static List jsontolist(String json) { // json="[{'name':'huangbiao','age':'15'},{'name':'liumei','age':'14'}]"; JSONArray jsonarray = JSONArray.fromObject(json); // List list = (List)JSONArray.toList(jsonarray,Txn.class); List list2 = new ArrayList(); Iterator it = jsonarray.iterator(); while (it.hasNext()) { Map<String, Object> map = parseJSON2Map3(it.next().toString()); list2.add(map); } // listtojson(list2); return list2; } public static Map<String, Object> parseJSON2Map3(String jsonStr) { Map<String, Object> map = new HashMap<String, Object>(); JSONObject json = JSONObject.fromObject(jsonStr); @SuppressWarnings("unused") List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (Object k : json.keySet()) { Object v = json.get(k); if (v instanceof JSONArray) { // List<Map<String, Object>> list = new // ArrayList<Map<String,Object>>(); @SuppressWarnings("unchecked") Iterator<JSONObject> it = ((JSONArray) v).iterator(); while (it.hasNext()) { JSONObject json2 = it.next(); if ((k.equals("array_txn"))) { map.put("array_txn", jsontolist(v.toString())); } else { map.putAll(parseJSON2Map2(json2.toString())); } // Map mapss = (Map) list2.get(0); // if(mapss.containsKey("array_txn")){ // mapss.put("array_txn", // jsontolist(mapss.get("array_txn").toString())); // } // list.add(parseJSON2Map(json2.toString())); } // map.put(k.toString(), list); } else { map.put(k.toString(), v + ""); } } return map; } }
[ "hbcztutu@qq.com" ]
hbcztutu@qq.com
0637bf31c9fc02f2a4a3112e33c7637628ad697b
a9b7e359c52f0474fb7e08bcef83fdba73a41241
/app/src/main/java/s/android/ffmpeg/http/BinaryHttpResponseHandler.java
111a867b46b4f1e51ac67532b8755fca12e605b9
[]
no_license
raye-deng/oc-student-android
e526efb5414660364d1bd2255daee8388fbe16d8
835373e946c0341ae8176955cd9f40edeb103959
refs/heads/master
2022-05-12T18:09:00.247649
2016-04-01T10:17:56
2016-04-01T10:17:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,792
java
/* Android Asynchronous Http Client Copyright (c) 2011 James Smith <james@loopj.com> http://loopj.com 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 s.android.ffmpeg.http; import java.io.IOException; import java.util.regex.Pattern; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpResponseException; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.util.EntityUtils; import android.os.Message; /** * Used to intercept and handle the responses from requests made using * {@link AsyncHttpClient}. Receives response body as byte array with a * content-type whitelist. (e.g. checks Content-Type against allowed list, * Content-length). * <p> * For example: * <p> * <pre> * AsyncHttpClient client = new AsyncHttpClient(); * String[] allowedTypes = new String[] { "image/png" }; * client.get("http://www.example.com/image.png", new BinaryHttpResponseHandler(allowedTypes) { * &#064;Override * public void onSuccess(byte[] imageData) { * // Successfully got a response * } * * &#064;Override * public void onFailure(Throwable e, byte[] imageData) { * // Response failed :( * } * }); * </pre> */ public class BinaryHttpResponseHandler extends AsyncHttpResponseHandler { // Allow images by default private static String[] mAllowedContentTypes = new String[] { "image/jpeg", "image/png" }; /** * Creates a new BinaryHttpResponseHandler */ public BinaryHttpResponseHandler() { super(); } /** * Creates a new BinaryHttpResponseHandler, and overrides the default allowed * content types with passed String array (hopefully) of content types. */ public BinaryHttpResponseHandler(String[] allowedContentTypes) { this(); mAllowedContentTypes = allowedContentTypes; } // // Callbacks to be overridden, typically anonymously // /** * Fired when a request returns successfully, override to handle in your own code * @param binaryData the body of the HTTP response from the server */ public void onSuccess(byte[] binaryData) {} /** * Fired when a request returns successfully, override to handle in your own code * @param statusCode the status code of the response * @param binaryData the body of the HTTP response from the server */ public void onSuccess(int statusCode, byte[] binaryData) { onSuccess(binaryData); } /** * Fired when a request fails to complete, override to handle in your own code * @param error the underlying cause of the failure * @param binaryData the response body, if any * @deprecated */ @Deprecated public void onFailure(Throwable error, byte[] binaryData) { // By default, call the deprecated onFailure(Throwable) for compatibility onFailure(error); } // // Pre-processing of messages (executes in background threadpool thread) // protected void sendSuccessMessage(int statusCode, byte[] responseBody) { sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[]{statusCode, responseBody})); } @Override protected void sendFailureMessage(Throwable e, byte[] responseBody) { sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[]{e, responseBody})); } // // Pre-processing of messages (in original calling thread, typically the UI thread) // protected void handleSuccessMessage(int statusCode, byte[] responseBody) { onSuccess(statusCode, responseBody); } protected void handleFailureMessage(Throwable e, byte[] responseBody) { onFailure(e, responseBody); } // Methods which emulate android's Handler and Message methods @Override protected void handleMessage(Message msg) { Object[] response; switch(msg.what) { case SUCCESS_MESSAGE: response = (Object[])msg.obj; handleSuccessMessage(((Integer) response[0]).intValue() , (byte[]) response[1]); break; case FAILURE_MESSAGE: response = (Object[])msg.obj; handleFailureMessage((Throwable)response[0], response[1].toString()); break; default: super.handleMessage(msg); break; } } // Interface to AsyncHttpRequest @Override void sendResponseMessage(HttpResponse response) { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders("Content-Type"); byte[] responseBody = null; if(contentTypeHeaders.length != 1) { //malformed/ambiguous HTTP Header, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"), responseBody); return; } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for(String anAllowedContentType : mAllowedContentTypes) { if(Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) { foundAllowedContentType = true; } } if(!foundAllowedContentType) { //Content-Type not in allowed list, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"), responseBody); return; } try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if(temp != null) { entity = new BufferedHttpEntity(temp); } responseBody = EntityUtils.toByteArray(entity); } catch(IOException e) { sendFailureMessage(e, (byte[]) null); } if(status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } else { sendSuccessMessage(status.getStatusCode(), responseBody); } } }
[ "roean@foxmail.com" ]
roean@foxmail.com
3932a8970d7002b6177b4f38b215b1e86d200d14
89eb98d19a5226f2849564ac8d0531746f84296e
/scalding-parquet-scrooge/src/test/java/com/twitter/scalding/parquet/scrooge/ParquetScroogeSchemeTest.java
4055da43b6f54cb92a11db88ef5be0d7ca753586
[ "Apache-2.0" ]
permissive
mishin/scalding
5fe28badb73d8a8fe2bf398e72dc4b4b888f4999
c2c77dec1752f2d11c38944637677dc14e57516a
refs/heads/develop
2020-12-26T01:38:49.484845
2016-01-08T22:19:10
2016-01-08T22:19:10
49,385,782
1
0
null
2016-01-10T21:14:48
2016-01-10T21:14:48
null
UTF-8
Java
false
false
10,242
java
/* * 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 com.twitter.scalding.parquet.scrooge; import cascading.flow.Flow; import cascading.flow.FlowProcess; import cascading.flow.hadoop.HadoopFlowConnector; import cascading.operation.BaseOperation; import cascading.operation.Function; import cascading.operation.FunctionCall; import cascading.pipe.Each; import cascading.pipe.Pipe; import cascading.scheme.Scheme; import cascading.scheme.hadoop.TextLine; import cascading.tap.Tap; import cascading.tap.hadoop.Hfs; import cascading.tuple.Fields; import cascading.tuple.Tuple; import cascading.tuple.TupleEntry; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.thrift.TBase; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TIOStreamTransport; import org.junit.Test; import org.apache.parquet.cascading.ParquetValueScheme.Config; import org.apache.parquet.hadoop.thrift.ThriftToParquetFileWriter; import org.apache.parquet.hadoop.util.ContextUtil; import com.twitter.scalding.parquet.scrooge.thrift_scala.test.TestPersonWithAllInformation; import com.twitter.scalding.parquet.scrooge.thrift_java.test.Address; import com.twitter.scalding.parquet.scrooge.thrift_java.test.Phone; import com.twitter.scalding.parquet.scrooge.thrift_java.test.RequiredPrimitiveFixture; import com.twitter.scalding.parquet.scrooge.thrift_scala.test.Name; import com.twitter.scalding.parquet.scrooge.thrift_scala.test.Name$; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import scala.Option; import static org.junit.Assert.assertEquals; /** * Write data in thrift, read in scrooge * * @author Tianshuo Deng */ public class ParquetScroogeSchemeTest { public static final String PARQUET_PATH = "target/test/TestParquetToThriftReadProjection/file.parquet"; public static final String TXT_OUTPUT_PATH = "target/test/TestParquetToThriftReadProjection/output.txt"; @Test public void testWritePrimitveThriftReadScrooge() throws Exception { RequiredPrimitiveFixture toWrite = new RequiredPrimitiveFixture(true, (byte)2, (short)3, 4, (long)5, 6.0, "7"); toWrite.setInfo_string("it's info"); verifyScroogeRead(thriftRecords(toWrite), com.twitter.scalding.parquet.scrooge.thrift_scala.test.RequiredPrimitiveFixture.class, "RequiredPrimitiveFixture(true,2,3,4,5,6.0,7,Some(it's info))\n", "**"); } @Test public void testNestedReadingInScrooge() throws Exception { Map<String, com.twitter.scalding.parquet.scrooge.thrift_java.test.Phone> phoneMap = new HashMap<String, Phone>(); phoneMap.put("key1", new com.twitter.scalding.parquet.scrooge.thrift_java.test.Phone("111", "222")); com.twitter.scalding.parquet.scrooge.thrift_java.test.TestPersonWithAllInformation toWrite = new com.twitter.scalding.parquet.scrooge.thrift_java.test.TestPersonWithAllInformation(new com.twitter.scalding.parquet.scrooge.thrift_java.test.Name("first"), new Address("my_street", "my_zip"), phoneMap); toWrite.setInfo("my_info"); String expected = "TestPersonWithAllInformation(Name(first,None),None,Address(my_street,my_zip),None,Some(my_info),Map(key1 -> Phone(111,222)),None,None)\n"; verifyScroogeRead(thriftRecords(toWrite), TestPersonWithAllInformation.class, expected, "**"); String expectedProjected = "TestPersonWithAllInformation(Name(first,None),None,Address(my_street,my_zip),None,Some(my_info),Map(),None,None)\n"; verifyScroogeRead(thriftRecords(toWrite), TestPersonWithAllInformation.class, expectedProjected, "address/*;info;name/first_name"); } private static class ObjectToStringFunction extends BaseOperation implements Function { @Override public void operate(FlowProcess flowProcess, FunctionCall functionCall) { Object record = functionCall.getArguments().getObject(0); Tuple result = new Tuple(); result.add(record.toString()); functionCall.getOutputCollector().add(result); } } public <T> void verifyScroogeRead(List<TBase> recordsToWrite, Class<T> readClass, String expectedStr, String projectionFilter) throws Exception { Configuration conf = new Configuration(); deleteIfExist(PARQUET_PATH); deleteIfExist(TXT_OUTPUT_PATH); final Path parquetFile = new Path(PARQUET_PATH); writeParquetFile(recordsToWrite, conf, parquetFile); Scheme sourceScheme = new ParquetScroogeScheme(new Config().withRecordClass(readClass).withProjectionString(projectionFilter)); Tap source = new Hfs(sourceScheme, PARQUET_PATH); Scheme sinkScheme = new TextLine(new Fields("first", "last")); Tap sink = new Hfs(sinkScheme, TXT_OUTPUT_PATH); Pipe assembly = new Pipe("namecp"); assembly = new Each(assembly, new ObjectToStringFunction()); Flow flow = new HadoopFlowConnector().connect("namecp", source, sink, assembly); flow.complete(); String result = FileUtils.readFileToString(new File(TXT_OUTPUT_PATH + "/part-00000")); assertEquals(expectedStr, result); } private void writeParquetFile(List<TBase> recordsToWrite, Configuration conf, Path parquetFile) throws IOException, InterruptedException, org.apache.thrift.TException { //create a test file final TProtocolFactory protocolFactory = new TCompactProtocol.Factory(); final TaskAttemptID taskId = new TaskAttemptID("local", 0, true, 0, 0); Class writeClass = recordsToWrite.get(0).getClass(); final ThriftToParquetFileWriter w = new ThriftToParquetFileWriter(parquetFile, ContextUtil.newTaskAttemptContext(conf, taskId), protocolFactory, writeClass); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final TProtocol protocol = protocolFactory.getProtocol(new TIOStreamTransport(baos)); for (TBase recordToWrite : recordsToWrite) { recordToWrite.write(protocol); } w.write(new BytesWritable(baos.toByteArray())); w.close(); } private List<TBase> thriftRecords(TBase... records) { List<TBase> result = new ArrayList<TBase>(); for (TBase record : records) { result.add(record); } return result; } private void deleteIfExist(String path) throws IOException { Path p = new Path(path); Configuration conf = new Configuration(); final FileSystem fs = p.getFileSystem(conf); if (fs.exists(p)) { fs.delete(p, true); } } final String txtInputPath = "src/test/resources/names.txt"; final String parquetOutputPath = "target/test/ParquetScroogeScheme/names-parquet-out"; final String txtOutputPath = "target/test/ParquetScroogeScheme/names-txt-out"; @Test public void testWriteThenRead() throws Exception { doWrite(); doRead(); } private void doWrite() throws Exception { Path path = new Path(parquetOutputPath); final FileSystem fs = path.getFileSystem(new Configuration()); if (fs.exists(path)) fs.delete(path, true); Scheme sourceScheme = new TextLine( new Fields( "first", "last" ) ); Tap source = new Hfs(sourceScheme, txtInputPath); Scheme sinkScheme = new ParquetScroogeScheme<Name>(Name.class); Tap sink = new Hfs(sinkScheme, parquetOutputPath); Pipe assembly = new Pipe( "namecp" ); assembly = new Each(assembly, new PackThriftFunction()); Flow flow = new HadoopFlowConnector().connect("namecp", source, sink, assembly); flow.complete(); } private void doRead() throws Exception { Path path = new Path(txtOutputPath); final FileSystem fs = path.getFileSystem(new Configuration()); if (fs.exists(path)) fs.delete(path, true); Scheme sourceScheme = new ParquetScroogeScheme<Name>(Name.class); Tap source = new Hfs(sourceScheme, parquetOutputPath); Scheme sinkScheme = new TextLine(new Fields("first", "last")); Tap sink = new Hfs(sinkScheme, txtOutputPath); Pipe assembly = new Pipe( "namecp" ); assembly = new Each(assembly, new UnpackThriftFunction()); Flow flow = new HadoopFlowConnector().connect("namecp", source, sink, assembly); flow.complete(); String result = FileUtils.readFileToString(new File(txtOutputPath+"/part-00000")); assertEquals("0\tAlice\tPractice\n15\tBob\tHope\n24\tCharlie\tHorse\n", result); } private static class PackThriftFunction extends BaseOperation implements Function { @Override public void operate(FlowProcess flowProcess, FunctionCall functionCall) { TupleEntry arguments = functionCall.getArguments(); Tuple result = new Tuple(); Name name = Name$.MODULE$.apply(arguments.getString(0), Option.apply(arguments.getString(1))); result.add(name); functionCall.getOutputCollector().add(result); } } private static class UnpackThriftFunction extends BaseOperation implements Function { @Override public void operate(FlowProcess flowProcess, FunctionCall functionCall) { TupleEntry arguments = functionCall.getArguments(); Tuple result = new Tuple(); Name name = (Name) arguments.getObject(0); result.add(name.firstName()); result.add(name.lastName().get()); functionCall.getOutputCollector().add(result); } } }
[ "ioconnell@twitter.com" ]
ioconnell@twitter.com
bf134e83ec7e334635555159efc4b863f096397a
89d7d42b316e7a91ce5ce98b43f91c0816a23bf0
/app/src/main/java/com/example/z7n/foodtruck/Fragments/OrderFragment.java
7d67b75fa1c4dc009839a51e7f72b04a66167cb8
[]
no_license
nawaf11/FoodTruck
840ac1b5ecada85d2a834f6f970a86ae1bd2c3d2
841bf3b08dc264f044198fb286242eee025d623e
refs/heads/master
2021-03-27T08:29:18.296506
2018-04-25T12:17:04
2018-04-25T12:17:04
120,486,323
0
0
null
null
null
null
UTF-8
Java
false
false
8,186
java
package com.example.z7n.foodtruck.Fragments; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.androidnetworking.interfaces.StringRequestListener; import com.example.z7n.foodtruck.Activity.MainActivity; import com.example.z7n.foodtruck.Database.DbHelper; import com.example.z7n.foodtruck.Order; import com.example.z7n.foodtruck.PHPHelper; import com.example.z7n.foodtruck.Product; import com.example.z7n.foodtruck.R; import com.example.z7n.foodtruck.Truck; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Locale; /** * Created by z7n on 3/27/2018. */ public class OrderFragment extends Fragment { private MenuEditorFragment.ProductAdapter productAdapter; private RecyclerView recyclerView; private TextView totalPrice_textView; private Button orderSubmit; private long truckID; private Order order; ProgressBar progressBar; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.order_form_fragment,container,false); truckID = getArguments().getLong("truck_id"); order = new Order(); initViews(view); getProductsTask(); return view; } @SuppressLint("SetTextI18n") private void initViews(View parentView) { recyclerView = parentView.findViewById(R.id.listView_menu); progressBar = parentView.findViewById(R.id.progressBar); progressBar.setVisibility(View.GONE); totalPrice_textView = parentView.findViewById(R.id.totalPrice_textView); orderSubmit = parentView.findViewById(R.id.orderSubmit); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); productAdapter = new MenuEditorFragment.ProductAdapter(this, new ArrayList<Product>()); productAdapter.withOrderForm(); recyclerView.setAdapter(productAdapter); totalPrice_textView.setText(getString(R.string.totalPrice) +" 0" ); orderSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(productAdapter.getTotalPrice() < 1){ Toast.makeText(getContext(), R.string.orderPrice_mustBe_moreThan_1 ,Toast.LENGTH_LONG).show(); return; } MainActivity mc = (MainActivity) getActivity(); if(mc != null && mc.getLoginState().getCustomer() != null){ order.setCustomerID(mc.getLoginState().getCustomer().getUserId()); order.setTruckID(truckID); order.setTotalPrice(productAdapter.getTotalPrice()); order.setOrderItems(getOrderItems()); startInsertOrderTask(); } } }); } private void startInsertOrderTask() { progressBar.setVisibility(View.VISIBLE); AndroidNetworking.post(PHPHelper.Order.add) .addBodyParameter("TruckID", String.valueOf(order.getTruckID())) .addBodyParameter("customerid", String.valueOf(order.getCustomerID())) .addBodyParameter("totalprice", String.valueOf(order.getTotalPrice())) .addBodyParameter("orderList", order.getOrderList_json().toString()) .build().getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { progressBar.setVisibility(View.GONE); Log.d("orderTask", response.toString()); try { if(response.getString("state").equals("success")) { order.setOrderID(response.getLong("orderID")); new DbHelper(getContext()).insertOrder(order.getOrderID()); Toast.makeText(getContext(), R.string.orderInserted_success, Toast.LENGTH_SHORT).show(); } else Toast.makeText(getContext(), R.string.unknownError, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { Toast.makeText(getContext(), R.string.unknownError, Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } @Override public void onError(ANError anError) { progressBar.setVisibility(View.GONE); Log.d("orderTask", anError.getErrorDetail()); Toast.makeText(getContext(), R.string.serverNotResponse, Toast.LENGTH_SHORT).show(); } }); } private ArrayList<Order.OrderItem> getOrderItems(){ ArrayList<Order.OrderItem> arr = new ArrayList<>(); ArrayList<Product> products = productAdapter.getProducts(); for ( Product p : products) { Order.OrderItem orderItem = new Order.OrderItem(); orderItem.setProductID(p.getProductId()); orderItem.setQuantity(p.getOrderQuantity()); arr.add(orderItem); } return arr; } private void getProductsTask(){ AndroidNetworking.post(PHPHelper.Product.getList) .addBodyParameter("truckid",String.valueOf(truckID)).build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { if(response.getString("state").equals("success")) startProductsTask(response); else Toast.makeText(getContext(),R.string.unknownError,Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getContext(),R.string.unknownError,Toast.LENGTH_SHORT).show(); } } @Override public void onError(ANError anError) { Toast.makeText(getContext(),R.string.serverNotResponse,Toast.LENGTH_SHORT).show(); } }); } private void startProductsTask(JSONObject response) throws JSONException { ArrayList<Product> arrayList = new ArrayList<>(); JSONArray jsonArray = response.getJSONArray("data"); for (int i=0; i < jsonArray.length(); i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); Product p = new Product(); p.setProductId(jsonObject.getLong("pid")); p.setName(jsonObject.getString("name")); p.setPrice(jsonObject.getDouble("price")); p.setDescription(jsonObject.getString("description")); arrayList.add(p); } productAdapter.getProducts().addAll(arrayList); productAdapter.notifyDataSetChanged(); } @SuppressLint("SetTextI18n") public void updateTotalPrice(double totalPrice) { DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(Locale.US); decimalFormat.applyPattern("0.00"); String fixedPrice = decimalFormat.format(totalPrice); totalPrice_textView.setText(getString(R.string.totalPrice) + " " +fixedPrice); } }
[ "nawafabdu@gmail.com" ]
nawafabdu@gmail.com
428fda4a0f430ad98c7f22ebf78d8c29df1c0534
4f12a79eeba57b43f708abbe20bd2cc4c965471d
/src/main/java/com/training/spring/factorybean/MessageFactoryBean.java
cbf9e6169c7084246d935f46d3553158f295d3a7
[]
no_license
KOO-YS/toby-spring
5ae13bac6635e536f41e100455dae0ec53ec0a26
ba1224e7fbf7848e7f6abaa0b1bc63089b48706d
refs/heads/master
2023-03-23T08:51:20.231811
2021-03-18T07:38:06
2021-03-18T07:38:06
319,549,491
2
0
null
2021-03-18T07:38:06
2020-12-08T06:39:16
Java
UTF-8
Java
false
false
840
java
package com.training.spring.factorybean; import org.springframework.beans.factory.FactoryBean; public class MessageFactoryBean implements FactoryBean<Message> { String text; // 오브젝트를 생성할 때 필요한 정보를 팩토리 빈의 프로퍼티로 설정해서 대신 DI 주입 public void setText(String text) { this.text = text; } // 실제 빈으로 사용될 오브젝트를 직접 생성 @Override public Message getObject() throws Exception { return Message.newMessage(this.text); } @Override public Class<?> getObjectType() { return Message.class; } // ?? // 팩토리 빈은 매번 요청할 때마다 새로운 오브젝트를 만들므로 false로 설정 @Override public boolean isSingleton() { return false; } }
[ "kbeeysk@naver.com" ]
kbeeysk@naver.com
df15dee873c888c282432be71e778b72696d0a11
71a28dd3448504e5c52bbe8ea034feae9153e381
/src/main/java/HashT/Item.java
6955f8a2cb8e840e63ecda54a8ff084aea64f6ca
[]
no_license
ksupenguin/algorithms
79465f47828ba6a7cdc520ba41cc3ffd4cd29b23
91e87145399707bf88667dc0f672630385a88ef2
refs/heads/master
2020-03-27T00:12:01.258026
2018-09-09T10:25:31
2018-09-09T10:25:31
145,603,138
0
0
null
null
null
null
UTF-8
Java
false
false
632
java
package HashT; public class Item { private String key; private String value; public Item(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return "Item{" + "key='" + key + '\'' + ", value='" + value + '\'' + '}'; } }
[ "k.chesnokova96@gmail.com" ]
k.chesnokova96@gmail.com
cdd7d3d153122242f462898ac99300451cb609e2
d0cbfbcaf465e51de17174773affa13d2f4a0a49
/src/uo/ri/model/Averia.java
f3458d07b190757da151b141fb0008e9a6b65e26
[]
no_license
danielmachado/CarWorkshop
96d7ef90f9919b29aea9b43383b0e60119dac56f
67cdf389dd44372f2e06d37a50dfb80cf00800dd
refs/heads/master
2021-01-19T17:41:49.668691
2013-05-01T11:52:23
2013-05-01T11:52:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,390
java
package uo.ri.model; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import uo.ri.amp.model.Mecanico; import uo.ri.model.types.AveriaStatus; /** * Avería * * @author Daniel Machado Fernández * */ @Entity @Table(name = "TAVERIAS") public class Averia { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String descripcion; @Temporal(TemporalType.DATE) private Date fecha; private Double importe; @Enumerated(EnumType.STRING) private AveriaStatus status; @ManyToOne private Factura factura; @ManyToOne private Mecanico mecanico; @OneToMany(mappedBy = "averia") private Set<Intervencion> intervenciones = new HashSet<Intervencion>(); @ManyToOne private Vehiculo vehiculo; public Averia() { } public Averia(String descripcion, Date fecha, double importe, AveriaStatus status) { super(); this.descripcion = descripcion; this.fecha = fecha; this.importe = importe; this.status = status; } public Averia(String descripcion) { this.descripcion = descripcion; fecha = new Date(); } public void addIntervencion(Intervencion i) { i._setAveria(this); intervenciones.add(i); } public void removeIntervencion(Intervencion i) { intervenciones.remove(i); i._setAveria(null); } @Override public String toString() { return "Averia [descripcion=" + descripcion + ", fecha=" + fecha + ", importe=" + importe + ", status=" + status + "]"; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public double getImporte() { double total = 0; for (Intervencion i : intervenciones) { total += i.getImporte(); } return total; } public void setImporte(double importe) { this.importe = importe; } public AveriaStatus getStatus() { return status; } public void setStatus(AveriaStatus status) { this.status = status; } public Factura getFactura() { return factura; } void _setFactura(Factura factura) { this.factura = factura; } public Long getId() { return id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((descripcion == null) ? 0 : descripcion.hashCode()); result = prime * result + ((fecha == null) ? 0 : fecha.hashCode()); result = prime * result + ((vehiculo == null) ? 0 : vehiculo.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Averia other = (Averia) obj; if (descripcion == null) { if (other.descripcion != null) return false; } else if (!descripcion.equals(other.descripcion)) return false; if (fecha == null) { if (other.fecha != null) return false; } else if (!fecha.equals(other.fecha)) return false; if (vehiculo == null) { if (other.vehiculo != null) return false; } else if (!vehiculo.equals(other.vehiculo)) return false; return true; } public void _setMecanico(Mecanico m) { this.mecanico = m; } public Mecanico getMecanico() { return mecanico; } void _setVehiculo(Vehiculo vehiculo) { this.vehiculo = vehiculo; } public Vehiculo getVehiculo() { return vehiculo; } public Set<Intervencion> getIntervenciones() { return Collections.unmodifiableSet(intervenciones); } public double calcularImporte() { importe = 0.0; for (Intervencion i : intervenciones) { importe += i.getImporte() + i.calcularManoObra(); } return importe; } Set<Intervencion> _getIntervenciones() { return intervenciones; } }
[ "daniel.machado.fernandez@gmail.com" ]
daniel.machado.fernandez@gmail.com
a911e7ed53abf56128ade1770b653f1b52841d94
0a3a89ab118afedf12d0d7e1bc2c5fcc25b9aacb
/src/main/java/me/bingyue/sword/Union.java
c9977e4d53d3803a7aa96f3191d20022efd13e14
[]
no_license
bingyue/practice
fbe24e8a265718b86cd364995d66295318546c47
328ee02b1ef4e4486122572e57ca439cf07f5146
refs/heads/master
2021-01-21T02:00:25.865940
2020-06-29T05:51:10
2020-06-29T05:51:10
51,685,509
0
1
null
null
null
null
UTF-8
Java
false
false
2,255
java
package me.bingyue.sword; import java.util.*; public class Union { class UF { // 连通分量个数 private int count; // 存储一棵树 private int[] parent; // 记录树的“重量” private int[] size; public UF(int n) { this.count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // 小树接到大树下面,较平衡 if (size[rootP] > size[rootQ]) { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } else { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } count--; } public boolean connected(int p, int q) { int rootP = find(p); int rootQ = find(q); return rootP == rootQ; } private int find(int x) { while (parent[x] != x) { // 进行路径压缩 parent[x] = parent[parent[x]]; x = parent[x]; } return x; } public int count() { return count; } } public Object[] intersection(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<>(); Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums1.length; i++) { map.put(nums1[i], i); } for (int j = 0; j < nums2.length; j++) { if (map.containsKey(nums2[j])) { set.add(nums2[j]); } } set.stream().toArray(); return set.toArray(); } public int findCircleNum(int[][] M) { int n = M.length; UF uf = new UF(n); for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (M[i][j] == 1) uf.union(i, j); } } return uf.count(); } }
[ "bingyue56@163.com" ]
bingyue56@163.com
3858e5c517ff751f74409f35fdee2929e4be3426
72f597e63e0c5dd1ad3e9efe6a7af1750e3c36fe
/publisher/src/main/java/com/example/springboot/Application.java
3d89fa2bddc1c9e34d592364db9295d5bd4ae02c
[]
no_license
charlesnjihia/pangaea
6b79ea8b3a1bdd02a073db5ffecdff758a5cf8e3
fda03bb78c2963271ccd1487535ae786ee1d8a74
refs/heads/master
2023-08-23T19:49:24.723375
2021-10-20T11:21:54
2021-10-20T11:21:54
419,298,756
0
0
null
null
null
null
UTF-8
Java
false
false
802
java
package com.example.springboot; import java.util.Arrays; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return args -> { System.out.println("Publisher Application"); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); for (String beanName : beanNames) { System.out.println(beanName); } }; } }
[ "chalzewanjohi@gmail.com" ]
chalzewanjohi@gmail.com
684b6304edc44d163a1863f2ec8efd4f72062afb
ec0f2632ab791ed3eccc9f5e905b47a3f0b12cdc
/src/BottPane/MenuBarPane.java
e0dca2d098b1fe546a3df98bfa602168e531f337
[]
no_license
DicuRazvanGabiel/Image-Archive
d2d7d9fc5db0b87cb8420142cfc26897a81ae420
8a6bae7c5b3aac2c52adbdc4c5cab5f39815c585
refs/heads/master
2020-07-26T20:50:34.784692
2016-11-14T14:51:00
2016-11-14T14:51:00
73,714,650
0
0
null
null
null
null
WINDOWS-1258
Java
false
false
1,875
java
package BottPane; import java.io.File; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuButton; import javafx.scene.control.MenuItem; import javafx.scene.control.ToolBar; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.stage.FileChooser; import javafx.stage.Stage; public class MenuBarPane { private Button addImageMenu = new Button("F1=Add Image"); private Button exportMenu = new Button("F3=Export"); private Button printMenu = new Button("F5=Print"); private Button exitMenu = new Button("F4=Exit"); private Button searchMenu = new Button("F7=Search"); private Button resetMenu = new Button("F8=Reset Filter"); private Button addToBufferMenu = new Button("F10=Add to Imagebuffer"); private Button showMenu = new Button("F11=Show Imagebuffer"); private Button todayMenu = new Button("F12=Today’s Images"); private ToolBar menuBar = new ToolBar(); private AddImageController addImageController; public MenuBarPane(AddImageController addImageController) { this.addImageController = addImageController; menuBar.getItems().addAll(addImageMenu,exportMenu,printMenu,exitMenu,searchMenu,resetMenu,addToBufferMenu,showMenu,todayMenu); addImageMenu.setOnAction(e -> addImage()); } private void addImage() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Resource File"); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Image Files", "*.jpg", "*.png")); File selectedFile = fileChooser.showOpenDialog(null); if (selectedFile != null) { addImageController.addImage(selectedFile); } } public Node getNode() { return menuBar; } }
[ "dicu.razvan.gabriel@gmail.com" ]
dicu.razvan.gabriel@gmail.com
900be05fcd378b70f75c98f78839ef5ca5fc4cd9
14d5f56ec6a7c44f75b937ca595460c9d35c6cdc
/Chapter1_Part3_VoVanMinh/src/builderpattern/AddressDirector.java
66d81ca9114c7923bd680593865bf333bf37565b
[]
no_license
VoVanMinh/AdvancedJavaSource
45707a5d74daf8b6b2e35017081b87c7c75d0aee
7189fedc273be50d4f1014d1619effebf2f65766
refs/heads/master
2020-09-21T08:59:11.983615
2017-09-12T15:46:11
2017-09-12T15:46:11
65,964,135
0
0
null
null
null
null
UTF-8
Java
false
false
241
java
package builderpattern; public class AddressDirector { public void Contruct(AddressBuilder builder, String street, String city, String region) { builder.buildStreet(street); builder.buildCity(city); builder.buildRegion(region); } }
[ "vovanminh1994@gmail.com" ]
vovanminh1994@gmail.com
2d7a4eb100321f2699ce02fc0e94a5f760a28c2a
ccf82688f082e26cba5fc397c76c77cc007ab2e8
/Mage.Sets/src/mage/cards/s/SecurityRhox.java
4da2c0ce9bc563dce8dc7d03b526968640ce82bf
[ "MIT" ]
permissive
magefree/mage
3261a89320f586d698dd03ca759a7562829f247f
5dba61244c738f4a184af0d256046312ce21d911
refs/heads/master
2023-09-03T15:55:36.650410
2023-09-03T03:53:12
2023-09-03T03:53:12
4,158,448
1,803
1,133
MIT
2023-09-14T20:18:55
2012-04-27T13:18:34
Java
UTF-8
Java
false
false
1,499
java
package mage.cards.s; import mage.MageInt; import mage.abilities.costs.AlternativeCostSourceAbility; import mage.abilities.costs.mana.ManaCost; import mage.abilities.costs.mana.ManaCostsImpl; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.FilterPermanent; import java.util.UUID; /** * @author TheElk801 */ public final class SecurityRhox extends CardImpl { private static final FilterPermanent filter = new FilterPermanent(SubType.TREASURE, ""); public SecurityRhox(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{R}{G}"); this.subtype.add(SubType.RHINO); this.subtype.add(SubType.WARRIOR); this.power = new MageInt(5); this.toughness = new MageInt(4); // You may pay {R}{G} rather than pay this spell's mana cost. Spend only mana produced by Treasures to cast it this way. ManaCost cost = new ManaCostsImpl<>("{R}{G}"); cost.setSourceFilter(filter); this.addAbility(new AlternativeCostSourceAbility( cost, null, "You may pay {R}{G} rather than pay this spell's mana cost. " + "Spend only mana produced by Treasures to cast it this way." )); } private SecurityRhox(final SecurityRhox card) { super(card); } @Override public SecurityRhox copy() { return new SecurityRhox(this); } }
[ "theelk801@gmail.com" ]
theelk801@gmail.com
3d0c4a0bca4ee4daf4cf047462f42f44d7f0270f
895939deecf394f80822537cb49c0fdb9746e047
/Tutorial1HelloWorld/Tutorial1Code.java
94ad52de8ead883723dca6f922630e2400c30bf3
[]
no_license
tarunbod/JavaFxTutorials
7c9cfadb054fa8b9adb2475d4ea2c9d49d973f1d
59c9fef26043e1b5d9e29b4d3894674aaaf859be
refs/heads/master
2021-01-22T22:56:52.679558
2014-09-13T14:30:05
2014-09-13T14:30:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,841
java
import javafx.application.Application; import static javafx.application.Application.launch; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; /* Welcome! THis is JavaFx Tutorial 1. Every JavaFX application's main class must extend the class Application. It provides an abstract method start(), in which the stage (window) and scene (main background) will be initialized. Here is an example of a basic JavaFx application. */ public class JavaFxTutorial1 extends Application { @Override public void start(Stage stage) { // Create a new button final Button button = new Button(); // set the text of the button to "Click me!" button.setText("Click Me!"); // add an event handler for when an action is performed on the button. // Event handler is a functional interface, which means it can be used in lmbda expressions // if you are using Java 8. button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { button.setText("Hello World!"); } }); // Here is an example of the above in Java 8 syntax. /* btn.setOnAction((event) -> System.out.println("Hello World!")); */ // When we click the button, it sets the button's text to "Hello World!" // A stackpane is a basic container which centers it's children. StackPane root = new StackPane(); // Now add the button to the StackPane's children. root.getChildren().add(button); // A scene is the main background for a JavaFx application. // Here we are making a new scene, with the root node as the stackpane, and // with a size of 300 x 300 Scene scene = new Scene(root, 300, 300); // Set the title of the window. stage.setTitle("Hello World!"); // Set the scene of the stage. All stages have a scene to show when application starts. stage.setScene(scene); // Show the stage, meaning open the window. stage.show(); } // In JavaFx applications, the main method isn't used to launch the application. // Just in case something goes wrong (which it probably won't), You should call the // launch(args) // method from the Application class in main. public static void main(String[] args) { launch(args); } /* This creates a basic JavaFx program. Note that if you are using Eclipse, you will need the e(fx)clipse plugin. If you are using netbeans, you can create a new JavaFx project from the new project window. I don't know about IntelliJ. */ }
[ "tarunbgamer@gmail.com" ]
tarunbgamer@gmail.com
d83cd7853f017773ec627c69c01da2db64a16e66
9a513db24f6d400f5aafc97615c1d0653b8d05a1
/OCCJava/TDataStd_Integer.java
d4f278adf2012488691b66fc4e2a8ac5df50450d
[]
no_license
Aircraft-Design-UniNa/jpad-occt
71d44cb3c2a906554caeae006199e1885b6ebc6c
f0aae35a8ae7c25c860d6c5ca5262f2b9da53432
refs/heads/master
2020-05-01T04:52:43.335920
2019-03-23T15:08:04
2019-03-23T15:08:04
177,285,955
3
1
null
null
null
null
UTF-8
Java
false
false
2,392
java
package opencascade; /** * The basis to define an integer attribute. */ public class TDataStd_Integer extends TDF_Attribute { TDataStd_Integer(long cPtr, boolean cMemoryOwn){super(cPtr, cMemoryOwn);} public synchronized void disposeUnused() {} /** * Integer methods * =============== */ public static TDataStd_Integer Set( TDF_Label label, int value) { return new TDataStd_Integer ( OCCwrapJavaJNI.TDataStd_Integer_Set__SWIG_0(TDF_Label.getCPtr(label), label, value), true ); } public static TDataStd_Integer Set( TDF_Label label, Standard_GUID guid, int value) { return new TDataStd_Integer ( OCCwrapJavaJNI.TDataStd_Integer_Set__SWIG_1(TDF_Label.getCPtr(label), label, Standard_GUID.getCPtr(guid), guid, value), true ); } public void Set(int V) { OCCwrapJavaJNI.TDataStd_Integer_Set__SWIG_2(swigCPtr, this, V); } /** * Sets the explicit GUID (user defined) for the attribute. */ public void SetID( Standard_GUID guid) { OCCwrapJavaJNI.TDataStd_Integer_SetID__SWIG_0(swigCPtr, this, Standard_GUID.getCPtr(guid), guid); } /** * Sets default GUID for the attribute. */ public void SetID() { OCCwrapJavaJNI.TDataStd_Integer_SetID__SWIG_1(swigCPtr, this); } /** * Returns the integer value contained in the attribute. */ public int Get() { return OCCwrapJavaJNI.TDataStd_Integer_Get(swigCPtr, this); } /** * Returns True if there is a reference on the same label */ public long IsCaptured() { return OCCwrapJavaJNI.TDataStd_Integer_IsCaptured(swigCPtr, this); } public TDataStd_Integer() { this(OCCwrapJavaJNI.new_TDataStd_Integer(), true); } public static String get_type_name() { return OCCwrapJavaJNI.TDataStd_Integer_get_type_name(); } public static Standard_Type get_type_descriptor() { return new Standard_Type ( OCCwrapJavaJNI.TDataStd_Integer_get_type_descriptor(), true ); } public static Standard_GUID GetId() { return new Standard_GUID(OCCwrapJavaJNI.TDataStd_Integer_GetId(), true); } public static TDataStd_Integer DownCast( Standard_Transient T) { return new TDataStd_Integer ( OCCwrapJavaJNI.TDataStd_Integer_DownCast( Standard_Transient.getCPtr(T) , T), true ); } public static Standard_Type TypeOf() { return new Standard_Type ( OCCwrapJavaJNI.TDataStd_Integer_TypeOf(), true ); } }
[ "agostino.demarco@unina.it" ]
agostino.demarco@unina.it
885fdd8e7266fb2b31230d4e59ac0c6cbb96f9da
9da60dc3ff0d47a7fc69a61302d46bcda45021e0
/rng-site/src/main/java/com/rng/site/web/controllers/TestController.java
3b7277007a7671042a756e1990804765f6d80e57
[ "MIT" ]
permissive
PPDonwhelan/Licenta
728df48410c5150d8739e6834f5364d5519bb5ad
e7adfb2ca131a8a064c56d98615117cade93b509
refs/heads/master
2020-03-19T21:34:25.584338
2017-07-17T14:49:28
2017-07-17T14:49:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,474
java
package com.rng.site.web.controllers; import com.rng.catalog.CatalogService; import com.rng.entities.Tests; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TestController extends SiteBaseController { @Autowired private CatalogService catalogService; @Override protected String getHeaderTitle() { return "Tests"; } @RequestMapping("/tests/{name}") public String test_by_name(@PathVariable String name, Model model) { Tests tests = catalogService.getTestsByName(name); model.addAttribute("tests", tests); return "tests"; } // @RequestMapping("/tests/{name}") // public String test_by_category(@PathVariable String name, Model model) // { // Tests tests = catalogService.getTestsByName(name); // model.addAttribute("tests", tests); // return "tests"; // } // @RequestMapping("/tests") // public String searchProducts(@RequestParam(name="name", defaultValue="") String query, Model model) // { // Tests tests = catalogService.getTestsByName(query); // List<Tests> lists_test= new ArrayList<Tests>(); // lists_test.add(tests); // model.addAttribute("tests", lists_test); // return "tests"; // } }
[ "Maria.Moldovan@paddypowerbetfair.com" ]
Maria.Moldovan@paddypowerbetfair.com
53ac81b1fe3a4169d07a0293192da5e1f6bd454f
b54343959f121c5daacb1db060cf6068160edd22
/app/src/androidTest/java/com/fjodor/fjodor_pset3/ExampleInstrumentedTest.java
8fbda0b934e95ae919bf1c060b827f6078ee6d6e
[]
no_license
fjodor-rs/Fjodor-pset3
b0deb0066e5448fa3f89fa5625122febfc6f9869
6e1e84b0f67bfab0359278d33305ae1173e29c72
refs/heads/master
2020-07-02T11:55:18.545543
2016-11-20T22:57:03
2016-11-20T22:57:03
74,307,537
0
0
null
null
null
null
UTF-8
Java
false
false
750
java
package com.fjodor.fjodor_pset3; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.fjodor.fjodor_pset3", appContext.getPackageName()); } }
[ "fjodor_rs@hotmail.com" ]
fjodor_rs@hotmail.com
160d39a83d72d8fe058c23ab60968ee2f676f01c
cc1b47db2b25d7f122d0fb48a4917fd01f129ff8
/domino-jnx-api/src/main/java/com/hcl/domino/design/frameset/FrameSizingType.java
36460712707c751d400f60436b8fff1a8f3d3ab0
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
savlpavel/domino-jnx
666f7e12abdf5e36b471cdd7c99086db589f923f
2d94e42cdfa56de3b117231f4488685f8e084e83
refs/heads/main
2023-09-04T10:20:43.968949
2023-07-31T16:41:34
2023-07-31T16:41:34
392,598,440
0
1
Apache-2.0
2021-08-04T07:49:29
2021-08-04T07:49:29
null
UTF-8
Java
false
false
1,607
java
/* * ========================================================================== * Copyright (C) 2019-2022 HCL America, Inc. ( http://www.hcl.com/ ) * 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. 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.hcl.domino.design.frameset; import com.hcl.domino.design.DesignConstants; import com.hcl.domino.misc.INumberEnum; /** * Represents the modes for sizing a frame within a frameset. * * @author Jesse Gallagher * @since 1.0.34 */ public enum FrameSizingType implements INumberEnum<Short> { PIXELS(DesignConstants.PIXELS_LengthType), PERCENTAGE(DesignConstants.PERCENTAGE_LengthType), RELATIVE(DesignConstants.RELATIVE_LengthType); private final short value; private FrameSizingType(short value) { this.value = value; } @Override public long getLongValue() { return value; } @Override public Short getValue() { return value; } }
[ "jesse@secondfoundation.org" ]
jesse@secondfoundation.org
e09252623f520b78425fec574e493991df64314c
ea1cec84d10b0845678098190b16cea9c1d920c6
/galaxy-dao/src/main/java/com/wasu/ptyw/galaxy/dal/dao/GalaxyFilmSectionDAO.java
5c60091c71e8d05acc99ab1aad9e3fc479729850
[]
no_license
kalegege/galaxy
4c4f463313e13230e1e70bc76d8510da4a751789
d2482a7de20d5f856e39b2a2a0bfb97cba833784
refs/heads/master
2021-01-19T09:37:16.668431
2017-04-10T06:35:03
2017-04-10T06:35:06
87,772,314
0
0
null
null
null
null
UTF-8
Java
false
false
647
java
package com.wasu.ptyw.galaxy.dal.dao; import java.util.Map; import com.wasu.ptyw.galaxy.dal.dataobject.GalaxyFilmSectionDO; import com.wasu.ptyw.galaxy.dal.persist.DAOException; import com.wasu.ptyw.galaxy.dal.persist.SimpleQuery; /** * @author wenguang * @date 2015年12月14日 */ public interface GalaxyFilmSectionDAO extends BaseDAO<GalaxyFilmSectionDO> { /** * 根据多个id更新状态 * * @param map * :int status,List ids * @return 更新成功的记录数 */ public int updateStatusByIds(Map<String, Object> map) throws DAOException; public int deleteByQuery(SimpleQuery query) throws DAOException; }
[ "xv88133536@163.com" ]
xv88133536@163.com
00309658790cd37b1addbe279388f160e1497a98
5a1b4df7d76abd49e01c482371b2e561135c3eeb
/app/src/main/java/com/volcano/holsansys/ui/user/UserFragment.java
f84d4e8bd38fa6b6e20351d9834a82ce25fcdff0
[]
no_license
Gene-He98/HolsanSys
0f7b5c11cfbcc14936716d388084f20e7d4f01a6
ccd090cc40a928d78ac30849892cb461e1ef6345
refs/heads/master
2022-07-26T10:33:21.971188
2020-05-17T13:45:36
2020-05-17T13:45:36
256,695,676
3
0
null
null
null
null
UTF-8
Java
false
false
11,405
java
package com.volcano.holsansys.ui.user; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.volcano.holsansys.MainActivity; import com.volcano.holsansys.R; import com.volcano.holsansys.add.AddPatientActivity; import com.volcano.holsansys.tools.WebServiceAPI; import java.util.LinkedList; import java.util.List; import java.util.Map; public class UserFragment extends Fragment { private List<Patient> mData = null; private Context mContext; private PatientAdapter mAdapter = null; private ListView list_user; private TextView userName; private View root; private LinearLayout userContent; private ScrollView patientContent; private VerifyTask myVerifyTask; private TextView me_name; private TextView me_user_age; private TextView me_sex; private TextView me_area; private TextView me_blood; private TextView me_medi; private TextView me_allergy; private boolean ifVisible; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { MainActivity.currentView=3; root = inflater.inflate(R.layout.fragment_user, container, false); userContent= root.findViewById(R.id.user_information); patientContent= root.findViewById(R.id.patients_information); me_name=root.findViewById(R.id.me_name); me_user_age=root.findViewById(R.id.me_user_age); me_sex=root.findViewById(R.id.me_sex); me_area=root.findViewById(R.id.me_area); me_blood=root.findViewById(R.id.me_blood); me_medi=root.findViewById(R.id.me_medi); me_allergy=root.findViewById(R.id.me_allergy); mContext =getActivity(); ifVisible=true; if(MainActivity.mode){ if(MainActivity.patientName.equals("")){ //提醒界面数据更新 updateUser(); }else { updatePatient(); userContent.setVisibility(View.GONE); patientContent.setVisibility(View.VISIBLE); } } else { if (MainActivity.textToSpeech != null) { MainActivity.textToSpeech.setPitch(1.0f); MainActivity.textToSpeech.setSpeechRate(1.0f); MainActivity.textToSpeech.speak("用户界面" , TextToSpeech.QUEUE_FLUSH, null); } updatePatient(); userContent.setVisibility(View.GONE); patientContent.setVisibility(View.VISIBLE); root.findViewById(R.id.me_bt_emer).setVisibility(View.VISIBLE); root.findViewById(R.id.edit_patient).setVisibility(View.GONE); root.findViewById(R.id.delete_patient).setVisibility(View.GONE); root.findViewById(R.id.back_main).setVisibility(View.GONE); } Thread refresh =new Thread() { @Override public void run() { while (ifVisible) { if (MainActivity.refreshPatientFlag) { if (MainActivity.patientName.equals("")) { String[] myParamsArr = {"UserInfo", MainActivity.userID}; myVerifyTask = new VerifyTask(); myVerifyTask.execute(myParamsArr); } else { String[] myParamsArr = {"PatientInfo", MainActivity.userID, MainActivity.patientName}; myVerifyTask = new VerifyTask(); myVerifyTask.execute(myParamsArr); } MainActivity.refreshPatientFlag = false; } } } }; refresh.start(); return root; } @Override public void onDestroyView() { super.onDestroyView(); ifVisible =false; } private void updatePatient() { String[] myParamsArr ={"PatientInfo",MainActivity.userID,MainActivity.patientName}; myVerifyTask = new VerifyTask(); myVerifyTask.execute(myParamsArr); root.findViewById(R.id.back_main).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.patientName=""; updateUser(); userContent.setVisibility(View.VISIBLE); patientContent.setVisibility(View.GONE); } }); root.findViewById(R.id.edit_patient).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent =new Intent(getActivity(), AddPatientActivity.class); intent.putExtra("kind","change"); startActivity(intent); } }); root.findViewById(R.id.delete_patient).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder normalDialog = new AlertDialog.Builder(getActivity()); normalDialog.setTitle("您将要删除此用药人"); normalDialog.setMessage("是否确定?"); normalDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deletePatient(); MainActivity.patientName=""; updateUser(); userContent.setVisibility(View.VISIBLE); patientContent.setVisibility(View.GONE); } }); normalDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); normalDialog.setCancelable(false); // 显示 normalDialog.show(); } }); } private void updateUser() { userName=root.findViewById(R.id.fra_user_name); userName.setText(MainActivity.userName); list_user = root.findViewById(R.id.listView_user); list_user.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { MainActivity.patientName=(String)((TextView)view.findViewById(R.id.patientName)).getText(); updatePatient(); userContent.setVisibility(View.GONE); patientContent.setVisibility(View.VISIBLE); } }); String[] myParamsArr={"UserInfo",MainActivity.userID}; myVerifyTask = new VerifyTask(); myVerifyTask.execute(myParamsArr); } private void deletePatient(){ String[] myParamsArr ={"DeletePatient",MainActivity.userID,MainActivity.patientName}; myVerifyTask = new VerifyTask(); myVerifyTask.execute(myParamsArr); } class VerifyTask extends AsyncTask<String, Integer, String> { private int kind=0; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... myParams) { if(myParams[0].equals("PatientInfo")) kind=1; String myResult=""; try { myResult = (new WebServiceAPI()).ConnectingWebService(myParams); } catch (Exception e) { e.printStackTrace(); } return myResult; } @Override protected void onProgressUpdate(Integer... myValues) { super.onProgressUpdate(myValues); } @Override protected void onPostExecute(String myResult) { switch (kind){ case 0 : if(myResult.equals("[{\"msg\":\"ok\"}]")){ } else { if(!myResult.equals("[]")){ Gson myGson = new Gson(); List<Map<String,String>> myList=myGson.fromJson(myResult, new TypeToken<List<Map<String,String>>>(){}.getType()); try { mData = new LinkedList<>(); for (int i=0;i<myList.size();i++){ Map<String,String> myMap=myList.get(i); String patientName = myMap.get("PatientName"); String location = myMap.get("Location"); mData.add(new Patient(patientName,location)); } mAdapter = new PatientAdapter((LinkedList<Patient>) mData, mContext); list_user.setAdapter(mAdapter); } catch (Exception ex){} } } break; case 1 : if(!myResult.equals("[]")){ Gson myGson = new Gson(); List<Map<String,String>> myList=myGson.fromJson(myResult, new TypeToken<List<Map<String,String>>>(){}.getType()); try { Map<String,String> myMap=myList.get(0); String patientName = myMap.get("PatientName"); String patientAge = myMap.get("PatientAge"); String patientSex = myMap.get("PatientSex"); String patientAddress = myMap.get("PatientAddress"); String patientBloodType = myMap.get("PatientBloodType"); String patientMedicalHistory = myMap.get("PatientMedicalHistory"); String patientAllergy = myMap.get("PatientAllergy"); me_name.setText(patientName); me_user_age.setText(patientAge); me_sex.setText(patientSex); me_area.setText(patientAddress); me_blood.setText(patientBloodType); me_medi.setText(patientMedicalHistory); me_allergy.setText(patientAllergy); } catch (Exception ex){} } } } } }
[ "1277923930@qq.com" ]
1277923930@qq.com
6a894d6ed52bca62d6d00d3771cfbfcfebf61338
5cd5ec2e1e5d4a5e61f31dae50eb402fb3bdbd52
/codes/07/7.2/HandDraw/gen/org/crazyit/image/R.java
160fd59da809cc20463e05e884073a200a76c82f
[]
no_license
wangcheng3986/CrazyAndroid
e25f1df147cf38cf35395bc97552294320a11a2e
9a5250e104f25c9910afcd546c98b3e623ce6b67
refs/heads/master
2021-01-01T19:56:41.041048
2015-04-18T14:45:42
2015-04-18T14:45:42
33,861,172
2
1
null
null
null
null
UTF-8
Java
false
false
1,841
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package org.crazyit.image; public final class R { public static final class attr { } public static final class drawable { public static final int ic_action_search=0x7f020000; public static final int ic_launcher=0x7f020001; } public static final class id { public static final int blue=0x7f060003; public static final int blur=0x7f060007; public static final int draw=0x7f060000; public static final int emboss=0x7f060008; public static final int green=0x7f060002; public static final int red=0x7f060001; public static final int width_1=0x7f060004; public static final int width_3=0x7f060005; public static final int width_5=0x7f060006; } public static final class layout { public static final int main=0x7f030000; } public static final class menu { public static final int my_menu=0x7f050000; } public static final class string { public static final int app_name=0x7f040001; public static final int blur=0x7f04000a; public static final int color=0x7f040008; public static final int color_blue=0x7f040007; public static final int color_green=0x7f040006; public static final int color_red=0x7f040005; public static final int emboss=0x7f04000b; public static final int hello=0x7f040000; public static final int width=0x7f040009; public static final int width_1=0x7f040002; public static final int width_3=0x7f040003; public static final int width_5=0x7f040004; } }
[ "wangcheng3986@navinfo.com" ]
wangcheng3986@navinfo.com
2209f1dda03b4e4a76507542ced3a2bfddc54e24
fe49198469b938a320692bd4be82134541e5e8eb
/scenarios/web/large/gradle/ClassLib033/src/main/java/ClassLib033/Class089.java
fd443675c4a90a3951cbbf7a479f6af77c968c44
[]
no_license
mikeharder/dotnet-cli-perf
6207594ded2d860fe699fd7ef2ca2ae2ac822d55
2c0468cb4de9a5124ef958b315eade7e8d533410
refs/heads/master
2022-12-10T17:35:02.223404
2018-09-18T01:00:26
2018-09-18T01:00:26
105,824,840
2
6
null
2022-12-07T19:28:44
2017-10-04T22:21:19
C#
UTF-8
Java
false
false
122
java
package ClassLib033; public class Class089 { public static String property() { return "ClassLib033"; } }
[ "mharder@microsoft.com" ]
mharder@microsoft.com
905442c85bf373c19916fb69ecaf0d89e51af085
6f6b0e9d83791fbe3591e0098927cb427d294383
/492.json/492.json.main/src/main/java/Main.java
40b5fd46ffc89e936db571742e611c6afda7db3d
[]
no_license
umurtrky/cmpe492-project
81c1ba768d498e2c3010b9e702465f126bfc60ee
52915a3f0c01f6d56553010f2db27a9e833b938f
refs/heads/master
2020-12-25T10:14:07.814956
2012-10-09T13:33:17
2012-10-09T13:33:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
131
java
/** * User: nyilmaz * Date: 10/3/12 * Time: 4:39 PM */ public class Main { public static void main(String[] args) { } }
[ "nyilmaz88@gmail.com" ]
nyilmaz88@gmail.com
1c50f0e2c995d7ddd96e4576f38f6f7d2107038d
fec94a43e9b95bf23b6ee40b9a166ac2cc94bc21
/src/Graph.java
02c9b23e8f11435a23f9717bb30181d32669cb07
[]
no_license
sypark0720/reproduce_santos
baf49c1ed5e24e0d6fa28d8da280b32b73437757
8f0e12822e0a7855b582bb8705ff00694e94f2f4
refs/heads/master
2021-01-19T10:00:50.951035
2017-05-17T14:04:38
2017-05-17T14:04:38
87,812,620
0
0
null
null
null
null
UTF-8
Java
false
false
2,742
java
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; public class Graph implements Cloneable { private int nNode; private List<List<Integer>> adjacencyList; private int[] degree; private int[] strategy; private double[] payoff; public Graph(int nNode, List<List<Integer>> adjacencyList, int[] degree) { this.adjacencyList = adjacencyList; this.degree = degree; this.strategy = new int[nNode]; this.payoff = new double[nNode]; } public Graph(int nNode,List<List<Integer>> adjacencyList, int[] degree, int[] strategy, double[] payoff) { this.nNode = nNode; this.adjacencyList = adjacencyList; this.degree = degree; this.strategy = strategy; this.payoff = payoff; } public void initializePayoff(){ this.payoff = new double[nNode]; } public int initializeStrategy(double rc){ int[] newStrategy = new int[this.getnNode()]; Random rand = new Random(); int numOfC = (int) (rc*this.getnNode()); ArrayList<Integer> selected = new ArrayList<>(); int counter = 0; while(counter<numOfC){ int r = rand.nextInt(this.getnNode()); if(selected.contains(r)) continue; selected.add(r); newStrategy[r]=Param.COOPERATOR; counter++; } this.setStrategy(newStrategy); return counter; } public Graph clone() throws CloneNotSupportedException { Graph graph = (Graph) super.clone(); return graph; } public List<List<Integer>> getAdjacencyList() { return adjacencyList; } public void setAdjacencyList(List<List<Integer>> adjacencyList) { this.adjacencyList = adjacencyList; } public int[] getDegree() { return degree; } public void setDegree(int[] degree) { this.degree = degree; } public int getnNode() { return nNode; } public void setnNode(int nNode) { this.nNode = nNode; } public int[] getStrategy() { return strategy; } public void setStrategy(int[] strategy) { this.strategy = strategy; } public double[] getPayoff() { return payoff; } public void setPayoff(double[] payoff) { this.payoff = payoff; } @Override public String toString() { return "Graph{" + "\nnNode=" + nNode + ",\nadjacencyList=" + adjacencyList + ",\ndegree=" + Arrays.toString(degree) + ",\nstrategy=" + Arrays.toString(strategy) + ",\npayoff=" + Arrays.toString(payoff) + '}'; } }
[ "sun@sunui-MacBook-Pro.local" ]
sun@sunui-MacBook-Pro.local
8eb5736ac207397c9c99dd86c00771ad27de3053
f5ac511aa742ea0fad493aa47a916f0370a41aa0
/src/main/java/ru/nik66/engine/player/Player.java
28f5f800c425b5a101c8f210729355ab2ef27cfe
[]
no_license
Nikbstar/JavaChess
42005550eb4e4e85d7e4142660daa41985ca3fb9
a9fc29cd2d6d25f63af98fd33137e51e277b9818
refs/heads/master
2020-05-21T03:37:51.409659
2017-04-04T14:28:31
2017-04-04T14:28:31
84,566,184
0
0
null
null
null
null
UTF-8
Java
false
false
5,767
java
package ru.nik66.engine.player; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import ru.nik66.engine.Alliance; import ru.nik66.engine.border.Board; import ru.nik66.engine.border.Move; import ru.nik66.engine.pieces.King; import ru.nik66.engine.pieces.Piece; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Created by nkotkin on 3/13/17. * Player. */ public abstract class Player { /** * board. */ private final Board board; /** * King. */ private final King playerKing; /** * legal moves. */ private final Collection<Move> legalMoves; /** * Check a check. */ private final boolean isInCheck; /** * Player initialization constructor. * @param boardArg board. * @param legalMovesArg legal moves. * @param opponentMovesArg opponent moves. */ Player(final Board boardArg, final Collection<Move> legalMovesArg, final Collection<Move> opponentMovesArg) { this.board = boardArg; this.playerKing = establishKing(); this.legalMoves = ImmutableList.copyOf( Iterables.concat(legalMovesArg, calculateKingCastles(legalMovesArg, opponentMovesArg)) ); this.isInCheck = !Player.calculateAttacksOnTile(this.playerKing.getPiecePosition(), opponentMovesArg).isEmpty(); } /** * Calculate attacks on tile. * @param piecePositionArg piece position. * @param movesArg move. * @return Attacks on tile collection. */ protected static Collection<Move> calculateAttacksOnTile(final int piecePositionArg, final Collection<Move> movesArg) { final List<Move> attackMoves = new ArrayList<>(); for (final Move move : movesArg) { if (piecePositionArg == move.getDestinationCoordinate()) { attackMoves.add(move); } } return ImmutableList.copyOf(attackMoves); } /** * Getter for board. * @return board. */ public Board getBoard() { return board; } /** * Getter for player king. * @return player king. */ public King getPlayerKing() { return playerKing; } /** * Getter for legalMoves. * @return legalMoves. */ public Collection<Move> getLegalMoves() { return legalMoves; } /** * King. * @return King piece. */ private King establishKing() { for (final Piece piece : getActivePieces()) { if (piece.getPieceType().isKing()) { return (King) piece; } } throw new RuntimeException("Should not reach here! Not a valid board!"); } /** * Check legal move. * @param moveArg move. * @return true if move is legal. */ public boolean isMoveLegal(final Move moveArg) { return this.legalMoves.contains(moveArg); } /** * check a check. * @return true if check. */ public boolean isInCheck() { return this.isInCheck; } /** * check check mate. * @return true if check mate. */ public boolean isInCheckMate() { return this.isInCheck && !hasEscapeMoves(); } /** * check stale mate. * @return true if stale mate. */ public boolean isInStaleMate() { return !this.isInCheck && !hasEscapeMoves(); } //TODO implement these methods below!!! /** * check castled. * @return true if castled. */ public boolean isCastled() { return false; } /** * Has escape moves? * @return true if it. */ protected boolean hasEscapeMoves() { boolean result = false; for (final Move move : this.legalMoves) { final MoveTransition transition = makeMove(move); if (transition.getMoveStatus().isDone()) { result = true; } } return result; } /** * make move. * @param moveArg move. * @return move transition. */ public MoveTransition makeMove(final Move moveArg) { MoveTransition result; if (!isMoveLegal(moveArg)) { result = new MoveTransition(this.board, moveArg, MoveStatus.ILLEGAL_MOVE); } else { final Board transitionBoard = moveArg.execute(); final Collection<Move> kingAttacks = Player.calculateAttacksOnTile( transitionBoard.getCurrentPlayer().getOpponent().getPlayerKing().getPiecePosition(), transitionBoard.getCurrentPlayer().getLegalMoves()); if (!kingAttacks.isEmpty()) { result = new MoveTransition(this.board, moveArg, MoveStatus.LEAVES_PLAYER_IN_CHECK); } else { result = new MoveTransition(transitionBoard, moveArg, MoveStatus.DONE); } } return result; } /** * Active pieces collection. * @return Pieces collection. */ public abstract Collection<Piece> getActivePieces(); /** * Get player alliance. * @return alliance. */ public abstract Alliance getAlliance(); /** * get opponent. * @return opponent. */ public abstract Player getOpponent(); /** * Calculate king castles. * @param playerLegalsArg Player legals. * @param opponentsLegalsArg Opponent legals. * @return Moves collection. */ protected abstract Collection<Move> calculateKingCastles(Collection<Move> playerLegalsArg, Collection<Move> opponentsLegalsArg); }
[ "nikbstar@gmail.com" ]
nikbstar@gmail.com
7197b0fe231899d24564173d36b55ffb837f58a8
2e407598058f0fdaaf4870ddc84172c3d651cab4
/Dynamic Programming/extra/House_Robber.java
77f9d3d12ac1b8574acd3c77559284d19533ddf6
[]
no_license
Shubham230198/CODE-IP
30196a53a9b72229c42c4eb09198862eb982078c
6322bae36834d6725b54cc7e03e00e5939aa43e2
refs/heads/master
2023-04-20T05:28:53.427957
2021-05-04T21:40:36
2021-05-04T21:40:36
330,550,118
0
0
null
null
null
null
UTF-8
Java
false
false
1,392
java
/* House Robber-1 Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. It will automatically contact the police if two adjacent houses were broken into on the same night Input: [5, 2, 1, 3] Output: 8 Explanation: Rob the first and the last house. */ public class House_Robber { /*Famous Dynamic Programming Approach. (for current postion last two-position answers are needed.) Time: O(n); Space: O(n); */ /*************************************************************************** */ /*Using 2-variables approach. {same above logic, just space optimised} Time: O(n); Space: O(1); */ public long houseRobber(int[] A) { if(A.length == 0) { return 0; } else if(A.length == 1) { return (long)A[0]; } long secondLastProfit = A[0]; long lastProfit = Math.max(A[0], A[1]); for(int i = 2; i < A.length; i++) { long nowProfit = Math.max(lastProfit, secondLastProfit + A[i]); secondLastProfit = lastProfit; lastProfit = nowProfit; } return lastProfit; } /********************************************************************************* */ }
[ "tiwari.98shubham@gmail.com" ]
tiwari.98shubham@gmail.com
9938f89e1d366cf3de544c8670152e5b6fb787da
805f41ac1b96e5a4c31a2e87f4cad1f31554caea
/src/main/java/com/oreilly/learningsparkexamples/mini/java/LineWithCharacterCount.java
2aa2576707f7f532a90d12d98d5b79ecefb38305
[]
no_license
manikandancvk/SparkExample
fdede496c079496dd245463b7faf9ee3d66afa1a
a32abde380a0bc965249eb0fba3e9c1b7a0641b5
refs/heads/master
2020-12-31T00:55:44.495457
2018-09-26T14:34:21
2018-09-26T14:34:21
80,601,231
0
0
null
null
null
null
UTF-8
Java
false
false
1,036
java
package com.oreilly.learningsparkexamples.mini.java; import org.apache.spark.api.java.*; import org.apache.spark.SparkConf; import org.apache.spark.api.java.function.Function; public class LineWithCharacterCount { public static void main(String[] args) { String logFile = "/Users/manikandan/Documents/official/smhack-app/softwares/spark-2.1.0-bin-hadoop2.7/README.md"; // Should be some file on your system SparkConf conf = new SparkConf().setAppName("Simple Application").setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); JavaRDD<String> logData = sc.textFile(logFile).cache(); long numAs = logData.filter(new Function<String, Boolean>() { public Boolean call(String s) { return s.contains("a"); } }).count(); long numBs = logData.filter(new Function<String, Boolean>() { public Boolean call(String s) { return s.contains("b"); } }).count(); System.out.println("Lines with a: " + numAs + ", lines with b: " + numBs); sc.stop(); } }
[ "manikandan.cvk@gmail.com" ]
manikandan.cvk@gmail.com
7eab32c6f1b89ffbb49bf3284b93de00899ee448
0945d1677bf4d7bb3d23f20e1c6f25581a0c4ab3
/polymer-core/src/test/java/com/truward/polymer/core/code/ModuleBuilderTest.java
9d69b935320b64a46950846f6c745dd0aa40c8c1
[ "Apache-2.0" ]
permissive
truward/polymer
8345a5ac59d302d441fc14c083d54143fe055935
ed1fc649bd02e004b34979c96370991eba7b267b
refs/heads/master
2020-12-24T14:27:01.018273
2014-05-21T03:40:02
2014-05-21T03:40:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
119
java
package com.truward.polymer.core.code; /** * @author Alexander Shabanov */ public final class ModuleBuilderTest { }
[ "avshabanov@gmail.com" ]
avshabanov@gmail.com
a46b7137b94763e28750ddcff9b11497bb2cc1bc
87d7375b752e34a81e351105ef557d39c6d9d294
/app/src/main/java/com/example/instagramclone/PostsAdapter.java
e5062f6ed1fa3fb35cfd5b5a174cd1edb42c7bcb
[ "Apache-2.0" ]
permissive
devanshgoyal25/InstagramClone
5504d802358bf2a90c7b9935a3305bb85ef49d24
7e4e2cfeec3618b1246e9b853c28ea7a09e9470c
refs/heads/master
2023-04-01T15:35:40.605174
2021-04-09T08:54:05
2021-04-09T08:54:05
349,968,529
0
0
null
null
null
null
UTF-8
Java
false
false
2,189
java
package com.example.instagramclone; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.parse.ParseFile; import org.w3c.dom.Text; import java.util.List; public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.ViewHolder> { private Context context; private List<Post> posts; public PostsAdapter(Context context, List<Post> posts) { this.context = context; this.posts = posts; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_post, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Post post = posts.get(position); holder.bind(post); } @Override public int getItemCount() { return posts.size(); } class ViewHolder extends RecyclerView.ViewHolder{ private TextView tvUsername; private TextView tvDescription; private ImageView ivImage; public ViewHolder(@NonNull View itemView) { super(itemView); tvUsername = itemView.findViewById(R.id.tvUsername); ivImage = itemView.findViewById(R.id.ivImage); tvDescription = itemView.findViewById(R.id.tvDescription); } public void bind(Post post) { tvDescription.setText(post.getDescription()); tvUsername.setText(post.getUser().getUsername()); ParseFile image = post.getImage(); if(image!=null){ Glide.with(context).load(image.getUrl()).into(ivImage); } } } public void clear() { posts.clear(); notifyDataSetChanged(); } public void addAll(List<Post> list) { posts.addAll(list); notifyDataSetChanged(); } }
[ "dgoyal@haverford.edu" ]
dgoyal@haverford.edu
42f775c585346589dee98802456e36919d2acb7c
bc800acdd48e53165f9fcfcf34e7aa30c4683ce6
/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/StillModelInstance.java
e4d80c7e5f270a42caf69a0cbd31049fe0e550d4
[]
no_license
jaredbracken/libgdx
e905064f6a0e27de331051a2c8a70c5c219862d4
15fb5ded7a8914fc77cea0efa5da2af703d631fe
refs/heads/master
2016-09-06T19:25:33.138335
2012-11-10T03:37:48
2012-11-10T03:37:48
6,623,954
2
2
null
null
null
null
UTF-8
Java
false
false
1,153
java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.graphics.g3d; import com.badlogic.gdx.graphics.g3d.materials.Material; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; public interface StillModelInstance { public Matrix4 getTransform (); public Vector3 getSortCenter (); public float getBoundingSphereRadius (); public Material[] getMaterials (); }
[ "jaredbracken@gmail.com" ]
jaredbracken@gmail.com
21aa5b48dfeef787da40cf828ba7c36bc9737cd4
04195075f84b645f7bebbc7f517c1113a0bb68a3
/hbase/src/main/java/com/wzl/hbase/HBaseConn.java
5d1719e34b568015ba271bd2a9fae4d4fc833fe2
[]
no_license
wangzili001/HBase
0f109706b3a5f4eb80747b29939026cb9f6ef5f0
d73471531c4f11b5d1202917016607ea4ff26436
refs/heads/master
2020-05-09T21:02:52.630721
2019-04-30T06:52:21
2019-04-30T06:52:21
181,428,394
0
0
null
null
null
null
UTF-8
Java
false
false
1,499
java
package com.wzl.hbase; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import java.io.IOException; public class HBaseConn { private static final HBaseConn INSTANCE = new HBaseConn(); //conf private static Configuration conf; //connection private static Connection connection; public HBaseConn() { if(conf==null){ conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum","jerry:2181"); } } public static Table getTable(String tableName) throws IOException { HBaseAdmin admin = (HBaseAdmin)getHBaseConn().getAdmin(); if(!admin.tableExists(tableName)){ throw new IOException("表不存在"); } return INSTANCE.getConnection().getTable(TableName.valueOf(tableName)); } private Connection getConnection() throws IOException { if(connection==null||connection.isClosed()){ connection = ConnectionFactory.createConnection(conf); } return connection; } public static Connection getHBaseConn() throws IOException { return INSTANCE.getConnection(); } public static void closeConn(){ if(connection!=null){ try { connection.close(); } catch (IOException e) { e.printStackTrace(); } } } }
[ "wangzili1995@qq.com" ]
wangzili1995@qq.com
b0b30106cbd994db0ab80137015c2896283684d2
e5cd8a4a496fcf02b0196db9f7cd571ce6e6db16
/AEP/src/main/java/observer/cofre/CofreListenerFechado.java
090610a520ee71989d2bbbbb11de13432ec59a02
[]
no_license
iRushGFX/4esoft2020
a59311a91599d1b877276a816a203117a799de94
cff88a237d6a0658a5d9bb314376cbeec78ba22a
refs/heads/master
2021-05-20T11:29:22.499149
2020-04-01T20:10:30
2020-04-01T20:10:30
252,276,343
0
0
null
null
null
null
UTF-8
Java
false
false
115
java
package observer.cofre; public interface CofreListenerFechado extends CofreListener{ void cofreFoiFechado(); }
[ "rodrigo.augusto.gimenes@gmail.com" ]
rodrigo.augusto.gimenes@gmail.com
7921ab9654ce8554bd6f72eaaa344f50fb2de3cc
93a3e9df19be9e24f632e3055e4a0cadf0dceeb0
/src/Hello.java
bb74df49491a941f9e110ac218075f3425ca7091
[]
no_license
GuillaumeJouetp/TP1_Java_2017-2018
91e5282f508ac4aefa0905e0f800b15e21248846
0f14ba2bc915bb998cbbb0e62056d18173c60870
refs/heads/master
2021-07-11T19:13:02.558971
2017-10-12T17:42:54
2017-10-12T17:42:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
153
java
public class Hello { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Hello le monde"); } }
[ "guillaume.jouet-pastre@hotmail.fr" ]
guillaume.jouet-pastre@hotmail.fr
0fe878e05c01134fbf5b1fa0afe4bd57a76a7276
203505b8cd5cfe4d1e7925fd44305726a7a9060d
/src/main/java/com/lv/zookeeper/HelloZK2.java
4441e49ae9d5d242a0a28a12886f2dafb99f1959
[]
no_license
lvrunsheng2014/ZooKeeperWatcher
3d033327691187b35b057d2c6408a3d545056a9d
e42de61ee62aebbbe7e8e9de1f61006a8293f90d
refs/heads/master
2021-04-15T13:51:50.055167
2018-04-15T00:39:19
2018-04-15T00:39:19
126,188,305
0
0
null
null
null
null
UTF-8
Java
false
false
2,230
java
package com.lv.zookeeper; import java.io.IOException; import org.apache.log4j.Logger; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; /** * eclipse此处为Client端,CentOS为ZooKeeper的server端 * 1 通过Java程序,新建连接ZK,类似jdbc的connection,open session * 2 新建一个znode节点/atguigu并设置为helloWorld 等同是 create /atguigu helloWorld * 3 获取当前节点/atguigu的最新值 * 4 关闭链接 * @author lvrun * * */ public class HelloZK2 extends ZooKeeperParent{ /** * Logger for this class */ private static final Logger logger = Logger.getLogger(HelloZK2.class); public ZooKeeper startZK() throws IOException { return new ZooKeeper(CONNECTSTRING, SESSIONTIMEOUT, new Watcher() { @Override public void process(WatchedEvent event) { // TODO Auto-generated method stub } }); } /** * 创建一个节点并赋值 * @param zk * @param path * @param data * @throws KeeperException * @throws InterruptedException */ public void createZnode(ZooKeeper zk,String path,String data) throws KeeperException, InterruptedException { zk.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } /** * 获取当前节点的最新值 * * @param zk * @param path * @return void * @throws Exception * @throws InterruptedException */ public String getZnode(ZooKeeper zk,String path) throws Exception, InterruptedException { String result=""; byte[] data = zk.getData(path, false, new Stat()); result=new String(data); return result; } public static void main(String[] args) throws Exception{ HelloZK2 hz=new HelloZK2(); ZooKeeper zk = hz.startZK(); if(zk.exists(PATH, false)==null) { hz.createZnode(zk, PATH, "helloWorld"); String result = hz.getZnode(zk, PATH); if (logger.isInfoEnabled()) { logger.info("main(String[]) - String result=" + result); } }else { logger.info("this is node exists"); } hz.stopZK(zk); } }
[ "lvrunsheng2014@163.com" ]
lvrunsheng2014@163.com
d558eb41e4cdc4e9334bb28fd141b26e693b6c3b
226b9b4fe991f4b4dbdc6dc62a51161da496dfe2
/Remove Duplicates from Sorted List II/src/Solution.java
ee49c19d9fb7188f60aeaeeca846d10dc1e519ad
[]
no_license
xiao-peng1006/Coding-Chanllenge2
43762e9e81e0457b2719fc7e2273dad39604415a
9fddd1919b91f43fe01e34332e9618c96d1134b7
refs/heads/master
2020-12-11T16:14:35.002265
2020-04-09T22:54:50
2020-04-09T22:54:50
233,894,381
0
0
null
null
null
null
UTF-8
Java
false
false
816
java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode deleteDuplicates(ListNode head) { ListNode dummyHead = new ListNode(0); dummyHead.next = head; ListNode pre = dummyHead, cur = head; while (cur != null) { while (cur.next != null && cur.val == cur.next.val) { cur = cur.next; } if (pre.next == cur) { pre = pre.next; } else { pre.next = cur.next; } cur = cur.next; } return dummyHead.next; } }
[ "xiao.peng1006@gmail.com" ]
xiao.peng1006@gmail.com
b1cdf141854b6e46c16700c82397907e1db9f527
5caf961912adbf5a0d881b04f5ec18968b6db091
/ExcelReadAndWrite/src/SampleExcelReader.java
ef08d8e04b8990113f068226cfac99dda3240d34
[]
no_license
mimran0/MavenSampleFirstTestCases
284bb46d3cba1f8a2cfde1d386f8339e131dafff
03e030774d80c1fa25aeca1da291dd780080ebc4
refs/heads/master
2021-07-15T11:54:41.533035
2018-10-09T04:32:58
2018-10-09T04:32:58
104,945,867
0
0
null
null
null
null
UTF-8
Java
false
false
1,939
java
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Iterator; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * */ /** * @author imran * */ public class SampleExcelReader { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { System.out.println("yes executed"); String excelFilePath = "C:\\Users\\imran\\workspace_Test\\MyExcel.xlsx"; FileInputStream inputStream = new FileInputStream(new File(excelFilePath)); Workbook workbook = new XSSFWorkbook(inputStream); Sheet firstSheet = workbook.getSheetAt(0); Iterator<Row> iterator = firstSheet.iterator(); while (iterator.hasNext()) { Row nextRow = iterator.next(); Iterator<Cell> cellIterator = nextRow.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); System.out.print(cell.getStringCellValue()); /*switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: System.out.print(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue()); break; }*/ System.out.print(" - "); } System.out.println(); } workbook.close(); inputStream.close(); } }
[ "jmrthan@gmail.com" ]
jmrthan@gmail.com
c4ecc6bc22698117e8f25842247f9a6271740882
9e6e72f992da5bd6437260430a61bfa98bb6bc55
/src/main/java/zollerngalaxy/blocks/BlockIngotStack.java
b249aed0ed343680b30f5a68d8daf857899efe85
[]
no_license
EndsM/Zollern-Galaxy
a1429fa2ee5a460510b5a869d039a7b279eef56c
fcd09ea4dbe73bcb0dc8f4d2f4812faaa828742f
refs/heads/master
2021-10-06T12:22:06.075199
2021-06-02T21:49:57
2021-06-02T21:49:57
245,354,597
0
0
null
2020-03-06T07:20:01
2020-03-06T07:20:00
null
UTF-8
Java
false
false
3,040
java
/** * Zollern Galaxy by @author Zollern Wolf * Copyright 2016 - 2025 * You may use this code to learn from, * but do not claim it as your own, and * do not redistribute it. */ package zollerngalaxy.blocks; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import zollerngalaxy.blocks.fluids.ZGFluidBase; public class BlockIngotStack extends ZGBlockBase { protected static final AxisAlignedBB INGOT_STACK_AABB = new AxisAlignedBB(0.0525D, 0.0D, 0.0525D, 0.8575D, 0.6D, 0.8575D); protected Item droppedItem = null; private final BlockIngotStack instance; public BlockIngotStack(String blockName, Item ingotIn) { super("ingotstack_" + blockName); this.instance = this; this.droppedItem = ingotIn; this.setHardResist(6.0F, 10.0F); this.setMaterial(Material.IRON); this.setShouldJSONIgnore(true); } public boolean canBlockStay(World world, BlockPos pos, IBlockState state) { Block block = world.getBlockState(new BlockPos(pos.getX(), pos.getY() - 1, pos.getZ())).getBlock(); if (block != Blocks.AIR && block != this.instance && !(block instanceof ZGFluidBase)) { return true; } return false; } public Item getDroppedItem() { return this.droppedItem; } public Block setDroppedItem(Item droppedItemIn) { this.droppedItem = droppedItemIn; return this; } @Override public Item getItemDropped(IBlockState par1BlockState, Random rand, int fortune) { return this.droppedItem; } @Override public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { int j = 7; for (int k = 0; k < j; ++k) { drops.add(new ItemStack(this.droppedItem, 1, 0)); } } @Override public int quantityDropped(Random rand) { return 7; } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return INGOT_STACK_AABB; } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean isFullCube(IBlockState state) { return false; } @Override @SideOnly(Side.CLIENT) public boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) { return true; } @Override public BlockFaceShape getBlockFaceShape(IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face) { return BlockFaceShape.UNDEFINED; } @Override public boolean shouldJSONIgnore() { return true; } }
[ "alphawolf918@users.noreply.github.com" ]
alphawolf918@users.noreply.github.com
46591f993a63b450ebcb724ff2e834a6fc78b209
69d16b0ed0a2cb9f8b9a60e2b6dbc0e1054bf865
/nachos-sjtu/src/nachos/ag/AutoGrader.java
5c83da910cd058d6e04d5c8f838de23dc211bfc5
[ "MIT-Modern-Variant" ]
permissive
bobchennan/nachos
710580c3d67a66353b92a13186039e52aafb100a
62aa8c41edbad630b540f9943c9e4fba4b676aeb
refs/heads/master
2020-12-30T22:34:59.974750
2012-11-12T04:59:08
2012-11-12T04:59:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,314
java
// PART OF THE MACHINE SIMULATION. DO NOT CHANGE. package nachos.ag; import nachos.machine.*; import nachos.security.*; import nachos.threads.*; import java.util.Hashtable; import java.util.StringTokenizer; /** * The default autograder. Loads the kernel, and then tests it using * <tt>Kernel.selfTest()</tt>. */ public class AutoGrader { /** * Allocate a new autograder. */ public AutoGrader() { } /** * Start this autograder. Extract the <tt>-#</tt> arguments, call * <tt>init()</tt>, load and initialize the kernel, and call <tt>run()</tt>. * * @param privilege * encapsulates privileged access to the Nachos machine. */ public void start(Privilege privilege) { Lib.assertTrue(this.privilege == null, "start() called multiple times"); this.privilege = privilege; String[] args = Machine.getCommandLineArguments(); extractArguments(args); System.out.print(" grader"); init(); System.out.print("\n"); kernel = (Kernel) Lib .constructObject(Config.getString("Kernel.kernel")); kernel.initialize(args); run(); } private void extractArguments(String[] args) { String testArgsString = Config.getString("AutoGrader.testArgs"); if (testArgsString == null) { testArgsString = ""; } for (int i = 0; i < args.length;) { String arg = args[i++]; if (arg.length() > 0 && arg.charAt(0) == '-') { if (arg.equals("-#")) { Lib.assertTrue(i < args.length, "-# switch missing argument"); testArgsString = args[i++]; } } } StringTokenizer st = new StringTokenizer(testArgsString, ",\n\t\f\r"); while (st.hasMoreTokens()) { StringTokenizer pair = new StringTokenizer(st.nextToken(), "="); Lib.assertTrue(pair.hasMoreTokens(), "test argument missing key"); String key = pair.nextToken(); Lib.assertTrue(pair.hasMoreTokens(), "test argument missing value"); String value = pair.nextToken(); testArgs.put(key, value); } } String getStringArgument(String key) { String value = (String) testArgs.get(key); Lib.assertTrue(value != null, "getStringArgument(" + key + ") failed to find key"); return value; } int getIntegerArgument(String key) { try { return Integer.parseInt(getStringArgument(key)); } catch (NumberFormatException e) { Lib.assertNotReached("getIntegerArgument(" + key + ") failed: " + "value is not an integer"); return 0; } } boolean getBooleanArgument(String key) { String value = getStringArgument(key); if (value.equals("1") || value.toLowerCase().equals("true")) { return true; } else if (value.equals("0") || value.toLowerCase().equals("false")) { return false; } else { Lib.assertNotReached("getBooleanArgument(" + key + ") failed: " + "value is not a boolean"); return false; } } long getTime() { return privilege.stats.totalTicks; } void targetLevel(int targetLevel) { this.targetLevel = targetLevel; } void level(int level) { this.level++; Lib.assertTrue(level == this.level, "level() advanced more than one step: test jumped ahead"); if (level == targetLevel) done(); } private int level = 0, targetLevel = 0; void done() { System.out.print("\nsuccess\n"); privilege.exit(162); } private Hashtable<String, String> testArgs = new Hashtable<String, String>(); void init() { } void run() { kernel.selfTest(); kernel.run(); kernel.terminate(); } Privilege privilege = null; Kernel kernel; /** * Notify the autograder that the specified thread is the idle thread. * <tt>KThread.createIdleThread()</tt> <i>must</i> call this method before * forking the idle thread. * * @param idleThread * the idle thread. */ public void setIdleThread(KThread idleThread) { } /** * Notify the autograder that the specified thread has moved to the ready * state. <tt>KThread.ready()</tt> <i>must</i> call this method before * returning. * * @param thread * the thread that has been added to the ready set. */ public void readyThread(KThread thread) { } /** * Notify the autograder that the specified thread is now running. * <tt>KThread.restoreState()</tt> <i>must</i> call this method before * returning. * * @param thread * the thread that is now running. */ public void runningThread(KThread thread) { privilege.tcb.associateThread(thread); currentThread = thread; } /** * Notify the autograder that the current thread has finished. * <tt>KThread.finish()</tt> <i>must</i> call this method before putting the * thread to sleep and scheduling its TCB to be destroyed. */ public void finishingCurrentThread() { privilege.tcb.authorizeDestroy(currentThread); } /** * Notify the autograder that a timer interrupt occurred and was handled by * software if a timer interrupt handler was installed. Called by the * hardware timer. * * @param privilege * proves the authenticity of this call. * @param time * the actual time at which the timer interrupt was issued. */ public void timerInterrupt(Privilege privilege, long time) { Lib.assertTrue(privilege == this.privilege, "security violation"); } /** * Notify the autograder that a user program executed a syscall instruction. * * @param privilege * proves the authenticity of this call. * @return <tt>true</tt> if the kernel exception handler should be called. */ public boolean exceptionHandler(Privilege privilege) { Lib.assertTrue(privilege == this.privilege, "security violation"); return true; } /** * Notify the autograder that <tt>Processor.run()</tt> was invoked. This can * be used to simulate user programs. * * @param privilege * proves the authenticity of this call. */ public void runProcessor(Privilege privilege) { Lib.assertTrue(privilege == this.privilege, "security violation"); } /** * Notify the autograder that a COFF loader is being constructed for the * specified file. The autograder can use this to provide its own COFF * loader, or return <tt>null</tt> to use the default loader. * * @param file * the executable file being loaded. * @return a loader to use in loading the file, or <tt>null</tt> to use the * default. */ public Coff createLoader(OpenFile file) { return null; } /** * Request permission to send a packet. The autograder can use this to drop * packets very selectively. * * @param privilege * proves the authenticity of this call. * @return <tt>true</tt> if the packet should be sent. */ public boolean canSendPacket(Privilege privilege) { Lib.assertTrue(privilege == this.privilege, "security violation"); return true; } /** * Request permission to receive a packet. The autograder can use this to * drop packets very selectively. * * @param privilege * proves the authenticity of this call. * @return <tt>true</tt> if the packet should be delivered to the kernel. */ public boolean canReceivePacket(Privilege privilege) { Lib.assertTrue(privilege == this.privilege, "security violation"); return true; } boolean hasArgument (String key) { return testArgs.get(key) != null; } private KThread currentThread; }
[ "wmhkebe@gmail.com" ]
wmhkebe@gmail.com
3eca241b0d16cd85cbb08ee6b3a907ff7c12816c
36c86af34d1651c1fc1a0cd62383fc00e1da2162
/src/test/java/com/winster/spring/scheduledtask/ApplicationTests.java
206f42fd2503bead255de266619ed0b9c92f3087
[]
no_license
winster/SpringSchedulerDynamic
c4606b855e0b2fe077a4dc0553933135d98e663f
3e7006e5cc339fd3b97706abd929c9918ba316c0
refs/heads/master
2022-12-03T23:57:41.362417
2020-07-14T13:04:45
2020-07-14T13:04:45
263,298,251
5
5
null
null
null
null
UTF-8
Java
false
false
227
java
package com.winster.spring.scheduledtask; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ApplicationTests { @Test void contextLoads() { } }
[ "winster.jose@amadeus.com" ]
winster.jose@amadeus.com
7c1836d006c166d2ecfbf415c576bc061ec1d96f
c62e4db74a0d85c01ab1bc3d5e5b8dee4fa5e1a1
/implementation/ase.QueryDsl/xtend-gen/ase/QueryDslStandaloneSetup.java
136876b22c25a696a477f3fe7c0cb6d71adc9d9e
[]
no_license
coalae/telemed
99a28bd19a1ad198a6169089d6483cf18612bd13
cb12ea078bd984606ac0418e9148cf4f5e083ea2
refs/heads/master
2020-03-19T05:59:54.086472
2019-03-28T21:35:01
2019-03-28T21:35:01
135,981,694
1
0
null
null
null
null
UTF-8
Java
false
false
414
java
/** * generated by Xtext 2.12.0.M1 */ package ase; import ase.QueryDslStandaloneSetupGenerated; /** * Initialization support for running Xtext languages without Equinox extension registry. */ @SuppressWarnings("all") public class QueryDslStandaloneSetup extends QueryDslStandaloneSetupGenerated { public static void doSetup() { new QueryDslStandaloneSetup().createInjectorAndDoEMFRegistration(); } }
[ "a00750881@unet.univie.ac.at" ]
a00750881@unet.univie.ac.at
ed674d9cc9472f17b7aa02c0472994d4a0c83dfb
e53f8ac314efd0fdd3e36716e303a9dd4aefcd68
/src/main/java/edu/nikon/simpleapi/api/office/dto/mapper/OfficeMapper.java
a8d0e029ee67d14c5d27bed1b97057803c827b43
[ "MIT" ]
permissive
nikon-petr/simple-api
ad976a88accadd88f4c1cb5f53d00a3957f3ab74
7ba56ceb3801e9f5163a5028ba27d743b602c55a
refs/heads/master
2021-06-27T06:32:10.341653
2020-10-05T19:57:21
2020-10-05T19:57:21
139,915,219
0
0
null
null
null
null
UTF-8
Java
false
false
1,462
java
package edu.nikon.simpleapi.api.office.dto.mapper; import edu.nikon.simpleapi.api.office.domain.Office; import edu.nikon.simpleapi.api.office.dto.OfficeDetailedDto; import edu.nikon.simpleapi.api.office.dto.OfficeItemDto; import edu.nikon.simpleapi.api.office.dto.SaveOfficeDto; import edu.nikon.simpleapi.api.office.dto.UpdateOfficeDto; import ma.glasnost.orika.MapperFactory; import ma.glasnost.orika.impl.ConfigurableMapper; import org.springframework.stereotype.Component; /** * Class for configure office mapper factory */ @Component public class OfficeMapper extends ConfigurableMapper { @Override protected void configure(MapperFactory factory) { factory.classMap(Office.class, OfficeItemDto.class) .byDefault() .register(); factory.classMap(Office.class, OfficeDetailedDto.class) .field("contact.address", "address") .field("contact.phone", "phone") .byDefault() .register(); factory.classMap(Office.class, SaveOfficeDto.class) .field("contact.address", "address") .field("contact.phone", "phone") .byDefault() .register(); factory.classMap(Office.class, UpdateOfficeDto.class) .field("contact.address", "address") .field("contact.phone", "phone") .byDefault() .register(); } }
[ "p.nikwv@gmail.com" ]
p.nikwv@gmail.com
d106c0782300a5f797db83c4f57ea889ef898b33
4a632a8729a568840afd18cf623ca4da90afd8dd
/modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201603/mcm/AccountLabelServiceInterface.java
809ce75cf144730f8a34231be7280c75678f695d
[ "Apache-2.0" ]
permissive
tagrawaleddycom/googleads-java-lib
10818b03d5343dd3d7fd46a69185b61a4c72ca25
de36c3cf36a330525e60b890f8309ce91a424ad7
refs/heads/master
2020-12-26T03:23:28.175751
2016-05-26T18:22:48
2016-05-26T18:22:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,833
java
package com.google.api.ads.adwords.jaxws.v201603.mcm; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; import com.google.api.ads.adwords.jaxws.v201603.cm.Selector; /** * * Service for creating, editing, and deleting labels that can be applied to managed customers. * * <p>Labels created by a manager are not accessible to any customers managed * by this manager. Only manager customers may create these labels. * * <p>Note that label access works a little differently in the API than it does in the * AdWords UI. In the UI, a manager will never see a submanager's labels, and will always * be using his own labels regardless of which managed account he is viewing. In this API, * like other API services, if you specify a submanager as the effective account for the API * request, then the request will operate on the submanager's labels. * * <p>To apply a label to a managed customer, see * {@link com.google.ads.api.services.mcm.customer.ManagedCustomerService#mutateLabel}. * * * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.1 * */ @WebService(name = "AccountLabelServiceInterface", targetNamespace = "https://adwords.google.com/api/adwords/mcm/v201603") @XmlSeeAlso({ com.google.api.ads.adwords.jaxws.v201603.cm.ObjectFactory.class, com.google.api.ads.adwords.jaxws.v201603.mcm.ObjectFactory.class }) public interface AccountLabelServiceInterface { /** * * Returns a list of labels specified by the selector for the authenticated user. * * @param selector filters the list of labels to return * @return response containing lists of labels that meet all the criteria of the selector * @throws ApiException if a problem occurs fetching the information requested * * * @param selector * @return * returns com.google.api.ads.adwords.jaxws.v201603.mcm.AccountLabelPage * @throws ApiException */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/mcm/v201603") @RequestWrapper(localName = "get", targetNamespace = "https://adwords.google.com/api/adwords/mcm/v201603", className = "com.google.api.ads.adwords.jaxws.v201603.mcm.AccountLabelServiceInterfaceget") @ResponseWrapper(localName = "getResponse", targetNamespace = "https://adwords.google.com/api/adwords/mcm/v201603", className = "com.google.api.ads.adwords.jaxws.v201603.mcm.AccountLabelServiceInterfacegetResponse") public AccountLabelPage get( @WebParam(name = "selector", targetNamespace = "https://adwords.google.com/api/adwords/mcm/v201603") Selector selector) throws ApiException ; /** * * Possible actions: * <ul> * <li> Create a new label - create a new {@link Label} and call mutate with ADD operator * <li> Edit the label name - set the appropriate fields in your {@linkplain Label} and call * mutate with the SET operator. Null fields will be interpreted to mean "no change" * <li> Delete the label - call mutate with REMOVE operator * </ul> * * @param operations list of unique operations to be executed in a single transaction, in the * order specified. * @return the mutated labels, in the same order that they were in as the parameter * @throws ApiException if problems occurs while modifying label information * * * @param operations * @return * returns com.google.api.ads.adwords.jaxws.v201603.mcm.AccountLabelReturnValue * @throws ApiException */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/mcm/v201603") @RequestWrapper(localName = "mutate", targetNamespace = "https://adwords.google.com/api/adwords/mcm/v201603", className = "com.google.api.ads.adwords.jaxws.v201603.mcm.AccountLabelServiceInterfacemutate") @ResponseWrapper(localName = "mutateResponse", targetNamespace = "https://adwords.google.com/api/adwords/mcm/v201603", className = "com.google.api.ads.adwords.jaxws.v201603.mcm.AccountLabelServiceInterfacemutateResponse") public AccountLabelReturnValue mutate( @WebParam(name = "operations", targetNamespace = "https://adwords.google.com/api/adwords/mcm/v201603") List<AccountLabelOperation> operations) throws ApiException ; }
[ "jradcliff@users.noreply.github.com" ]
jradcliff@users.noreply.github.com
c7d51f0b67478e56db9872955322e4b9dcf78a44
c0a38d91933001047a91920a995e86b9e0b84d06
/src/DatabaseAndTools/ImagePanel.java
30fc8954a45bcc6b604f9b8b0725b50693e8803b
[]
no_license
earthcodet/UI_Project_Big_Sale
d9cccb3bf8cd36b42153eb59e04aa9ecf5af8a9c
21dbd1c4a32d84a07ad6b3082e83911b7a873fad
refs/heads/master
2021-09-25T10:52:57.293682
2018-10-21T13:39:49
2018-10-21T13:39:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
677
java
package DatabaseAndTools; import java.awt.Graphics; import java.awt.Image; import javax.swing.JPanel; @SuppressWarnings("serial") public class ImagePanel extends JPanel { Image img; public static boolean isDraw; public ImagePanel() {} public ImagePanel(Image ximg) { img = ximg; } public void setImage(Image img) { this.img = img; repaint(); } public Image getImage() { return img; } public void paint(Graphics g) { if(img != null) { isDraw = true; g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), 0, 0, img.getWidth(this), img.getHeight(this), this); } else { isDraw = false; g.fillRect(0, 0, getWidth(), getHeight()); } } }
[ "houstenbosh@hotmail.com" ]
houstenbosh@hotmail.com
5f6fb7e2b0f2b275bc9e070b9fd0342efb9c9f63
9dab5c69697b7dd8a7bfab4cc8c2f6d580ef2d1a
/JavaSE/src/Projects/TeamProject/View/TeamView.java
e85a9d26ef063c3f574dc981ed0774a0b5dcb6c9
[]
no_license
Jexn/MyCode
f7b7eee50c28161c11d047ebac5ddd7d8a4a1833
23a2833f82534a65a816ed2424ff80f4af94dab5
refs/heads/master
2022-12-23T12:06:45.266482
2019-08-20T00:37:25
2019-08-20T00:37:25
185,705,380
0
0
null
2022-12-16T05:04:07
2019-05-09T01:38:16
Java
UTF-8
Java
false
false
4,245
java
package Projects.TeamProject.View; import Projects.TeamProject.Domain.Employee; import Projects.TeamProject.Domain.Programmer; import Projects.TeamProject.Service.NameListService; import Projects.TeamProject.Service.TeamException; import Projects.TeamProject.Service.TeamService; public class TeamView { private NameListService listSvc = new NameListService(); private TeamService teamSvc = new TeamService(); public void enterMainMenu() { boolean loopFlag = true; char key = 0; do { if (key != '1') { listAllEmployees(); } System.out.print("1-团队列表 2-添加团队成员 3-删除团队成员 4-退出 请选择(1-4):"); key = TSUtility.readMenuSelection(); System.out.println(); switch (key) { case '1': listTeam(); break; case '2': addMember(); break; case '3': deleteMember(); break; case '4': System.out.print("确认是否退出(Y/N):"); char yn = TSUtility.readConfirmSelection(); if (yn == 'Y') loopFlag = false; break; } } while (loopFlag); } // 显示所有的员工成员 private void listAllEmployees() { System.out .println("\n-------------------------------开发团队调度软件--------------------------------\n"); Employee[] emps = listSvc.getEmployees(); if (emps.length == 0) { System.out.println("没有客户记录!"); } else { System.out.println("ID\t姓名\t年龄\t工资\t职位\t状态\t奖金\t股票\t领用设备"); } for (Employee e : emps) { System.out.println(" " + e); } System.out .println("-------------------------------------------------------------------------------"); } // 显示开发团队成员列表 private void listTeam() { System.out .println("\n--------------------团队成员列表---------------------\n"); Programmer[] team = teamSvc.getTeam(); if (team.length == 0) { System.out.println("开发团队目前没有成员!"); } else { System.out.println("TID/ID\t姓名\t年龄\t工资\t职位\t奖金\t股票"); } for (Programmer p : team) { if (p != null) { System.out.println(" " + p.getDetailsForTeam()); } } System.out .println("-----------------------------------------------------"); } // 添加成员到团队 private void addMember() { System.out.println("---------------------添加成员---------------------"); System.out.print("请输入要添加的员工ID:"); int id = TSUtility.readInt(); try { Employee e = listSvc.getEmployee(id); teamSvc.addMember(e); System.out.println("添加成功"); } catch (TeamException e) { System.out.println("添加失败,原因:" + e.getMessage()); } // 按回车键继续... TSUtility.readReturn(); } // 从团队中删除指定id的成员 private void deleteMember() { System.out.println("---------------------删除成员---------------------"); System.out.print("请输入要删除员工的TID:"); int id = TSUtility.readInt(); System.out.print("确认是否删除(Y/N):"); char yn = TSUtility.readConfirmSelection(); if (yn == 'N') return; try { teamSvc.removeMember(id); System.out.println("删除成功"); } catch (TeamException e) { System.out.println("删除失败,原因:" + e.getMessage()); } // 按回车键继续... TSUtility.readReturn(); } public static void main(String[] args) { TeamView view = new TeamView(); view.enterMainMenu(); } }
[ "cube-root@outlook.com" ]
cube-root@outlook.com
a2b5ce0b8b141dbc477bdcf937c5891a5cc97fa3
623f09682b425a04b63a2f0b3efa609cb48e894d
/J001/src/J001.java
7dc910292f3f850e41587349561a86a99fa56eb9
[]
no_license
HSIUMIN/JavaClasses
00906e7c757bae5b538f31a49ba337fe233948bc
125a36b91698b2f8fad464510d4663c5cd2d0bfa
refs/heads/master
2021-01-01T19:28:08.302712
2017-07-28T01:49:23
2017-07-28T01:49:23
98,258,447
0
0
null
null
null
null
UTF-8
Java
false
false
158
java
public class J001 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Hello, world!!"); } }
[ "st60099@gmail.com" ]
st60099@gmail.com
5db1d1daa77dafe2292007b8d4618b9f97e62edb
15e6acaac65ea5ef89cfd8a2555a07fbbf58c522
/com/dylantjohnson/webserver/DefaultErrorBody.java
08a88d6910226e8362ca87a43ea16c95aeb85c36
[]
no_license
dylantjohnson/com.dylantjohnson.webserver
abaf8374d0583740a24aa8bf8f860bf7c14f7611
1676ec16a7dfd5d66f1c737209aea2395e46e809
refs/heads/master
2020-07-21T17:56:05.542621
2019-11-27T09:46:15
2019-11-27T09:46:15
206,936,681
0
0
null
null
null
null
UTF-8
Java
false
false
749
java
package com.dylantjohnson.webserver; import java.io.*; import java.util.function.*; /** * The error page generator used by {@link WebServer} if another is not configured. */ class DefaultErrorBody implements Supplier<InputStream> { @Override public InputStream get() { var body = String.join("\n", "<!DOCTYPE html>", "<html lang=\"en\">", " <head>", " <meta charset=\"UTF-8\">", " <title>Internal Error</title>", " </head>", " <body>", " <p>com.dylantjohnson.webserver experienced an internal error.</p>", " </body>", "</html>"); return new ByteArrayInputStream(body.getBytes()); } }
[ "spfyyy@gmail.com" ]
spfyyy@gmail.com
ab9395f65b01dc8113121c4853c6f0f338cdbea1
aaaff0546c359c7aaccac5b90f3bc86cb32566bf
/ChatClient.java
af589a208534a1437b095314000ec80212541778
[]
no_license
fika4life/Internetprogramming
d24979e9bb0d78b1e2fe69335ba4a35d59d8d726
720eef56fcbd3f4b9ac1ccba24ef170b146b6375
refs/heads/master
2016-09-10T11:02:10.139720
2015-01-28T13:44:20
2015-01-28T13:44:20
29,967,596
0
0
null
null
null
null
UTF-8
Java
false
false
2,021
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; /** * Created by Fredrik on 2015-01-26. */ public class ChatClient { private BufferedReader in; private PrintWriter out; private static final Scanner scan=new Scanner(System.in); public ChatClient(Socket socket) { try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream()); new Thread(){ @Override public void run() { super.run(); while(true) { try { String message=in.readLine(); if(message==null){ break; } System.out.println(message); } catch (IOException e) { e.printStackTrace(); break; } } } }.start(); } catch(IOException e){ e.printStackTrace(); } } private void start(){ sendName(); writeSomeThing(); } private void sendName(){ System.out.println("Write your name here: "); String name=scan.nextLine(); out.println("!name!: "+name); out.flush(); } public void writeSomeThing(){ while(true){ out.println(scan.nextLine()); out.flush(); } } public static void main(String[] args){ System.out.println("Write the IP of the server:"); String IP=scan.nextLine(); try { new ChatClient(new Socket(IP,ServerConnection.portNumber)).start(); } catch (IOException e) { e.printStackTrace(); } } }
[ "fredde_wallen@hotmail.com" ]
fredde_wallen@hotmail.com
17265c66b9c57049cf42fa21e2aa50614db95612
d4dbb0571226af5809cc953e73924d505094e211
/Hibernate/04.HibernateCodeFirst/BookShop/src/main/java/app/serviceImpls/CategoryServiceImpl.java
80085005fe42fb93a27dc2cb1ffad67c9536aab9
[]
no_license
vasilgramov/database-fundamentals
45e258e965e85514e60b849d9049737ae25e81c0
0ebe74ab4bffef0d29d6ee2e200f07bdc24fe6bf
refs/heads/master
2021-06-18T17:54:36.238976
2017-07-10T14:49:44
2017-07-10T14:49:44
89,739,950
0
1
null
null
null
null
UTF-8
Java
false
false
1,021
java
package app.serviceImpls; import app.daos.CategoryRepository; import app.entities.Category; import app.services.CategoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; import java.util.List; @Service @Primary public class CategoryServiceImpl implements CategoryService { private final CategoryRepository categoryRepository; @Autowired public CategoryServiceImpl(CategoryRepository categoryRepository) { this.categoryRepository = categoryRepository; } @Override public void save(Category category) { this.categoryRepository.saveAndFlush(category); } @Override public List<Category> findByNameIn(String... categories) { return this.categoryRepository.findByNameIn(categories); } @Override public List<Object[]> findTotalProfitByCategory() { return this.categoryRepository.findTotalProfitByCategory(); } }
[ "gramovv@gmail.com" ]
gramovv@gmail.com
b980236816ba766b45ed21c00a3a65cb8f13f9eb
832815fa3d65b121a15ae162efd01432f32df1cc
/src/com/dp2345/dao/impl/SeoDaoImpl.java
126407625f81e7cc5ffe0fd70598e75e8bcc4ee6
[]
no_license
jeffson1985/dp2345
a7c04907eda300ed73ccd921f4a509fcf5821de8
11618f889baef48a659251146d32085f478ed0ef
refs/heads/master
2020-05-31T23:44:59.895931
2015-09-18T12:52:40
2015-09-18T12:52:41
42,158,460
0
0
null
null
null
null
UTF-8
Java
false
false
927
java
/* * Copyright 2013-2015 cetvision.com. All rights reserved. * Support: http://www.cetvision.com * License: http://www.cetvision.com/license */ package com.dp2345.dao.impl; import javax.persistence.FlushModeType; import javax.persistence.NoResultException; import org.springframework.stereotype.Repository; import com.dp2345.dao.SeoDao; import com.dp2345.entity.Seo; import com.dp2345.entity.Seo.Type; /** * Dao - SEO设置 * * @author CETVISION CORP * @version 2.0.3 */ @Repository("seoDaoImpl") public class SeoDaoImpl extends BaseDaoImpl<Seo, Long> implements SeoDao { public Seo find(Type type) { if (type == null) { return null; } try { String jpql = "select seo from Seo seo where seo.type = :type"; return entityManager.createQuery(jpql, Seo.class).setFlushMode(FlushModeType.COMMIT).setParameter("type", type).getSingleResult(); } catch (NoResultException e) { return null; } } }
[ "kevionsun@gmail.com" ]
kevionsun@gmail.com
e7ff14053b435becc22281649ef9c26dd3d2b342
a99e3dcc3fbff2e39e90fd0df21fac85a1132e64
/contrib/scripting/xproc/src/main/java/org/apache/sling/scripting/xproc/xpl/impl/OutputStreamWrapper.java
c0525ba32f17544f39cca937b76f2eff4b1a3356
[ "Apache-2.0", "JSON" ]
permissive
MRivas-XumaK/slingBuild
246f10ccdd17ace79696d760f0801aec188a38fc
c153c22d893cd55c805606041b1292e628d5461e
refs/heads/master
2023-01-09T22:49:01.251652
2014-05-08T15:46:12
2014-05-08T15:46:12
19,578,020
3
3
Apache-2.0
2022-12-21T18:50:52
2014-05-08T15:13:56
Java
UTF-8
Java
false
false
1,715
java
/* * 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.sling.scripting.xproc.xpl.impl; import java.io.IOException; import java.io.OutputStream; /** OutputStream that wraps another one using a method * that's only called if the wrapped stream is actually * used. */ abstract class OutputStreamWrapper extends OutputStream { protected abstract OutputStream getWrappedStream() throws IOException; @Override public void close() throws IOException { getWrappedStream().close(); } @Override public void flush() throws IOException { getWrappedStream().flush(); } @Override public void write(byte[] arg0, int arg1, int arg2) throws IOException { getWrappedStream().write(arg0, arg1, arg2); } @Override public void write(byte[] arg0) throws IOException { getWrappedStream().write(arg0); } @Override public void write(int arg0) throws IOException { getWrappedStream().write(arg0); } }
[ "marito.rivas@hotmail.com" ]
marito.rivas@hotmail.com
90866bcb4a427261ec5f43c7baf4ef9fc539f32a
70e587e18ac0ff9237975536fe223fa1da4758f6
/MobileServer_tacademy/day5/webSettings/BoardDAO.java
03f1ff11b68962fd5559e001fe5240d6a5bfa037
[]
no_license
lazyTitan157/Java-study
2d62548ad62df61e3253a5100a7a72a0632c4a2d
940fc66dbab3ac6f8edd9ccad83ae6bfeee14819
refs/heads/master
2022-12-23T03:28:14.955233
2020-09-29T05:21:34
2020-09-29T05:21:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
930
java
package com.multicampus.biz.board.impl; import java.sql.SQLException; import java.util.List; import com.ibatis.sqlmap.client.SqlMapClient; import com.multicampus.biz.board.vo.BoardVO; import com.multicampus.biz.util.SqlMapClientFactoryBean; public class BoardDAO { private SqlMapClient ibatis; public BoardDAO(){ ibatis = SqlMapClientFactoryBean.getSqlMapClientInstance(); } public void addBoard(BoardVO vo) throws SQLException { ibatis.insert("addBoard", vo); } public void updateBoard(BoardVO vo) throws SQLException { ibatis.update("updateBoard", vo); } public void deleteBoard(BoardVO vo) throws SQLException { ibatis.delete("deleteBoard", vo); } public BoardVO getBoard(BoardVO vo) throws SQLException { return (BoardVO)ibatis.queryForObject("getBoard", vo); } public List<BoardVO> getBoardList(BoardVO vo) throws SQLException { return ibatis.queryForList("getBoardList", vo); } }
[ "2983rgt@naver.com" ]
2983rgt@naver.com
b9da451613303b0d27da63e8d2dd26a95224a1e1
5597e08dc2c75a97b76ebff9b3e39d9cd9bf71cb
/tree_codes/src/Code112.java
97bbb7bdca9d0a7744d9615f675ae70625ae3430
[]
no_license
airphoto/LeetCode
5d15ec6e85355eedf9fa5fb473360eca263f79c2
b7385623c221552f48710c5bc4cf861c4571b210
refs/heads/master
2022-09-29T20:45:07.568113
2022-09-11T08:10:42
2022-09-11T08:10:42
132,338,600
0
0
null
null
null
null
UTF-8
Java
false
false
2,233
java
import java.util.LinkedList; import java.util.Queue; /** * @ClassName Code112 * @Author lihuasong * @Description * 给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。 * 判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。 * 如果存在,返回 true ;否则,返回 false 。 * * 叶子节点 是指没有子节点的节点。 * 示例 1: * 输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 * 输出:true * 解释:等于目标和的根节点到叶节点路径如上图所示。 * * 示例 2: * 输入:root = [1,2,3], targetSum = 5 * 输出:false * 解释:树中存在两条根节点到叶子节点的路径: * (1 --> 2): 和为 3 * (1 --> 3): 和为 4 * 不存在 sum = 5 的根节点到叶子节点的路径。 * * 示例 3: * 输入:root = [], targetSum = 0 * 输出:false * 解释:由于树是空的,所以不存在根节点到叶子节点的路径。 * * 提示: * 树中节点的数目在范围 [0, 5000] 内 * -1000 <= Node.val <= 1000 * -1000 <= targetSum <= 1000 * * @Date 2021/12/9 21:43 * @Version V1.0 **/ public class Code112 { public static boolean hasPathSum(TreeNode root, int targetSum) { if(root==null){ return false; } Queue<TreeNode> tq = new LinkedList<>(); Queue<Integer> vq = new LinkedList<>(); tq.offer(root); vq.offer(root.val); int levelSize = 1; while (!tq.isEmpty()){ TreeNode node = tq.poll(); Integer sum = vq.poll(); levelSize--; if(node.left!=null){ tq.offer(node.left); vq.offer(sum+node.left.val); } if(node.right!=null){ tq.offer(node.right); vq.offer(sum+node.right.val); } if(levelSize==0){ levelSize=vq.size(); } if(node.left==null && node.right==null && sum==targetSum){ return true; } } return false; } public static void main(String[] args) { } }
[ "lihuasong@ixianlai.com" ]
lihuasong@ixianlai.com
24437dc7f882ac8c5352974fe06701661ba88f9c
1baf29e52392547baa9cb270bf237512b3d7df8c
/testServlet/src/test/java/ru/guiceServlet/data/DataHandlerImplTest.java
cd05f7fece971598a0ebafbe0f7fc6ccbbaca909
[]
no_license
axel36/javaProj
4607168a80ac50fbc3205203ec1c49202a4308d5
eb3b923ba8878711e737b484667be68118a9fca3
refs/heads/master
2020-03-19T04:40:30.010999
2018-08-19T23:51:45
2018-08-19T23:51:45
135,852,589
0
0
null
null
null
null
UTF-8
Java
false
false
1,008
java
package ru.mbtc.guiceServlet.data; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class DataHandlerImplTest { DataHandlerImpl juiInstance; Map<String, String> testMap; String testJsonStr; @Before public void setUp() throws Exception { juiInstance = new DataHandlerImpl(); testMap = new HashMap<>(); testMap.put("firstName", "АННА"); testMap.put("surName", "СИЗИКОВА"); testMap.put("middleName", "АЛЕКСЕЕВНА"); testJsonStr = "{\"firstName\":\"АННА\",\"surName\":\"СИЗИКОВА\",\"middleName\":\"АЛЕКСЕЕВНА\"}"; } @Test public void getMapFromJsonTest() throws Exception { assertEquals(testMap,juiInstance.getMapFromJson(testJsonStr)); } @Test public void packMapToJson() throws Exception { assertEquals(testJsonStr,juiInstance.packMapToJson(testMap)); } }
[ "khramov@alexey.by" ]
khramov@alexey.by
17f868c208e7e09f8ade3df28b6746a5220c3d18
430a05944d5c5fe47162e37fc18e93dde68ce6c4
/MVCExample/src/edu/asupoly/ser422/t6mvc2/views/SuccessView.java
cb8144079474ffb1ab8a89554231a073308fd2c3
[ "CC0-1.0" ]
permissive
swaroope/ser422asu_public
e1fcad5cf35e32f169a3abf82ddfffbc32170724
15d32fadba7a8095ba004b97ba498843cd7a8eea
refs/heads/master
2021-04-03T06:13:53.232485
2018-03-05T21:47:10
2018-03-05T21:47:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,947
java
/** * */ package edu.asupoly.ser422.t6mvc2.views; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import edu.asupoly.ser422.t6mvc2.model.User; /** * @author kevinagary * */ public class SuccessView extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = null; try { response.setContentType("text/html"); HttpSession session = request.getSession(false); // do not create if it does not exist! out = response.getWriter(); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<title>SampleWebApplication: Logged in</title>\r\n"); out.write("</head>\r\n"); if (session != null) { out.write("<body>\r\n"); edu.asupoly.ser422.t6mvc2.model.User user = (User) session.getAttribute("user"); if (user != null) { out.write("\r\n"); out.write("<h1>Sample Web Application: Logged in</h1>\r\n"); out.write("<br/>\r\n"); out.write("<br/>\r\n"); out.write("Welcome " + user.getDisplayName()); out.write(", you have successfully logged in!\r\n"); out.write("Click <a href=\"controller?action=list\">here</a> to order some books!\r\n"); out.write("\r\n"); out.write("</body>\r\n"); out.write("</html>\r\n"); } else { out.write("I have lost the User!!!"); session.invalidate(); } } else { out.write("No valid conversation exists between client and server"); } } finally { if (out != null) { out.close(); out = null; } } } }
[ "kgary@asu.edu" ]
kgary@asu.edu
8ddb29f6d676895a1670c6489259c91d814e4f17
ab7c374e12ef55482d1c622a0099a7b262195322
/jami-core/src/main/java/psidev/psi/mi/jami/utils/clone/ParticipantCloner.java
2bb0e56bf86de5d86959b1b37be04ea945b22af0
[ "Apache-2.0" ]
permissive
colin-combe/psi-jami
9f945d885d76454f7b652382cc676ac98e6faa39
64fb0596b99aa8996d865b5eae0a2094be0889c8
refs/heads/master
2020-12-07T02:17:10.909871
2017-06-07T07:05:14
2017-06-07T07:05:14
64,655,225
0
0
null
2017-03-09T14:26:30
2016-08-01T09:43:06
Java
UTF-8
Java
false
false
11,022
java
package psidev.psi.mi.jami.utils.clone; import psidev.psi.mi.jami.model.*; import psidev.psi.mi.jami.model.impl.*; /** * Utility class for cloning a participant * * @author Marine Dumousseau (marine@ebi.ac.uk) * @version $Id$ * @since <pre>13/02/13</pre> */ public class ParticipantCloner { /*** * This method will copy properties of participant source in participant target and will override all the other properties of Target participant. * This method will ignore interaction * @param source * @param target * @param createNewFeature If true, this method will clone each feature from source instead of reusing the feature instances from source. * It will then set the participantEvidence of the cloned features to target */ public static void copyAndOverrideParticipantEvidenceProperties(ParticipantEvidence source, ParticipantEvidence target, boolean createNewFeature){ if (source != null && target != null){ target.setExperimentalRole(source.getExperimentalRole()); target.setExpressedInOrganism(source.getExpressedInOrganism()); target.setBiologicalRole(source.getBiologicalRole()); target.setStoichiometry(source.getStoichiometry()); // copy collections target.getCausalRelationships().clear(); target.getCausalRelationships().addAll(source.getCausalRelationships()); target.getAnnotations().clear(); target.getAnnotations().addAll(source.getAnnotations()); target.getConfidences().clear(); target.getConfidences().addAll(source.getConfidences()); target.getXrefs().clear(); target.getXrefs().addAll(source.getXrefs()); target.getAliases().clear(); target.getAliases().addAll(source.getAliases()); target.getExperimentalPreparations().clear(); target.getExperimentalPreparations().addAll(source.getExperimentalPreparations()); target.getParameters().clear(); target.getParameters().addAll(source.getParameters()); target.getIdentificationMethods().clear(); target.getIdentificationMethods().addAll(source.getIdentificationMethods()); // special case for participant candidates if (source instanceof ExperimentalParticipantPool && target instanceof ExperimentalParticipantPool){ ExperimentalParticipantPool poolTarget = (ExperimentalParticipantPool)target; ExperimentalParticipantPool poolSource = (ExperimentalParticipantPool)source; poolTarget.clear(); for (ExperimentalParticipantCandidate candidate : poolSource){ ExperimentalParticipantCandidate candidateClone = new DefaultExperimentalParticipantCandidate(candidate.getInteractor()); ParticipantCandidateCloner.copyAndOverrideExperimentalCandidateProperties(candidate, candidateClone, createNewFeature); poolTarget.add(candidateClone); } } else{ target.setInteractor(source.getInteractor()); } // copy features or create new ones if (!createNewFeature){ target.getFeatures().clear(); target.getFeatures().addAll(source.getFeatures()); } else { target.getFeatures().clear(); for (FeatureEvidence f : source.getFeatures()){ FeatureEvidence clone = new DefaultFeatureEvidence(); FeatureCloner.copyAndOverrideFeatureEvidenceProperties(f, clone); target.addFeature(clone); } } } } /*** * This method will copy properties of modelled participant source in modelled participant target and will override all the other properties of Target modelled participant. * This method will ignore interaction * @param source * @param target * @param createNewFeature If true, this method will clone each feature from source instead of reusing the feature instances from source. * It will then set the modelledParticipant of the cloned features to target */ public static void copyAndOverrideModelledParticipantProperties(ModelledParticipant source, ModelledParticipant target, boolean createNewFeature){ if (source != null && target != null){ target.setBiologicalRole(source.getBiologicalRole()); target.setStoichiometry(source.getStoichiometry()); // copy collections target.getCausalRelationships().clear(); target.getCausalRelationships().addAll(source.getCausalRelationships()); target.getAnnotations().clear(); target.getAnnotations().addAll(source.getAnnotations()); target.getXrefs().clear(); target.getXrefs().addAll(source.getXrefs()); target.getAliases().clear(); target.getAliases().addAll(source.getAliases()); // special case for participant candidates if (source instanceof ModelledParticipantPool && target instanceof ModelledParticipantPool){ ModelledParticipantPool poolTarget = (ModelledParticipantPool)target; ModelledParticipantPool poolSource = (ModelledParticipantPool)source; poolTarget.clear(); for (ModelledParticipantCandidate candidate : poolSource){ ModelledParticipantCandidate candidateClone = new DefaultModelledParticipantCandidate(candidate.getInteractor()); ParticipantCandidateCloner.copyAndOverrideModelledPCandidateProperties(candidate, candidateClone, createNewFeature); poolTarget.add(candidateClone); } } else{ target.setInteractor(source.getInteractor()); } // copy features or create new ones if (!createNewFeature){ target.getFeatures().clear(); target.getFeatures().addAll(source.getFeatures()); } else { target.getFeatures().clear(); for (ModelledFeature f : source.getFeatures()){ ModelledFeature clone = new DefaultModelledFeature(); FeatureCloner.copyAndOverrideModelledFeaturesProperties(f, clone); target.addFeature(clone); } } } } /** * This method will copy properties of participant source in participant target and will override all the other properties of Target participant. * @param source * @param target * @param createNewFeature If true, this method will clone each feature from source instead of reusing the feature instances from source. */ public static void copyAndOverrideBasicParticipantProperties(Participant source, Participant target, boolean createNewFeature){ if (source != null && target != null){ target.setBiologicalRole(source.getBiologicalRole()); target.setStoichiometry(source.getStoichiometry()); // copy collections target.getCausalRelationships().clear(); target.getCausalRelationships().addAll(source.getCausalRelationships()); target.getAnnotations().clear(); target.getAnnotations().addAll(source.getAnnotations()); target.getXrefs().clear(); target.getXrefs().addAll(source.getXrefs()); target.getAliases().clear(); target.getAliases().addAll(source.getAliases()); // special case for participant candidates if (source instanceof ParticipantPool && target instanceof ParticipantPool){ ParticipantPool poolTarget = (ParticipantPool)target; ParticipantPool poolSource = (ParticipantPool)source; poolTarget.clear(); for (Object candidate : poolSource){ ParticipantCandidate candidateClone = new DefaultParticipantCandidate(((ParticipantCandidate)candidate).getInteractor()); ParticipantCandidateCloner.copyAndOverrideBasicCandidateProperties((ParticipantCandidate)candidate, candidateClone, createNewFeature); poolTarget.add(candidateClone); } } else{ target.setInteractor(source.getInteractor()); } // copy features or create new ones if (!createNewFeature){ target.getFeatures().clear(); target.addAllFeatures(source.getFeatures()); } else { target.getFeatures().clear(); for (Object f : source.getFeatures()){ Feature clone = new DefaultFeature(); FeatureCloner.copyAndOverrideBasicFeaturesProperties((Feature)f, clone); target.addFeature(clone); } } } } public static void copyAndOverrideBasicEntityProperties(Entity source, Entity target, boolean createNewFeature){ if (source != null && target != null){ target.setStoichiometry(source.getStoichiometry()); // copy collections target.getCausalRelationships().clear(); target.getCausalRelationships().addAll(source.getCausalRelationships()); // special case for participant candidates if (source instanceof ParticipantPool && target instanceof ParticipantPool){ ParticipantPool poolTarget = (ParticipantPool)target; ParticipantPool poolSource = (ParticipantPool)source; poolTarget.clear(); for (Object candidate : poolSource){ ParticipantCandidate candidateClone = new DefaultParticipantCandidate(((ParticipantCandidate)candidate).getInteractor()); ParticipantCandidateCloner.copyAndOverrideBasicCandidateProperties((ParticipantCandidate)candidate, candidateClone, createNewFeature); poolTarget.add(candidateClone); } } else{ target.setInteractor(source.getInteractor()); } // copy features or create new ones if (!createNewFeature){ target.getFeatures().clear(); target.addAllFeatures(source.getFeatures()); } else { target.getFeatures().clear(); for (Object f : source.getFeatures()){ Feature clone = new DefaultFeature(); FeatureCloner.copyAndOverrideBasicFeaturesProperties((Feature)f, clone); target.addFeature(clone); } } } } }
[ "mdumousseau@yahoo.com@73e66818-4ebf-11de-a6a3-df26d2c71dbe" ]
mdumousseau@yahoo.com@73e66818-4ebf-11de-a6a3-df26d2c71dbe
a3157cb093c4143ad325fb7d82d76d800a8e92c3
e6c44c8c0346e88280cad6ae5f52d6148a3bd30b
/android/VertxMonitoring/app/src/test/java/com/twiden/vertxmonitoring/ExampleUnitTest.java
3bc49f3a18136f35b55b13b6c10a6977d78512be
[]
no_license
twiden/vertex-monitoring
67aeb8d84f83ed0637aab49e1decf93736ea0c34
9668899891dd558f3702133dfbd1420859c99ec1
refs/heads/master
2021-01-11T18:26:55.042357
2017-01-29T20:42:14
2017-01-29T20:42:14
79,548,201
0
0
null
null
null
null
UTF-8
Java
false
false
404
java
package com.twiden.vertxmonitoring; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "tobias.widen@trioptima.com" ]
tobias.widen@trioptima.com
58c24c80e0ac9611897961881344109558025643
48a88aea6e9774279c8563f1be665a540e02a894
/src/opennlp/tools/cmdline/parser/ModelUpdaterTool.java
cd40199ac713d513b6f7052a3d661e087f466098
[]
no_license
josepvalls/parserservices
0994aa0fc56919985474aaebb9fa64581928b5b4
903363685e5cea4bd50d9161d60500800e42b167
refs/heads/master
2021-01-17T08:36:23.455855
2016-01-19T19:49:54
2016-01-19T19:49:54
60,540,533
2
0
null
null
null
null
UTF-8
Java
false
false
2,964
java
/* * 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 opennlp.tools.cmdline.parser; import java.io.File; import java.io.IOException; import opennlp.tools.cmdline.AbstractTypedParamTool; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.ObjectStreamFactory; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.TrainingToolParams; import opennlp.tools.parser.Parse; import opennlp.tools.parser.ParserModel; import opennlp.tools.util.ObjectStream; /** * Abstract base class for tools which update the parser model. */ abstract class ModelUpdaterTool extends AbstractTypedParamTool<Parse, ModelUpdaterTool.ModelUpdaterParams> { interface ModelUpdaterParams extends TrainingToolParams { } protected ModelUpdaterTool() { super(Parse.class, ModelUpdaterParams.class); } protected abstract ParserModel trainAndUpdate(ParserModel originalModel, ObjectStream<Parse> parseSamples, ModelUpdaterParams parameters) throws IOException; @Override public final void run(String format, String[] args) { ModelUpdaterParams params = validateAndParseParams( ArgumentParser.filter(args, ModelUpdaterParams.class), ModelUpdaterParams.class); // Load model to be updated File modelFile = params.getModel(); ParserModel originalParserModel = new ParserModelLoader().load(modelFile); ObjectStreamFactory<Parse> factory = getStreamFactory(format); String[] fargs = ArgumentParser.filter(args, factory.getParameters()); validateFactoryArgs(factory, fargs); ObjectStream<Parse> sampleStream = factory.create(fargs); ParserModel updatedParserModel; try { updatedParserModel = trainAndUpdate(originalParserModel, sampleStream, params); } catch (IOException e) { throw new TerminateToolException(-1, "IO error while reading training data or indexing data: " + e.getMessage(), e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } CmdLineUtil.writeModel("parser", modelFile, updatedParserModel); } }
[ "josepvalls@Valls.local" ]
josepvalls@Valls.local
926a43d997c5657720270c6c1372d536b8803193
e7c02b26e6da1b0652203285071edef433fae4cb
/rest-annotations/src/main/java/one/xingyi/restAnnotations/annotations/XingYiClient.java
2c0c7d5f7e371337d66f4126714a9e648dbc7481
[]
no_license
phil-rice/rest
155af53fe32e6571001a4b640fcb546896e24dc8
3a31ce94c04871faded6fea645c2da0d99e342bb
refs/heads/master
2020-04-15T19:11:11.276133
2019-01-18T00:58:20
2019-01-18T00:58:20
164,940,369
0
0
null
null
null
null
UTF-8
Java
false
false
363
java
package one.xingyi.restAnnotations.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.CLASS) // Make it class retention for incremental compilation public @interface XingYiClient { }
[ "phil.rice@iee.org" ]
phil.rice@iee.org
39f3e7d9f08766fe75c656dbc78d0fb29e278564
6169bf3ae7b8b3d12b9b39f837cc361c8768c9fe
/35 Search Insert Position/src/main/java/com/etoitau/leetcode/searchinsertposition/Main.java
79e4af6550f6dac45d2784f20c6b98c46dd56337
[]
no_license
etoitau/LeetCode-Problems
a5debaea5a1ed5f9e16fbd47881e397221f334f9
c69b248037496db0cffc8111e73255a3917354d9
refs/heads/master
2021-06-18T10:11:05.158317
2021-05-19T22:55:44
2021-05-19T22:55:44
207,673,870
0
0
null
null
null
null
UTF-8
Java
false
false
1,404
java
package com.etoitau.leetcode.searchinsertposition; /** * LeetCode Problem 35 - Search Insert Position * * Result: * Runtime: 0 ms, faster than 100.00% * Memory Usage: 39.1 MB, less than 100.00% * * Description: * Given a sorted array and a target value, return the index if the target is found. If not, * return the index where it would be if it were inserted in order. * * You may assume no duplicates in the array. */ class Solution { public int searchInsert(int[] nums, int target) { // trivial cases if (nums == null) { return 0; } if (nums.length == 0) { return 0; } else if (nums.length == 1) { if (target <= nums[0]) { return 0; } else { return 1; } } // nums is at least two long // binary search int high = nums.length, low = 0, mid = (high + low) / 2; while(low < high) { if (nums[mid] < target) { low = mid + 1; } else if (nums[mid] > target) { high = mid; } else { return mid; } mid = (high + low) / 2; } if (mid > nums.length - 1) { return nums.length; } else if (nums[mid] >= target) { return mid; } else { return mid + 1; } } }
[ "kchatman@gmail.com" ]
kchatman@gmail.com
3efe083bc24a6e3583b88f74b4c285c31d5506c3
0e97171d925d8b72dde03148a974e743d24e96a7
/super-nomina/src/main/java/com/quat/api/EmpleadoApiController.java
afaf3ac92f259d8e06f8aea4d766dddfc69d6727
[]
no_license
badillosoft/java-quat
50916aed28f43a3fd1a102e8dabdfcdae6871a29
6cb568ae3149f0e8f873cc6f70b2a8b88d7c2d0d
refs/heads/master
2020-03-10T07:58:48.293674
2018-06-09T18:54:14
2018-06-09T18:54:14
129,275,010
2
0
null
null
null
null
UTF-8
Java
false
false
2,334
java
package com.quat.api; import java.io.IOException; import java.util.Optional; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.quat.model.Empleado; import com.quat.reposity.EmpleadoRepository; import com.quat.service.EmpleadoService; @RestController @RequestMapping("/api/empleado") public class EmpleadoApiController { @Autowired EmpleadoService empleadoService; @Autowired EmpleadoRepository empleadoRepository; @GetMapping("/{id}") @ResponseBody public Empleado verEmpleado(@PathVariable Long id, HttpServletResponse response) throws IOException { Optional<Empleado> empleadoOptional = empleadoRepository.findById(id); if (!empleadoOptional.isPresent()) { response.sendError(HttpStatus.BAD_REQUEST.value(), "No existe ese Empleado >: ("); return null; } Empleado empleado = empleadoOptional.get(); return empleado; } @PostMapping("/{id}/asignar/sueldo") @ResponseBody public Empleado asignarSueldo(@PathVariable Long id, @RequestParam Double sueldo, HttpServletResponse response) throws IOException { Empleado empleado = empleadoService.asignarSueldo(id, sueldo); if (empleado == null) { response.sendError(HttpStatus.BAD_REQUEST.value(), empleadoService.getLastMessage()); } return empleado; } @GetMapping("/nomina") @ResponseBody public Double calcularNomina() { return empleadoRepository.sumaNomina(); } @PutMapping("") @ResponseBody public Empleado crearEmpleado(@RequestParam String nombre) { Empleado empleado = new Empleado(); empleado.setNombre(nombre); return empleadoService.crearEmpleado(empleado); } @GetMapping("") @ResponseBody public Iterable<Empleado> mostrarEmpleados() { return empleadoRepository.findAll(); } }
[ "badillo.soft@hotmail.com" ]
badillo.soft@hotmail.com
7a49b52954a8e4670d978d54643fbc1a873de11a
4bc8156da35733e6bc4774def5e922f8acac8e2f
/jsonschema2pojo-integration-tests/src/test/resources/integration/output/GsonIT/productset/com/googlecode/jsonschema2pojo/integration/generation/gsonit/WarehouseLocation.java
3ea9e6566660cb3e17125673c045dd72c332745d
[ "Apache-2.0" ]
permissive
gmale/jsonschema2pojo
097774e8faab1e135ce3eb59b605e91518ba16dd
fd19ebb3d1310d97e11793c229bbffeb68e241d0
refs/heads/master
2021-01-17T23:12:56.128319
2013-07-01T23:32:38
2013-07-01T23:32:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
975
java
package com.googlecode.jsonschema2pojo.integration.generation.gsonit; import java.util.HashMap; import java.util.Map; import javax.annotation.Generated; /** * A geographical coordinate * */ @Generated("com.googlecode.jsonschema2pojo") public class WarehouseLocation { private Double latitude; private Double longitude; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } public void setAdditionalProperties(String name, Object value) { this.additionalProperties.put(name, value); } }
[ "kevin@silverchalice.com" ]
kevin@silverchalice.com
92ac2edef6e4c12bb41345bfa48b2359cf2712e4
7f96077b9de06f4321daacecd7f31610ac82bb10
/app/src/main/java/com/example/zhaolexi/horizontalscrollviewex/ListViewAdapter.java
71a7ad8d4606ad68ecb0a7b96bda0e77bf6c952c
[ "MIT" ]
permissive
MindSelf/HorizontalScrollView
70d314e5ad4d63031a9c1f7f0b244da5112ff1a9
0df52ac43791fdb3dbe1fac4edc488c926e6dd46
refs/heads/master
2021-07-12T12:47:09.969874
2017-10-15T09:39:35
2017-10-15T09:39:35
102,972,849
0
0
null
null
null
null
UTF-8
Java
false
false
1,341
java
package com.example.zhaolexi.horizontalscrollviewex; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; /** * Created by ZHAOLEXI on 2017/9/4. */ public class ListViewAdapter extends BaseAdapter { private ArrayList<String> data; public ListViewAdapter(ArrayList<String> data) { this.data=data; } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder vh; if (convertView != null) { vh = (ViewHolder) convertView.getTag(); }else{ vh=new ViewHolder(); convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_list_item, parent, false); vh.tv = (TextView) convertView.findViewById(R.id.name); convertView.setTag(vh); } vh.tv.setText(data.get(position)); return convertView; } class ViewHolder{ TextView tv; } }
[ "492739459@qq.com" ]
492739459@qq.com
fd92573d40eeccf6b3479ed38ce01ea08a92c5b2
522db6b552176066229ae68bb58bdb58e38b0981
/app/src/main/java/id/slametriyadi/halalmui/Main/view/MainView.java
9b41154368682f1617f0f651353246798b0c759b
[]
no_license
slamet33/HalalMUI
f96d97087e82835749c84ee61f2861f2548524d2
6adcbef4d440fff0f15e2f307679a9e8fedd0685
refs/heads/master
2020-04-01T09:13:27.188248
2018-10-15T06:52:31
2018-10-15T06:52:31
153,065,603
0
0
null
null
null
null
UTF-8
Java
false
false
348
java
package id.slametriyadi.halalmui.Main.view; import java.util.List; import id.slametriyadi.halalmui.Base.BaseView; import id.slametriyadi.halalmui.Main.model.DataItem; import id.slametriyadi.halalmui.Main.model.ResponseProduct; public interface MainView extends BaseView { void onError(String msg); void onSuccess(List<DataItem> data); }
[ "slametngeblog@gmail.com" ]
slametngeblog@gmail.com
3ef8067555a54f2c1d6fbfbd9a3a38ed71a74c5e
24a2d8c1aed6ba3f2f65605e8a3f34670d55176b
/app/src/main/java/lab/ourteam/newlab/result_bridge.java
f0af73927c34ea4a6cf0fd0c1470faca07d351ec
[]
no_license
random-zhang/newLab
f0c2935e306b843c195f6bbd057aa2619d64ea7f
c8b5aa63f85defcae4d0be37550f3548bc8843ba
refs/heads/master
2020-04-18T11:55:40.091412
2019-07-12T02:43:47
2019-07-12T02:43:47
167,517,655
0
0
null
null
null
null
UTF-8
Java
false
false
935
java
package lab.ourteam.newlab; /** * 該類用於傳值回MainActivity */ public class result_bridge { private boolean isAppoint=true; private boolean isSeries_sv=false; private long time_remaining=0; private boolean hint=false; private int series_sv; public void setTime_remaining(long time_remaining){ this.time_remaining=time_remaining; } public long getTime_remaining(){ return time_remaining; } public boolean getIsAppoint(){ return isAppoint; } public void setAppoint(boolean isAppoint){ this.isAppoint=isAppoint; } public void setHint(boolean hint){ this.hint=hint;} public boolean getHint(){return hint;} public int getSeries_sv() { return series_sv; } public void setSeries_sv(int series_sv) { this.series_sv = series_sv; } public boolean getIsSeries_sv() { return isSeries_sv; } public void setisSeries_sv(boolean isSeries_sv) { this.isSeries_sv = isSeries_sv; } }
[ "2586814380@qq.com" ]
2586814380@qq.com
58201528fd16c5bd82c10a6602923e76361742b6
de3bf11b6038f63c25cf3c39c51b6c61944025cc
/src/main/java/com/zxing/camera/AutoFocusManager.java
bf14b98e44583f0fca66e2542d483907e7f1ed7d
[]
no_license
sws1011/ZxingDemo
96daeaa52b7d89ad4a1ac88950321287bcbebb24
fede7bb7ecd6234827d6b2cad25ccec086affdca
refs/heads/master
2020-03-18T11:25:27.701290
2018-05-24T06:25:51
2018-05-24T06:25:51
134,670,353
0
0
null
null
null
null
UTF-8
Java
false
false
4,672
java
/* * Copyright (C) 2012 ZXing 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 * * 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.zxing.camera; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.hardware.Camera; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.util.Log; import com.zxing.PreferencesActivity; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.RejectedExecutionException; @SuppressWarnings("deprecation") // camera APIs final class AutoFocusManager implements Camera.AutoFocusCallback { private static final String TAG = AutoFocusManager.class.getSimpleName(); private static final long AUTO_FOCUS_INTERVAL_MS = 2000L; private static final Collection<String> FOCUS_MODES_CALLING_AF; static { FOCUS_MODES_CALLING_AF = new ArrayList<>(2); FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO); FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO); } private boolean stopped; private boolean focusing; private final boolean useAutoFocus; private final Camera camera; private AsyncTask<?, ?, ?> outstandingTask; AutoFocusManager(Context context, Camera camera) { this.camera = camera; SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); String currentFocusMode = camera.getParameters().getFocusMode(); useAutoFocus = sharedPrefs.getBoolean(PreferencesActivity.KEY_AUTO_FOCUS, true) && FOCUS_MODES_CALLING_AF.contains(currentFocusMode); Log.i(TAG, "Current focus mode '" + currentFocusMode + "'; use auto focus? " + useAutoFocus); start(); } @Override public synchronized void onAutoFocus(boolean success, Camera theCamera) { focusing = false; autoFocusAgainLater(); } private synchronized void autoFocusAgainLater() { if (!stopped && outstandingTask == null) { AutoFocusTask newTask = new AutoFocusTask(); try { newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); outstandingTask = newTask; } catch (RejectedExecutionException ree) { Log.w(TAG, "Could not request auto focus", ree); } } } synchronized void start() { if (useAutoFocus) { outstandingTask = null; if (!stopped && !focusing) { try { camera.autoFocus(this); focusing = true; } catch (RuntimeException re) { // Have heard RuntimeException reported in Android 4.0.x+; continue? Log.w(TAG, "Unexpected exception while focusing", re); // Try again later to keep cycle going autoFocusAgainLater(); } } } } private synchronized void cancelOutstandingTask() { if (outstandingTask != null) { if (outstandingTask.getStatus() != AsyncTask.Status.FINISHED) { outstandingTask.cancel(true); } outstandingTask = null; } } synchronized void stop() { stopped = true; if (useAutoFocus) { cancelOutstandingTask(); // Doesn't hurt to call this even if not focusing try { camera.cancelAutoFocus(); } catch (RuntimeException re) { // Have heard RuntimeException reported in Android 4.0.x+; continue? Log.w(TAG, "Unexpected exception while cancelling focusing", re); } } } @SuppressLint("StaticFieldLeak") private final class AutoFocusTask extends AsyncTask<Object, Object, Object> { @Override protected Object doInBackground(Object... voids) { try { Thread.sleep(AUTO_FOCUS_INTERVAL_MS); } catch (InterruptedException e) { // continue } start(); return null; } } }
[ "397141365@qq.com" ]
397141365@qq.com
91bd072b78e5edd689ba16554d45407bd7a12dea
db065d84741a312392290720e2b2579bb5a765f9
/traductor/src/org/ibit/rol/sac/integracion/ws/provider/ActualizacionServicio.java
b40258abf4b96d4136b5702f5b3fd6fdd38b1e78
[]
no_license
enricjaen/webservices
8038992264b6cf63ec518d12a1f13ba09f539308
5f0a7cb5afea434e67bf919dba16b7c43f246707
refs/heads/master
2020-12-24T15:04:35.033727
2014-01-29T09:37:19
2014-01-29T09:37:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,469
java
package org.ibit.rol.sac.integracion.ws.provider; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ibit.rol.sac.model.*; import org.ibit.rol.sac.model.ws.*; import org.ibit.rol.sac.persistence.delegate.*; public class ActualizacionServicio{ protected static Log log = LogFactory.getLog(ActualizacionServicio.class); public Boolean actualizarFicha(final String idRemoto, FichaTransferible fichaT) throws DelegateException { if (!DelegateUtil.getAdministracionRemotaDelegate().isEmpty(idRemoto) && (fichaT.getCodigoEstandarMaterias() != null && fichaT .getCodigoEstandarMaterias().length > 0) || (fichaT.getCodigoEstandarHV() != null && fichaT .getCodigoEstandarHV().length > 0)) { log.debug("Recibida ficha para actualizar"); FichaRemotaDelegate delegate = DelegateUtil .getFichaRemotaDelegate(); FichaRemota fichaRemota = delegate.obtenerFichaRemota(idRemoto,fichaT .getId()); if (fichaRemota == null){ fichaRemota = new FichaRemota(); log.debug("La ficha no Existia"); } fichaRemota.rellenar(fichaT); delegate.grabarFichaRemota(idRemoto,fichaRemota, fichaT.getFichasUA(), fichaT .getCodigoEstandarMaterias(), fichaT.getCodigoEstandarHV()); } return null; } public Boolean actualizarUnidadAdministrativa(final String idRemoto, UnidadAdministrativaTransferible uaT) throws DelegateException { if(!DelegateUtil.getAdministracionRemotaDelegate().isEmpty(idRemoto)){ log.debug("Recibida UA para actualizar"); UARemotaDelegate delegate = DelegateUtil.getUARemotaDelegate(); UnidadAdministrativaRemota unidad = delegate.obtenerUARemota(idRemoto,uaT .getId()); Long idPadre= null; if(uaT.getIdPadre()!=null) idPadre = delegate.obtenerUARemota(idRemoto,uaT.getIdPadre()).getId(); if (unidad == null){ if(idPadre==null){ return null; } unidad = new UnidadAdministrativaRemota(); } unidad.rellenar(uaT); delegate.grabarUARemota(idRemoto,unidad, idPadre, uaT.getCodigoEstandarTratamiento() ,uaT.getCodigoEstandarMaterias()); } return null; } public Boolean actualizarProcedimiento(final String idRemoto, ProcedimientoTransferible procT) throws DelegateException { if (!DelegateUtil.getAdministracionRemotaDelegate().isEmpty(idRemoto) && (procT.getCodigoEstandarMaterias() != null && procT .getCodigoEstandarMaterias().length > 0) || (procT.getCodigoEstandarHV() != null && procT .getCodigoEstandarHV().length > 0)) { log.debug("Recibido Procedimiento para actualizar"); UARemotaDelegate auDelegate = DelegateUtil .getUARemotaDelegate(); UnidadAdministrativaRemota unidad = auDelegate.obtenerUARemota(idRemoto,procT.getIdUnidadAdministrativa()); if(unidad==null) return false; ProcedimientoRemotoDelegate delegate = DelegateUtil .getProcedimientoRemotoDelegate(); ProcedimientoRemoto proc = delegate .obtenerProcedimientoRemoto(idRemoto,procT.getId()); if (proc == null){ proc = new ProcedimientoRemoto(); } proc.rellenear(procT); proc.setUnidadAdministrativa(unidad); if(procT.getIdOrganResolutori()!=null){ proc.setOrganResolutori(auDelegate.obtenerUARemota(idRemoto, procT.getIdOrganResolutori())); } //INICIACION boolean actualizarIniciacion=false; if(procT.getCodigoEstandarIniciacion()!=null){ Iniciacion iniciacion = delegate.obtenerIniciacion(procT.getCodigoEstandarIniciacion()); if (iniciacion != null) { proc.setIniciacion(iniciacion); actualizarIniciacion=true; } } if(!actualizarIniciacion){ proc.setIniciacion(null); } delegate.grabarProcedimientoRemoto(idRemoto, proc, procT .getCodigoEstandarMaterias(), procT.getCodigoEstandarHV()); } return null; } public Boolean actualizarEdificio(final String idRemoto, EdificioTransferible edifT) throws DelegateException { if (!DelegateUtil.getAdministracionRemotaDelegate().isEmpty(idRemoto)) { log.debug("Recibido edificio para actualizar"); UARemotaDelegate delegate = DelegateUtil.getUARemotaDelegate(); EdificioRemoto edificioRemoto = delegate.obtenerEdificioRemoto(idRemoto,edifT.getId()); if (edificioRemoto == null){ edificioRemoto = new EdificioRemoto(); } edificioRemoto.rellenar(edifT); delegate.grabarEdificioRemoto(edificioRemoto); } return null; } public Boolean actualizarTramite(final String idRemoto, TramiteTransferible tramT) throws DelegateException { if (!DelegateUtil.getAdministracionRemotaDelegate().isEmpty(idRemoto)) { log.debug("Recibido tramite para actualizar"); TramiteRemotoDelegate delegate = DelegateUtil.getTramiteRemotoDelegate(); TramiteRemoto tramiteRemoto = delegate.obtenerTramiteRemoto(idRemoto,tramT.getId()); if (tramiteRemoto == null){ UARemotaDelegate uaRemotaDelegate = DelegateUtil.getUARemotaDelegate(); ProcedimientoRemotoDelegate procedimientoRemotoDelegate = DelegateUtil.getProcedimientoRemotoDelegate(); AdministracionRemota administracionRemota = uaRemotaDelegate.obtenerAdministracionRemota(idRemoto); ProcedimientoRemoto procedimientoRemoto =procedimientoRemotoDelegate.obtenerProcedimientoRemoto(idRemoto,tramT.getIdProcedimiento()); tramiteRemoto = new TramiteRemoto(); tramiteRemoto.setAdministracionRemota(administracionRemota); tramiteRemoto.rellenar(tramT); delegate.grabarTramiteRemoto(tramiteRemoto, procedimientoRemoto.getId(),tramT.getIdOrganCompetent()); } else{ tramiteRemoto.rellenar(tramT); delegate.grabarTramiteRemoto(tramiteRemoto,tramT.getIdOrganCompetent()); } } return null; } public Boolean actualizarEdificioUA(final String idRemoto, EdificioTransferible edifT,final Long idUA) throws DelegateException { if (!DelegateUtil.getAdministracionRemotaDelegate().isEmpty(idRemoto)) { UARemotaDelegate delegate = DelegateUtil.getUARemotaDelegate(); EdificioRemoto edificioRemoto = delegate.obtenerEdificioRemoto(idRemoto,edifT.getId()); UnidadAdministrativaRemota unidadAdministrativaRemota = delegate.obtenerUARemota(idRemoto,idUA); if(unidadAdministrativaRemota!=null){ if (edificioRemoto == null){ AdministracionRemota administracionRemota = delegate.obtenerAdministracionRemota(idRemoto); edificioRemoto = new EdificioRemoto(); edificioRemoto.setAdministracionRemota(administracionRemota); } edificioRemoto.rellenar(edifT); edificioRemoto.getUnidadesAdministrativas().add(unidadAdministrativaRemota); delegate.grabarEdificioRemoto(edificioRemoto); } } return null; } public Boolean actualizarNormativa(final String idRemoto, NormativaTransferible normT) throws DelegateException { if (!DelegateUtil.getAdministracionRemotaDelegate().isEmpty(idRemoto)) { log.debug("Recibido normativa para actualizar"); NormativaExternaRemotaDelegate delegate = DelegateUtil.getNormativaExternaRemotaDelegate(); NormativaExternaRemota normExtRemota = delegate.obtenerNormativaExternaRemota(idRemoto,normT.getId()); if (normExtRemota == null){ normExtRemota = new NormativaExternaRemota(); } normExtRemota.rellenar(normT); delegate.grabarNormativaExternaRemota(normExtRemota); } return null; } public Boolean actualizarNormativaProcedimiento(final String idRemoto, NormativaTransferible normT,final Long idProc) throws DelegateException { if (!DelegateUtil.getAdministracionRemotaDelegate().isEmpty(idRemoto)) { log.debug("Recibido Normativa para actualizar"); NormativaExternaRemotaDelegate normDelegate = DelegateUtil.getNormativaExternaRemotaDelegate(); ProcedimientoRemotoDelegate procDelegate = DelegateUtil.getProcedimientoRemotoDelegate(); UARemotaDelegate uaRemDelegate = DelegateUtil.getUARemotaDelegate(); NormativaExternaRemota normRemota = normDelegate.obtenerNormativaExternaRemota(idRemoto,normT.getId()); ProcedimientoRemoto procRemoto = procDelegate.obtenerProcedimientoRemoto(idRemoto,idProc); if(procRemoto!=null){ if (normRemota == null){ AdministracionRemota administracionRemota = uaRemDelegate.obtenerAdministracionRemota(idRemoto); normRemota = new NormativaExternaRemota(); normRemota.setAdministracionRemota(administracionRemota); } normRemota.rellenar(normT); normDelegate.grabarNormativaExternaRemota(normRemota); normDelegate.anyadirProcedimiento(procRemoto.getId(),normRemota.getId()); } } return null; } public Boolean actualizarDocumentoProcedimiento(final String idRemoto, DocumentoTransferible docT,final Long idProc) throws DelegateException { if (!DelegateUtil.getAdministracionRemotaDelegate().isEmpty(idRemoto)) { log.info("Recibido Documento para actualizar"); ProcedimientoRemotoDelegate procDelegate = DelegateUtil.getProcedimientoRemotoDelegate(); UARemotaDelegate uaRemDelegate = DelegateUtil.getUARemotaDelegate(); ProcedimientoRemoto procRemoto = procDelegate.obtenerProcedimientoRemoto(idRemoto,idProc); DocumentoRemoto documentoRemoto = procDelegate.obtenerDocumentoRemoto(idRemoto,docT.getId()); if(procRemoto!=null){ if (documentoRemoto == null){ AdministracionRemota administracionRemota = uaRemDelegate.obtenerAdministracionRemota(idRemoto); documentoRemoto = new DocumentoRemoto(); documentoRemoto.setAdministracionRemota(administracionRemota); } documentoRemoto.rellenar(docT); procDelegate.grabarDocumentoRemoto(documentoRemoto, procRemoto.getId(), null); } } return null; } public void borrarFicha(final String idRemoto, Long idExt) throws DelegateException { log.debug("Borrando Ficha"); DelegateUtil.getFichaRemotaDelegate().borrarFichaRemota(idRemoto,idExt); } public void borrarProcedimiento(final String idRemoto, Long idExt) throws DelegateException { log.debug("Borrando Procedimiento"); DelegateUtil.getProcedimientoRemotoDelegate().borrarProcedimientoRemoto(idRemoto,idExt); } public void borrarUnidadAdministrativa(final String idRemoto, Long idExt) throws DelegateException { log.debug("Borrando Unidad"); DelegateUtil.getUARemotaDelegate().borrarUARemota(idRemoto,idExt); } public void borrarFichaUA(final String idRemoto, Long idFicha, Long idUA, String codEst) throws DelegateException { log.debug("Borrando FichaUA"); DelegateUtil.getFichaRemotaDelegate().borrarFichaUA(idRemoto,idFicha, idUA, codEst); } public void borrarEdificio(final String idRemoto,Long idExt) throws DelegateException { log.debug("Borrando Edificio"); DelegateUtil.getUARemotaDelegate().borrarEdificioRemoto(idRemoto,idExt); } public void borrarEdificioUA(final String idRemoto, Long idExt, Long idUA) throws DelegateException { log.debug("Borrando EdificioUA"); DelegateUtil.getUARemotaDelegate().eliminarUnidad(idRemoto,idExt,idUA); } public void borrarTramite(final String idRemoto,Long idExt) throws DelegateException { log.debug("Borrando Edificio"); DelegateUtil.getTramiteRemotoDelegate().borrarTramiteRemoto(idRemoto,idExt); } public void borrarNormativa(final String idRemoto,Long idExt) throws DelegateException { log.debug("Borrando Normativa"); DelegateUtil.getNormativaExternaRemotaDelegate().borrarNormativaRemota(idRemoto,idExt); } public void borrarNormativaProcedimiento(final String idRemoto, Long idExt, Long idProc) throws DelegateException { log.debug("Borrando NormativaProc"); DelegateUtil.getNormativaExternaRemotaDelegate().eliminarProcNormativa(idRemoto,idExt,idProc); } public void borrarDocumentoProcedimiento(final String idRemoto, Long idExt) throws DelegateException { log.debug("Borrando DocumentoProc"); DelegateUtil.getProcedimientoRemotoDelegate().borrarDocumentoRemoto(idRemoto,idExt); } }
[ "enricjaen@yahoo.es" ]
enricjaen@yahoo.es
c78646c4de26d6311066c2bca23ad7389e48742b
66268c59bfe326a8242e3e596c0b37e81d36d641
/apache-normal/consumer/src/main/java/com/hp/dubbo/test/ConsumerApplication.java
481b4db961c0ef7197f1c8614bb7dd8c5671aa91
[]
no_license
hxvvxh/dubbo-test-apache
e0f99205448987c1253def25d44df298a291b815
2e5892a770c2888d6b71cd584ee9a7764e78bafd
refs/heads/master
2023-01-09T02:39:51.456995
2020-11-03T14:11:30
2020-11-03T14:11:30
290,782,680
0
0
null
null
null
null
UTF-8
Java
false
false
511
java
package com.hp.dubbo.test; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author hp * @version 1.0 * @date 2020/8/27 21:51 */ @EnableDubbo @SpringBootApplication(scanBasePackages = {"com.hp.dubbo.test"}) public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class,args); } }
[ "2732259311@qq.com" ]
2732259311@qq.com
e1ac9558cb809dd7c48990c0d6251bd77edc3bbc
3ecb825eca092ba98c5a29985db2c9c198a5fba8
/src/main/WaterDetector.java
15c17799704dd0139e11c3b2db627c7d782df19a
[]
no_license
golembovskiy/protectSystem
3f265e5e24b3f35f107710c16da321467f33b199
fce399dcdbf0e5a278d18607b2ed8a501e5edc54
refs/heads/master
2021-01-19T02:30:34.187592
2016-07-03T21:27:44
2016-07-03T21:27:44
62,515,800
0
0
null
null
null
null
UTF-8
Java
false
false
842
java
package main; import java.beans.PropertyChangeEvent; public class WaterDetector extends Detector { public WaterDetector(ControlBoard controlBoard) { super(controlBoard); // TODO Auto-generated constructor stub } @Override public void signal() { // TODO Auto-generated method stub System.out.println("The water level sensor sends a signal to the control panel"); AlarmMsg msg = new AlarmMsg("Off the water supply", DetectorType.WATER_DETECTOR); controlBoard.doSomething(msg); } @Override public void propertyChange(PropertyChangeEvent event) { // TODO Auto-generated method stub System.out.println("Triggered the water level sensor in the room " + event.getPropertyName()); signal(); } @Override public DetectorType getType() { // TODO Auto-generated method stub return DetectorType.WATER_DETECTOR; } }
[ "badzbogdan@i.ua" ]
badzbogdan@i.ua
fbdd9f86974e1fb0d1982be9fd9d29ec0d4e0a7f
445ecc4c63df622aabb1335b3784de7aaaf4441f
/MyFirstApp/src/com/example/myfirstapp/ItemListFragment.java
34160ac9290269f563870ef14910aacce1830aa0
[]
no_license
optimalmanager/CellNetProj
b9000b96d9e273f2de090d975ec1fdcc7efbb759
75dd3aeb91439c0bc9ab3f8c1a0737ceb48bca4e
refs/heads/master
2020-04-13T15:48:55.164168
2012-12-02T00:55:02
2012-12-02T00:55:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,031
java
package com.example.myfirstapp; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import com.example.myfirstapp.dummy.DummyContent; /** * A list fragment representing a list of Items. This fragment * also supports tablet devices by allowing list items to be given an * 'activated' state upon selection. This helps indicate which item is * currently being viewed in a {@link ItemDetailFragment}. * <p> * Activities containing this fragment MUST implement the {@link Callbacks} * interface. */ public class ItemListFragment extends ListFragment { /** * The serialization (saved instance state) Bundle key representing the * activated item position. Only used on tablets. */ private static final String STATE_ACTIVATED_POSITION = "activated_position"; /** * The fragment's current callback object, which is notified of list item * clicks. */ private Callbacks mCallbacks = sDummyCallbacks; /** * The current activated item position. Only used on tablets. */ private int mActivatedPosition = ListView.INVALID_POSITION; /** * A callback interface that all activities containing this fragment must * implement. This mechanism allows activities to be notified of item * selections. */ public interface Callbacks { /** * Callback for when an item has been selected. */ public void onItemSelected(String id); } /** * A dummy implementation of the {@link Callbacks} interface that does * nothing. Used only when this fragment is not attached to an activity. */ private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onItemSelected(String id) { } }; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public ItemListFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: replace with a real list adapter. setListAdapter(new ArrayAdapter<DummyContent.DummyItem>( getActivity(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, DummyContent.ITEMS)); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Restore the previously serialized activated item position. if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION)); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); // Activities containing this fragment must implement its callbacks. if (!(activity instanceof Callbacks)) { throw new IllegalStateException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); // Reset the active callbacks interface to the dummy implementation. mCallbacks = sDummyCallbacks; } @Override public void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mActivatedPosition != ListView.INVALID_POSITION) { // Serialize and persist the activated item position. outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); } } /** * Turns on activate-on-click mode. When this mode is on, list items will be * given the 'activated' state when touched. */ public void setActivateOnItemClick(boolean activateOnItemClick) { // When setting CHOICE_MODE_SINGLE, ListView will automatically // give items the 'activated' state when touched. getListView().setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE); } private void setActivatedPosition(int position) { if (position == ListView.INVALID_POSITION) { getListView().setItemChecked(mActivatedPosition, false); } else { getListView().setItemChecked(position, true); } mActivatedPosition = position; } }
[ "kum2104@columbia.edu" ]
kum2104@columbia.edu
782400501656777a56d2f0e0bc89feaef641a739
40889d53e6e175f4d5360fd8664f6611fd11ac07
/src/main/java/com/example/springjwt/domain/Jwtresponse.java
03182ccf402b5678bce27a35b73596608391df13
[]
no_license
grElena/spring-jwt
ff0248a7abb7f03939dd9b44b51fb6001a7e349e
2e6de1a8096d837633daafa00a5e70548bedfd92
refs/heads/main
2023-02-07T05:33:50.101609
2020-12-31T06:35:44
2020-12-31T06:35:44
325,732,715
0
0
null
null
null
null
UTF-8
Java
false
false
188
java
package com.example.springjwt.domain; import lombok.AllArgsConstructor; import lombok.Getter; @AllArgsConstructor @Getter public class Jwtresponse { private final String jwttoken; }
[ "gr.elena@mail.ru" ]
gr.elena@mail.ru
eb0e0d715c2c415c0527dffabf224b5f0d668a9a
84347984984dc7ff989388c184ba68f2fd301cc9
/src/main/game/com/models/Ladder.java
da2cf4c633b263b6d3b7dc5ee4fd073824372f4b
[]
no_license
VickyMohite/assignment
b7c8508d3d3a0107acb5e873f7a13fadbd6ea7f2
da2f2872dd161ade211a478ab29fd056fc19d854
refs/heads/master
2023-06-04T03:03:21.480397
2021-06-29T08:29:44
2021-06-29T08:29:44
380,925,554
0
0
null
null
null
null
UTF-8
Java
false
false
385
java
package main.game.com.models; public class Ladder { private int start; private int end; public Ladder(int start, int end) { super(); this.start = start; this.end = end; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } }
[ "vickymohite96@gmail.com" ]
vickymohite96@gmail.com
aa1b45aef2b253870e30a14a6d8f58c62eaf7f2f
42fa8a48867f614f927226190625dab74b6532af
/src/main/java/net/kurien/blog/module/mail/service/MailService.java
0f4664dcc171a760f98527932249ec4892118dfe
[ "MIT" ]
permissive
kurien92/kreBlog
2cd250a9894d30debf0b95a38489aedc13d5872b
1f46086be36dbdaa86ef663a495fafb029440f5b
refs/heads/master
2022-12-24T07:01:50.772317
2021-02-24T11:49:07
2021-02-24T11:49:07
139,170,292
12
0
MIT
2022-12-16T15:41:54
2018-06-29T16:06:50
Java
UTF-8
Java
false
false
386
java
package net.kurien.blog.module.mail.service; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import java.util.List; public interface MailService { void send(String from, String to, String title, String content) throws MessagingException; void send(String from, List<String> toList, String title, String content) throws MessagingException; }
[ "kurien92@gmail.com" ]
kurien92@gmail.com