blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
62a824b3c62a5d5a8e5100262d0728fd88e7db34 | 34,815,004,923,293 | 281700bc00fb47d88d6ffe7f908acf1019eadb11 | /designpattern-1/src/main/java/com/chen/dayaction/designpattern/factory4/FactoryHumanDemo.java | d0c381deabc45da5705f7ec36ccc95293f5005a0 | [] | no_license | langlaile1221/100-dayaction | https://github.com/langlaile1221/100-dayaction | b086dff0835b65ed6190e8aa83e249f7378fc508 | b0918329f34560b9cd9fe0e599c5747ded12a04f | refs/heads/master | 2020-07-30T07:59:02.642000 | 2018-11-05T16:57:51 | 2018-11-05T16:57:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chen.dayaction.designpattern.factory4;
import com.chen.dayaction.designpattern.factory4.factoryhuman.BlackHumanFactory;
import com.chen.dayaction.designpattern.factory4.factoryhuman.HumanFactory;
import com.chen.dayaction.designpattern.factory4.factoryhuman.WhiteHumanFactory;
import com.chen.dayaction.designpattern.factory4.factoryhuman.YellowHumanFactory;
/**
* 女娲造人案例:
* 女娲使用乾坤鼎造出不同肤色的人。
*
* 案例分析:
* 对造人过程进行分析,该过程涉及三个对象:女娲、乾坤鼎、三种不同肤色的人。
* 女娲可以用客户来表示,乾坤鼎类似于一个工厂,负责制造生产产品(即人类),
* 三种不同肤色的人,都是同一个接口下的不同实现类, 对于乾坤鼎来说都是它生产出的产品。
*
* 总结:
* 优点:
* 1)良好的封装性,代码结构清晰。一个对象创建是有条件约束的,如一个调用者需要一个具体的产品对象,只要知道这个产品的类名就可以了,不用知道创建对象的过程, 降低模块间的耦合。
* 2)工厂方法模式的扩展性非常优秀。在增加产品类的情况下,只要适当地修改具体的工厂类或扩展一个工厂类,就可以完成“拥抱变化”。
* 3)屏蔽产品类。调用者只需要关心产品的接口,只要接口保持不变,系统中的上层模块就不需要发生变化。因为产品类的实例化工作是由工厂类负责的,生成具体哪一个产品是由工厂类决定的。
* 4)工厂方法模式是典型的解耦框架。高层模块值需要知道产品的抽象类,其他的实现类都不用关心。
* 使用场景:
* 1)工厂方法模式是new一个对象的替代品,所有需要生成对象的地方都可以使用,但需要慎重地考虑是否要增加一个工厂类进行管理增加代码的复杂度。
* 2)需要灵活的、可扩展的框架时,可以考虑采用工厂方法模式。
*/
public class FactoryHumanDemo {
public static void main(String[] args) {
HumanFactory factory1 = new WhiteHumanFactory();
HumanFactory factory2 = new BlackHumanFactory();
HumanFactory factory3 = new YellowHumanFactory();
createHuman(factory1);
createHuman(factory2);
createHuman(factory3);
}
public static void createHuman(HumanFactory factory){
System.out.print("女娲造人:");
factory.factoryMethod().display();
System.out.println("--------------------");
}
}
| UTF-8 | Java | 2,567 | java | FactoryHumanDemo.java | Java | [] | null | [] | package com.chen.dayaction.designpattern.factory4;
import com.chen.dayaction.designpattern.factory4.factoryhuman.BlackHumanFactory;
import com.chen.dayaction.designpattern.factory4.factoryhuman.HumanFactory;
import com.chen.dayaction.designpattern.factory4.factoryhuman.WhiteHumanFactory;
import com.chen.dayaction.designpattern.factory4.factoryhuman.YellowHumanFactory;
/**
* 女娲造人案例:
* 女娲使用乾坤鼎造出不同肤色的人。
*
* 案例分析:
* 对造人过程进行分析,该过程涉及三个对象:女娲、乾坤鼎、三种不同肤色的人。
* 女娲可以用客户来表示,乾坤鼎类似于一个工厂,负责制造生产产品(即人类),
* 三种不同肤色的人,都是同一个接口下的不同实现类, 对于乾坤鼎来说都是它生产出的产品。
*
* 总结:
* 优点:
* 1)良好的封装性,代码结构清晰。一个对象创建是有条件约束的,如一个调用者需要一个具体的产品对象,只要知道这个产品的类名就可以了,不用知道创建对象的过程, 降低模块间的耦合。
* 2)工厂方法模式的扩展性非常优秀。在增加产品类的情况下,只要适当地修改具体的工厂类或扩展一个工厂类,就可以完成“拥抱变化”。
* 3)屏蔽产品类。调用者只需要关心产品的接口,只要接口保持不变,系统中的上层模块就不需要发生变化。因为产品类的实例化工作是由工厂类负责的,生成具体哪一个产品是由工厂类决定的。
* 4)工厂方法模式是典型的解耦框架。高层模块值需要知道产品的抽象类,其他的实现类都不用关心。
* 使用场景:
* 1)工厂方法模式是new一个对象的替代品,所有需要生成对象的地方都可以使用,但需要慎重地考虑是否要增加一个工厂类进行管理增加代码的复杂度。
* 2)需要灵活的、可扩展的框架时,可以考虑采用工厂方法模式。
*/
public class FactoryHumanDemo {
public static void main(String[] args) {
HumanFactory factory1 = new WhiteHumanFactory();
HumanFactory factory2 = new BlackHumanFactory();
HumanFactory factory3 = new YellowHumanFactory();
createHuman(factory1);
createHuman(factory2);
createHuman(factory3);
}
public static void createHuman(HumanFactory factory){
System.out.print("女娲造人:");
factory.factoryMethod().display();
System.out.println("--------------------");
}
}
| 2,567 | 0.751806 | 0.740643 | 43 | 34.418606 | 28.455786 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.348837 | false | false | 2 |
56a69cff951178e29fcf6daf2f9f4cdb310b6059 | 34,754,875,393,314 | c2e7333bdcefebb3acd50062e2d8c28415dd9873 | /core/src/com/mursaat/zelda/items/ItemSword.java | 00b37fd255a46524b2c7a996eb6e27a937bd6b2b | [
"Apache-2.0"
] | permissive | Mursaat/zelda | https://github.com/Mursaat/zelda | cc3b6229b36293f78ff855b34eb065b6f318e46f | 7c9ef67776e4238ca66ca943992fc5097ef99054 | refs/heads/master | 2018-01-08T08:12:51.614000 | 2016-01-18T10:00:45 | 2016-01-18T10:00:45 | 48,512,604 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mursaat.zelda.items;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.mursaat.zelda.sound.Sounds;
import com.mursaat.zelda.world.World;
import java.util.Arrays;
import java.util.List;
/**
* Created by Aurelien on 12/01/2016.
*/
public class ItemSword extends Item
{
private static final int regionHeight = 16;
private static final int regionWidth = 16;
// Ensemble des frames de textures possible
public TextureRegion[][] textureFrames;
// Animations
public Animation animSlashTop;
public Animation animSlashBottom;
public Animation animSlashLeft;
public Animation animSlashRight;
// Le temps pour donner une coup d'épée
public final float slashTime;
// Tous les sonds qui peuvent êtres joués lors du slash de l'épée
public List<Sound> slashSounds;
// L'allonge de l'epee en pixels
public float allonge;
public ItemSword(String textureName, String name, int id, float slashTime, float allonge)
{
super(textureName, name, id);
this.slashTime = slashTime;
this.allonge = allonge;
this.textureFrames = TextureRegion.split(texture, regionWidth, regionHeight);
this.slashSounds = Arrays.asList(Sounds.swordSlash1, Sounds.swordSlash2, Sounds.swordSlash3);
makeAnimations();
}
protected void makeAnimations()
{
// MOVE
this.animSlashBottom = new Animation(slashTime /4, this.textureFrames[0][0], this.textureFrames[0][1], this.textureFrames[0][2], this.textureFrames[0][2]);
this.animSlashBottom.setPlayMode(Animation.PlayMode.LOOP);
this.animSlashLeft = new Animation(slashTime /4, this.textureFrames[1][0], this.textureFrames[1][1], this.textureFrames[1][2], this.textureFrames[1][2]);
this.animSlashLeft.setPlayMode(Animation.PlayMode.LOOP);
this.animSlashRight = new Animation(slashTime /4, this.textureFrames[2][0], this.textureFrames[2][1], this.textureFrames[2][2], this.textureFrames[2][2]);
this.animSlashRight.setPlayMode(Animation.PlayMode.LOOP);
this.animSlashTop = new Animation(slashTime /4, this.textureFrames[3][0], this.textureFrames[3][1], this.textureFrames[3][2], this.textureFrames[3][2]);
this.animSlashTop.setPlayMode(Animation.PlayMode.LOOP);
}
public void playRandomSlashSound()
{
this.slashSounds.get(World.random.nextInt(this.slashSounds.size())).play();
}
}
| UTF-8 | Java | 2,537 | java | ItemSword.java | Java | [
{
"context": ".Arrays;\nimport java.util.List;\n\n/**\n * Created by Aurelien on 12/01/2016.\n */\npublic class ItemSword extends",
"end": 324,
"score": 0.9987418055534363,
"start": 316,
"tag": "USERNAME",
"value": "Aurelien"
}
] | null | [] | package com.mursaat.zelda.items;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.mursaat.zelda.sound.Sounds;
import com.mursaat.zelda.world.World;
import java.util.Arrays;
import java.util.List;
/**
* Created by Aurelien on 12/01/2016.
*/
public class ItemSword extends Item
{
private static final int regionHeight = 16;
private static final int regionWidth = 16;
// Ensemble des frames de textures possible
public TextureRegion[][] textureFrames;
// Animations
public Animation animSlashTop;
public Animation animSlashBottom;
public Animation animSlashLeft;
public Animation animSlashRight;
// Le temps pour donner une coup d'épée
public final float slashTime;
// Tous les sonds qui peuvent êtres joués lors du slash de l'épée
public List<Sound> slashSounds;
// L'allonge de l'epee en pixels
public float allonge;
public ItemSword(String textureName, String name, int id, float slashTime, float allonge)
{
super(textureName, name, id);
this.slashTime = slashTime;
this.allonge = allonge;
this.textureFrames = TextureRegion.split(texture, regionWidth, regionHeight);
this.slashSounds = Arrays.asList(Sounds.swordSlash1, Sounds.swordSlash2, Sounds.swordSlash3);
makeAnimations();
}
protected void makeAnimations()
{
// MOVE
this.animSlashBottom = new Animation(slashTime /4, this.textureFrames[0][0], this.textureFrames[0][1], this.textureFrames[0][2], this.textureFrames[0][2]);
this.animSlashBottom.setPlayMode(Animation.PlayMode.LOOP);
this.animSlashLeft = new Animation(slashTime /4, this.textureFrames[1][0], this.textureFrames[1][1], this.textureFrames[1][2], this.textureFrames[1][2]);
this.animSlashLeft.setPlayMode(Animation.PlayMode.LOOP);
this.animSlashRight = new Animation(slashTime /4, this.textureFrames[2][0], this.textureFrames[2][1], this.textureFrames[2][2], this.textureFrames[2][2]);
this.animSlashRight.setPlayMode(Animation.PlayMode.LOOP);
this.animSlashTop = new Animation(slashTime /4, this.textureFrames[3][0], this.textureFrames[3][1], this.textureFrames[3][2], this.textureFrames[3][2]);
this.animSlashTop.setPlayMode(Animation.PlayMode.LOOP);
}
public void playRandomSlashSound()
{
this.slashSounds.get(World.random.nextInt(this.slashSounds.size())).play();
}
}
| 2,537 | 0.712367 | 0.691426 | 69 | 35.68116 | 40.198959 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.855072 | false | false | 2 |
37e1d22a890d236d525da8a99316e3fc04b9762c | 34,754,875,392,756 | 3bf5dea755461a9d93e4d6ee8b2914914a46d608 | /app/src/main/java/com/t3h/immunization/vacxin/presenter/PresenterVacxinListener.java | be546bfe0a6b615d70d0c5870402910760dfa463 | [] | no_license | xuantien36/ExampleProject | https://github.com/xuantien36/ExampleProject | 040edfba6ce3797ad30a48c8d0fede0b9edb1c3d | f59f2b4bc76182fca6f21685dbc551d479d5c064 | refs/heads/master | 2021-01-04T06:03:14.215000 | 2020-02-20T10:45:31 | 2020-02-20T10:45:31 | 240,420,845 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.t3h.immunization.vacxin.presenter;
import com.t3h.immunization.basemvp.MvpPresenter;
import com.t3h.immunization.vacxin.view.VacxinView;
public interface PresenterVacxinListener<V extends VacxinView>extends MvpPresenter<V>{
void onshowList();
}
| UTF-8 | Java | 262 | java | PresenterVacxinListener.java | Java | [] | null | [] | package com.t3h.immunization.vacxin.presenter;
import com.t3h.immunization.basemvp.MvpPresenter;
import com.t3h.immunization.vacxin.view.VacxinView;
public interface PresenterVacxinListener<V extends VacxinView>extends MvpPresenter<V>{
void onshowList();
}
| 262 | 0.828244 | 0.816794 | 7 | 36.42857 | 28.559998 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 2 |
e43219e4066c01ea00c9b3974e47681ab3be21fe | 37,014,028,169,055 | 5f1fb5cae281aaf1b7ed47267e2edcccb57e2202 | /leadnews-service/leadnews-service-admin/src/main/java/com/feng/admin/service/impl/AdMenuServiceImpl.java | a76c95a59bd8ed94b99436c386fdfdf1c3d72dca | [] | no_license | catSpace123/leadnews | https://github.com/catSpace123/leadnews | d9d5aba09aeef16576802b2de4a31cc50f6c3a60 | b5cd6308fac0eeae5193052d6fb2c580a7ac161e | refs/heads/master | 2023-06-23T20:55:03.964000 | 2021-07-31T14:38:28 | 2021-07-31T14:38:28 | 391,369,902 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.feng.admin.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.admin.mapper.AdMenuMapper;
import com.feng.admin.pojo.AdMenu;
import com.feng.admin.service.AdMenuService;
import org.springframework.stereotype.Service;
/**
* <p>
* 菜单资源信息表 服务实现类
* </p>
*
* @author ljh
* @since 2021-07-08
*/
@Service
public class AdMenuServiceImpl extends ServiceImpl<AdMenuMapper, AdMenu> implements AdMenuService {
}
| UTF-8 | Java | 492 | java | AdMenuServiceImpl.java | Java | [
{
"context": "\n/**\n * <p>\n * 菜单资源信息表 服务实现类\n * </p>\n *\n * @author ljh\n * @since 2021-07-08\n */\n@Service\npublic class Ad",
"end": 330,
"score": 0.999467670917511,
"start": 327,
"tag": "USERNAME",
"value": "ljh"
}
] | null | [] | package com.feng.admin.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.admin.mapper.AdMenuMapper;
import com.feng.admin.pojo.AdMenu;
import com.feng.admin.service.AdMenuService;
import org.springframework.stereotype.Service;
/**
* <p>
* 菜单资源信息表 服务实现类
* </p>
*
* @author ljh
* @since 2021-07-08
*/
@Service
public class AdMenuServiceImpl extends ServiceImpl<AdMenuMapper, AdMenu> implements AdMenuService {
}
| 492 | 0.773504 | 0.75641 | 20 | 22.4 | 26.025757 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 2 |
27192262cb04f0dfe3933ae816b3209fbca228a6 | 35,570,919,167,978 | d9ded1f1fedce8bf8765b0459fa85dc85dd2dc23 | /jse7programmerI/t01/Data.java | c5390a6d48829350a0ec5b6deb19f4f302c1e910 | [] | no_license | comandantecm/java_exercices_1 | https://github.com/comandantecm/java_exercices_1 | 1689e95f366916971c11ad93a45e5f64acdc7984 | 20cafc5b5fb2e777cef84a780828ccbb91e553d1 | refs/heads/master | 2021-01-15T16:28:57.853000 | 2012-09-18T17:23:02 | 2012-09-18T17:23:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jse7programmerI.t01;
public Class Data {
} | UTF-8 | Java | 52 | java | Data.java | Java | [] | null | [] | package jse7programmerI.t01;
public Class Data {
} | 52 | 0.769231 | 0.711538 | 5 | 9.6 | 11.706409 | 28 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 2 |
6f6cd1eb60c572081984836e5f406636728102d6 | 34,273,839,063,353 | e42c151f1178f130bde08ba844c87017e67d2ede | /src/test/java/com/importador/importador/ImportadorApplicationTests.java | ce304b82b85fe3b5c918b274fdf9107daf80039d | [] | no_license | OvejeroMiguel/example_spring_batch | https://github.com/OvejeroMiguel/example_spring_batch | 79b7ed94d6885188b84a4696db889f69c7e410dd | 4a3c8896ddb4e472b9bd8c02123b52141144913a | refs/heads/master | 2022-12-08T17:18:08.772000 | 2020-09-02T18:22:43 | 2020-09-02T18:22:43 | 292,361,067 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.importador.importador;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ImportadorApplicationTests {
@Test
void contextLoads() {
}
}
| UTF-8 | Java | 230 | java | ImportadorApplicationTests.java | Java | [] | null | [] | package com.importador.importador;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ImportadorApplicationTests {
@Test
void contextLoads() {
}
}
| 230 | 0.765217 | 0.765217 | 13 | 16.692308 | 18.403112 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 2 |
1c522f3662d6edd304bf4d0e190908387a3c209a | 36,661,840,854,567 | 52df2adae5b949edac66b32d0b4271a08a96c1ad | /src/main/java/com/xinyan/logprocessor/record/util/CheckingUtil.java | 871d2af7e465f3727cc48b64b060687ded1c2073 | [] | no_license | sharkshore/log-record | https://github.com/sharkshore/log-record | d41ab65cb4ee93291e6c6868b9ecebe52a830dad | db26db9b8632806bf6a94d43812778cf87b4a093 | refs/heads/master | 2018-10-15T20:56:28.161000 | 2017-06-12T07:25:11 | 2017-06-12T07:25:11 | 94,065,613 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xinyan.logprocessor.record.util;
import com.xinyan.logprocessor.common.model.ErrorMessage;
import com.xinyan.logprocessor.common.model.MemberRequest;
import com.xinyan.logprocessor.common.model.MemberResponse;
import com.xinyan.logprocessor.common.model.NormalMessage;
import com.xinyan.logprocessor.common.util.AssertUtils;
import org.springframework.util.Assert;
/**
* Created by fugang on 2017/4/7.
*/
public class CheckingUtil {
public static void checkingMemberResp(MemberResponse memberResp){
Assert.hasLength(memberResp.getOccur_time(),"occur_time为空");
AssertUtils.isValidDate(memberResp.getOccur_time(),"20yy-MM-dd HH:mm:ss","occur_time格式不正确");
Assert.hasLength(memberResp.getMember(),"member为空");
Assert.hasLength(memberResp.getOccur_ip(),"occur_ip为空");
Assert.hasLength(memberResp.getProduct(),"product为空");
Assert.hasLength(memberResp.getTrade_no(),"trade_no为空");
Assert.hasLength(memberResp.getTrans_id(),"trans_id为空");
Assert.hasLength(memberResp.getLogId(),"LogId为空");
//Assert.hasLength(memberResp.getMsg_desc(),"msg_desc为空");
//Assert.hasLength(memberResp.getCode(),"code为空");
}
public static void checkingErrorMessage(ErrorMessage errorMessage){
Assert.hasLength(errorMessage.getOccur_time(),"occur_time为空");
AssertUtils.isValidDate(errorMessage.getOccur_time(),"20yy-MM-dd HH:mm:ss","occur_time格式不正确");
Assert.hasLength(errorMessage.getExceptionClassName(),"exceptionClassName为空");
Assert.hasLength(errorMessage.getOccur_ip(),"occur_ip为空");
Assert.hasLength(errorMessage.getExceptionPhrase(),"trade_no为空");
Assert.hasLength(errorMessage.getLogId(),"LogId为空");
Assert.hasLength(errorMessage.getMessage(),"message为空");
}
public static void checkingMemberRequest(MemberRequest memberRequest){
Assert.hasLength(memberRequest.getOccur_time(),"occur_time为空");
AssertUtils.isValidDate(memberRequest.getOccur_time(),"20yy-MM-dd HH:mm:ss","occur_time格式不正确");
Assert.hasLength(memberRequest.getTerminal_id(),"terminal_id为空");
Assert.hasLength(memberRequest.getOccur_ip(),"occur_ip为空");
Assert.hasLength(memberRequest.getId_holder(),"id_holder为空");
Assert.hasLength(memberRequest.getLogId(),"LogId为空");
Assert.hasLength(memberRequest.getId_card(),"id_card为空");
Assert.hasLength(memberRequest.getMember_id(),"member_id为空");
Assert.hasLength(memberRequest.getTrade_date(),"trade_date为空");
Assert.hasLength(memberRequest.getTrans_id(),"trans_id为空");
}
public static void checkingNormalMessage(NormalMessage normalMessage){
Assert.hasLength(normalMessage.getOccur_time(),"occur_time为空");
AssertUtils.isValidDate(normalMessage.getOccur_time(),"20yy-MM-dd HH:mm:ss,SSS","occur_time格式不正确");
Assert.hasLength(normalMessage.getOccur_ip(),"occur_ip为空");
Assert.hasLength(normalMessage.getLogId(),"LogId为空");
}
}
| UTF-8 | Java | 3,160 | java | CheckingUtil.java | Java | [
{
"context": "rg.springframework.util.Assert;\n\n/**\n * Created by fugang on 2017/4/7.\n */\npublic class CheckingUtil {\n ",
"end": 403,
"score": 0.9995785355567932,
"start": 397,
"tag": "USERNAME",
"value": "fugang"
}
] | null | [] | package com.xinyan.logprocessor.record.util;
import com.xinyan.logprocessor.common.model.ErrorMessage;
import com.xinyan.logprocessor.common.model.MemberRequest;
import com.xinyan.logprocessor.common.model.MemberResponse;
import com.xinyan.logprocessor.common.model.NormalMessage;
import com.xinyan.logprocessor.common.util.AssertUtils;
import org.springframework.util.Assert;
/**
* Created by fugang on 2017/4/7.
*/
public class CheckingUtil {
public static void checkingMemberResp(MemberResponse memberResp){
Assert.hasLength(memberResp.getOccur_time(),"occur_time为空");
AssertUtils.isValidDate(memberResp.getOccur_time(),"20yy-MM-dd HH:mm:ss","occur_time格式不正确");
Assert.hasLength(memberResp.getMember(),"member为空");
Assert.hasLength(memberResp.getOccur_ip(),"occur_ip为空");
Assert.hasLength(memberResp.getProduct(),"product为空");
Assert.hasLength(memberResp.getTrade_no(),"trade_no为空");
Assert.hasLength(memberResp.getTrans_id(),"trans_id为空");
Assert.hasLength(memberResp.getLogId(),"LogId为空");
//Assert.hasLength(memberResp.getMsg_desc(),"msg_desc为空");
//Assert.hasLength(memberResp.getCode(),"code为空");
}
public static void checkingErrorMessage(ErrorMessage errorMessage){
Assert.hasLength(errorMessage.getOccur_time(),"occur_time为空");
AssertUtils.isValidDate(errorMessage.getOccur_time(),"20yy-MM-dd HH:mm:ss","occur_time格式不正确");
Assert.hasLength(errorMessage.getExceptionClassName(),"exceptionClassName为空");
Assert.hasLength(errorMessage.getOccur_ip(),"occur_ip为空");
Assert.hasLength(errorMessage.getExceptionPhrase(),"trade_no为空");
Assert.hasLength(errorMessage.getLogId(),"LogId为空");
Assert.hasLength(errorMessage.getMessage(),"message为空");
}
public static void checkingMemberRequest(MemberRequest memberRequest){
Assert.hasLength(memberRequest.getOccur_time(),"occur_time为空");
AssertUtils.isValidDate(memberRequest.getOccur_time(),"20yy-MM-dd HH:mm:ss","occur_time格式不正确");
Assert.hasLength(memberRequest.getTerminal_id(),"terminal_id为空");
Assert.hasLength(memberRequest.getOccur_ip(),"occur_ip为空");
Assert.hasLength(memberRequest.getId_holder(),"id_holder为空");
Assert.hasLength(memberRequest.getLogId(),"LogId为空");
Assert.hasLength(memberRequest.getId_card(),"id_card为空");
Assert.hasLength(memberRequest.getMember_id(),"member_id为空");
Assert.hasLength(memberRequest.getTrade_date(),"trade_date为空");
Assert.hasLength(memberRequest.getTrans_id(),"trans_id为空");
}
public static void checkingNormalMessage(NormalMessage normalMessage){
Assert.hasLength(normalMessage.getOccur_time(),"occur_time为空");
AssertUtils.isValidDate(normalMessage.getOccur_time(),"20yy-MM-dd HH:mm:ss,SSS","occur_time格式不正确");
Assert.hasLength(normalMessage.getOccur_ip(),"occur_ip为空");
Assert.hasLength(normalMessage.getLogId(),"LogId为空");
}
}
| 3,160 | 0.724768 | 0.72012 | 56 | 52.785713 | 29.839878 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.321429 | false | false | 2 |
5f2d553682278895cbfaa5f616dc472c632941d5 | 39,118,562,133,404 | b4d08a6b84ea0713a5b727eba6cf9c7557e73fe2 | /210605_Kopo_Openbanking_pj/src/UI/AdminUI.java | ecd0547a2777f1347354051eafe6306b75d76cd9 | [] | no_license | Yoon-ddo/chloe_Project | https://github.com/Yoon-ddo/chloe_Project | e590c24e8aff80f040e793cc78fb2e35e8901579 | e5e67cc096a2947c7c6a89144085b3edb6e65665 | refs/heads/main | 2023-05-14T07:10:06.800000 | 2021-06-06T06:40:05 | 2021-06-06T06:40:05 | 374,121,581 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package UI;
import java.util.ArrayList;
import java.util.List;
import VO.LogVO;
public class AdminUI extends BaseUI{
@Override
public void execute() throws Exception {
List<LogVO> lst = new ArrayList<>();
printMenu();
BaseUI ui = null;
while(true) {
String m = scanStr("원하는 메뉴를 선택하세요. : ");
boolean isNumeric = isValidNum(m);
if(!isNumeric) {
System.out.println("유효하지 않은 값입니다. 다시 입력하세요!");
continue;
}else {
int menu = adminservice.getMenu(m);
switch(menu) {
case 0 :
ui = new LogOutUI();
ui.execute();
break;
case 1:
lst = adminservice.showUserService(menu, "");
adminservice.PrintUser(lst);
break;
case 2:
String id = scanStr("id를 입력하세요. : ");
lst = adminservice.showUserService(menu, id);
adminservice.PrintUser(lst);
break;
case 3:
String name = scanStr("이름을 입력하세요. : ");
lst = adminservice.showUserService(menu, name);
adminservice.PrintUser(lst);
break;
case 4:
while(true) {
String num = scanStr("연락처를 입력하세요(숫자만 입력) : ");
boolean isNum = isValidNum(num);
if(!isNum) {
System.out.println("유효하지 않은 값입니다. 다시입력하세요!");
continue;
}else {
lst = adminservice.showUserService(menu, num);
adminservice.PrintUser(lst);
break;
}
}
default : System.out.println("유효하지 않은 값입니다. 다시입력하세요!");
}
}
}
//adminservice.showUserService();
}
public void printMenu() throws Exception{
System.out.println("-------------------------------------------------------------------");
System.out.println(" [1]전체고객조회 [2]ID로 조회 [3]이름으로 조회 [4]연락처로 조회 [0]. 로그아웃");
System.out.println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
}
}
| UTF-8 | Java | 2,253 | java | AdminUI.java | Java | [] | null | [] | package UI;
import java.util.ArrayList;
import java.util.List;
import VO.LogVO;
public class AdminUI extends BaseUI{
@Override
public void execute() throws Exception {
List<LogVO> lst = new ArrayList<>();
printMenu();
BaseUI ui = null;
while(true) {
String m = scanStr("원하는 메뉴를 선택하세요. : ");
boolean isNumeric = isValidNum(m);
if(!isNumeric) {
System.out.println("유효하지 않은 값입니다. 다시 입력하세요!");
continue;
}else {
int menu = adminservice.getMenu(m);
switch(menu) {
case 0 :
ui = new LogOutUI();
ui.execute();
break;
case 1:
lst = adminservice.showUserService(menu, "");
adminservice.PrintUser(lst);
break;
case 2:
String id = scanStr("id를 입력하세요. : ");
lst = adminservice.showUserService(menu, id);
adminservice.PrintUser(lst);
break;
case 3:
String name = scanStr("이름을 입력하세요. : ");
lst = adminservice.showUserService(menu, name);
adminservice.PrintUser(lst);
break;
case 4:
while(true) {
String num = scanStr("연락처를 입력하세요(숫자만 입력) : ");
boolean isNum = isValidNum(num);
if(!isNum) {
System.out.println("유효하지 않은 값입니다. 다시입력하세요!");
continue;
}else {
lst = adminservice.showUserService(menu, num);
adminservice.PrintUser(lst);
break;
}
}
default : System.out.println("유효하지 않은 값입니다. 다시입력하세요!");
}
}
}
//adminservice.showUserService();
}
public void printMenu() throws Exception{
System.out.println("-------------------------------------------------------------------");
System.out.println(" [1]전체고객조회 [2]ID로 조회 [3]이름으로 조회 [4]연락처로 조회 [0]. 로그아웃");
System.out.println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
}
}
| 2,253 | 0.524616 | 0.519322 | 80 | 21.612499 | 21.580948 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.725 | false | false | 2 |
9b42bf991d1a3050d4e643e66a36deecb1d33e94 | 31,688,268,778,146 | 8e184c6c41ddc0bb8f37c03ee2fadcb2d5e85660 | /robozonky-app/src/test/java/com/github/robozonky/app/AbstractZonkyLeveragingTest.java | 1deb602aba815a7d1c3a468a24c4fac1072bcfa2 | [
"Apache-2.0"
] | permissive | pmacik/robozonky | https://github.com/pmacik/robozonky | 598d1f02929535292ad47dd778ed1ac4a30a3102 | fae2e727e32aa00042e7210b74136b7244a441b2 | refs/heads/master | 2020-08-03T15:17:34.782000 | 2019-10-19T11:08:38 | 2019-10-19T11:08:38 | 211,797,261 | 0 | 0 | Apache-2.0 | true | 2019-09-30T07:06:29 | 2019-09-30T07:06:28 | 2019-09-28T18:52:26 | 2019-09-28T18:52:24 | 13,674 | 0 | 0 | 0 | null | false | false | /*
* Copyright 2019 The RoboZonky Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.robozonky.app;
import com.github.robozonky.api.remote.entities.MyInvestment;
import com.github.robozonky.api.remote.enums.Rating;
import com.github.robozonky.api.strategies.LoanDescriptor;
import com.github.robozonky.app.events.AbstractEventLeveragingTest;
import com.github.robozonky.internal.Settings;
import com.github.robozonky.test.mock.MockLoanBuilder;
import java.time.OffsetDateTime;
import java.util.Random;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public abstract class AbstractZonkyLeveragingTest extends AbstractEventLeveragingTest {
private static final Random RANDOM = new Random(0);
protected static MyInvestment mockMyInvestment() {
return mockMyInvestment(OffsetDateTime.now());
}
private static MyInvestment mockMyInvestment(final OffsetDateTime creationDate) {
final MyInvestment m = mock(MyInvestment.class);
when(m.getId()).thenReturn(RANDOM.nextLong());
when(m.getTimeCreated()).thenReturn(creationDate);
return m;
}
protected static LoanDescriptor mockLoanDescriptor() {
return AbstractZonkyLeveragingTest.mockLoanDescriptor(true);
}
protected static LoanDescriptor mockLoanDescriptorWithoutCaptcha() {
return AbstractZonkyLeveragingTest.mockLoanDescriptor(false);
}
private static LoanDescriptor mockLoanDescriptor(final boolean withCaptcha) {
final MockLoanBuilder b = new MockLoanBuilder()
.setNonReservedRemainingInvestment(Integer.MAX_VALUE)
.setDatePublished(OffsetDateTime.now());
if (withCaptcha) {
System.setProperty(Settings.Key.CAPTCHA_DELAY_D.getName(), "120"); // enable CAPTCHA for the rating
b.setRating(Rating.D);
} else {
System.setProperty(Settings.Key.CAPTCHA_DELAY_AAAAA.getName(), "0"); // disable CAPTCHA for the rating
b.setRating(Rating.AAAAA);
}
return new LoanDescriptor(b.build());
}
}
| UTF-8 | Java | 2,631 | java | AbstractZonkyLeveragingTest.java | Java | [] | null | [] | /*
* Copyright 2019 The RoboZonky Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.robozonky.app;
import com.github.robozonky.api.remote.entities.MyInvestment;
import com.github.robozonky.api.remote.enums.Rating;
import com.github.robozonky.api.strategies.LoanDescriptor;
import com.github.robozonky.app.events.AbstractEventLeveragingTest;
import com.github.robozonky.internal.Settings;
import com.github.robozonky.test.mock.MockLoanBuilder;
import java.time.OffsetDateTime;
import java.util.Random;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public abstract class AbstractZonkyLeveragingTest extends AbstractEventLeveragingTest {
private static final Random RANDOM = new Random(0);
protected static MyInvestment mockMyInvestment() {
return mockMyInvestment(OffsetDateTime.now());
}
private static MyInvestment mockMyInvestment(final OffsetDateTime creationDate) {
final MyInvestment m = mock(MyInvestment.class);
when(m.getId()).thenReturn(RANDOM.nextLong());
when(m.getTimeCreated()).thenReturn(creationDate);
return m;
}
protected static LoanDescriptor mockLoanDescriptor() {
return AbstractZonkyLeveragingTest.mockLoanDescriptor(true);
}
protected static LoanDescriptor mockLoanDescriptorWithoutCaptcha() {
return AbstractZonkyLeveragingTest.mockLoanDescriptor(false);
}
private static LoanDescriptor mockLoanDescriptor(final boolean withCaptcha) {
final MockLoanBuilder b = new MockLoanBuilder()
.setNonReservedRemainingInvestment(Integer.MAX_VALUE)
.setDatePublished(OffsetDateTime.now());
if (withCaptcha) {
System.setProperty(Settings.Key.CAPTCHA_DELAY_D.getName(), "120"); // enable CAPTCHA for the rating
b.setRating(Rating.D);
} else {
System.setProperty(Settings.Key.CAPTCHA_DELAY_AAAAA.getName(), "0"); // disable CAPTCHA for the rating
b.setRating(Rating.AAAAA);
}
return new LoanDescriptor(b.build());
}
}
| 2,631 | 0.732041 | 0.7271 | 69 | 37.130436 | 30.800863 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.463768 | false | false | 2 |
d4b9e68c5cf676bccbf450a8e56989078ca94a3d | 22,643,067,644,718 | e3b2a6ea401ee7f9f5c1be96828527143f0a924e | /P2Cloud/src/main/java/movi/ui/fragment/SaveLiuliangFragment.java | 61e70c561257a6c4be60b29496a1c02a71a9f530 | [] | no_license | 1193708911/P2Cloud | https://github.com/1193708911/P2Cloud | f3862e83860e732a70d2e508cbdb127b542577ca | 97aa7e591d2493d6b6f7817188063b14299a7758 | refs/heads/master | 2020-03-23T21:13:17.762000 | 2018-07-24T01:58:36 | 2018-07-24T01:58:36 | 142,090,713 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package movi.ui.fragment;
import android.widget.TextView;
import com.ctvit.p2cloud.R;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import movi.base.BaseFragment;
import movi.base.Response;
import movi.ui.bean.NewsLiuLiangListBean;
import movi.net.biz.NewsSelectLiuLiangBiz;
import movi.net.config.ServerConfig;
import movi.net.request.NetCallBack;
import movi.utils.CommonUtils;
import movi.utils.ToastUtils;
/**
* Created by chjj on 2016/5/13.
*/
@ContentView(value = R.layout.home_saveliu)
public class SaveLiuliangFragment extends BaseFragment implements NetCallBack {
@ViewInject(value = R.id.txtMaxSaveLiuLiang)
private TextView txtMaxSaveLiuLiang;
@ViewInject(value = R.id.txtTimeSave)
private TextView txtTimeSave;
@ViewInject(value = R.id.txtTotalLiuLiang)
private TextView txtTotalLiuLiang;
@ViewInject(value = R.id.txtEffectTime)
private TextView txtEffectTime;
//使用期
@ViewInject(value = R.id.txtTime)
private TextView txtTime;
@Override
protected int getResource() {
return R.layout.home_saveliu;
}
@Override
protected void afterViews() {
super.afterViews();
sendGetLiuLiangRequest();
}
/**
* 獲取流量請求
*/
private void sendGetLiuLiangRequest() {
NewsSelectLiuLiangBiz biz=new NewsSelectLiuLiangBiz();
biz.setNetCallBack(this);
biz.requestSelectLiuLiang(ServerConfig.GET);
}
@Override
public void onSuccess(Response response) {
NewsLiuLiangListBean listBean= (NewsLiuLiangListBean) response;
NewsLiuLiangListBean.NewsLiuLiangBean bean=listBean.getData();
showResult(bean);
}
@Override
public void onFailure(Response error) {
ToastUtils.showToast(context,"数据请求失败");
}
private void showResult(NewsLiuLiangListBean.NewsLiuLiangBean bean) {
txtTotalLiuLiang.setText(CommonUtils.fromHtml("#1341DD", bean.getTraffic())+"GB");
txtTime.setText(bean.getCreated()+"到"+bean.getModified());
txtMaxSaveLiuLiang.setText(CommonUtils.fromHtml("#1341DD", bean.getStorage())+"TB");
txtTimeSave.setText(CommonUtils.fromHtml("#1341DD", bean.getStoragedate())+"GB");
txtEffectTime.setText(bean.getDatemark());
}
}
| UTF-8 | Java | 2,337 | java | SaveLiuliangFragment.java | Java | [
{
"context": ";\nimport movi.utils.ToastUtils;\n\n/**\n * Created by chjj on 2016/5/13.\n */\n@ContentView(value = R.layout.h",
"end": 481,
"score": 0.9995352029800415,
"start": 477,
"tag": "USERNAME",
"value": "chjj"
}
] | null | [] | package movi.ui.fragment;
import android.widget.TextView;
import com.ctvit.p2cloud.R;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import movi.base.BaseFragment;
import movi.base.Response;
import movi.ui.bean.NewsLiuLiangListBean;
import movi.net.biz.NewsSelectLiuLiangBiz;
import movi.net.config.ServerConfig;
import movi.net.request.NetCallBack;
import movi.utils.CommonUtils;
import movi.utils.ToastUtils;
/**
* Created by chjj on 2016/5/13.
*/
@ContentView(value = R.layout.home_saveliu)
public class SaveLiuliangFragment extends BaseFragment implements NetCallBack {
@ViewInject(value = R.id.txtMaxSaveLiuLiang)
private TextView txtMaxSaveLiuLiang;
@ViewInject(value = R.id.txtTimeSave)
private TextView txtTimeSave;
@ViewInject(value = R.id.txtTotalLiuLiang)
private TextView txtTotalLiuLiang;
@ViewInject(value = R.id.txtEffectTime)
private TextView txtEffectTime;
//使用期
@ViewInject(value = R.id.txtTime)
private TextView txtTime;
@Override
protected int getResource() {
return R.layout.home_saveliu;
}
@Override
protected void afterViews() {
super.afterViews();
sendGetLiuLiangRequest();
}
/**
* 獲取流量請求
*/
private void sendGetLiuLiangRequest() {
NewsSelectLiuLiangBiz biz=new NewsSelectLiuLiangBiz();
biz.setNetCallBack(this);
biz.requestSelectLiuLiang(ServerConfig.GET);
}
@Override
public void onSuccess(Response response) {
NewsLiuLiangListBean listBean= (NewsLiuLiangListBean) response;
NewsLiuLiangListBean.NewsLiuLiangBean bean=listBean.getData();
showResult(bean);
}
@Override
public void onFailure(Response error) {
ToastUtils.showToast(context,"数据请求失败");
}
private void showResult(NewsLiuLiangListBean.NewsLiuLiangBean bean) {
txtTotalLiuLiang.setText(CommonUtils.fromHtml("#1341DD", bean.getTraffic())+"GB");
txtTime.setText(bean.getCreated()+"到"+bean.getModified());
txtMaxSaveLiuLiang.setText(CommonUtils.fromHtml("#1341DD", bean.getStorage())+"TB");
txtTimeSave.setText(CommonUtils.fromHtml("#1341DD", bean.getStoragedate())+"GB");
txtEffectTime.setText(bean.getDatemark());
}
}
| 2,337 | 0.716269 | 0.707592 | 74 | 30.148649 | 24.117775 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
5fdf667d78ca9173bdf600b8453b785bbb012e7a | 27,668,179,379,605 | 38e15b9eba246a4c359022bc7d769f240487dbd7 | /java/PE002.java | 44d5274fff4e4d61629f99c44d8748ca2b5f78ef | [] | no_license | qianlongzju/project_euler | https://github.com/qianlongzju/project_euler | 8743a52ad4a9abe442eb59857f394e2d44648e14 | 1e840c2086b4c319e0efb54ac7b9ee8c2c179010 | refs/heads/master | 2021-05-30T07:56:31.386000 | 2015-03-17T10:58:30 | 2015-03-17T10:58:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class PE002 {
public static void main (String [] args)
{
int a = 2;
int b = 8;
int sum = a + b;
int c = 4*b + a;
while(c <= 4000000) {
sum += c;
a = b;
b = c;
c = 4*b + a;
}
System.out.println(sum);
}
}
| UTF-8 | Java | 326 | java | PE002.java | Java | [] | null | [] | public class PE002 {
public static void main (String [] args)
{
int a = 2;
int b = 8;
int sum = a + b;
int c = 4*b + a;
while(c <= 4000000) {
sum += c;
a = b;
b = c;
c = 4*b + a;
}
System.out.println(sum);
}
}
| 326 | 0.352761 | 0.309816 | 16 | 19.375 | 10.582267 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false | 2 |
94a68b81d6edf2bf6d126eee31c7787157f8fea3 | 5,394,478,983,365 | 58ae065b94fe5e9dd1a78391cf2b31d5a816daf3 | /springapp/src/main/java/com/mtc/app/service/IProductService.java | 604b75ecdfc52c73f6dd42a3c63b65c7f3d31f80 | [] | no_license | MounicaChanda0809/Java-spring | https://github.com/MounicaChanda0809/Java-spring | 9d69846a67c38e9c40a6396043d47fa74fdaafcd | 4860dd7de95401bcf064253175a0ced019923bb0 | refs/heads/master | 2020-04-15T04:20:33.049000 | 2019-01-07T05:23:17 | 2019-01-07T05:23:17 | 164,379,342 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mtc.app.service;
import com.mtc.app.vo.Order;
public interface IProductService {
boolean processOrder(Order order);
void printProducts();
void printOrders();
}
| UTF-8 | Java | 191 | java | IProductService.java | Java | [] | null | [] | package com.mtc.app.service;
import com.mtc.app.vo.Order;
public interface IProductService {
boolean processOrder(Order order);
void printProducts();
void printOrders();
}
| 191 | 0.712042 | 0.712042 | 11 | 15.363636 | 14.265488 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.818182 | false | false | 2 |
3727644fa7f7ed3e69b529737f75c12120d189f7 | 4,363,686,830,193 | c9380639346b4c29fa34278fee2cf3017c85c917 | /src/org/test/day8/Quest9.java | efc43e305e40df6e0d50829df202b5289591a432 | [] | no_license | raseemGit/Day-By-Day-Selenium-Tasks | https://github.com/raseemGit/Day-By-Day-Selenium-Tasks | 49198b823a48898866eefdd7b629a2bbee0583fe | 698989579587c910a8af877279533045ac4f7fe6 | refs/heads/master | 2020-06-28T13:48:41.680000 | 2019-08-02T14:09:39 | 2019-08-02T14:09:39 | 200,247,908 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.test.day8;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Quest9 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\WorkSpace\\Alerts\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://infinity.icicibank.com/corp/AuthenticationController?FORMSGROUP_ID__=AuthenticationFG&__START_TRAN_FLAG__=Y&FG_BUTTONS__=LOAD&ACTION.LOAD=Y&AuthenticationFG.LOGIN_FLAG=1&BANK_ID=ICI");
//*******************************************************************************************
Thread.sleep(3000);
WebElement userName= driver.findElement(By.xpath("(//input[@type='text'])[1]"));
userName.sendKeys("raseem66");
WebElement pass= driver.findElement(By.xpath("(//input[@type='password'])[4]"));
pass.sendKeys("raseem66");
}
}
| UTF-8 | Java | 1,007 | java | Quest9.java | Java | [
{
"context": "/input[@type='text'])[1]\"));\n\t\tuserName.sendKeys(\"raseem66\");\n\t\t\n\t\t\n\t\tWebElement pass= driver.findElement(By",
"end": 852,
"score": 0.9992993474006653,
"start": 844,
"tag": "USERNAME",
"value": "raseem66"
},
{
"context": "/input[@type='password'])[4]\"));\n\t\tpass.sendKeys(\"raseem66\");\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t}\n\n}\n",
"end": 970,
"score": 0.9986741542816162,
"start": 962,
"tag": "PASSWORD",
"value": "raseem66"
}
] | null | [] | package org.test.day8;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Quest9 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\WorkSpace\\Alerts\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://infinity.icicibank.com/corp/AuthenticationController?FORMSGROUP_ID__=AuthenticationFG&__START_TRAN_FLAG__=Y&FG_BUTTONS__=LOAD&ACTION.LOAD=Y&AuthenticationFG.LOGIN_FLAG=1&BANK_ID=ICI");
//*******************************************************************************************
Thread.sleep(3000);
WebElement userName= driver.findElement(By.xpath("(//input[@type='text'])[1]"));
userName.sendKeys("raseem66");
WebElement pass= driver.findElement(By.xpath("(//input[@type='password'])[4]"));
pass.sendKeys("<PASSWORD>");
}
}
| 1,009 | 0.657398 | 0.644489 | 32 | 30.46875 | 43.555988 | 206 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.75 | false | false | 2 |
7b2751309c119393e3092c9f96062264b495e0fa | 4,363,686,831,451 | 700fe309f2eff8063ee6acf51f5265b14ccdb7a5 | /DTW/CEPReader.java | 14986d39ae949f40adb17c81fd60d809049c2034 | [
"MIT"
] | permissive | MarkusZoppelt/speech-recognition | https://github.com/MarkusZoppelt/speech-recognition | 2d54c5935f31338b5593e03131ac993a6541cd97 | 4f04e097d7bed39945daab663e44b2e24ba48c71 | refs/heads/master | 2016-09-24T07:46:12.163000 | 2016-06-03T13:25:17 | 2016-06-03T13:25:17 | 51,914,607 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Constantin on 17.02.2016.
*/
@SuppressWarnings({"unused", "DefaultFileTemplate"})
class CEPReader {
public static float[] getVector(String fileName) {
byte[] bytes;
Path path = Paths.get(fileName);
try {
bytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new RuntimeException(fileName + " not found");
}
int start = 4 + 52 * ((int) Math.floor((double) (bytes.length - 4) / 104));
float[] result = new float[13];
byte[] tmp;
for (int i = 0; i < 13; i++) {
tmp = new byte[4];
tmp[3] = bytes[start];
tmp[2] = bytes[start + 1];
tmp[1] = bytes[start + 2];
tmp[0] = bytes[start + 3];
result[i] = bytesToFloat(tmp);
start += 4;
}
return result;
}
public static List<float[]> getAllVectors(String fileName) {
byte[] bytes;
List<float[]> features= new ArrayList<>();
Path path = Paths.get(fileName);
try {
bytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new RuntimeException(fileName + " not found");
}
byte[] anzahl = new byte[4];
anzahl[3] = bytes[0];
anzahl[2] = bytes[1];
anzahl[1] = bytes[2];
anzahl[0] = bytes[3];
int counter= bytesToInteger(anzahl);
counter/=13;
int start=4;
float[] result = new float[13];
byte[] tmp;
for (int j = 0; j < counter; j++) {
for (int i = 0; i < 13; i++) {
tmp = new byte[4];
tmp[3] = bytes[start];
tmp[2] = bytes[start + 1];
tmp[1] = bytes[start + 2];
tmp[0] = bytes[start + 3];
result[i] = bytesToFloat(tmp);
start += 4;
}
features.add(result.clone());
}
return features;
}
private static float bytesToFloat(byte[] bytes) {
return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();
}
private static int bytesToInteger(byte[] bytes) {
return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt();
}
}
| UTF-8 | Java | 2,220 | java | CEPReader.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Constantin on 17.02.2016.\n */\n@SuppressWarnings({\"unused\", \"",
"end": 246,
"score": 0.9990935325622559,
"start": 236,
"tag": "NAME",
"value": "Constantin"
}
] | null | [] | import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Constantin on 17.02.2016.
*/
@SuppressWarnings({"unused", "DefaultFileTemplate"})
class CEPReader {
public static float[] getVector(String fileName) {
byte[] bytes;
Path path = Paths.get(fileName);
try {
bytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new RuntimeException(fileName + " not found");
}
int start = 4 + 52 * ((int) Math.floor((double) (bytes.length - 4) / 104));
float[] result = new float[13];
byte[] tmp;
for (int i = 0; i < 13; i++) {
tmp = new byte[4];
tmp[3] = bytes[start];
tmp[2] = bytes[start + 1];
tmp[1] = bytes[start + 2];
tmp[0] = bytes[start + 3];
result[i] = bytesToFloat(tmp);
start += 4;
}
return result;
}
public static List<float[]> getAllVectors(String fileName) {
byte[] bytes;
List<float[]> features= new ArrayList<>();
Path path = Paths.get(fileName);
try {
bytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new RuntimeException(fileName + " not found");
}
byte[] anzahl = new byte[4];
anzahl[3] = bytes[0];
anzahl[2] = bytes[1];
anzahl[1] = bytes[2];
anzahl[0] = bytes[3];
int counter= bytesToInteger(anzahl);
counter/=13;
int start=4;
float[] result = new float[13];
byte[] tmp;
for (int j = 0; j < counter; j++) {
for (int i = 0; i < 13; i++) {
tmp = new byte[4];
tmp[3] = bytes[start];
tmp[2] = bytes[start + 1];
tmp[1] = bytes[start + 2];
tmp[0] = bytes[start + 3];
result[i] = bytesToFloat(tmp);
start += 4;
}
features.add(result.clone());
}
return features;
}
private static float bytesToFloat(byte[] bytes) {
return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();
}
private static int bytesToInteger(byte[] bytes) {
return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt();
}
}
| 2,220 | 0.59009 | 0.564865 | 88 | 24.227272 | 19.073259 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 2 |
0d7594ce822331524208a8659e601e6b81717167 | 27,608,049,844,495 | d8a379b6353e15356fb8897f969e2d340a3db1b3 | /app/src/main/java/com/tutoriales/messagequeuehandler/TaskThread.java | 2c50d1b1259a986c41c03fcb4e279f7b7beeeff8 | [] | no_license | swbvelasquez/MessageQueueHandler | https://github.com/swbvelasquez/MessageQueueHandler | 2ab50be2f77874494c5154485f04f08bc2084828 | 4f0ee93252707df22e1fc029f403ec69e545d25b | refs/heads/master | 2023-04-29T05:36:16.240000 | 2021-05-18T01:07:09 | 2021-05-18T01:07:09 | 368,362,641 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tutoriales.messagequeuehandler;
import android.os.SystemClock;
import android.util.Log;
public class TaskThread extends Thread{
private static final String TAG = "TaskThread";
private final ManagerMessageTask managerMessageTask;
public TaskThread(ManagerMessageTask managerMessageTask) {
this.managerMessageTask = managerMessageTask;
}
@Override
public synchronized void start() {
super.start();
Log.d(TAG, "start: ");
}
@Override
public void run() {
try{
for (int i = 0; i < 3; i++) {
Log.d(TAG, "run: " + i);
managerMessageTask.setResult(1000+i);
managerMessageTask.sendMessage(i);
SystemClock.sleep(3000);
}
Log.d(TAG, "run: finished");
}catch (Exception ex){
ex.printStackTrace();
}
}
@Override
public void interrupt() {
super.interrupt();
Log.d(TAG, "interrupt: ");
}
@Override
protected void finalize() throws Throwable {
super.finalize();
Log.d(TAG, "finalize: ");
}
}
| UTF-8 | Java | 1,141 | java | TaskThread.java | Java | [] | null | [] | package com.tutoriales.messagequeuehandler;
import android.os.SystemClock;
import android.util.Log;
public class TaskThread extends Thread{
private static final String TAG = "TaskThread";
private final ManagerMessageTask managerMessageTask;
public TaskThread(ManagerMessageTask managerMessageTask) {
this.managerMessageTask = managerMessageTask;
}
@Override
public synchronized void start() {
super.start();
Log.d(TAG, "start: ");
}
@Override
public void run() {
try{
for (int i = 0; i < 3; i++) {
Log.d(TAG, "run: " + i);
managerMessageTask.setResult(1000+i);
managerMessageTask.sendMessage(i);
SystemClock.sleep(3000);
}
Log.d(TAG, "run: finished");
}catch (Exception ex){
ex.printStackTrace();
}
}
@Override
public void interrupt() {
super.interrupt();
Log.d(TAG, "interrupt: ");
}
@Override
protected void finalize() throws Throwable {
super.finalize();
Log.d(TAG, "finalize: ");
}
}
| 1,141 | 0.579316 | 0.570552 | 47 | 23.276596 | 18.498652 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.531915 | false | false | 2 |
3dcb3665ab80cfedb426f65ff1f13efb133afdad | 1,984,274,890,760 | efb16fcec4c665d8d9e7b04d18235172182c2da6 | /src/main/java/com/yxr/NIO/TestBuffer.java | 8d8a271fb5c6c545811395602ef179468c107c4a | [] | no_license | baijianruoliorz/netty-learning | https://github.com/baijianruoliorz/netty-learning | 9cc8dea6e775991aa2995842fc73db508175a1d5 | 7d3b29294a4c101837fb807a4be8bd0dc4fc39ab | refs/heads/master | 2023-06-05T01:22:06.498000 | 2021-06-20T14:02:10 | 2021-06-20T14:02:10 | 373,076,564 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yxr.NIO;
import java.nio.IntBuffer;
public class TestBuffer {
public static void main(String[] args){
IntBuffer intBuffer = IntBuffer.allocate(10);
for (int i = 0; i < 10; i++) {
intBuffer.put(i);
}
intBuffer.flip();
while (intBuffer.hasRemaining()){
System.out.println(intBuffer.get());
}
}
}
| UTF-8 | Java | 388 | java | TestBuffer.java | Java | [] | null | [] | package com.yxr.NIO;
import java.nio.IntBuffer;
public class TestBuffer {
public static void main(String[] args){
IntBuffer intBuffer = IntBuffer.allocate(10);
for (int i = 0; i < 10; i++) {
intBuffer.put(i);
}
intBuffer.flip();
while (intBuffer.hasRemaining()){
System.out.println(intBuffer.get());
}
}
}
| 388 | 0.561856 | 0.548969 | 16 | 23.25 | 17.307875 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
7d44edf2a367750918f6be28ac6d82cc0db00ad4 | 14,568,529,071,476 | 6d7df5ce6a6580bc3f4085eb7446d9c1092c90cc | /example/src/main/java/com/latte/example/ExampleActivity.java | ce98ebd13f4f7c9bdc8b67f91fdca5119f2097f0 | [] | no_license | ywzrookie/MMall | https://github.com/ywzrookie/MMall | 145a1205a0f1b57d3c698e71b771952a6e59f84e | c2c4f0c1651fa004b56b16cc354b8bf4a91c843e | refs/heads/master | 2020-03-30T06:01:16.011000 | 2018-11-28T13:51:43 | 2018-11-28T13:51:43 | 150,833,968 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.latte.example;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.diabin.fastec.example.R;
import com.late.core.activities.ProxyActivity;
import com.late.core.app.Latte;
import com.late.core.fragments.LatteFragment;
import com.late.core.ui.launcher.ILauncherListener;
import com.late.core.ui.launcher.OnLauncherFinishTag;
import com.latte.ec.main.EcBottomFragment;
import launcher.LauncherDelegate;
import launcher.LauncherScrollDelegate;
import qiu.niorgai.StatusBarCompat;
import sign.ISignListener;
import sign.SignInFragment;
import sign.SignUpFragment;
public class ExampleActivity extends ProxyActivity implements
ISignListener,
ILauncherListener {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
Latte.getConfigurator().withActivity(this);
StatusBarCompat.translucentStatusBar(this, true);
}
@Override
public LatteFragment setRootDelegate() {
return new LauncherDelegate();
}
@Override
public void onSignInSuccess() {
Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onSignUpSuccess() {
Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onLauncherFinish(OnLauncherFinishTag tag) {
switch (tag) {
case SIGNED:
// Toast.makeText(this, "启动结束,用户登录", Toast.LENGTH_SHORT).show();
startWithPop(new EcBottomFragment());
break;
case NOT_SIGNED:
// Toast.makeText(this, "启动结束,用户没登录", Toast.LENGTH_SHORT).show();
startWithPop(new SignInFragment());
break;
default:
break;
}
}
}
| UTF-8 | Java | 2,150 | java | ExampleActivity.java | Java | [] | null | [] | package com.latte.example;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.diabin.fastec.example.R;
import com.late.core.activities.ProxyActivity;
import com.late.core.app.Latte;
import com.late.core.fragments.LatteFragment;
import com.late.core.ui.launcher.ILauncherListener;
import com.late.core.ui.launcher.OnLauncherFinishTag;
import com.latte.ec.main.EcBottomFragment;
import launcher.LauncherDelegate;
import launcher.LauncherScrollDelegate;
import qiu.niorgai.StatusBarCompat;
import sign.ISignListener;
import sign.SignInFragment;
import sign.SignUpFragment;
public class ExampleActivity extends ProxyActivity implements
ISignListener,
ILauncherListener {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
Latte.getConfigurator().withActivity(this);
StatusBarCompat.translucentStatusBar(this, true);
}
@Override
public LatteFragment setRootDelegate() {
return new LauncherDelegate();
}
@Override
public void onSignInSuccess() {
Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onSignUpSuccess() {
Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onLauncherFinish(OnLauncherFinishTag tag) {
switch (tag) {
case SIGNED:
// Toast.makeText(this, "启动结束,用户登录", Toast.LENGTH_SHORT).show();
startWithPop(new EcBottomFragment());
break;
case NOT_SIGNED:
// Toast.makeText(this, "启动结束,用户没登录", Toast.LENGTH_SHORT).show();
startWithPop(new SignInFragment());
break;
default:
break;
}
}
}
| 2,150 | 0.673187 | 0.672233 | 71 | 28.521128 | 21.402159 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619718 | false | false | 2 |
40eab3e3ed295339665fef57d70423aef7ea3651 | 21,801,254,052,520 | d434aac8ccf5578a345b78fad22b2670290189b8 | /app/src/main/java/bcx47/com/bcx47/view/EquilateralTriangleView.java | 1a3f3b2cae43fe8dd6df9f643ff6467cbaee88cd | [] | no_license | aoboturov/bcx47 | https://github.com/aoboturov/bcx47 | a703d46ff5bff64eeb10e062d6384030e9284441 | 31128d85c805dc6cd842dfa269277267e713eb0b | refs/heads/master | 2016-08-12T04:15:23.371000 | 2016-03-09T15:56:14 | 2016-03-09T15:56:20 | 53,422,426 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bcx47.com.bcx47.view;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.View;
public class EquilateralTriangleView extends View {
private int color = Color.BLUE;
private Point point = new Point(0, 0);
private int width = 100;
private Direction direction = Direction.EAST;
Paint trianglePaint = new Paint();
public EquilateralTriangleView setColor(int color) {
this.color = color;
return EquilateralTriangleView.this;
}
public EquilateralTriangleView setPoint(Point point) {
this.point = point;
return EquilateralTriangleView.this;
}
public EquilateralTriangleView setWidth(int width) {
this.width = width;
return EquilateralTriangleView.this;
}
public EquilateralTriangleView setDirection(Direction direction) {
this.direction = direction;
return EquilateralTriangleView.this;
}
public EquilateralTriangleView(Context context) {
super(context);
}
public EquilateralTriangleView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EquilateralTriangleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
trianglePaint.setStyle(Paint.Style.FILL);
trianglePaint.setColor(color);
Path trianglePath = getEquilateralTriangle(point, width, direction);
canvas.drawPath(trianglePath, trianglePaint);
}
private Path getEquilateralTriangle(Point p1, int width, Direction direction) {
Point p2 = null, p3 = null;
if (direction == Direction.NORTH) {
p2 = new Point(p1.x + width, p1.y);
p3 = new Point(p1.x + (width / 2), p1.y - width);
} else if (direction == Direction.SOUTH) {
p2 = new Point(p1.x + width, p1.y);
p3 = new Point(p1.x + (width / 2), p1.y + width);
} else if (direction == Direction.EAST) {
p2 = new Point(p1.x, p1.y + width);
p3 = new Point(p1.x - width, p1.y + (width / 2));
} else if (direction == Direction.WEST) {
p2 = new Point(p1.x, p1.y + width);
p3 = new Point(p1.x + width, p1.y + (width / 2));
}
Path path = new Path();
path.moveTo(p1.x, p1.y);
path.lineTo(p2.x, p2.y);
path.lineTo(p3.x, p3.y);
return path;
}
public enum Direction {
NORTH, SOUTH, EAST, WEST;
}
}
| UTF-8 | Java | 2,625 | java | EquilateralTriangleView.java | Java | [] | null | [] | package bcx47.com.bcx47.view;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.View;
public class EquilateralTriangleView extends View {
private int color = Color.BLUE;
private Point point = new Point(0, 0);
private int width = 100;
private Direction direction = Direction.EAST;
Paint trianglePaint = new Paint();
public EquilateralTriangleView setColor(int color) {
this.color = color;
return EquilateralTriangleView.this;
}
public EquilateralTriangleView setPoint(Point point) {
this.point = point;
return EquilateralTriangleView.this;
}
public EquilateralTriangleView setWidth(int width) {
this.width = width;
return EquilateralTriangleView.this;
}
public EquilateralTriangleView setDirection(Direction direction) {
this.direction = direction;
return EquilateralTriangleView.this;
}
public EquilateralTriangleView(Context context) {
super(context);
}
public EquilateralTriangleView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EquilateralTriangleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
trianglePaint.setStyle(Paint.Style.FILL);
trianglePaint.setColor(color);
Path trianglePath = getEquilateralTriangle(point, width, direction);
canvas.drawPath(trianglePath, trianglePaint);
}
private Path getEquilateralTriangle(Point p1, int width, Direction direction) {
Point p2 = null, p3 = null;
if (direction == Direction.NORTH) {
p2 = new Point(p1.x + width, p1.y);
p3 = new Point(p1.x + (width / 2), p1.y - width);
} else if (direction == Direction.SOUTH) {
p2 = new Point(p1.x + width, p1.y);
p3 = new Point(p1.x + (width / 2), p1.y + width);
} else if (direction == Direction.EAST) {
p2 = new Point(p1.x, p1.y + width);
p3 = new Point(p1.x - width, p1.y + (width / 2));
} else if (direction == Direction.WEST) {
p2 = new Point(p1.x, p1.y + width);
p3 = new Point(p1.x + width, p1.y + (width / 2));
}
Path path = new Path();
path.moveTo(p1.x, p1.y);
path.lineTo(p2.x, p2.y);
path.lineTo(p3.x, p3.y);
return path;
}
public enum Direction {
NORTH, SOUTH, EAST, WEST;
}
}
| 2,625 | 0.623238 | 0.605714 | 84 | 30.25 | 23.348742 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.809524 | false | false | 2 |
8e6f4a4f3b0cf03a261f937896b3044ca9c0e25e | 22,582,938,064,859 | 9686617158c88977a5dbdf5bed29fdf0605e66c5 | /src/main/java/com/chatroom/app/dao/authorities/AuthoritiesDAO.java | 202b2855f1fa678bb15cc583e1e42c34326d2c7a | [] | no_license | AaryaZemoso/Project-Chatroom | https://github.com/AaryaZemoso/Project-Chatroom | e58cd5ebd903747fb31694c09533922ae765525a | 971ac65e81a46ee4e33ac93db9265d6086ed14d9 | refs/heads/master | 2023-08-15T07:06:13.250000 | 2021-09-22T14:11:08 | 2021-09-22T14:11:08 | 406,645,441 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chatroom.app.dao.authorities;
import com.chatroom.app.entity.Authorities;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface AuthoritiesDAO {
List<Authorities> findByUsername(String username);
void save(Authorities a);
void delete(String username);
}
| UTF-8 | Java | 327 | java | AuthoritiesDAO.java | Java | [] | null | [] | package com.chatroom.app.dao.authorities;
import com.chatroom.app.entity.Authorities;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface AuthoritiesDAO {
List<Authorities> findByUsername(String username);
void save(Authorities a);
void delete(String username);
}
| 327 | 0.788991 | 0.788991 | 13 | 24.153847 | 19.154619 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 2 |
0366dad8bbeba50fce02632fdb3b784e65c13cf1 | 26,963,804,702,514 | 25c5aec674209083e290c40477e816d92fdaf4bc | /qhhhq-project/qhhhq-consumer/src/main/java/net/qhhhq/global/auth/AuthService.java | 699dab310ae2db9a1e69a59726f7a128660b82f2 | [] | no_license | qhhhq/java | https://github.com/qhhhq/java | 5f679880b102a2617f72b4d723fec0b6a9bcab16 | 5bd8c74c97c1b4afed5c691ab1e0f99f2124efac | refs/heads/master | 2018-07-11T08:11:52.952000 | 2018-06-01T08:03:05 | 2018-06-01T08:03:05 | 116,893,847 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.qhhhq.global.auth;
import net.qhhhq.global.auth.config.AuthServiceConfig;
import net.qhhhq.service.common.SysHead;
public interface AuthService {
public boolean doHandler(SysHead sysHead, AuthServiceConfig service);
}
| UTF-8 | Java | 234 | java | AuthService.java | Java | [] | null | [] | package net.qhhhq.global.auth;
import net.qhhhq.global.auth.config.AuthServiceConfig;
import net.qhhhq.service.common.SysHead;
public interface AuthService {
public boolean doHandler(SysHead sysHead, AuthServiceConfig service);
}
| 234 | 0.820513 | 0.820513 | 9 | 25 | 24.926559 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 2 |
f885a764b64008342fec56ea20399bffad3211d2 | 26,963,804,706,913 | b78ef22bb36307caad30fe5c30a82441e427282d | /java/tree/$116_PopulatingNextRightPointersInEachNode.java | 4880ba03eea2c1892e3d1962cc794bb8a0d6f2e3 | [] | no_license | xftzy/Leetcode-1 | https://github.com/xftzy/Leetcode-1 | f518a1b5e6e0d345d594632ab3434eed990c323b | 2c6afa849533ed839598c93b0670a189620178ed | refs/heads/master | 2020-07-10T13:42:15.487000 | 2019-08-25T08:56:09 | 2019-08-25T08:56:09 | 204,275,685 | 1 | 0 | null | true | 2019-08-25T09:54:08 | 2019-08-25T09:54:08 | 2019-08-25T08:56:24 | 2019-08-25T08:56:22 | 448 | 0 | 0 | 0 | null | false | false | /**
* 自顶向下,因为给出的是完美二叉树,所有的节点都是满的,于是,当前节点的左孩子的next为当前节点的右孩子,如果当前节点还有兄弟节点,
* 则当前节点有孩子的next节点为兄弟节点的左节点,如果当前节点没有兄弟节点则next指向Null
*/
public class $116_PopulatingNextRightPointersInEachNode {
public Node connect(Node root) {
if (root == null) return null;
//判断左孩子是否为null
if (root.left != null) {
//一定有右孩子
root.left.next = root.right;
//判断是否有兄弟节点
if (root.next != null) {
//右孩子的next为兄弟节点的左孩子
root.right.next = root.next.left;
}
}
//自顶向下
connect(root.left);
connect(root.right);
return root;
}
}
| UTF-8 | Java | 930 | java | $116_PopulatingNextRightPointersInEachNode.java | Java | [] | null | [] | /**
* 自顶向下,因为给出的是完美二叉树,所有的节点都是满的,于是,当前节点的左孩子的next为当前节点的右孩子,如果当前节点还有兄弟节点,
* 则当前节点有孩子的next节点为兄弟节点的左节点,如果当前节点没有兄弟节点则next指向Null
*/
public class $116_PopulatingNextRightPointersInEachNode {
public Node connect(Node root) {
if (root == null) return null;
//判断左孩子是否为null
if (root.left != null) {
//一定有右孩子
root.left.next = root.right;
//判断是否有兄弟节点
if (root.next != null) {
//右孩子的next为兄弟节点的左孩子
root.right.next = root.next.left;
}
}
//自顶向下
connect(root.left);
connect(root.right);
return root;
}
}
| 930 | 0.559633 | 0.555046 | 23 | 27.434782 | 17.939091 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.26087 | false | false | 2 |
72cc04761417e0eafca055e79a889f472699a211 | 2,757,369,005,421 | ff071c14b2faa76e9638c14bb23a94cb6edc80c4 | /hw01-0036518478/src/main/java/hr/fer/oprpp1/custom/collections/demo/Demo.java | 3f0d5cf4282d02ff7a046409e40bf7208d6f9718 | [] | no_license | mihaelrodek/OprppHomework | https://github.com/mihaelrodek/OprppHomework | 18aad01caa13923b808cde8714c91134a18f5652 | f6cf57519bd15c8a0153ffb9fe9c6990e2378c02 | refs/heads/main | 2023-06-10T07:04:59.608000 | 2021-07-02T23:37:50 | 2021-07-02T23:37:50 | 372,334,423 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hr.fer.oprpp1.custom.collections.demo;
import java.util.Arrays;
import hr.fer.oprpp1.custom.collections.ArrayIndexedCollection;
import hr.fer.oprpp1.custom.collections.LinkedListIndexedCollection;
import hr.fer.oprpp1.custom.collections.Processor;
/**
* Demo class that demonstrates usage of {@link ArrayIndexedCollection} and
* {@link LinkedListIndexedCollection}. Commented lines represent expected
* return. Demo cases are taken from task documentation.
*
* @author Mihael Rodek
*
*/
public class Demo {
/**
* Main method that starts the program.
*
*/
public static void main(String[] args) {
ArrayIndexedCollection col = new ArrayIndexedCollection(2);
col.add(Integer.valueOf(20));
col.add("New York");
col.add("San Francisco"); // here the internal array is reallocated to 4
System.out.println(col.contains("New York")); // writes: true
col.remove(1); // removes "New York"; shifts "San Francisco" to position
// 1
System.out.println(col.get(1)); // writes: "San Francisco"
System.out.println(col.size()); // writes: 2
col.add("Los Angeles");
LinkedListIndexedCollection col2 = new LinkedListIndexedCollection(col);
class P extends Processor {
public void process(Object o) {
System.out.println(o);
}
}
;
System.out.println("col1 elements:");
// 20
// San Francisco
// Los Angeles
col.forEach(new P());
System.out.println("col1 elements again:");// [20, San Francisco, Los Angeles]
System.out.println(Arrays.toString(col.toArray()));
System.out.println("col2 elements:");
// 20
// San Francisco
// Los Angeles
col2.forEach(new P());
System.out.println("col2 elements again:");// [20, San Francisco, Los Angeles]
System.out.println(Arrays.toString(col2.toArray()));
System.out.println(col.contains(col2.get(1))); // true
System.out.println(col2.contains(col.get(1))); // true
col.remove(Integer.valueOf(20));
System.out.println(col.contains(20)); // false
}
}
| UTF-8 | Java | 1,973 | java | Demo.java | Java | [
{
"context": " are taken from task documentation.\n * \n * @author Mihael Rodek\n *\n */\npublic class Demo {\n\t\n\t/**\n\t * Main method",
"end": 498,
"score": 0.9998939633369446,
"start": 486,
"tag": "NAME",
"value": "Mihael Rodek"
}
] | null | [] | package hr.fer.oprpp1.custom.collections.demo;
import java.util.Arrays;
import hr.fer.oprpp1.custom.collections.ArrayIndexedCollection;
import hr.fer.oprpp1.custom.collections.LinkedListIndexedCollection;
import hr.fer.oprpp1.custom.collections.Processor;
/**
* Demo class that demonstrates usage of {@link ArrayIndexedCollection} and
* {@link LinkedListIndexedCollection}. Commented lines represent expected
* return. Demo cases are taken from task documentation.
*
* @author <NAME>
*
*/
public class Demo {
/**
* Main method that starts the program.
*
*/
public static void main(String[] args) {
ArrayIndexedCollection col = new ArrayIndexedCollection(2);
col.add(Integer.valueOf(20));
col.add("New York");
col.add("San Francisco"); // here the internal array is reallocated to 4
System.out.println(col.contains("New York")); // writes: true
col.remove(1); // removes "New York"; shifts "San Francisco" to position
// 1
System.out.println(col.get(1)); // writes: "San Francisco"
System.out.println(col.size()); // writes: 2
col.add("Los Angeles");
LinkedListIndexedCollection col2 = new LinkedListIndexedCollection(col);
class P extends Processor {
public void process(Object o) {
System.out.println(o);
}
}
;
System.out.println("col1 elements:");
// 20
// San Francisco
// Los Angeles
col.forEach(new P());
System.out.println("col1 elements again:");// [20, San Francisco, Los Angeles]
System.out.println(Arrays.toString(col.toArray()));
System.out.println("col2 elements:");
// 20
// San Francisco
// Los Angeles
col2.forEach(new P());
System.out.println("col2 elements again:");// [20, San Francisco, Los Angeles]
System.out.println(Arrays.toString(col2.toArray()));
System.out.println(col.contains(col2.get(1))); // true
System.out.println(col2.contains(col.get(1))); // true
col.remove(Integer.valueOf(20));
System.out.println(col.contains(20)); // false
}
}
| 1,967 | 0.706538 | 0.688799 | 64 | 29.828125 | 26.114265 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.796875 | false | false | 2 |
473c055659692b853f00fe0aecb0de9d8f847c6c | 10,033,043,657,453 | 75eda2482b8c91ea543ecda0e778c12e598d6b4f | /src/main/java/com/hegongshan/mooc/controller/admin/BasicAdminController.java | 3e589984264ad3dfab9d957f1b37fc75c8731f2f | [] | no_license | hegongshan/mooc | https://github.com/hegongshan/mooc | b86546a9680bda823fa604a11a48cf570797ab28 | 9ca3eefd480486113e0c73bae54e525a4e0701c7 | refs/heads/master | 2020-03-22T20:03:15.045000 | 2018-07-11T12:09:54 | 2018-07-11T12:09:54 | 140,558,734 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hegongshan.mooc.controller.admin;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.hegongshan.mooc.entity.Admin;
import com.hegongshan.mooc.service.IAdminService;
import com.hegongshan.mooc.util.CryptographyUtils;
import com.hegongshan.mooc.util.FileUtils;
@Controller
@RequestMapping("/admin")
public class BasicAdminController {
private static Logger logger = LoggerFactory.getLogger(BasicAdminController.class);
@Resource
private IAdminService adminService;
//管理员登录
@RequestMapping("")
public ModelAndView toLoginPage(ModelAndView mv) {
mv.setViewName("/admin/login");
return mv;
}
@RequestMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpServletRequest request) {
String realPassword = CryptographyUtils.encryptByMd5(password, username);
Admin admin = new Admin(username,realPassword);
Admin resultAdmin = adminService.getAdminByUsernameAndPassword(admin);
if(resultAdmin == null) {
request.setAttribute("resultAdmin", resultAdmin);
request.setAttribute("errorMsg", "用户名或密码错误");
return "/admin/login";
} else {
request.getSession().setAttribute("currentAdmin", resultAdmin);
return "/admin/index";
}
}
@RequestMapping("/index")
public ModelAndView toHomePage(ModelAndView mv) {
mv.setViewName("/admin/index");
return mv;
}
@RequestMapping("/info")
public String updateAdminInfo(@RequestParam(value="image",required=false) MultipartFile image,
@RequestParam(value="nickname",required=false) String nickname,
HttpServletRequest request) {
Admin currentAdmin = (Admin) request.getSession().getAttribute("currentAdmin");
if(image == null && nickname == null) {
request.setAttribute("mainPage", "/WEB-INF/jsp/admin/center/admin_info.jsp");
} else {
Admin admin = new Admin();
admin.setAdminId(currentAdmin.getAdminId());
if(!image.isEmpty()) {
try {
String relativeFilePath = FileUtils.uploadImage(image);
admin.setImageSrc(relativeFilePath);
} catch (IllegalStateException | IOException e) {
logger.error("fail:upload image",e);
}
}
if(nickname != null) {
admin.setNickname(nickname);
}
adminService.updateAdmin(admin);
Admin resultAdmin = adminService.getAdminById(currentAdmin.getAdminId());
if(resultAdmin != null) {
request.getSession().removeAttribute("currentAdmin");
request.getSession().setAttribute("currentAdmin", resultAdmin);
request.setAttribute("mainPage", "/WEB-INF/jsp/admin/center/admin_info.jsp");
}
}
return "/admin/index";
}
@RequestMapping("/updatepwd")
public ModelAndView toUpdatePasswordPage(@RequestParam(value="password",required=false) String password,ModelAndView mav,HttpSession session) {
if(password != null) {
Admin admin = new Admin();
Admin currentAdmin = (Admin) session.getAttribute("currentAdmin");
String encryptPassword = CryptographyUtils.encryptByMd5(password,currentAdmin.getUsername());
admin.setAdminId(currentAdmin.getAdminId());
admin.setPassword(encryptPassword);
adminService.updateAdmin(admin);
} else {
mav.addObject("mainPage", "/WEB-INF/jsp/admin/center/updatepwd.jsp");
}
mav.setViewName("/admin/index");
return mav;
}
@RequestMapping("/logout")
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/index";
}
} | UTF-8 | Java | 4,013 | java | BasicAdminController.java | Java | [] | null | [] | package com.hegongshan.mooc.controller.admin;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.hegongshan.mooc.entity.Admin;
import com.hegongshan.mooc.service.IAdminService;
import com.hegongshan.mooc.util.CryptographyUtils;
import com.hegongshan.mooc.util.FileUtils;
@Controller
@RequestMapping("/admin")
public class BasicAdminController {
private static Logger logger = LoggerFactory.getLogger(BasicAdminController.class);
@Resource
private IAdminService adminService;
//管理员登录
@RequestMapping("")
public ModelAndView toLoginPage(ModelAndView mv) {
mv.setViewName("/admin/login");
return mv;
}
@RequestMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpServletRequest request) {
String realPassword = CryptographyUtils.encryptByMd5(password, username);
Admin admin = new Admin(username,realPassword);
Admin resultAdmin = adminService.getAdminByUsernameAndPassword(admin);
if(resultAdmin == null) {
request.setAttribute("resultAdmin", resultAdmin);
request.setAttribute("errorMsg", "用户名或密码错误");
return "/admin/login";
} else {
request.getSession().setAttribute("currentAdmin", resultAdmin);
return "/admin/index";
}
}
@RequestMapping("/index")
public ModelAndView toHomePage(ModelAndView mv) {
mv.setViewName("/admin/index");
return mv;
}
@RequestMapping("/info")
public String updateAdminInfo(@RequestParam(value="image",required=false) MultipartFile image,
@RequestParam(value="nickname",required=false) String nickname,
HttpServletRequest request) {
Admin currentAdmin = (Admin) request.getSession().getAttribute("currentAdmin");
if(image == null && nickname == null) {
request.setAttribute("mainPage", "/WEB-INF/jsp/admin/center/admin_info.jsp");
} else {
Admin admin = new Admin();
admin.setAdminId(currentAdmin.getAdminId());
if(!image.isEmpty()) {
try {
String relativeFilePath = FileUtils.uploadImage(image);
admin.setImageSrc(relativeFilePath);
} catch (IllegalStateException | IOException e) {
logger.error("fail:upload image",e);
}
}
if(nickname != null) {
admin.setNickname(nickname);
}
adminService.updateAdmin(admin);
Admin resultAdmin = adminService.getAdminById(currentAdmin.getAdminId());
if(resultAdmin != null) {
request.getSession().removeAttribute("currentAdmin");
request.getSession().setAttribute("currentAdmin", resultAdmin);
request.setAttribute("mainPage", "/WEB-INF/jsp/admin/center/admin_info.jsp");
}
}
return "/admin/index";
}
@RequestMapping("/updatepwd")
public ModelAndView toUpdatePasswordPage(@RequestParam(value="password",required=false) String password,ModelAndView mav,HttpSession session) {
if(password != null) {
Admin admin = new Admin();
Admin currentAdmin = (Admin) session.getAttribute("currentAdmin");
String encryptPassword = CryptographyUtils.encryptByMd5(password,currentAdmin.getUsername());
admin.setAdminId(currentAdmin.getAdminId());
admin.setPassword(encryptPassword);
adminService.updateAdmin(admin);
} else {
mav.addObject("mainPage", "/WEB-INF/jsp/admin/center/updatepwd.jsp");
}
mav.setViewName("/admin/index");
return mav;
}
@RequestMapping("/logout")
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/index";
}
} | 4,013 | 0.724856 | 0.723853 | 115 | 32.686958 | 27.016699 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.547826 | false | false | 2 |
308ab38e3b59b8f8be465650095717cb0d9ece47 | 20,736,102,167,275 | a8eb13e507d8c3c0bbf515dc757dd12d5b86c6c1 | /aimxcel-common/src/main/java/com/aimxcel/abclearn/common/aimxcelcommon/model/clock/ZAbstractClockTester.java | ee6081170580fe6c95989bda2f7f4c94ece62ae8 | [] | no_license | venkat-thota/java-simulations | https://github.com/venkat-thota/java-simulations | 41bb30375c1a2dedff1e1d64fade90c0ab2eac6a | d4c94d9cc84c9ee57c7b541843f8235352726f5e | refs/heads/master | 2020-12-04T01:33:55.211000 | 2020-01-24T16:26:12 | 2020-01-24T16:26:12 | 231,548,090 | 0 | 0 | null | false | 2020-10-13T18:37:51 | 2020-01-03T08:47:26 | 2020-01-24T16:26:21 | 2020-10-13T18:37:50 | 67,751 | 0 | 0 | 4 | Java | false | false |
package com.aimxcel.abclearn.common.aimxcelcommon.model.clock;
import junit.framework.TestCase;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.aimxcel.abclearn.common.aimxcelcommon.model.clock.Clock;
import com.aimxcel.abclearn.common.aimxcelcommon.model.clock.ClockEvent;
import com.aimxcel.abclearn.common.aimxcelcommon.model.clock.ClockListener;
import com.aimxcel.abclearn.common.aimxcelcommon.model.clock.ZAbstractClockTester;
public class ZAbstractClockTester extends TestCase {
public static interface ClockFactory {
Clock createInstance( int defaultDelay, double v );
}
private static final int DEFAULT_DELAY = 10;
private volatile Clock threadClock;
private volatile MockClockListener clockListener;
private final ClockFactory factory;
public ZAbstractClockTester( ZAbstractClockTester.ClockFactory factory ) {
this.factory = factory;
}
public void setUp() {
this.clockListener = new MockClockListener();
this.threadClock = factory.createInstance( DEFAULT_DELAY, 1.0 );
this.threadClock.addClockListener( clockListener );
threadClock.start();
}
public void tearDown() {
this.threadClock.stop();
}
public void testThatClockListenerInvokedAtRegularIntervals() throws InterruptedException {
while ( clockListener.ticked < 4 ) {
Thread.yield();
}
}
public void testThatClockListenerInvokedAtSpecifiedIntervals() throws InterruptedException {
double averageDelay = getAverageDelayBetweenTicks( 100 );
System.out.println( "average delay = " + averageDelay );
assertEquals( DEFAULT_DELAY, averageDelay, 2 );
}
public void testThatTicksAreCoalescedWhenListenerTakesMoreTimeThanDelay() {
clockListener.maxDelay = DEFAULT_DELAY + DEFAULT_DELAY / 2;
double averageDelay = getAverageDelayBetweenTicks( 100 );
assertEquals( 15.0, averageDelay, 2 );
}
public void testThatSwingRunnablesAreProcessedWhenListenerTakesMoreTimeThanDelay() {
clockListener.maxDelay = DEFAULT_DELAY + DEFAULT_DELAY / 2;
while ( clockListener.ticked < 1 ) {
Thread.yield();
}
final boolean[] invoked = new boolean[] { false };
SwingUtilities.invokeLater( new Runnable() {
public void run() {
invoked[0] = true;
}
} );
long start = System.currentTimeMillis();
while ( !invoked[0] ) {
Thread.yield();
if ( System.currentTimeMillis() - start > 500 ) {
assertFalse( false );
}
}
}
public void testThatInputEventsAreProcessedWhenListenerTakesMoreTimeThanDelay() throws AWTException {
JFrame frame = new JFrame();
frame.setSize( 100, 100 );
frame.setLocation( 0, 0 );
JButton button = new JButton();
button.setSize( 100, 100 );
frame.setContentPane( button );
frame.setSize( 200, 200 );
frame.setVisible( true );
Robot robot = new Robot();
clockListener.maxDelay = DEFAULT_DELAY + DEFAULT_DELAY / 2;
while ( clockListener.ticked < 1 ) {
Thread.yield();
}
final boolean[] invoked = new boolean[] { false };
button.addChangeListener( new ChangeListener() {
public void stateChanged( ChangeEvent changeEvent ) {
invoked[0] = true;
}
} );
robot.mouseMove( 50, 60 );
robot.mousePress( InputEvent.BUTTON1_MASK );
long start = System.currentTimeMillis();
while ( !invoked[0] ) {
Thread.yield();
if ( System.currentTimeMillis() - start > 500 ) {
assertFalse( false );
}
}
robot.mouseRelease( InputEvent.BUTTON1_MASK );
}
private double getAverageDelayBetweenTicks( int maxTicks ) {
long start = System.currentTimeMillis();
while ( clockListener.ticked < maxTicks ) {
Thread.yield();
}
threadClock.stop();
long end = System.currentTimeMillis();
return ( end - start ) / (double) clockListener.ticked;
}
private static class MockClockListener implements ClockListener {
int ticked = 0;
int maxDelay = 0;
public void clockTicked( ClockEvent clockEvent ) {
if ( maxDelay > 0 ) {
try {
Thread.sleep( maxDelay );
}
catch ( InterruptedException e ) {
}
}
++ticked;
}
public void clockStarted( ClockEvent clockEvent ) {
}
public void clockPaused( ClockEvent clockEvent ) {
}
public void simulationTimeChanged( ClockEvent clockEvent ) {
}
public void simulationTimeReset( ClockEvent clockEvent ) {
}
}
}
| UTF-8 | Java | 5,183 | java | ZAbstractClockTester.java | Java | [] | null | [] |
package com.aimxcel.abclearn.common.aimxcelcommon.model.clock;
import junit.framework.TestCase;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.aimxcel.abclearn.common.aimxcelcommon.model.clock.Clock;
import com.aimxcel.abclearn.common.aimxcelcommon.model.clock.ClockEvent;
import com.aimxcel.abclearn.common.aimxcelcommon.model.clock.ClockListener;
import com.aimxcel.abclearn.common.aimxcelcommon.model.clock.ZAbstractClockTester;
public class ZAbstractClockTester extends TestCase {
public static interface ClockFactory {
Clock createInstance( int defaultDelay, double v );
}
private static final int DEFAULT_DELAY = 10;
private volatile Clock threadClock;
private volatile MockClockListener clockListener;
private final ClockFactory factory;
public ZAbstractClockTester( ZAbstractClockTester.ClockFactory factory ) {
this.factory = factory;
}
public void setUp() {
this.clockListener = new MockClockListener();
this.threadClock = factory.createInstance( DEFAULT_DELAY, 1.0 );
this.threadClock.addClockListener( clockListener );
threadClock.start();
}
public void tearDown() {
this.threadClock.stop();
}
public void testThatClockListenerInvokedAtRegularIntervals() throws InterruptedException {
while ( clockListener.ticked < 4 ) {
Thread.yield();
}
}
public void testThatClockListenerInvokedAtSpecifiedIntervals() throws InterruptedException {
double averageDelay = getAverageDelayBetweenTicks( 100 );
System.out.println( "average delay = " + averageDelay );
assertEquals( DEFAULT_DELAY, averageDelay, 2 );
}
public void testThatTicksAreCoalescedWhenListenerTakesMoreTimeThanDelay() {
clockListener.maxDelay = DEFAULT_DELAY + DEFAULT_DELAY / 2;
double averageDelay = getAverageDelayBetweenTicks( 100 );
assertEquals( 15.0, averageDelay, 2 );
}
public void testThatSwingRunnablesAreProcessedWhenListenerTakesMoreTimeThanDelay() {
clockListener.maxDelay = DEFAULT_DELAY + DEFAULT_DELAY / 2;
while ( clockListener.ticked < 1 ) {
Thread.yield();
}
final boolean[] invoked = new boolean[] { false };
SwingUtilities.invokeLater( new Runnable() {
public void run() {
invoked[0] = true;
}
} );
long start = System.currentTimeMillis();
while ( !invoked[0] ) {
Thread.yield();
if ( System.currentTimeMillis() - start > 500 ) {
assertFalse( false );
}
}
}
public void testThatInputEventsAreProcessedWhenListenerTakesMoreTimeThanDelay() throws AWTException {
JFrame frame = new JFrame();
frame.setSize( 100, 100 );
frame.setLocation( 0, 0 );
JButton button = new JButton();
button.setSize( 100, 100 );
frame.setContentPane( button );
frame.setSize( 200, 200 );
frame.setVisible( true );
Robot robot = new Robot();
clockListener.maxDelay = DEFAULT_DELAY + DEFAULT_DELAY / 2;
while ( clockListener.ticked < 1 ) {
Thread.yield();
}
final boolean[] invoked = new boolean[] { false };
button.addChangeListener( new ChangeListener() {
public void stateChanged( ChangeEvent changeEvent ) {
invoked[0] = true;
}
} );
robot.mouseMove( 50, 60 );
robot.mousePress( InputEvent.BUTTON1_MASK );
long start = System.currentTimeMillis();
while ( !invoked[0] ) {
Thread.yield();
if ( System.currentTimeMillis() - start > 500 ) {
assertFalse( false );
}
}
robot.mouseRelease( InputEvent.BUTTON1_MASK );
}
private double getAverageDelayBetweenTicks( int maxTicks ) {
long start = System.currentTimeMillis();
while ( clockListener.ticked < maxTicks ) {
Thread.yield();
}
threadClock.stop();
long end = System.currentTimeMillis();
return ( end - start ) / (double) clockListener.ticked;
}
private static class MockClockListener implements ClockListener {
int ticked = 0;
int maxDelay = 0;
public void clockTicked( ClockEvent clockEvent ) {
if ( maxDelay > 0 ) {
try {
Thread.sleep( maxDelay );
}
catch ( InterruptedException e ) {
}
}
++ticked;
}
public void clockStarted( ClockEvent clockEvent ) {
}
public void clockPaused( ClockEvent clockEvent ) {
}
public void simulationTimeChanged( ClockEvent clockEvent ) {
}
public void simulationTimeReset( ClockEvent clockEvent ) {
}
}
}
| 5,183 | 0.624349 | 0.612773 | 180 | 27.783333 | 26.167044 | 105 | false | false | 0 | 0 | 0 | 0 | 68 | 0.025661 | 0.444444 | false | false | 2 |
3599a23cc43b83013563255a066884be5b9cf048 | 20,109,036,933,148 | a78780580d09856c612483c699be320271aaf1fb | /dagger2/src/main/java/didag2/example/Main.java | 486883bb0859f70cdc734d3d506e984d3ecd50ca | [] | no_license | Dirgningrid/dagger2inject | https://github.com/Dirgningrid/dagger2inject | e217cb2bc2f5251b86c340f4b7de9865dbd41336 | 28c8d9ec0d289906ecbbd82a0b2a595d457d8d48 | refs/heads/master | 2020-12-30T14:20:42.365000 | 2017-05-25T22:12:46 | 2017-05-25T22:12:46 | 91,315,297 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package didag2.example;
import didag2.example.dagger.DaggerPopBandComponent;
import didag2.example.dagger.DaggerRockBandComponent;
import didag2.example.dagger.PopBandComponent;
import didag2.example.dagger.RockBandComponent;
import didag2.example.musicians.Guitarist;
import didag2.example.musicians.Singer;
/**
* Created by ingrid on 14/05/17.
*/
public class Main {
public static void main(String[] args) {
String weWillRockYou;
String weWillPopYou;
RockBandComponent rockComponent =
DaggerRockBandComponent
.builder()
.build();
PopBandComponent popComponent =
DaggerPopBandComponent
.builder()
.build();
DepositoGiordani rock = rockComponent.injectDeposito();
weWillRockYou = rock.hiresRockBand();
System.out.println(weWillRockYou);
DepositoGiordani pop = popComponent.injectDeposito();
weWillPopYou = pop.hiresPopBand();
System.out.println(weWillPopYou);
}
}
| UTF-8 | Java | 1,062 | java | Main.java | Java | [
{
"context": "idag2.example.musicians.Singer;\n\n/**\n * Created by ingrid on 14/05/17.\n */\npublic class Main {\n\n public ",
"end": 335,
"score": 0.9993828535079956,
"start": 329,
"tag": "USERNAME",
"value": "ingrid"
}
] | null | [] | package didag2.example;
import didag2.example.dagger.DaggerPopBandComponent;
import didag2.example.dagger.DaggerRockBandComponent;
import didag2.example.dagger.PopBandComponent;
import didag2.example.dagger.RockBandComponent;
import didag2.example.musicians.Guitarist;
import didag2.example.musicians.Singer;
/**
* Created by ingrid on 14/05/17.
*/
public class Main {
public static void main(String[] args) {
String weWillRockYou;
String weWillPopYou;
RockBandComponent rockComponent =
DaggerRockBandComponent
.builder()
.build();
PopBandComponent popComponent =
DaggerPopBandComponent
.builder()
.build();
DepositoGiordani rock = rockComponent.injectDeposito();
weWillRockYou = rock.hiresRockBand();
System.out.println(weWillRockYou);
DepositoGiordani pop = popComponent.injectDeposito();
weWillPopYou = pop.hiresPopBand();
System.out.println(weWillPopYou);
}
}
| 1,062 | 0.665725 | 0.653484 | 42 | 24.285715 | 20.487261 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.404762 | false | false | 2 |
71d92a1a5822ab551f1360cc76687df0a58eb607 | 21,388,937,165,703 | b6c4e3aad4d974bcc31b7a1ea3fca2b7a173c9f2 | /src/main/java/bam/algorithms/alt/new_variational/GaussianDensity.java | 4457c0f0486a2d7b58a8dde9f6c4e541000209f8 | [] | no_license | rtloftin/discrete_bam | https://github.com/rtloftin/discrete_bam | af6b7e0f2b5d92008eb122fe7704f478178e0ed1 | 56159c3b0f1991a999df4c17799a842fa86cdf43 | refs/heads/master | 2022-09-02T18:20:24.432000 | 2019-08-03T14:29:06 | 2019-08-03T14:29:06 | 120,841,340 | 1 | 0 | null | false | 2022-08-18T19:05:29 | 2018-02-09T01:42:42 | 2019-08-08T05:19:41 | 2022-08-18T19:05:26 | 389 | 1 | 0 | 2 | Java | false | false | package bam.algorithms.alt.new_variational;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* A variational model of a gaussian density.
*/
public class GaussianDensity implements Density {
public static class Builder {
// Number of samples to generate
private int num_samples = 1;
// Don't update variance
private boolean fixed_variance = true;
// Prior distribution
private double prior_mean = 0.0;
private double prior_deviation = 1.0;
private Builder() {}
public Builder numSamples(int num_samples) {
this.num_samples = num_samples;
return this;
}
public Builder fixedVariance(boolean fixed_variance) {
this.fixed_variance = fixed_variance;
return this;
}
public Builder priorMean(double prior_mean) {
this.prior_mean = prior_mean;
return this;
}
public Builder priorDeviation(double prior_deviation) {
this.prior_deviation = prior_deviation;
return this;
}
public GaussianDensity build() {
return new GaussianDensity(this);
}
}
public static Builder builder() {
return new Builder();
}
// Sampling method
private final int num_samples;
private final boolean fixed_variance;
private final double prior_mean;
private final double prior_deviation;
private GaussianDensity(Builder config) {
this.num_samples = config.num_samples;
this.fixed_variance = config.fixed_variance;
this.prior_mean = config.prior_mean;
this.prior_deviation = config.prior_deviation;
}
@Override
public int numParameters(int dimensions) {
return 2 * dimensions;
}
@Override
public void initialize(double[] parameters) {
int dimensions = parameters.length / 2;
for(int i=0; i < dimensions; ++i) {
parameters[i] = prior_mean;
parameters[i + dimensions] = prior_deviation;
}
}
@Override
public List<? extends Sample> sample(double[] parameters, Random random) {
List<Sample> samples = new ArrayList<>(num_samples);
int dimensions = parameters.length / 2;
for(int sample = 0; sample < num_samples; ++sample) {
double[] input = new double[dimensions];
double[] output = new double[dimensions];
for(int i=0; i < dimensions; ++i) {
input[i] = random.nextGaussian();
output[i] = (parameters[i + dimensions] * input[i]) + parameters[i];
}
samples.add(new Sample() {
@Override
public double[] value() {
return output;
}
@Override
public void gradient(double[] weights, double[] gradient) {
for(int i=0; i < dimensions; ++i) {
gradient[i] += weights[i];
if(!fixed_variance)
gradient[i + dimensions] += weights[i] * input[i];
}
}
});
}
return samples;
}
@Override
public void regularize(double[] parameters, double[] gradient, double weight) {
int dimensions = parameters.length / 2;
double variance = prior_deviation * prior_deviation;
for(int i=0; i < dimensions; ++i) {
gradient[i] += weight * (prior_mean - parameters[i]) / variance;
if(!fixed_variance) {
double deviation = parameters[i + dimensions];
gradient[i + dimensions] += weight * ((1.0 / deviation) - (deviation / variance));
}
}
}
@Override
public double[] mean(double[] parameters) {
int dimensions = parameters.length / 2;
double[] mean = new double[dimensions];
System.arraycopy(parameters, 0, mean, 0, dimensions);
return mean;
}
@Override
public String name() {
return "Gaussian Distribution";
}
@Override
public JSONObject serialize() throws JSONException {
return new JSONObject()
.put("name", name())
.put("num samples", num_samples)
.put("fixed variance", fixed_variance)
.put("prior mean", prior_mean)
.put("prior deviation", prior_deviation);
}
}
| UTF-8 | Java | 4,598 | java | GaussianDensity.java | Java | [] | null | [] | package bam.algorithms.alt.new_variational;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* A variational model of a gaussian density.
*/
public class GaussianDensity implements Density {
public static class Builder {
// Number of samples to generate
private int num_samples = 1;
// Don't update variance
private boolean fixed_variance = true;
// Prior distribution
private double prior_mean = 0.0;
private double prior_deviation = 1.0;
private Builder() {}
public Builder numSamples(int num_samples) {
this.num_samples = num_samples;
return this;
}
public Builder fixedVariance(boolean fixed_variance) {
this.fixed_variance = fixed_variance;
return this;
}
public Builder priorMean(double prior_mean) {
this.prior_mean = prior_mean;
return this;
}
public Builder priorDeviation(double prior_deviation) {
this.prior_deviation = prior_deviation;
return this;
}
public GaussianDensity build() {
return new GaussianDensity(this);
}
}
public static Builder builder() {
return new Builder();
}
// Sampling method
private final int num_samples;
private final boolean fixed_variance;
private final double prior_mean;
private final double prior_deviation;
private GaussianDensity(Builder config) {
this.num_samples = config.num_samples;
this.fixed_variance = config.fixed_variance;
this.prior_mean = config.prior_mean;
this.prior_deviation = config.prior_deviation;
}
@Override
public int numParameters(int dimensions) {
return 2 * dimensions;
}
@Override
public void initialize(double[] parameters) {
int dimensions = parameters.length / 2;
for(int i=0; i < dimensions; ++i) {
parameters[i] = prior_mean;
parameters[i + dimensions] = prior_deviation;
}
}
@Override
public List<? extends Sample> sample(double[] parameters, Random random) {
List<Sample> samples = new ArrayList<>(num_samples);
int dimensions = parameters.length / 2;
for(int sample = 0; sample < num_samples; ++sample) {
double[] input = new double[dimensions];
double[] output = new double[dimensions];
for(int i=0; i < dimensions; ++i) {
input[i] = random.nextGaussian();
output[i] = (parameters[i + dimensions] * input[i]) + parameters[i];
}
samples.add(new Sample() {
@Override
public double[] value() {
return output;
}
@Override
public void gradient(double[] weights, double[] gradient) {
for(int i=0; i < dimensions; ++i) {
gradient[i] += weights[i];
if(!fixed_variance)
gradient[i + dimensions] += weights[i] * input[i];
}
}
});
}
return samples;
}
@Override
public void regularize(double[] parameters, double[] gradient, double weight) {
int dimensions = parameters.length / 2;
double variance = prior_deviation * prior_deviation;
for(int i=0; i < dimensions; ++i) {
gradient[i] += weight * (prior_mean - parameters[i]) / variance;
if(!fixed_variance) {
double deviation = parameters[i + dimensions];
gradient[i + dimensions] += weight * ((1.0 / deviation) - (deviation / variance));
}
}
}
@Override
public double[] mean(double[] parameters) {
int dimensions = parameters.length / 2;
double[] mean = new double[dimensions];
System.arraycopy(parameters, 0, mean, 0, dimensions);
return mean;
}
@Override
public String name() {
return "Gaussian Distribution";
}
@Override
public JSONObject serialize() throws JSONException {
return new JSONObject()
.put("name", name())
.put("num samples", num_samples)
.put("fixed variance", fixed_variance)
.put("prior mean", prior_mean)
.put("prior deviation", prior_deviation);
}
}
| 4,598 | 0.557851 | 0.553719 | 164 | 27.036585 | 23.403379 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.469512 | false | false | 2 |
ce84651cb45aeb7c8064fc16404ee8c6a078c045 | 24,842,090,844,807 | 906c045739d1b2f91e3a77ad07e9375eaaa0f917 | /src/main/java/com/example/demo/model/PO/User.java | e743227ecd639cc4a9b4f7675b821247118eeec6 | [] | no_license | xilPikachu/userDemo | https://github.com/xilPikachu/userDemo | 9121ccbf81bc1febb825aa0ce41cd047f940013e | e8fe8e70fe7151819e8e3953c7ad126fdef81227 | refs/heads/master | 2020-05-27T12:57:36.580000 | 2019-05-30T13:55:01 | 2019-05-30T13:55:01 | 188,627,248 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.model.PO;
import com.example.demo.model.PO.base.BaseEntity;
import lombok.Data;
@Data
public class User extends BaseEntity {
private String username;
private String password;
public User(){}
public User(String username, String password) {
this.username = username;
this.password = password;
}
}
| UTF-8 | Java | 360 | java | User.java | Java | [
{
"context": "ername, String password) {\n this.username = username;\n this.password = password;\n }\n}\n",
"end": 316,
"score": 0.9989262223243713,
"start": 308,
"tag": "USERNAME",
"value": "username"
},
{
"context": " this.username = username;\n this.password = password;\n }\n}\n",
"end": 350,
"score": 0.9978691339492798,
"start": 342,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | package com.example.demo.model.PO;
import com.example.demo.model.PO.base.BaseEntity;
import lombok.Data;
@Data
public class User extends BaseEntity {
private String username;
private String password;
public User(){}
public User(String username, String password) {
this.username = username;
this.password = <PASSWORD>;
}
}
| 362 | 0.697222 | 0.697222 | 17 | 20.17647 | 17.490284 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 2 |
0434aa853addf0b12ba4dba0ed24b5b244147a84 | 16,990,890,647,362 | 2cd4ed5792b10994ed36afc0fd730af14cf5aeb3 | /health club/code/src/update_package.java | 233a54cd8f97318920fc8e804ba8c3928ce05337 | [] | no_license | achal04/DxHealthClub | https://github.com/achal04/DxHealthClub | 2ce88fba5e9f38fc80c2acdfb5cbfff0c089d4a7 | 099c2ca70841d6b9ff0066a1bda466a3d858d1d3 | refs/heads/master | 2021-03-12T20:36:39.036000 | 2013-11-15T18:46:05 | 2013-11-15T18:46:05 | 14,431,637 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.sql.*;
import javax.swing.*;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* update_package.java
*
* Created on Sep 26, 2010, 9:43:45 AM
*/
/**
*
* @author Agarwal's
*/
public class update_package extends javax.swing.JFrame {
/** Creates new form update_package */
public update_package() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jSeparator2 = new javax.swing.JSeparator();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jTextField4 = new javax.swing.JTextField();
UpdateCmdButton = new javax.swing.JButton();
ClearCmdButton = new javax.swing.JButton();
ExitCmdButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
jLabel1.setFont(new java.awt.Font("Monotype Corsiva", 1, 30));
jLabel1.setForeground(new java.awt.Color(51, 0, 255));
jLabel1.setText("UPDATE PACKAGE INFO");
jLabel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jSeparator1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jList1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 153, 51), 3, true), "ID-DURATION", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 14), new java.awt.Color(0, 153, 51))); // NOI18N
jList1.setModel(new DefaultListModel());
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jList1);
jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18));
jLabel2.setForeground(new java.awt.Color(204, 0, 0));
jLabel2.setText("PACKAGE ID");
jTextField1.setEditable(false);
jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18));
jLabel3.setForeground(new java.awt.Color(204, 0, 0));
jLabel3.setText("DURATION");
jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 18));
jLabel4.setForeground(new java.awt.Color(204, 0, 0));
jLabel4.setText("SPORTS");
jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 18));
jLabel5.setForeground(new java.awt.Color(204, 0, 0));
jLabel5.setText("GYM ");
UpdateCmdButton.setFont(new java.awt.Font("Times New Roman", 1, 18));
UpdateCmdButton.setForeground(new java.awt.Color(204, 0, 0));
UpdateCmdButton.setText("UPDATE");
UpdateCmdButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
UpdateCmdButtonActionPerformed(evt);
}
});
ClearCmdButton.setFont(new java.awt.Font("Times New Roman", 1, 16));
ClearCmdButton.setForeground(new java.awt.Color(204, 0, 0));
ClearCmdButton.setText("CLEAR");
ClearCmdButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ClearCmdButtonActionPerformed(evt);
}
});
ExitCmdButton.setFont(new java.awt.Font("Times New Roman", 1, 16));
ExitCmdButton.setForeground(new java.awt.Color(204, 0, 0));
ExitCmdButton.setText("EXIT");
ExitCmdButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitCmdButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(80, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 525, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(ClearCmdButton, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(145, 145, 145)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(57, 57, 57)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(88, 88, 88))))
.addGroup(layout.createSequentialGroup()
.addComponent(UpdateCmdButton, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
.addComponent(ExitCmdButton, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField4, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)))
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(20, 20, 20))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(11, 11, 11)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 9, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(41, 41, 41)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jSeparator2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ClearCmdButton)
.addComponent(ExitCmdButton)
.addComponent(UpdateCmdButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(16, 16, 16))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/healthclub","root","");
String cid=(String)jList1.getSelectedValue();
cid=cid.substring(0,3).trim();
String sql="select * from PACKAGE where PACKAGEID="+cid;
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {
String a=rs.getString("PACKAGEID");
String b=rs.getString("DURATION");
String c=rs.getString("PRICE");
String d=rs.getString("GYM_FACILITY");
jTextField1.setText(a);
jTextField2.setText(b);
jTextField3.setText(c);
jTextField4.setText(d);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e.getMessage());
e.printStackTrace();
} // TODO add your handling code here:
}//GEN-LAST:event_jList1MouseClicked
private void UpdateCmdButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UpdateCmdButtonActionPerformed
DefaultListModel model=(DefaultListModel)jList1.getModel();
int ans = JOptionPane.showConfirmDialog(null,"ARE YOU SURE YOU WANT TO UPDATE THIS ENTRY!!!");
if (ans == JOptionPane.YES_OPTION) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/healthclub","root","");
Statement stmt=con.createStatement();
ResultSet rs=null;
String a=jTextField2.getText();
String b=jTextField3.getText();
String c=jTextField4.getText();
String h=jTextField1.getText();
String sql="update PACKAGE set DURATION='"+(a)+"',PRICE="+(b)+",GYM_FACILITY='"+(c)+"' where PACKAGEID="+(h)+"";
stmt.executeUpdate(sql);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());}
model.clear();
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
} else if (ans == JOptionPane.NO_OPTION) {
model.clear();
this.setVisible(true);
} else if (ans == JOptionPane.CANCEL_OPTION) {
model.clear();
this.setVisible(true);
}
// TODO add your handling code here:
}//GEN-LAST:event_UpdateCmdButtonActionPerformed
private void ClearCmdButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearCmdButtonActionPerformed
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
// TODO add your handling code here:
}//GEN-LAST:event_ClearCmdButtonActionPerformed
private void ExitCmdButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitCmdButtonActionPerformed
this.setVisible(false);
MainUI.setVisible(true); // TODO add your handling code here:
}//GEN-LAST:event_ExitCmdButtonActionPerformed
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
DefaultListModel model=(DefaultListModel)jList1.getModel();
String q1="select * from PACKAGE";
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/healthclub","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(q1);
while(rs.next())
{
String a=rs.getString("PACKAGEid");
String b=rs.getString("DURATION");
model.addElement(a+" - "+b);
jList1.setModel(model);}}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage());} // TODO add your handling code here:
}//GEN-LAST:event_formWindowActivated
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new update_package().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton ClearCmdButton;
private javax.swing.JButton ExitCmdButton;
private javax.swing.JButton UpdateCmdButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 18,775 | java | update_package.java | Java | [
{
"context": "on Sep 26, 2010, 9:43:45 AM\n */\n\n/**\n *\n * @author Agarwal's\n */\npublic class update_package extends javax.swi",
"end": 242,
"score": 0.9997690916061401,
"start": 233,
"tag": "NAME",
"value": "Agarwal's"
}
] | null | [] | import java.sql.*;
import javax.swing.*;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* update_package.java
*
* Created on Sep 26, 2010, 9:43:45 AM
*/
/**
*
* @author Agarwal's
*/
public class update_package extends javax.swing.JFrame {
/** Creates new form update_package */
public update_package() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jSeparator2 = new javax.swing.JSeparator();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jTextField4 = new javax.swing.JTextField();
UpdateCmdButton = new javax.swing.JButton();
ClearCmdButton = new javax.swing.JButton();
ExitCmdButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
jLabel1.setFont(new java.awt.Font("Monotype Corsiva", 1, 30));
jLabel1.setForeground(new java.awt.Color(51, 0, 255));
jLabel1.setText("UPDATE PACKAGE INFO");
jLabel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jSeparator1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jList1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 153, 51), 3, true), "ID-DURATION", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 14), new java.awt.Color(0, 153, 51))); // NOI18N
jList1.setModel(new DefaultListModel());
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jList1);
jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18));
jLabel2.setForeground(new java.awt.Color(204, 0, 0));
jLabel2.setText("PACKAGE ID");
jTextField1.setEditable(false);
jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18));
jLabel3.setForeground(new java.awt.Color(204, 0, 0));
jLabel3.setText("DURATION");
jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 18));
jLabel4.setForeground(new java.awt.Color(204, 0, 0));
jLabel4.setText("SPORTS");
jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 18));
jLabel5.setForeground(new java.awt.Color(204, 0, 0));
jLabel5.setText("GYM ");
UpdateCmdButton.setFont(new java.awt.Font("Times New Roman", 1, 18));
UpdateCmdButton.setForeground(new java.awt.Color(204, 0, 0));
UpdateCmdButton.setText("UPDATE");
UpdateCmdButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
UpdateCmdButtonActionPerformed(evt);
}
});
ClearCmdButton.setFont(new java.awt.Font("Times New Roman", 1, 16));
ClearCmdButton.setForeground(new java.awt.Color(204, 0, 0));
ClearCmdButton.setText("CLEAR");
ClearCmdButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ClearCmdButtonActionPerformed(evt);
}
});
ExitCmdButton.setFont(new java.awt.Font("Times New Roman", 1, 16));
ExitCmdButton.setForeground(new java.awt.Color(204, 0, 0));
ExitCmdButton.setText("EXIT");
ExitCmdButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitCmdButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(80, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 525, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(ClearCmdButton, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(145, 145, 145)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(57, 57, 57)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(88, 88, 88))))
.addGroup(layout.createSequentialGroup()
.addComponent(UpdateCmdButton, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
.addComponent(ExitCmdButton, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField4, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)))
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(20, 20, 20))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(11, 11, 11)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 9, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(41, 41, 41)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jSeparator2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ClearCmdButton)
.addComponent(ExitCmdButton)
.addComponent(UpdateCmdButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(16, 16, 16))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/healthclub","root","");
String cid=(String)jList1.getSelectedValue();
cid=cid.substring(0,3).trim();
String sql="select * from PACKAGE where PACKAGEID="+cid;
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {
String a=rs.getString("PACKAGEID");
String b=rs.getString("DURATION");
String c=rs.getString("PRICE");
String d=rs.getString("GYM_FACILITY");
jTextField1.setText(a);
jTextField2.setText(b);
jTextField3.setText(c);
jTextField4.setText(d);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e.getMessage());
e.printStackTrace();
} // TODO add your handling code here:
}//GEN-LAST:event_jList1MouseClicked
private void UpdateCmdButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UpdateCmdButtonActionPerformed
DefaultListModel model=(DefaultListModel)jList1.getModel();
int ans = JOptionPane.showConfirmDialog(null,"ARE YOU SURE YOU WANT TO UPDATE THIS ENTRY!!!");
if (ans == JOptionPane.YES_OPTION) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/healthclub","root","");
Statement stmt=con.createStatement();
ResultSet rs=null;
String a=jTextField2.getText();
String b=jTextField3.getText();
String c=jTextField4.getText();
String h=jTextField1.getText();
String sql="update PACKAGE set DURATION='"+(a)+"',PRICE="+(b)+",GYM_FACILITY='"+(c)+"' where PACKAGEID="+(h)+"";
stmt.executeUpdate(sql);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());}
model.clear();
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
} else if (ans == JOptionPane.NO_OPTION) {
model.clear();
this.setVisible(true);
} else if (ans == JOptionPane.CANCEL_OPTION) {
model.clear();
this.setVisible(true);
}
// TODO add your handling code here:
}//GEN-LAST:event_UpdateCmdButtonActionPerformed
private void ClearCmdButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearCmdButtonActionPerformed
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
// TODO add your handling code here:
}//GEN-LAST:event_ClearCmdButtonActionPerformed
private void ExitCmdButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitCmdButtonActionPerformed
this.setVisible(false);
MainUI.setVisible(true); // TODO add your handling code here:
}//GEN-LAST:event_ExitCmdButtonActionPerformed
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
DefaultListModel model=(DefaultListModel)jList1.getModel();
String q1="select * from PACKAGE";
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/healthclub","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(q1);
while(rs.next())
{
String a=rs.getString("PACKAGEid");
String b=rs.getString("DURATION");
model.addElement(a+" - "+b);
jList1.setModel(model);}}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage());} // TODO add your handling code here:
}//GEN-LAST:event_formWindowActivated
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new update_package().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton ClearCmdButton;
private javax.swing.JButton ExitCmdButton;
private javax.swing.JButton UpdateCmdButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
// End of variables declaration//GEN-END:variables
}
| 18,775 | 0.614541 | 0.595792 | 350 | 52.642857 | 41.28619 | 354 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.86 | false | false | 2 |
bda62e7f3ab5f1c7aa4fb04e963d15b6fe06e672 | 13,048,110,657,467 | 104b421e536d1667a70f234ec61864f9278137c4 | /code/org/apache/cordova/whitelist/WhitelistPlugin.java | 6bfa8b572eecdc5fd4687db59ffe70d21d6fe058 | [] | no_license | AshwiniVijayaKumar/Chrome-Cars | https://github.com/AshwiniVijayaKumar/Chrome-Cars | f2e61347c7416d37dae228dfeaa58c3845c66090 | 6a5e824ad5889f0e29d1aa31f7a35b1f6894f089 | refs/heads/master | 2021-01-15T11:07:57.050000 | 2016-05-13T05:01:09 | 2016-05-13T05:01:09 | 58,521,050 | 1 | 0 | null | true | 2016-05-11T06:51:56 | 2016-05-11T06:51:56 | 2016-05-06T14:21:56 | 2016-05-11T06:20:45 | 45,786 | 0 | 0 | 0 | null | null | null | package org.apache.cordova.whitelist;
import android.content.Context;
import android.util.Log;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.Whitelist;
import org.xmlpull.v1.XmlPullParser;
public class WhitelistPlugin
extends CordovaPlugin
{
private static final String LOG_TAG = "WhitelistPlugin";
private Whitelist allowedIntents;
private Whitelist allowedNavigations;
private Whitelist allowedRequests;
public WhitelistPlugin() {}
public WhitelistPlugin(Context paramContext)
{
this(new Whitelist(), new Whitelist(), null);
new CustomConfigXmlParser(null).parse(paramContext);
}
public WhitelistPlugin(Whitelist paramWhitelist1, Whitelist paramWhitelist2, Whitelist paramWhitelist3)
{
Whitelist localWhitelist = paramWhitelist3;
if (paramWhitelist3 == null)
{
localWhitelist = new Whitelist();
localWhitelist.addWhiteListEntry("file:///*", false);
localWhitelist.addWhiteListEntry("data:*", false);
}
this.allowedNavigations = paramWhitelist1;
this.allowedIntents = paramWhitelist2;
this.allowedRequests = localWhitelist;
}
public WhitelistPlugin(XmlPullParser paramXmlPullParser)
{
this(new Whitelist(), new Whitelist(), null);
new CustomConfigXmlParser(null).parse(paramXmlPullParser);
}
public Whitelist getAllowedIntents()
{
return this.allowedIntents;
}
public Whitelist getAllowedNavigations()
{
return this.allowedNavigations;
}
public Whitelist getAllowedRequests()
{
return this.allowedRequests;
}
public void pluginInitialize()
{
if (this.allowedNavigations == null)
{
this.allowedNavigations = new Whitelist();
this.allowedIntents = new Whitelist();
this.allowedRequests = new Whitelist();
new CustomConfigXmlParser(null).parse(this.webView.getContext());
}
}
public void setAllowedIntents(Whitelist paramWhitelist)
{
this.allowedIntents = paramWhitelist;
}
public void setAllowedNavigations(Whitelist paramWhitelist)
{
this.allowedNavigations = paramWhitelist;
}
public void setAllowedRequests(Whitelist paramWhitelist)
{
this.allowedRequests = paramWhitelist;
}
public Boolean shouldAllowNavigation(String paramString)
{
if (this.allowedNavigations.isUrlWhiteListed(paramString)) {
return Boolean.valueOf(true);
}
return null;
}
public Boolean shouldAllowRequest(String paramString)
{
if (Boolean.TRUE == shouldAllowNavigation(paramString)) {
return Boolean.valueOf(true);
}
if (this.allowedRequests.isUrlWhiteListed(paramString)) {
return Boolean.valueOf(true);
}
return null;
}
public Boolean shouldOpenExternalUrl(String paramString)
{
if (this.allowedIntents.isUrlWhiteListed(paramString)) {
return Boolean.valueOf(true);
}
return null;
}
private class CustomConfigXmlParser
extends ConfigXmlParser
{
private CustomConfigXmlParser() {}
public void handleEndTag(XmlPullParser paramXmlPullParser) {}
public void handleStartTag(XmlPullParser paramXmlPullParser)
{
boolean bool2 = true;
boolean bool1 = true;
String str1 = paramXmlPullParser.getName();
if (str1.equals("content"))
{
paramXmlPullParser = paramXmlPullParser.getAttributeValue(null, "src");
WhitelistPlugin.this.allowedNavigations.addWhiteListEntry(paramXmlPullParser, false);
}
do
{
return;
if (str1.equals("allow-navigation"))
{
paramXmlPullParser = paramXmlPullParser.getAttributeValue(null, "href");
if ("*".equals(paramXmlPullParser))
{
WhitelistPlugin.this.allowedNavigations.addWhiteListEntry("http://*/*", false);
WhitelistPlugin.this.allowedNavigations.addWhiteListEntry("https://*/*", false);
WhitelistPlugin.this.allowedNavigations.addWhiteListEntry("data:*", false);
return;
}
WhitelistPlugin.this.allowedNavigations.addWhiteListEntry(paramXmlPullParser, false);
return;
}
if (str1.equals("allow-intent"))
{
paramXmlPullParser = paramXmlPullParser.getAttributeValue(null, "href");
WhitelistPlugin.this.allowedIntents.addWhiteListEntry(paramXmlPullParser, false);
return;
}
} while (!str1.equals("access"));
str1 = paramXmlPullParser.getAttributeValue(null, "origin");
String str2 = paramXmlPullParser.getAttributeValue(null, "subdomains");
int i;
if (paramXmlPullParser.getAttributeValue(null, "launch-external") != null)
{
i = 1;
label207:
if (str1 == null) {
break label258;
}
if (i == 0) {
break label265;
}
Log.w("WhitelistPlugin", "Found <access launch-external> within config.xml. Please use <allow-intent> instead.");
paramXmlPullParser = WhitelistPlugin.this.allowedIntents;
if ((str2 == null) || (str2.compareToIgnoreCase("true") != 0)) {
break label260;
}
}
for (;;)
{
paramXmlPullParser.addWhiteListEntry(str1, bool1);
return;
i = 0;
break label207;
label258:
break;
label260:
bool1 = false;
}
label265:
if ("*".equals(str1))
{
WhitelistPlugin.this.allowedRequests.addWhiteListEntry("http://*/*", false);
WhitelistPlugin.this.allowedRequests.addWhiteListEntry("https://*/*", false);
return;
}
paramXmlPullParser = WhitelistPlugin.this.allowedRequests;
if ((str2 != null) && (str2.compareToIgnoreCase("true") == 0)) {}
for (bool1 = bool2;; bool1 = false)
{
paramXmlPullParser.addWhiteListEntry(str1, bool1);
return;
}
}
}
}
/* Location: C:\Users\ADMIN\Desktop\foss\dex2jar-2.0\classes-dex2jar.jar!\org\apache\cordova\whitelist\WhitelistPlugin.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 6,195 | java | WhitelistPlugin.java | Java | [] | null | [] | package org.apache.cordova.whitelist;
import android.content.Context;
import android.util.Log;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.Whitelist;
import org.xmlpull.v1.XmlPullParser;
public class WhitelistPlugin
extends CordovaPlugin
{
private static final String LOG_TAG = "WhitelistPlugin";
private Whitelist allowedIntents;
private Whitelist allowedNavigations;
private Whitelist allowedRequests;
public WhitelistPlugin() {}
public WhitelistPlugin(Context paramContext)
{
this(new Whitelist(), new Whitelist(), null);
new CustomConfigXmlParser(null).parse(paramContext);
}
public WhitelistPlugin(Whitelist paramWhitelist1, Whitelist paramWhitelist2, Whitelist paramWhitelist3)
{
Whitelist localWhitelist = paramWhitelist3;
if (paramWhitelist3 == null)
{
localWhitelist = new Whitelist();
localWhitelist.addWhiteListEntry("file:///*", false);
localWhitelist.addWhiteListEntry("data:*", false);
}
this.allowedNavigations = paramWhitelist1;
this.allowedIntents = paramWhitelist2;
this.allowedRequests = localWhitelist;
}
public WhitelistPlugin(XmlPullParser paramXmlPullParser)
{
this(new Whitelist(), new Whitelist(), null);
new CustomConfigXmlParser(null).parse(paramXmlPullParser);
}
public Whitelist getAllowedIntents()
{
return this.allowedIntents;
}
public Whitelist getAllowedNavigations()
{
return this.allowedNavigations;
}
public Whitelist getAllowedRequests()
{
return this.allowedRequests;
}
public void pluginInitialize()
{
if (this.allowedNavigations == null)
{
this.allowedNavigations = new Whitelist();
this.allowedIntents = new Whitelist();
this.allowedRequests = new Whitelist();
new CustomConfigXmlParser(null).parse(this.webView.getContext());
}
}
public void setAllowedIntents(Whitelist paramWhitelist)
{
this.allowedIntents = paramWhitelist;
}
public void setAllowedNavigations(Whitelist paramWhitelist)
{
this.allowedNavigations = paramWhitelist;
}
public void setAllowedRequests(Whitelist paramWhitelist)
{
this.allowedRequests = paramWhitelist;
}
public Boolean shouldAllowNavigation(String paramString)
{
if (this.allowedNavigations.isUrlWhiteListed(paramString)) {
return Boolean.valueOf(true);
}
return null;
}
public Boolean shouldAllowRequest(String paramString)
{
if (Boolean.TRUE == shouldAllowNavigation(paramString)) {
return Boolean.valueOf(true);
}
if (this.allowedRequests.isUrlWhiteListed(paramString)) {
return Boolean.valueOf(true);
}
return null;
}
public Boolean shouldOpenExternalUrl(String paramString)
{
if (this.allowedIntents.isUrlWhiteListed(paramString)) {
return Boolean.valueOf(true);
}
return null;
}
private class CustomConfigXmlParser
extends ConfigXmlParser
{
private CustomConfigXmlParser() {}
public void handleEndTag(XmlPullParser paramXmlPullParser) {}
public void handleStartTag(XmlPullParser paramXmlPullParser)
{
boolean bool2 = true;
boolean bool1 = true;
String str1 = paramXmlPullParser.getName();
if (str1.equals("content"))
{
paramXmlPullParser = paramXmlPullParser.getAttributeValue(null, "src");
WhitelistPlugin.this.allowedNavigations.addWhiteListEntry(paramXmlPullParser, false);
}
do
{
return;
if (str1.equals("allow-navigation"))
{
paramXmlPullParser = paramXmlPullParser.getAttributeValue(null, "href");
if ("*".equals(paramXmlPullParser))
{
WhitelistPlugin.this.allowedNavigations.addWhiteListEntry("http://*/*", false);
WhitelistPlugin.this.allowedNavigations.addWhiteListEntry("https://*/*", false);
WhitelistPlugin.this.allowedNavigations.addWhiteListEntry("data:*", false);
return;
}
WhitelistPlugin.this.allowedNavigations.addWhiteListEntry(paramXmlPullParser, false);
return;
}
if (str1.equals("allow-intent"))
{
paramXmlPullParser = paramXmlPullParser.getAttributeValue(null, "href");
WhitelistPlugin.this.allowedIntents.addWhiteListEntry(paramXmlPullParser, false);
return;
}
} while (!str1.equals("access"));
str1 = paramXmlPullParser.getAttributeValue(null, "origin");
String str2 = paramXmlPullParser.getAttributeValue(null, "subdomains");
int i;
if (paramXmlPullParser.getAttributeValue(null, "launch-external") != null)
{
i = 1;
label207:
if (str1 == null) {
break label258;
}
if (i == 0) {
break label265;
}
Log.w("WhitelistPlugin", "Found <access launch-external> within config.xml. Please use <allow-intent> instead.");
paramXmlPullParser = WhitelistPlugin.this.allowedIntents;
if ((str2 == null) || (str2.compareToIgnoreCase("true") != 0)) {
break label260;
}
}
for (;;)
{
paramXmlPullParser.addWhiteListEntry(str1, bool1);
return;
i = 0;
break label207;
label258:
break;
label260:
bool1 = false;
}
label265:
if ("*".equals(str1))
{
WhitelistPlugin.this.allowedRequests.addWhiteListEntry("http://*/*", false);
WhitelistPlugin.this.allowedRequests.addWhiteListEntry("https://*/*", false);
return;
}
paramXmlPullParser = WhitelistPlugin.this.allowedRequests;
if ((str2 != null) && (str2.compareToIgnoreCase("true") == 0)) {}
for (bool1 = bool2;; bool1 = false)
{
paramXmlPullParser.addWhiteListEntry(str1, bool1);
return;
}
}
}
}
/* Location: C:\Users\ADMIN\Desktop\foss\dex2jar-2.0\classes-dex2jar.jar!\org\apache\cordova\whitelist\WhitelistPlugin.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 6,195 | 0.666667 | 0.655206 | 207 | 28.932367 | 27.655844 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52657 | false | false | 2 |
2bce5db9434890b8ced07e32a2ab3b63244b4206 | 27,410,481,288,081 | 7e4039769ea3210427b5e99ca761c31da17a94ef | /src/main/java/fernando/estudos/designpatterns/strategy/Investimento.java | b6367f5f7cc38b2710c91c1a12c9c9be35604deb | [] | no_license | fppfurtado/estudos-java | https://github.com/fppfurtado/estudos-java | 405607970ce13021a87667eeadd262bcade8b387 | 386fc2b791b8f4f2834345ee93bfab77ca1d6b3c | refs/heads/master | 2020-07-09T16:08:58.273000 | 2019-09-23T22:50:42 | 2019-09-23T22:50:42 | 204,018,889 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fernando.estudos.designpatterns.strategy;
public interface Investimento {
double calculaRendimento(double valor);
}
| UTF-8 | Java | 131 | java | Investimento.java | Java | [] | null | [] | package fernando.estudos.designpatterns.strategy;
public interface Investimento {
double calculaRendimento(double valor);
}
| 131 | 0.801527 | 0.801527 | 5 | 24.200001 | 20.17325 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 2 |
51d24070946a4df80452156e93f7829b69a57364 | 32,865,089,749,887 | e07ec4029fd51ce92fb43890bd9e39535173cb54 | /Happy/app/src/main/java/hu/ait/android/happy/fragment/WeatherFragment.java | 67767b5f9fbf99b89e3d36e2d7a90f496f0fb3a4 | [] | no_license | madelinelee99/HappyApp | https://github.com/madelinelee99/HappyApp | a330e30eb4dc1d7d73e58aebca9dcf965b10e197 | 073d7be6d809dd58eb11ddabb25676c947693cfe | refs/heads/master | 2020-12-31T07:32:15.484000 | 2016-05-23T12:22:19 | 2016-05-23T12:22:19 | 57,954,147 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hu.ait.android.happy.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import hu.ait.android.happy.R;
import hu.ait.android.happy.data.WeatherResult;
public class WeatherFragment extends Fragment {
private TextView tvResult;
private ImageView ivWeather;
private TextView tvIdea;
private ImageView ivIdea;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.weather_fragment, null);
tvResult = (TextView) rootView.findViewById(R.id.tvResult);
tvIdea = (TextView) rootView.findViewById(R.id.tvIdea);
ivWeather = (ImageView) rootView.findViewById(R.id.ivWeather);
ivIdea = (ImageView) rootView.findViewById(R.id.ivIdea);
return rootView;
}
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(WeatherResult weatherResult) {
tvResult.setText("The weather today is: " + "\n" + weatherResult.getWeather().get(0).getDescription());
String iconName = weatherResult.getWeather().get(0).getIcon();
Glide.with(this).load("http://openweathermap.org/img/w/" + iconName + ".png").into(ivWeather);
if(weatherResult.getWeather().get(0).getDescription().equals("clear sky")){
tvIdea.setText("Spend the day in the park reading and soaking in the rays!");
ivIdea.setImageResource(R.drawable.park);
}
if(weatherResult.getWeather().get(0).getDescription().equals("broken clouds")){
tvIdea.setText("Hike in a nearby national park");
ivIdea.setImageResource(R.drawable.hike);
}
if(weatherResult.getWeather().get(0).getDescription().equals("overcast clouds")){
tvIdea.setText("Swim at your local swimming pool");
ivIdea.setImageResource(R.drawable.swim);
}
if(weatherResult.getWeather().get(0).getDescription().equals("few clouds")){
tvIdea.setText("Get on your bike and explore your neighborhood");
ivIdea.setImageResource(R.drawable.bike);
}
if(weatherResult.getWeather().get(0).getDescription().equals("light rain")){
tvIdea.setText("Sing in the rain!");
ivIdea.setImageResource(R.drawable.sing);
}
if(weatherResult.getWeather().get(0).getDescription().equals("moderate rain")){
tvIdea.setText("Do any art project that you've been meaning to get to");
ivIdea.setImageResource(R.drawable.art);
}
if(weatherResult.getWeather().get(0).getDescription().equals("heavy intensity rain")){
tvIdea.setText("Play boardgames with friends indoors");
ivIdea.setImageResource(R.drawable.boardgames);
}
}
}
| UTF-8 | Java | 3,675 | java | WeatherFragment.java | Java | [] | null | [] | package hu.ait.android.happy.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import hu.ait.android.happy.R;
import hu.ait.android.happy.data.WeatherResult;
public class WeatherFragment extends Fragment {
private TextView tvResult;
private ImageView ivWeather;
private TextView tvIdea;
private ImageView ivIdea;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.weather_fragment, null);
tvResult = (TextView) rootView.findViewById(R.id.tvResult);
tvIdea = (TextView) rootView.findViewById(R.id.tvIdea);
ivWeather = (ImageView) rootView.findViewById(R.id.ivWeather);
ivIdea = (ImageView) rootView.findViewById(R.id.ivIdea);
return rootView;
}
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(WeatherResult weatherResult) {
tvResult.setText("The weather today is: " + "\n" + weatherResult.getWeather().get(0).getDescription());
String iconName = weatherResult.getWeather().get(0).getIcon();
Glide.with(this).load("http://openweathermap.org/img/w/" + iconName + ".png").into(ivWeather);
if(weatherResult.getWeather().get(0).getDescription().equals("clear sky")){
tvIdea.setText("Spend the day in the park reading and soaking in the rays!");
ivIdea.setImageResource(R.drawable.park);
}
if(weatherResult.getWeather().get(0).getDescription().equals("broken clouds")){
tvIdea.setText("Hike in a nearby national park");
ivIdea.setImageResource(R.drawable.hike);
}
if(weatherResult.getWeather().get(0).getDescription().equals("overcast clouds")){
tvIdea.setText("Swim at your local swimming pool");
ivIdea.setImageResource(R.drawable.swim);
}
if(weatherResult.getWeather().get(0).getDescription().equals("few clouds")){
tvIdea.setText("Get on your bike and explore your neighborhood");
ivIdea.setImageResource(R.drawable.bike);
}
if(weatherResult.getWeather().get(0).getDescription().equals("light rain")){
tvIdea.setText("Sing in the rain!");
ivIdea.setImageResource(R.drawable.sing);
}
if(weatherResult.getWeather().get(0).getDescription().equals("moderate rain")){
tvIdea.setText("Do any art project that you've been meaning to get to");
ivIdea.setImageResource(R.drawable.art);
}
if(weatherResult.getWeather().get(0).getDescription().equals("heavy intensity rain")){
tvIdea.setText("Play boardgames with friends indoors");
ivIdea.setImageResource(R.drawable.boardgames);
}
}
}
| 3,675 | 0.636463 | 0.633741 | 92 | 38.923912 | 31.78092 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.532609 | false | false | 2 |
6b48ca0293c23d59bfb6538edfb59d9764ead543 | 31,121,333,040,793 | 22f9be218f9acc8e2bb83451c292313107b4c432 | /BSc-projects-old/eshop/Card.java | 8a8674a659ffb2f341c0cb91320d5c227b851359 | [] | no_license | lefteran/Programming | https://github.com/lefteran/Programming | 9992694fbc41f03bd9edadc10e1cb2e9fe649f55 | c274bb369b045ffe8e34f2d96c7e296060e8068f | refs/heads/master | 2020-03-07T17:49:53.670000 | 2018-05-07T10:54:52 | 2018-05-07T10:54:52 | 127,622,141 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package login;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import database.Database;
import java.util.Calendar;
/**
*
* @author johnfouf
*/
public class Card implements java.io.Serializable{
private Database db;
protected Integer elegxos(String username){
try {
db = new Database();
db.connect();
ResultSet rs = null;
ResultSet result = null;
java.util.Date d1 = new java.util.Date();
ResultSet rs2 = null;
String query23 = "SELECT * FROM cards WHERE username=\"" + username + "\"";
rs2 = db.selectquery(query23);
rs2.next();
String cardno = rs2.getString("card");
String date = rs2.getString("date");
String cvv = rs2.getString("cvv");
rs2.close();
Integer index = date.indexOf('/');
String mymonth = date.substring(0,index);
String myyear = date.substring(index+1);
if( Integer.parseInt(myyear) < (d1.getYear()+1900))
return -1;
else if(Integer.parseInt(myyear) == (d1.getYear()+1900) && Integer.parseInt(mymonth) <= d1.getMonth())
return -2; //
Calendar cal = Calendar.getInstance();
if(Integer.parseInt(myyear) == (d1.getYear()+1900) && Integer.parseInt(mymonth) == d1.getMonth()+1 && cal.get(Calendar.DAY_OF_MONTH) >=27)
return -3;//
rs2.close();
}
catch (ServletException ex) {
Logger.getLogger(Card.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException e) {
try {
throw new ServletException("Servlet Could not display records.", e);
} catch (ServletException ex) {
Logger.getLogger(Card.class.getName()).log(Level.SEVERE, null, ex);
}
}
finally{
try {
db.close();
} catch (ServletException ex) {
Logger.getLogger(Card.class.getName()).log(Level.SEVERE, null, ex);
}
}
return 0;
}
}
| UTF-8 | Java | 2,300 | java | Card.java | Java | [
{
"context": "ase;\nimport java.util.Calendar;\n\n/**\n *\n * @author johnfouf\n */\npublic class Card implements java.io.Seriali",
"end": 343,
"score": 0.9995909929275513,
"start": 335,
"tag": "USERNAME",
"value": "johnfouf"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package login;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import database.Database;
import java.util.Calendar;
/**
*
* @author johnfouf
*/
public class Card implements java.io.Serializable{
private Database db;
protected Integer elegxos(String username){
try {
db = new Database();
db.connect();
ResultSet rs = null;
ResultSet result = null;
java.util.Date d1 = new java.util.Date();
ResultSet rs2 = null;
String query23 = "SELECT * FROM cards WHERE username=\"" + username + "\"";
rs2 = db.selectquery(query23);
rs2.next();
String cardno = rs2.getString("card");
String date = rs2.getString("date");
String cvv = rs2.getString("cvv");
rs2.close();
Integer index = date.indexOf('/');
String mymonth = date.substring(0,index);
String myyear = date.substring(index+1);
if( Integer.parseInt(myyear) < (d1.getYear()+1900))
return -1;
else if(Integer.parseInt(myyear) == (d1.getYear()+1900) && Integer.parseInt(mymonth) <= d1.getMonth())
return -2; //
Calendar cal = Calendar.getInstance();
if(Integer.parseInt(myyear) == (d1.getYear()+1900) && Integer.parseInt(mymonth) == d1.getMonth()+1 && cal.get(Calendar.DAY_OF_MONTH) >=27)
return -3;//
rs2.close();
}
catch (ServletException ex) {
Logger.getLogger(Card.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException e) {
try {
throw new ServletException("Servlet Could not display records.", e);
} catch (ServletException ex) {
Logger.getLogger(Card.class.getName()).log(Level.SEVERE, null, ex);
}
}
finally{
try {
db.close();
} catch (ServletException ex) {
Logger.getLogger(Card.class.getName()).log(Level.SEVERE, null, ex);
}
}
return 0;
}
}
| 2,300 | 0.561739 | 0.544783 | 72 | 30.944445 | 28.46874 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false | 2 |
9002f3a0949bbf0edf4ee78a354b162919eb9c1e | 25,142,738,585,972 | c900a4643f6cb4e7634612ab20a7b2d02dbb7979 | /src/main/java/com/fvgprinc/app/web/reggastos/actions/catalogs/ListMonedasAction.java | 3a89daf7eb6002cfdb3cc679ab6e50ddfcefd1b3 | [] | no_license | f-vargasg/WebAppRegGastos | https://github.com/f-vargasg/WebAppRegGastos | 6ad29fd6cc039eab5b074b42814fae7e709acccc | d2e5f46ef7ee37938353865d7c6d2b46bcd5d957 | refs/heads/master | 2023-02-17T07:13:46.158000 | 2021-01-07T03:44:53 | 2021-01-07T03:44:53 | 323,232,142 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 com.fvgprinc.app.web.reggastos.actions.catalogs;
import com.fvgprinc.app.web.reggastos.bean.Moneda;
import com.fvgprinc.app.web.reggastos.bl.MonedaBL;
import static com.opensymphony.xwork2.Action.SUCCESS;
import com.opensymphony.xwork2.ActionSupport;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
/**
*
* @author garfi
*/
@Namespace(value = "/")
@Action(value = "listmonedasaction", results = {
@Result(name = SUCCESS, location = "/listmonedas.jsp")})
public class ListMonedasAction extends ActionSupport {
// private static final long serialVersionUID = -7591893545033222898L;
private ListMonedasAction dto = null;
private int codMonedaN;
private String desMoneda;
private String usuIngreso;
private Timestamp fecIngreso;
private List<ListMonedasAction> lstMonedas = null;
@Override
public String execute() throws Exception {
// ResultSet rs = DisplayDao.Report();
MonedaBL monBL = new MonedaBL();
ArrayList<Moneda> lstMonBL = monBL.getList(-1);
lstMonedas = new ArrayList<ListMonedasAction>();
// xxxxxxx
if (lstMonBL.size() > 0) {
for (Moneda mon : lstMonBL) {
dto = new ListMonedasAction();
dto.setCodMonedaN(mon.getCodMonedaN());
dto.setDesMoneda(mon.getDesMoneda());
dto.setUsuIngreso(mon.getUsuIngreso());
dto.setFecIngreso(mon.getFecIngreso());
lstMonedas.add(dto);
}
}
return SUCCESS;
}
public List<ListMonedasAction> getLstMonedas() {
return lstMonedas;
}
public void setLstMonedas(List<ListMonedasAction> lstMonedas) {
this.lstMonedas = lstMonedas;
}
public int getCodMonedaN() {
return codMonedaN;
}
public void setCodMonedaN(int codMonedaN) {
this.codMonedaN = codMonedaN;
}
public String getDesMoneda() {
return desMoneda;
}
public void setDesMoneda(String desMoneda) {
this.desMoneda = desMoneda;
}
public String getUsuIngreso() {
return usuIngreso;
}
public void setUsuIngreso(String usuIngreso) {
this.usuIngreso = usuIngreso;
}
public Timestamp getFecIngreso() {
return fecIngreso;
}
public void setFecIngreso(Timestamp fecIngreso) {
this.fecIngreso = fecIngreso;
}
}
| UTF-8 | Java | 2,820 | java | ListMonedasAction.java | Java | [
{
"context": "2.convention.annotation.Result;\n\n/**\n *\n * @author garfi\n */\n\n@Namespace(value = \"/\")\n@Action(value = \"lis",
"end": 718,
"score": 0.9987666010856628,
"start": 713,
"tag": "USERNAME",
"value": "garfi"
}
] | null | [] | /*
* 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 com.fvgprinc.app.web.reggastos.actions.catalogs;
import com.fvgprinc.app.web.reggastos.bean.Moneda;
import com.fvgprinc.app.web.reggastos.bl.MonedaBL;
import static com.opensymphony.xwork2.Action.SUCCESS;
import com.opensymphony.xwork2.ActionSupport;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
/**
*
* @author garfi
*/
@Namespace(value = "/")
@Action(value = "listmonedasaction", results = {
@Result(name = SUCCESS, location = "/listmonedas.jsp")})
public class ListMonedasAction extends ActionSupport {
// private static final long serialVersionUID = -7591893545033222898L;
private ListMonedasAction dto = null;
private int codMonedaN;
private String desMoneda;
private String usuIngreso;
private Timestamp fecIngreso;
private List<ListMonedasAction> lstMonedas = null;
@Override
public String execute() throws Exception {
// ResultSet rs = DisplayDao.Report();
MonedaBL monBL = new MonedaBL();
ArrayList<Moneda> lstMonBL = monBL.getList(-1);
lstMonedas = new ArrayList<ListMonedasAction>();
// xxxxxxx
if (lstMonBL.size() > 0) {
for (Moneda mon : lstMonBL) {
dto = new ListMonedasAction();
dto.setCodMonedaN(mon.getCodMonedaN());
dto.setDesMoneda(mon.getDesMoneda());
dto.setUsuIngreso(mon.getUsuIngreso());
dto.setFecIngreso(mon.getFecIngreso());
lstMonedas.add(dto);
}
}
return SUCCESS;
}
public List<ListMonedasAction> getLstMonedas() {
return lstMonedas;
}
public void setLstMonedas(List<ListMonedasAction> lstMonedas) {
this.lstMonedas = lstMonedas;
}
public int getCodMonedaN() {
return codMonedaN;
}
public void setCodMonedaN(int codMonedaN) {
this.codMonedaN = codMonedaN;
}
public String getDesMoneda() {
return desMoneda;
}
public void setDesMoneda(String desMoneda) {
this.desMoneda = desMoneda;
}
public String getUsuIngreso() {
return usuIngreso;
}
public void setUsuIngreso(String usuIngreso) {
this.usuIngreso = usuIngreso;
}
public Timestamp getFecIngreso() {
return fecIngreso;
}
public void setFecIngreso(Timestamp fecIngreso) {
this.fecIngreso = fecIngreso;
}
}
| 2,820 | 0.661702 | 0.652482 | 109 | 24.871559 | 22.410311 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.40367 | false | false | 2 |
39a3df5f6d474e81019fb77151fc562aa0a3355f | 31,842,887,597,233 | ff5d3450792ca178d26d494ad8413694236f0b60 | /src/main/java/com/javatechie/spring/ajax/api/service/AdminService.java | c1364cd43e06acd7d30e094d597f683d19fd5d24 | [] | no_license | sattarasif/PreMoney | https://github.com/sattarasif/PreMoney | 62906942ef6d7da5cf0821503c6ffb7d025c468d | 67c89a91c4853de3c12792c6f6b5587a70ad786a | refs/heads/master | 2023-06-23T08:11:35.663000 | 2021-07-11T06:43:19 | 2021-07-11T06:43:19 | 384,876,088 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.javatechie.spring.ajax.api.service;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.javatechie.spring.ajax.api.dto.AdhaarExtraction;
import com.javatechie.spring.ajax.api.dto.KycResult;
import com.javatechie.spring.ajax.api.dto.UpdateCustomerInfo;
import com.javatechie.spring.ajax.api.entity.AddressDetails;
import com.javatechie.spring.ajax.api.entity.CaptureKyc;
import com.javatechie.spring.ajax.api.entity.CustomerAccountsDetails;
import com.javatechie.spring.ajax.api.entity.CustomerBankDetails;
import com.javatechie.spring.ajax.api.entity.CustomerDetails;
import com.javatechie.spring.ajax.api.entity.CustomerEmployerDetails;
import com.javatechie.spring.ajax.api.entity.CustomerReferenceDetails;
import com.javatechie.spring.ajax.api.entity.Users;
import com.javatechie.spring.ajax.api.repository.AddressDtlRepository;
import com.javatechie.spring.ajax.api.repository.CaptureKycRepository;
import com.javatechie.spring.ajax.api.repository.CustAccountDtlRepository;
import com.javatechie.spring.ajax.api.repository.CustBankDtlRepository;
import com.javatechie.spring.ajax.api.repository.CustEmployerDtlRepository;
import com.javatechie.spring.ajax.api.repository.CustRefDtlRepository;
import com.javatechie.spring.ajax.api.repository.CustomerDtlRepository;
@Service
public class AdminService {
@Autowired
private CaptureKycService captureKycService;
@Autowired
private CaptureKycRepository captureRepository;
@Autowired
private CustomerDtlService customerDtlService;
@Autowired
private AddressDtlService addressDtlService;
@Autowired
private CustAccountDtlService custAccountDtlService;
@Autowired
private CustEmployerDtlService custEmployerDtlService;
@Autowired
private CustRefDtlService custRefDtlService;
@Autowired
private CustomerDtlRepository customerDtlRepository;
@Autowired
private AddressDtlRepository addressDtlRepository;
@Autowired
private CustAccountDtlRepository custAccountDtlRepository;
@Autowired
private CustEmployerDtlRepository custEmployerDtlRepository;
@Autowired
private CustRefDtlRepository custRefDtlRepository;
public void saveCaptureKyc(Map<String, Object> mapToJson,int userId) {
CaptureKyc caputureKyc = new CaptureKyc();
Map config = (Map) mapToJson.get("config");
Map profile_data = (Map) mapToJson.get("profile_data");
List list = (ArrayList) mapToJson.get("tasks");
Map tasks = (Map) list.get(0);
Map xml_output = (Map) ((Map<String, Object>) ((Map<String, Object>) tasks.get("result")).get("automated_response")).get("xml_output");
caputureKyc.setUserId(userId);
caputureKyc.setConfig_id(config.get("id").toString());
caputureKyc.setCompleted_at(profile_data.get("completed_at").toString());
caputureKyc.setCreated_at(profile_data.get("created_at").toString());
caputureKyc.setProfile_id(mapToJson.get("profile_id").toString());
caputureKyc.setReference_id(mapToJson.get("reference_id").toString());
KycResult kycResult = new KycResult();
AdhaarExtraction adhaarExtraction = new AdhaarExtraction();
adhaarExtraction.setAddress(xml_output.get("address").toString());
adhaarExtraction.setDate_of_birth(xml_output.get("date_of_birth").toString());
adhaarExtraction.setGender(xml_output.get("gender").toString());
adhaarExtraction.setGenerated_at(xml_output.get("generated_at").toString());
adhaarExtraction.setName(xml_output.get("name").toString());
adhaarExtraction.setReference_number(xml_output.get("reference_number").toString());
adhaarExtraction.setYear_of_birth(xml_output.get("year_of_birth").toString());
adhaarExtraction.setStatus(tasks.get("status").toString());
adhaarExtraction.setTask_id(tasks.get("task_id").toString());
adhaarExtraction.setTast_type(tasks.get("task_type").toString());
kycResult.setExtraction_output(adhaarExtraction);
caputureKyc.setResult(kycResult);
CaptureKyc updateCaputureKyc = captureKycService.getCaputureKycByUserId(userId);
if(updateCaputureKyc!=null)
caputureKyc.setId(updateCaputureKyc.getId());
captureRepository.save(caputureKyc);
}
public void generatePDFFromHTML(String filename) throws FileNotFoundException, IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/Users/asifsattar/Desktop/Node/html.pdf"));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream("/Users/asifsattar/Desktop/Node/Sanction_Letter.html"));
document.close();
}
public void updateCustomer(int id, UpdateCustomerInfo updateCustomer) {
CustomerDetails custDtl = customerDtlService.getCustomerByUserId(id);
setCustDtl(updateCustomer, custDtl);
AddressDetails addressDtl = addressDtlService.getAddressUserById(id);
setAddressDtl(updateCustomer, addressDtl);
CustomerAccountsDetails accountDtl = custAccountDtlService.getCustomerAccountByUserId(id);
setAccountDtl(updateCustomer, accountDtl);
CustomerEmployerDetails employerDtl = custEmployerDtlService.getCustomerEmployerByUserId(id);
setEmploymentDtl(updateCustomer, employerDtl);
CustomerReferenceDetails refDtl = custRefDtlService.getCustRefDtlByUserId(id);
setRefDtl(updateCustomer, refDtl);
addressDtlRepository.save(addressDtl);
custAccountDtlRepository.save(accountDtl);
custEmployerDtlRepository.save(employerDtl);
customerDtlRepository.save(custDtl);
custRefDtlRepository.save(refDtl);
}
private void setRefDtl(UpdateCustomerInfo updateCustomer, CustomerReferenceDetails refDtl) {
refDtl.setRefAddress1(updateCustomer.getRefAddress1());
refDtl.setRefName1(updateCustomer.getRefName1());
refDtl.setRefContactNo1(updateCustomer.getRefContactNo1());
refDtl.setRelation1(updateCustomer.getRelation1());
refDtl.setRefAddress2(updateCustomer.getRefAddress2());
refDtl.setRefName2(updateCustomer.getRefName2());
refDtl.setRefContactNo2(updateCustomer.getRefContactNo2());
refDtl.setRelation2(updateCustomer.getRelation2());
}
private void setAccountDtl(UpdateCustomerInfo updateCustomer, CustomerAccountsDetails accountDtl) {
}
private void setEmploymentDtl(UpdateCustomerInfo updateCustomer, CustomerEmployerDetails employerDtl) {
employerDtl.setEmployerType(updateCustomer.getEmployerType());
employerDtl.setEmployerName(updateCustomer.getEmployerName());
employerDtl.setEmployerContactNo(updateCustomer.getEmployerContactNo());
employerDtl.setFullAddress(updateCustomer.getEmpfullAddress());
employerDtl.setCity(updateCustomer.getEmpcity());
employerDtl.setState(updateCustomer.getEmpstate());
employerDtl.setZipCode(updateCustomer.getEmpzipCode());
}
private void setAddressDtl(UpdateCustomerInfo updateCustomer, AddressDetails addressDtl) {
addressDtl.setAddressLine1(updateCustomer.getAddressLine1());
addressDtl.setAddressLine2(updateCustomer.getAddressLine2());
addressDtl.setAddressLine3(updateCustomer.getAddressLine3());
addressDtl.setFullAddress(updateCustomer.getFullAddress());
addressDtl.setIsPrimaryAddress(updateCustomer.getIsPrimaryAddress());
addressDtl.setAddressType(updateCustomer.getAddressType());
addressDtl.setCity(updateCustomer.getCity());
addressDtl.setState(updateCustomer.getState());
addressDtl.setZipCode(updateCustomer.getZipCode());
}
private void setCustDtl(UpdateCustomerInfo updateCustomer, CustomerDetails custDtl) {
custDtl.setFirstName(updateCustomer.getFirstName());
custDtl.setMiddleName(updateCustomer.getMiddleName());
custDtl.setLastName(updateCustomer.getLastName());
custDtl.setFullName(updateCustomer.getFullName());
custDtl.setDob(updateCustomer.getDob());
custDtl.setEmailAddress(updateCustomer.getEmailAddress());
custDtl.setGender(updateCustomer.getGender());
custDtl.setAdhaarNo(updateCustomer.getAdhaarNo());
custDtl.setPanNo(updateCustomer.getPanNo());
custDtl.setFatherName(updateCustomer.getFatherName());
}
}
| UTF-8 | Java | 8,394 | java | AdminService.java | Java | [
{
"context": "etInstance(document, new FileOutputStream(\"/Users/asifsattar/Desktop/Node/html.pdf\"));\n\t document.open();\n\t",
"end": 4772,
"score": 0.9578597545623779,
"start": 4762,
"tag": "USERNAME",
"value": "asifsattar"
},
{
"context": "tml(writer, document, new FileInputStream(\"/Users/asifsattar/Desktop/Node/Sanction_Letter.html\"));\n\t docume",
"end": 4923,
"score": 0.8692686557769775,
"start": 4913,
"tag": "USERNAME",
"value": "asifsattar"
}
] | null | [] | package com.javatechie.spring.ajax.api.service;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.javatechie.spring.ajax.api.dto.AdhaarExtraction;
import com.javatechie.spring.ajax.api.dto.KycResult;
import com.javatechie.spring.ajax.api.dto.UpdateCustomerInfo;
import com.javatechie.spring.ajax.api.entity.AddressDetails;
import com.javatechie.spring.ajax.api.entity.CaptureKyc;
import com.javatechie.spring.ajax.api.entity.CustomerAccountsDetails;
import com.javatechie.spring.ajax.api.entity.CustomerBankDetails;
import com.javatechie.spring.ajax.api.entity.CustomerDetails;
import com.javatechie.spring.ajax.api.entity.CustomerEmployerDetails;
import com.javatechie.spring.ajax.api.entity.CustomerReferenceDetails;
import com.javatechie.spring.ajax.api.entity.Users;
import com.javatechie.spring.ajax.api.repository.AddressDtlRepository;
import com.javatechie.spring.ajax.api.repository.CaptureKycRepository;
import com.javatechie.spring.ajax.api.repository.CustAccountDtlRepository;
import com.javatechie.spring.ajax.api.repository.CustBankDtlRepository;
import com.javatechie.spring.ajax.api.repository.CustEmployerDtlRepository;
import com.javatechie.spring.ajax.api.repository.CustRefDtlRepository;
import com.javatechie.spring.ajax.api.repository.CustomerDtlRepository;
@Service
public class AdminService {
@Autowired
private CaptureKycService captureKycService;
@Autowired
private CaptureKycRepository captureRepository;
@Autowired
private CustomerDtlService customerDtlService;
@Autowired
private AddressDtlService addressDtlService;
@Autowired
private CustAccountDtlService custAccountDtlService;
@Autowired
private CustEmployerDtlService custEmployerDtlService;
@Autowired
private CustRefDtlService custRefDtlService;
@Autowired
private CustomerDtlRepository customerDtlRepository;
@Autowired
private AddressDtlRepository addressDtlRepository;
@Autowired
private CustAccountDtlRepository custAccountDtlRepository;
@Autowired
private CustEmployerDtlRepository custEmployerDtlRepository;
@Autowired
private CustRefDtlRepository custRefDtlRepository;
public void saveCaptureKyc(Map<String, Object> mapToJson,int userId) {
CaptureKyc caputureKyc = new CaptureKyc();
Map config = (Map) mapToJson.get("config");
Map profile_data = (Map) mapToJson.get("profile_data");
List list = (ArrayList) mapToJson.get("tasks");
Map tasks = (Map) list.get(0);
Map xml_output = (Map) ((Map<String, Object>) ((Map<String, Object>) tasks.get("result")).get("automated_response")).get("xml_output");
caputureKyc.setUserId(userId);
caputureKyc.setConfig_id(config.get("id").toString());
caputureKyc.setCompleted_at(profile_data.get("completed_at").toString());
caputureKyc.setCreated_at(profile_data.get("created_at").toString());
caputureKyc.setProfile_id(mapToJson.get("profile_id").toString());
caputureKyc.setReference_id(mapToJson.get("reference_id").toString());
KycResult kycResult = new KycResult();
AdhaarExtraction adhaarExtraction = new AdhaarExtraction();
adhaarExtraction.setAddress(xml_output.get("address").toString());
adhaarExtraction.setDate_of_birth(xml_output.get("date_of_birth").toString());
adhaarExtraction.setGender(xml_output.get("gender").toString());
adhaarExtraction.setGenerated_at(xml_output.get("generated_at").toString());
adhaarExtraction.setName(xml_output.get("name").toString());
adhaarExtraction.setReference_number(xml_output.get("reference_number").toString());
adhaarExtraction.setYear_of_birth(xml_output.get("year_of_birth").toString());
adhaarExtraction.setStatus(tasks.get("status").toString());
adhaarExtraction.setTask_id(tasks.get("task_id").toString());
adhaarExtraction.setTast_type(tasks.get("task_type").toString());
kycResult.setExtraction_output(adhaarExtraction);
caputureKyc.setResult(kycResult);
CaptureKyc updateCaputureKyc = captureKycService.getCaputureKycByUserId(userId);
if(updateCaputureKyc!=null)
caputureKyc.setId(updateCaputureKyc.getId());
captureRepository.save(caputureKyc);
}
public void generatePDFFromHTML(String filename) throws FileNotFoundException, IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/Users/asifsattar/Desktop/Node/html.pdf"));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream("/Users/asifsattar/Desktop/Node/Sanction_Letter.html"));
document.close();
}
public void updateCustomer(int id, UpdateCustomerInfo updateCustomer) {
CustomerDetails custDtl = customerDtlService.getCustomerByUserId(id);
setCustDtl(updateCustomer, custDtl);
AddressDetails addressDtl = addressDtlService.getAddressUserById(id);
setAddressDtl(updateCustomer, addressDtl);
CustomerAccountsDetails accountDtl = custAccountDtlService.getCustomerAccountByUserId(id);
setAccountDtl(updateCustomer, accountDtl);
CustomerEmployerDetails employerDtl = custEmployerDtlService.getCustomerEmployerByUserId(id);
setEmploymentDtl(updateCustomer, employerDtl);
CustomerReferenceDetails refDtl = custRefDtlService.getCustRefDtlByUserId(id);
setRefDtl(updateCustomer, refDtl);
addressDtlRepository.save(addressDtl);
custAccountDtlRepository.save(accountDtl);
custEmployerDtlRepository.save(employerDtl);
customerDtlRepository.save(custDtl);
custRefDtlRepository.save(refDtl);
}
private void setRefDtl(UpdateCustomerInfo updateCustomer, CustomerReferenceDetails refDtl) {
refDtl.setRefAddress1(updateCustomer.getRefAddress1());
refDtl.setRefName1(updateCustomer.getRefName1());
refDtl.setRefContactNo1(updateCustomer.getRefContactNo1());
refDtl.setRelation1(updateCustomer.getRelation1());
refDtl.setRefAddress2(updateCustomer.getRefAddress2());
refDtl.setRefName2(updateCustomer.getRefName2());
refDtl.setRefContactNo2(updateCustomer.getRefContactNo2());
refDtl.setRelation2(updateCustomer.getRelation2());
}
private void setAccountDtl(UpdateCustomerInfo updateCustomer, CustomerAccountsDetails accountDtl) {
}
private void setEmploymentDtl(UpdateCustomerInfo updateCustomer, CustomerEmployerDetails employerDtl) {
employerDtl.setEmployerType(updateCustomer.getEmployerType());
employerDtl.setEmployerName(updateCustomer.getEmployerName());
employerDtl.setEmployerContactNo(updateCustomer.getEmployerContactNo());
employerDtl.setFullAddress(updateCustomer.getEmpfullAddress());
employerDtl.setCity(updateCustomer.getEmpcity());
employerDtl.setState(updateCustomer.getEmpstate());
employerDtl.setZipCode(updateCustomer.getEmpzipCode());
}
private void setAddressDtl(UpdateCustomerInfo updateCustomer, AddressDetails addressDtl) {
addressDtl.setAddressLine1(updateCustomer.getAddressLine1());
addressDtl.setAddressLine2(updateCustomer.getAddressLine2());
addressDtl.setAddressLine3(updateCustomer.getAddressLine3());
addressDtl.setFullAddress(updateCustomer.getFullAddress());
addressDtl.setIsPrimaryAddress(updateCustomer.getIsPrimaryAddress());
addressDtl.setAddressType(updateCustomer.getAddressType());
addressDtl.setCity(updateCustomer.getCity());
addressDtl.setState(updateCustomer.getState());
addressDtl.setZipCode(updateCustomer.getZipCode());
}
private void setCustDtl(UpdateCustomerInfo updateCustomer, CustomerDetails custDtl) {
custDtl.setFirstName(updateCustomer.getFirstName());
custDtl.setMiddleName(updateCustomer.getMiddleName());
custDtl.setLastName(updateCustomer.getLastName());
custDtl.setFullName(updateCustomer.getFullName());
custDtl.setDob(updateCustomer.getDob());
custDtl.setEmailAddress(updateCustomer.getEmailAddress());
custDtl.setGender(updateCustomer.getGender());
custDtl.setAdhaarNo(updateCustomer.getAdhaarNo());
custDtl.setPanNo(updateCustomer.getPanNo());
custDtl.setFatherName(updateCustomer.getFatherName());
}
}
| 8,394 | 0.809626 | 0.806886 | 204 | 40.14706 | 30.992693 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.95098 | false | false | 2 |
efac8ef776c2f0c79863c000a1bf37c1dbba937d | 12,240,656,810,225 | 4ea520ba151f3616b845881c2fbb2108c44b38d4 | /lottery_android.git/src/com/caixiang/lottery/ui/widget/ZjqPlayView.java | d7e2c70aa92035bf4eb64a02ee49326ae9496165 | [] | no_license | DirkZhao/java-git | https://github.com/DirkZhao/java-git | 1274649c3fa2eb42f72c81757b2e0bdc4332d62e | b2d133dcda64bfbc57896e8b8ccc3dcb526aed2f | refs/heads/master | 2016-05-22T17:19:12.993000 | 2015-03-16T05:48:33 | 2015-03-16T05:48:33 | 30,006,971 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.caixiang.lottery.ui.widget;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.caixiang.lottery.R;
import com.caixiang.lottery.core.service.match.model.JczqMatchInfo;
import com.caixiang.lottery.core.service.match.model.MatchInfo;
import com.caixiang.lottery.ui.widget.HunhePlayView.OnOddsChooseFinishListener;
public class ZjqPlayView extends HunhePlayView
{
// /**
// * 总进球
// */
// private List<TextView> popZjqViews;
//
// private List<LinearLayout> popZjqLayoutViews;
//
// private int[] popZjqViewIds = new int[] {R.id.tv_pop_zjq_0,
// R.id.tv_pop_zjq_1, R.id.tv_pop_zjq_2,
// R.id.tv_pop_zjq_3, R.id.tv_pop_zjq_4, R.id.tv_pop_zjq_5,
// R.id.tv_pop_zjq_6, R.id.tv_pop_zjq_7};
//
// private int[] popZjqLayoutViewIds = new int[] {R.id.ll_pop_zjq_0,
// R.id.ll_pop_zjq_1, R.id.ll_pop_zjq_2,
// R.id.ll_pop_zjq_3, R.id.ll_pop_zjq_4, R.id.ll_pop_zjq_5,
// R.id.ll_pop_zjq_6, R.id.ll_pop_zjq_7};
public ZjqPlayView(Context context, AttributeSet attrs)
{
super(context, attrs);
this.mContext = (Activity) context;
// TODO Auto-generated constructor stub
}
protected LayoutInflater inflater;
public ZjqPlayView(Activity activity, MatchInfo matchInfo,HashMap<String, String> map,OnOddsChooseFinishListener onOddsChooseFinishListener)
{
super(activity);
this.mContext = activity;
this.jczqMatchInfo = (JczqMatchInfo) matchInfo;
this.listener=onOddsChooseFinishListener;
this.hasChoosedMap=map;
initViewDatas();
initView();
}
protected void initViewDatas()
{
initZjqDatas();
}
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
}
protected void initView()
{
// 获取当前屏幕的横竖屏
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.jczq_pop_view_zjq, this);
initHeadview();
initPopZjqViews();
initPopZjqLayoutViews();
confirmBtn = findViewById(R.id.zjq_pop_confirm);
cancelBtn = findViewById(R.id.zjq_pop_cancel);
confirmBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
onConfirmChoose();
onDismiss();
}
});
cancelBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
onDismiss();
}
});
}
protected void initHeadview()
{
popHostView = (TextView) findViewById(R.id.tv_pop_bf_host);
popGuestView = (TextView) findViewById(R.id.tv_pop_bf_guest);
popHostView.setText(jczqMatchInfo.getHome());
popGuestView.setText(jczqMatchInfo.getGuest());
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
// TODO Auto-generated method stub
return true;
}
public void dismissAdView()
{
this.setVisibility(View.GONE);
}
}
| UTF-8 | Java | 3,551 | java | ZjqPlayView.java | Java | [] | null | [] | package com.caixiang.lottery.ui.widget;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.caixiang.lottery.R;
import com.caixiang.lottery.core.service.match.model.JczqMatchInfo;
import com.caixiang.lottery.core.service.match.model.MatchInfo;
import com.caixiang.lottery.ui.widget.HunhePlayView.OnOddsChooseFinishListener;
public class ZjqPlayView extends HunhePlayView
{
// /**
// * 总进球
// */
// private List<TextView> popZjqViews;
//
// private List<LinearLayout> popZjqLayoutViews;
//
// private int[] popZjqViewIds = new int[] {R.id.tv_pop_zjq_0,
// R.id.tv_pop_zjq_1, R.id.tv_pop_zjq_2,
// R.id.tv_pop_zjq_3, R.id.tv_pop_zjq_4, R.id.tv_pop_zjq_5,
// R.id.tv_pop_zjq_6, R.id.tv_pop_zjq_7};
//
// private int[] popZjqLayoutViewIds = new int[] {R.id.ll_pop_zjq_0,
// R.id.ll_pop_zjq_1, R.id.ll_pop_zjq_2,
// R.id.ll_pop_zjq_3, R.id.ll_pop_zjq_4, R.id.ll_pop_zjq_5,
// R.id.ll_pop_zjq_6, R.id.ll_pop_zjq_7};
public ZjqPlayView(Context context, AttributeSet attrs)
{
super(context, attrs);
this.mContext = (Activity) context;
// TODO Auto-generated constructor stub
}
protected LayoutInflater inflater;
public ZjqPlayView(Activity activity, MatchInfo matchInfo,HashMap<String, String> map,OnOddsChooseFinishListener onOddsChooseFinishListener)
{
super(activity);
this.mContext = activity;
this.jczqMatchInfo = (JczqMatchInfo) matchInfo;
this.listener=onOddsChooseFinishListener;
this.hasChoosedMap=map;
initViewDatas();
initView();
}
protected void initViewDatas()
{
initZjqDatas();
}
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
}
protected void initView()
{
// 获取当前屏幕的横竖屏
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.jczq_pop_view_zjq, this);
initHeadview();
initPopZjqViews();
initPopZjqLayoutViews();
confirmBtn = findViewById(R.id.zjq_pop_confirm);
cancelBtn = findViewById(R.id.zjq_pop_cancel);
confirmBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
onConfirmChoose();
onDismiss();
}
});
cancelBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
onDismiss();
}
});
}
protected void initHeadview()
{
popHostView = (TextView) findViewById(R.id.tv_pop_bf_host);
popGuestView = (TextView) findViewById(R.id.tv_pop_bf_guest);
popHostView.setText(jczqMatchInfo.getHome());
popGuestView.setText(jczqMatchInfo.getGuest());
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
// TODO Auto-generated method stub
return true;
}
public void dismissAdView()
{
this.setVisibility(View.GONE);
}
}
| 3,551 | 0.630922 | 0.626383 | 125 | 27.200001 | 24.962051 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.552 | false | false | 2 |
e2b80f34b7af466353c95265809f9f04d86c5625 | 12,429,635,376,428 | 0f6d5e0c322298fcfb384deed78d55bb8abdce3e | /src/ibm/WordFactor.java | 92e6256c8f17f601423c3bc46fd6e0a92c4beda8 | [] | no_license | vnkt/IBMRemote | https://github.com/vnkt/IBMRemote | c052bf3e20f0338508886cb64713083c3721beb8 | bb436f26391fb4f28c5c82823e0e4321a5ac2654 | refs/heads/master | 2021-01-10T01:28:37.820000 | 2015-12-19T13:40:53 | 2015-12-19T13:40:53 | 48,283,268 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ibm;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.*;
public class WordFactor
{
static String answer_Text;
static String question_Text;
static String query_ID;
static String query_Category;
static String query_Type;
static String result;
static String questionResult;
static String domain[] = {"eng_faq"};
static String queries[] = {"English"};
static String catgry;
static int tokenCount;
static int i,j,k;
static String[] strQuestion;
static String bannedWords[] = {"what","the","is","was","a","and","but","will","can","could","would","an","who"};
static boolean flagRepeatedWord = true;
static boolean flagIsBanned = true;
static Writer outputWriter = null;
public WordFactor()
{
try
{
for(int a=0;a<domain.length;a++)
{
//Source file
File file = new File("E:\\E Books\\FIRE_TRAINING_DATA\\FIRE_TRAINING_DATA\\FAQs\\"+queries[a]+"\\"+domain[a]+".xml");
//Document Builder
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
//Getting all Sms
NodeList nodeLst = doc.getElementsByTagName("FAQ");
//creating the parent directory
String s1 = "E:\\IBM Temp\\Trainigsetanswers\\"+queries[a];
(new File(s1)).mkdirs();
try
{
System.out.print("DOne \n");
//to read all the nodes from the file under each language
for (int loop_count = 0; loop_count < nodeLst.getLength(); loop_count++)
{
//Looping for all SMS
Node fstNode = nodeLst.item(loop_count);
if (fstNode.getNodeType() == Node.ELEMENT_NODE)
{
//Getting query ID
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("FAQID");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
query_ID = ((Node) fstNm.item(0)).getNodeValue();
//getting domain name
Element fstElmnt1 = (Element) fstNode;
NodeList fstNmElmntLst1 = fstElmnt1.getElementsByTagName("DOMAIN");
Element fstNmElmnt1 = (Element) fstNmElmntLst1.item(0);
NodeList fstNm1 = fstNmElmnt1.getChildNodes();
catgry = ((Node) fstNm1.item(0)).getNodeValue();
//loops for matching the category from the file and the given string array
//to create a new folder with the domain name
(new File(s1+"/"+catgry)).mkdirs();
File file2 = new File(s1+"/"+catgry+ "/"+"log.txt");
FileWriter fstream = new FileWriter(file2,true);
outputWriter = new BufferedWriter(fstream);
outputWriter.write(query_ID);
outputWriter.write(" - ");
fstNmElmntLst = fstElmnt.getElementsByTagName("QUESTION");
fstNmElmnt = (Element) fstNmElmntLst.item(0);
fstNm = fstNmElmnt.getChildNodes();
question_Text = ((Node) fstNm.item(0)).getNodeValue();
StringTokenizer token2 = new StringTokenizer(question_Text);
tokenCount = token2.countTokens();
strQuestion = new String[tokenCount];
try
{
for(i=0;i<tokenCount;i++)
{
questionResult = token2.nextToken();
questionResult = questionResult.trim();
strQuestion[i] = questionResult;
if(questionResult.endsWith("?")||questionResult.endsWith("."))
questionResult = questionResult.substring(0, questionResult.length()-1);
for(j=0;j<i;j++)
{
if(strQuestion[j].equalsIgnoreCase(questionResult))
flagRepeatedWord=false;
}
for(j=0;j<12;j++)
{
if(questionResult.equalsIgnoreCase(bannedWords[j]))
flagIsBanned=false;
}
if(flagRepeatedWord==true && flagIsBanned==true)
{
outputWriter.write(questionResult);
//outputWriter.write(" ");
System.out.println(questionResult);
questionResult = questionResult.trim();
try
{
//System.out.println("E:\\IBM Temp\\dictionary\\" + questionResult);
FileInputStream synonymStream = new FileInputStream(new File("E:\\IBM Temp\\dictionary\\" + questionResult));
BufferedReader synonymReader = new BufferedReader(new InputStreamReader(new DataInputStream(synonymStream)));
String synonymLine = new String();
System.out.println(query_ID + " " + questionResult + " ");
while((synonymLine = synonymReader.readLine()) != null)
{
outputWriter.write(synonymLine);
//outputWriter.write(" ");
System.out.println("\t" + synonymLine);
}
System.out.println("\n");
}
catch(Exception e)
{
System.out.println("+1");
continue;
}
}
flagRepeatedWord = true;
flagIsBanned = true;
}
}
catch(Exception e)
{
System.out.print("Exception:" + e);
}
outputWriter.close();
//to create answer files under each domain after matching
File file1 = new File(s1+"/"+catgry+"/"+query_ID+".txt");
Writer output = null;
output = new BufferedWriter(new FileWriter(file1));
//Getting SMS Content
fstNmElmntLst = fstElmnt.getElementsByTagName("ANSWER");
fstNmElmnt = (Element) fstNmElmntLst.item(0);
fstNm = fstNmElmnt.getChildNodes();
answer_Text = ((Node) fstNm.item(0)).getNodeValue();
StringTokenizer token = new StringTokenizer(answer_Text);
try
{
while (token.hasMoreTokens())
{
result = token.nextToken();
output.write(result);
}
output.close();
}
catch(Exception e)
{
System.out.print("Exception" + e);
}
}
}
}
catch(Exception e)
{
System.out.print("Exception:" + e);
}
}
}
catch (Exception e)
{
System.out.println("Exception " + e );
}
}
}
| UTF-8 | Java | 10,668 | java | WordFactor.java | Java | [] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ibm;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.*;
public class WordFactor
{
static String answer_Text;
static String question_Text;
static String query_ID;
static String query_Category;
static String query_Type;
static String result;
static String questionResult;
static String domain[] = {"eng_faq"};
static String queries[] = {"English"};
static String catgry;
static int tokenCount;
static int i,j,k;
static String[] strQuestion;
static String bannedWords[] = {"what","the","is","was","a","and","but","will","can","could","would","an","who"};
static boolean flagRepeatedWord = true;
static boolean flagIsBanned = true;
static Writer outputWriter = null;
public WordFactor()
{
try
{
for(int a=0;a<domain.length;a++)
{
//Source file
File file = new File("E:\\E Books\\FIRE_TRAINING_DATA\\FIRE_TRAINING_DATA\\FAQs\\"+queries[a]+"\\"+domain[a]+".xml");
//Document Builder
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
//Getting all Sms
NodeList nodeLst = doc.getElementsByTagName("FAQ");
//creating the parent directory
String s1 = "E:\\IBM Temp\\Trainigsetanswers\\"+queries[a];
(new File(s1)).mkdirs();
try
{
System.out.print("DOne \n");
//to read all the nodes from the file under each language
for (int loop_count = 0; loop_count < nodeLst.getLength(); loop_count++)
{
//Looping for all SMS
Node fstNode = nodeLst.item(loop_count);
if (fstNode.getNodeType() == Node.ELEMENT_NODE)
{
//Getting query ID
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("FAQID");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
query_ID = ((Node) fstNm.item(0)).getNodeValue();
//getting domain name
Element fstElmnt1 = (Element) fstNode;
NodeList fstNmElmntLst1 = fstElmnt1.getElementsByTagName("DOMAIN");
Element fstNmElmnt1 = (Element) fstNmElmntLst1.item(0);
NodeList fstNm1 = fstNmElmnt1.getChildNodes();
catgry = ((Node) fstNm1.item(0)).getNodeValue();
//loops for matching the category from the file and the given string array
//to create a new folder with the domain name
(new File(s1+"/"+catgry)).mkdirs();
File file2 = new File(s1+"/"+catgry+ "/"+"log.txt");
FileWriter fstream = new FileWriter(file2,true);
outputWriter = new BufferedWriter(fstream);
outputWriter.write(query_ID);
outputWriter.write(" - ");
fstNmElmntLst = fstElmnt.getElementsByTagName("QUESTION");
fstNmElmnt = (Element) fstNmElmntLst.item(0);
fstNm = fstNmElmnt.getChildNodes();
question_Text = ((Node) fstNm.item(0)).getNodeValue();
StringTokenizer token2 = new StringTokenizer(question_Text);
tokenCount = token2.countTokens();
strQuestion = new String[tokenCount];
try
{
for(i=0;i<tokenCount;i++)
{
questionResult = token2.nextToken();
questionResult = questionResult.trim();
strQuestion[i] = questionResult;
if(questionResult.endsWith("?")||questionResult.endsWith("."))
questionResult = questionResult.substring(0, questionResult.length()-1);
for(j=0;j<i;j++)
{
if(strQuestion[j].equalsIgnoreCase(questionResult))
flagRepeatedWord=false;
}
for(j=0;j<12;j++)
{
if(questionResult.equalsIgnoreCase(bannedWords[j]))
flagIsBanned=false;
}
if(flagRepeatedWord==true && flagIsBanned==true)
{
outputWriter.write(questionResult);
//outputWriter.write(" ");
System.out.println(questionResult);
questionResult = questionResult.trim();
try
{
//System.out.println("E:\\IBM Temp\\dictionary\\" + questionResult);
FileInputStream synonymStream = new FileInputStream(new File("E:\\IBM Temp\\dictionary\\" + questionResult));
BufferedReader synonymReader = new BufferedReader(new InputStreamReader(new DataInputStream(synonymStream)));
String synonymLine = new String();
System.out.println(query_ID + " " + questionResult + " ");
while((synonymLine = synonymReader.readLine()) != null)
{
outputWriter.write(synonymLine);
//outputWriter.write(" ");
System.out.println("\t" + synonymLine);
}
System.out.println("\n");
}
catch(Exception e)
{
System.out.println("+1");
continue;
}
}
flagRepeatedWord = true;
flagIsBanned = true;
}
}
catch(Exception e)
{
System.out.print("Exception:" + e);
}
outputWriter.close();
//to create answer files under each domain after matching
File file1 = new File(s1+"/"+catgry+"/"+query_ID+".txt");
Writer output = null;
output = new BufferedWriter(new FileWriter(file1));
//Getting SMS Content
fstNmElmntLst = fstElmnt.getElementsByTagName("ANSWER");
fstNmElmnt = (Element) fstNmElmntLst.item(0);
fstNm = fstNmElmnt.getChildNodes();
answer_Text = ((Node) fstNm.item(0)).getNodeValue();
StringTokenizer token = new StringTokenizer(answer_Text);
try
{
while (token.hasMoreTokens())
{
result = token.nextToken();
output.write(result);
}
output.close();
}
catch(Exception e)
{
System.out.print("Exception" + e);
}
}
}
}
catch(Exception e)
{
System.out.print("Exception:" + e);
}
}
}
catch (Exception e)
{
System.out.println("Exception " + e );
}
}
}
| 10,668 | 0.365298 | 0.361361 | 208 | 50.28846 | 33.765503 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false | 2 |
29451bf53f3ee5d96fc4a97a869893a340faf36e | 7,473,243,159,052 | 77f1f3e56f5b27071189eb4c61a7a59e11e2a958 | /sevenget/src/main/java/com/sevenget/seven/LoginController.java | 9aa31b1ad7b10bf8741e3a287177e65ec00feaad | [] | no_license | sevenget/finpjt | https://github.com/sevenget/finpjt | 9d38bf382aa5dd53d1cda971f4d4f99297fbeacb | 25db02851f44b714b1d4b738606eb7d710603a93 | refs/heads/master | 2021-04-30T10:13:03.167000 | 2018-03-07T07:32:20 | 2018-03-07T07:32:20 | 121,327,239 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sevenget.seven;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import model.member.MemBasicInfoDAO;
import model.member.MemBasicInfoDTO;
import model.member.MemIdCheckDaoImpl;
import model.member.MemLoginDao;
/**
* Handles requests for the application home page.
*/
@Controller
@RequestMapping(value="/main")
public class LoginController {
// 로그인화면
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String Login(HttpSession session, Locale locale, Model model) {
String id = (String)session.getAttribute("id");
if(id!=null) {
return "redirect:/main/main";
}
return "main/login";
}
// 로그인 체크
@RequestMapping(value = "/loginCheck", method = RequestMethod.GET)
public ModelAndView loginCheck(String id,String pw, MemLoginDao dao,MemBasicInfoDTO dto,
ModelAndView mav, HttpSession session, HttpServletResponse response) {
dto = dao.loginCheck(id,pw);
if(dto == null){
System.out.println("컨트롤러 - 로그인 실패");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out;
try {
out = response.getWriter();
out.println("<script>alert('로그인 정보를 확인해주세요.'); history.go(-1);</script>");
return null;
} catch (IOException e) {
System.out.println("LoginController -> loginCheck -> PrintWriter 변수 생성 오류");
}
return null;
}else{
System.out.printf("컨트롤러 - %s 로그인 성공",id);
session.setAttribute("id", id);
mav.setViewName("main/loginCheck");
return mav;
}
}
// 로그아웃
@RequestMapping(value = "/logOut", method = RequestMethod.GET)
public ModelAndView loginCheck(MemLoginDao dao, ModelAndView mav, HttpSession session) {
session.invalidate();
mav.setViewName("main/logOut");
return mav;
}
// 회원가입페이지로 이동
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String Register(Locale locale, Model model) {
return "main/register";
}
//@아이디 중복확인
@RequestMapping(value="/checkID", method = RequestMethod.GET)
public ModelAndView CheckId(ModelAndView mav,@RequestParam("id")String id){
MemIdCheckDaoImpl dao = new MemIdCheckDaoImpl();
int check = dao.Check(id);
mav.addObject("id",id);
mav.addObject("check",check);
mav.setViewName("main/member_id_check");
return mav;
}
// 회원가입 하기
@RequestMapping(value="/insertUser", method = RequestMethod.POST)
public ModelAndView insertMember(ModelAndView mav,@RequestParam("id")String id,
@RequestParam("password")String password,@RequestParam("name")String name,@RequestParam("birth") String birth,
@RequestParam("gender")String gender,@RequestParam("address")String address,
@RequestParam("email")String email,@RequestParam("dateCon")int dateCon,
@RequestParam("marryCon")int marryCon,@RequestParam("babyCon")int babyCon,
@RequestParam("houseCon")int houseCon,@RequestParam("relationCon")int relationCon,
@RequestParam("dreamCon")int dreamCon,@RequestParam("hopeCon")int hopeCon){
MemBasicInfoDAO dao = new MemBasicInfoDAO();
MemBasicInfoDTO dto = new MemBasicInfoDTO();
dto.setId(id);
dto.setPassword(password);
dto.setName(name);
dto.setBirth(birth);
dto.setGender(gender);
dto.setAddress(address);
dto.setEmail(email);
dto.setDateCon(dateCon);
dto.setMarryCon(marryCon);
dto.setBabyCon(babyCon);
dto.setHouseCon(houseCon);
dto.setRelationCon(relationCon);
dto.setDreamCon(dreamCon);
dto.setHopeCon(hopeCon);
dao.insertMember(dto);
mav.setViewName("main/login");
return mav;
}
}
| UTF-8 | Java | 4,201 | java | LoginController.java | Java | [
{
"context": "foDTO();\r\n\t\t\r\n\t\tdto.setId(id);\r\n\t\tdto.setPassword(password);\r\n\t\tdto.setName(name);\r\n\t\tdto.setBirth(birth);\r\n",
"end": 3621,
"score": 0.9975790977478027,
"start": 3613,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | package com.sevenget.seven;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import model.member.MemBasicInfoDAO;
import model.member.MemBasicInfoDTO;
import model.member.MemIdCheckDaoImpl;
import model.member.MemLoginDao;
/**
* Handles requests for the application home page.
*/
@Controller
@RequestMapping(value="/main")
public class LoginController {
// 로그인화면
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String Login(HttpSession session, Locale locale, Model model) {
String id = (String)session.getAttribute("id");
if(id!=null) {
return "redirect:/main/main";
}
return "main/login";
}
// 로그인 체크
@RequestMapping(value = "/loginCheck", method = RequestMethod.GET)
public ModelAndView loginCheck(String id,String pw, MemLoginDao dao,MemBasicInfoDTO dto,
ModelAndView mav, HttpSession session, HttpServletResponse response) {
dto = dao.loginCheck(id,pw);
if(dto == null){
System.out.println("컨트롤러 - 로그인 실패");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out;
try {
out = response.getWriter();
out.println("<script>alert('로그인 정보를 확인해주세요.'); history.go(-1);</script>");
return null;
} catch (IOException e) {
System.out.println("LoginController -> loginCheck -> PrintWriter 변수 생성 오류");
}
return null;
}else{
System.out.printf("컨트롤러 - %s 로그인 성공",id);
session.setAttribute("id", id);
mav.setViewName("main/loginCheck");
return mav;
}
}
// 로그아웃
@RequestMapping(value = "/logOut", method = RequestMethod.GET)
public ModelAndView loginCheck(MemLoginDao dao, ModelAndView mav, HttpSession session) {
session.invalidate();
mav.setViewName("main/logOut");
return mav;
}
// 회원가입페이지로 이동
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String Register(Locale locale, Model model) {
return "main/register";
}
//@아이디 중복확인
@RequestMapping(value="/checkID", method = RequestMethod.GET)
public ModelAndView CheckId(ModelAndView mav,@RequestParam("id")String id){
MemIdCheckDaoImpl dao = new MemIdCheckDaoImpl();
int check = dao.Check(id);
mav.addObject("id",id);
mav.addObject("check",check);
mav.setViewName("main/member_id_check");
return mav;
}
// 회원가입 하기
@RequestMapping(value="/insertUser", method = RequestMethod.POST)
public ModelAndView insertMember(ModelAndView mav,@RequestParam("id")String id,
@RequestParam("password")String password,@RequestParam("name")String name,@RequestParam("birth") String birth,
@RequestParam("gender")String gender,@RequestParam("address")String address,
@RequestParam("email")String email,@RequestParam("dateCon")int dateCon,
@RequestParam("marryCon")int marryCon,@RequestParam("babyCon")int babyCon,
@RequestParam("houseCon")int houseCon,@RequestParam("relationCon")int relationCon,
@RequestParam("dreamCon")int dreamCon,@RequestParam("hopeCon")int hopeCon){
MemBasicInfoDAO dao = new MemBasicInfoDAO();
MemBasicInfoDTO dto = new MemBasicInfoDTO();
dto.setId(id);
dto.setPassword(<PASSWORD>);
dto.setName(name);
dto.setBirth(birth);
dto.setGender(gender);
dto.setAddress(address);
dto.setEmail(email);
dto.setDateCon(dateCon);
dto.setMarryCon(marryCon);
dto.setBabyCon(babyCon);
dto.setHouseCon(houseCon);
dto.setRelationCon(relationCon);
dto.setDreamCon(dreamCon);
dto.setHopeCon(hopeCon);
dao.insertMember(dto);
mav.setViewName("main/login");
return mav;
}
}
| 4,203 | 0.709741 | 0.709248 | 130 | 29.192308 | 26.036098 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.176923 | false | false | 2 |
b7d00d588fcf5b3af69940bece87ce1c91555773 | 10,960,756,610,824 | db8d0016325aec485bf8b66a7d0f84bb925cc7d0 | /shop-service-api/src/main/java/com/rt/shop/service/IComplaintSubjectService.java | 39bf0f59d69ebdcf0679a4c2c62a61e7c3ee4c7b | [] | no_license | jjmnbv/shop | https://github.com/jjmnbv/shop | a0ff70e235de91198cea0a7b0efc270a8719ccd0 | 48c6d47f12468b5692f13c20f7c7f24592acb1b0 | refs/heads/master | 2021-06-12T14:09:31.784000 | 2017-04-07T02:59:12 | 2017-04-07T02:59:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rt.shop.service;
import com.rt.shop.entity.ComplaintSubject;
import com.baomidou.framework.service.ISuperService;
/**
*
* ComplaintSubject 表数据服务层接口
*
*/
public interface IComplaintSubjectService extends ISuperService<ComplaintSubject> {
} | UTF-8 | Java | 274 | java | IComplaintSubjectService.java | Java | [] | null | [] | package com.rt.shop.service;
import com.rt.shop.entity.ComplaintSubject;
import com.baomidou.framework.service.ISuperService;
/**
*
* ComplaintSubject 表数据服务层接口
*
*/
public interface IComplaintSubjectService extends ISuperService<ComplaintSubject> {
} | 274 | 0.794574 | 0.794574 | 14 | 17.5 | 24.999287 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.214286 | false | false | 2 |
d1224f445e70e5b145d8e9aa23c4a1063e7a37a0 | 31,971,736,593,171 | 516a623e5ea846a83123de733271184d9f5238b3 | /src/main/java/markprojects/SubImage.java | ab8439c28010a8e92874e0decfa8383d7a591fc4 | [] | no_license | markers920/image-collage | https://github.com/markers920/image-collage | 01a41fce730a67a105b3502f8b94103b014870b6 | 49730a971612f871de50316a097a28662fb26108 | refs/heads/master | 2021-01-10T07:17:17.281000 | 2015-12-27T23:43:12 | 2015-12-27T23:43:12 | 48,595,931 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package markprojects;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SubImage {
private static final int[] WIDTH_NUMERATOR = {1, 2, 3, 4, 1, 3, 1, 2, 4, 1, 3};
private static final int[] HEIGHT_DENOMINATOR = {1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4};
public static final int SIZE_ONE = 80;
//private BufferedImage image;
private int origWidth;
private int origHeight;
private double origRatio;
private int bestRatioIndex;
private double bestRatio;
private BufferedImage cleanImage;
private double avgRed = 0.0;
private double avgGreen = 0.0;
private double avgBlue = 0.0;
private double avgAlpha = 0.0;
public SubImage(File file) throws IOException {
BufferedImage image = ImageIO.read(file);
this.origWidth = image.getWidth();
this.origHeight = image.getHeight();
origRatio = (double)origWidth / origHeight;
bestRatioIndex = -1;
double smallestDifference = Double.MAX_VALUE;
for(int ratioIndex = 0; ratioIndex < WIDTH_NUMERATOR.length; ratioIndex++) {
double testRatio = (double)WIDTH_NUMERATOR[ratioIndex] / HEIGHT_DENOMINATOR[ratioIndex];
double difference = Math.abs(origRatio - testRatio);
if(difference < smallestDifference) {
bestRatioIndex = ratioIndex;
smallestDifference = difference;
}
}
bestRatio = (double)WIDTH_NUMERATOR[bestRatioIndex] / HEIGHT_DENOMINATOR[bestRatioIndex];
cropImage(image);
getAverageColor();
}
public int cellWidth() {
return WIDTH_NUMERATOR[bestRatioIndex];
}
public int cellHeight() {
return HEIGHT_DENOMINATOR[bestRatioIndex];
}
private void cropImage(BufferedImage image) {
int x, y, w, h;
if(origRatio < bestRatio) {
//width is smaller than expected
w = origWidth;
h = (int)(w / bestRatio);
x = 0;
y = (int)((origHeight - h)/2.0);
} else {
//height is smaller than expected
h = origHeight;
w = (int)(h * bestRatio);
y = 0;
x = (int)((origWidth - w)/2.0);
}
BufferedImage croppedImage = image.getSubimage(x, y, w, h);
cleanImage = new BufferedImage(
SIZE_ONE * WIDTH_NUMERATOR[bestRatioIndex],
SIZE_ONE * HEIGHT_DENOMINATOR[bestRatioIndex],
croppedImage.getType());
// scales the input image to the output image
Graphics2D g2d = cleanImage.createGraphics();
g2d.drawImage(
croppedImage,
0, 0,
SIZE_ONE * WIDTH_NUMERATOR[bestRatioIndex],
SIZE_ONE * HEIGHT_DENOMINATOR[bestRatioIndex],
null);
g2d.dispose();
}
public BufferedImage getImage() {
//return this.croppedImage;
return this.cleanImage;
}
private void getAverageColor() {
avgRed = 0.0;
avgGreen = 0.0;
avgBlue = 0.0;
avgAlpha = 0.0;
int numConsidderd = 0;
for(int imageX = 0; imageX < cleanImage.getWidth(); imageX++) {
for(int imageY = 0; imageY < cleanImage.getHeight(); imageY++) {
Color c = new Color(cleanImage.getRGB(imageX, imageY));
avgRed += c.getRed() / 255.0;
avgGreen += c.getGreen() / 255.0;
avgBlue += c.getBlue() / 255.0;
avgAlpha += c.getAlpha() / 255.0;
numConsidderd++;
}
}
avgRed /= numConsidderd;
avgGreen /= numConsidderd;
avgBlue /= numConsidderd;
avgAlpha /= numConsidderd;
}
public double getColorDistance(Color c) {
double ret = 0.0;
ret += Math.pow(avgRed - (c.getRed()/255.0), 2.0);
ret += Math.pow(avgGreen - (c.getGreen()/255.0), 2.0);
ret += Math.pow(avgBlue - (c.getBlue()/255.0), 2.0);
ret += Math.pow(avgAlpha - (c.getAlpha()/255.0), 2.0);
return Math.sqrt(ret);
}
}
| UTF-8 | Java | 3,587 | java | SubImage.java | Java | [] | null | [] | package markprojects;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SubImage {
private static final int[] WIDTH_NUMERATOR = {1, 2, 3, 4, 1, 3, 1, 2, 4, 1, 3};
private static final int[] HEIGHT_DENOMINATOR = {1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4};
public static final int SIZE_ONE = 80;
//private BufferedImage image;
private int origWidth;
private int origHeight;
private double origRatio;
private int bestRatioIndex;
private double bestRatio;
private BufferedImage cleanImage;
private double avgRed = 0.0;
private double avgGreen = 0.0;
private double avgBlue = 0.0;
private double avgAlpha = 0.0;
public SubImage(File file) throws IOException {
BufferedImage image = ImageIO.read(file);
this.origWidth = image.getWidth();
this.origHeight = image.getHeight();
origRatio = (double)origWidth / origHeight;
bestRatioIndex = -1;
double smallestDifference = Double.MAX_VALUE;
for(int ratioIndex = 0; ratioIndex < WIDTH_NUMERATOR.length; ratioIndex++) {
double testRatio = (double)WIDTH_NUMERATOR[ratioIndex] / HEIGHT_DENOMINATOR[ratioIndex];
double difference = Math.abs(origRatio - testRatio);
if(difference < smallestDifference) {
bestRatioIndex = ratioIndex;
smallestDifference = difference;
}
}
bestRatio = (double)WIDTH_NUMERATOR[bestRatioIndex] / HEIGHT_DENOMINATOR[bestRatioIndex];
cropImage(image);
getAverageColor();
}
public int cellWidth() {
return WIDTH_NUMERATOR[bestRatioIndex];
}
public int cellHeight() {
return HEIGHT_DENOMINATOR[bestRatioIndex];
}
private void cropImage(BufferedImage image) {
int x, y, w, h;
if(origRatio < bestRatio) {
//width is smaller than expected
w = origWidth;
h = (int)(w / bestRatio);
x = 0;
y = (int)((origHeight - h)/2.0);
} else {
//height is smaller than expected
h = origHeight;
w = (int)(h * bestRatio);
y = 0;
x = (int)((origWidth - w)/2.0);
}
BufferedImage croppedImage = image.getSubimage(x, y, w, h);
cleanImage = new BufferedImage(
SIZE_ONE * WIDTH_NUMERATOR[bestRatioIndex],
SIZE_ONE * HEIGHT_DENOMINATOR[bestRatioIndex],
croppedImage.getType());
// scales the input image to the output image
Graphics2D g2d = cleanImage.createGraphics();
g2d.drawImage(
croppedImage,
0, 0,
SIZE_ONE * WIDTH_NUMERATOR[bestRatioIndex],
SIZE_ONE * HEIGHT_DENOMINATOR[bestRatioIndex],
null);
g2d.dispose();
}
public BufferedImage getImage() {
//return this.croppedImage;
return this.cleanImage;
}
private void getAverageColor() {
avgRed = 0.0;
avgGreen = 0.0;
avgBlue = 0.0;
avgAlpha = 0.0;
int numConsidderd = 0;
for(int imageX = 0; imageX < cleanImage.getWidth(); imageX++) {
for(int imageY = 0; imageY < cleanImage.getHeight(); imageY++) {
Color c = new Color(cleanImage.getRGB(imageX, imageY));
avgRed += c.getRed() / 255.0;
avgGreen += c.getGreen() / 255.0;
avgBlue += c.getBlue() / 255.0;
avgAlpha += c.getAlpha() / 255.0;
numConsidderd++;
}
}
avgRed /= numConsidderd;
avgGreen /= numConsidderd;
avgBlue /= numConsidderd;
avgAlpha /= numConsidderd;
}
public double getColorDistance(Color c) {
double ret = 0.0;
ret += Math.pow(avgRed - (c.getRed()/255.0), 2.0);
ret += Math.pow(avgGreen - (c.getGreen()/255.0), 2.0);
ret += Math.pow(avgBlue - (c.getBlue()/255.0), 2.0);
ret += Math.pow(avgAlpha - (c.getAlpha()/255.0), 2.0);
return Math.sqrt(ret);
}
}
| 3,587 | 0.67438 | 0.646501 | 138 | 24.992754 | 21.291115 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.521739 | false | false | 2 |
1dbcf35c189327288561ec25d9c66ef7014590b3 | 2,147,483,710,976 | aa088773dddbc242c438225a6bf44dd4cd47f390 | /src/com/chute/parser/source/CustomEventSource.java | 6ca600306129a2700c02f8da61b60d558568ece8 | [] | no_license | standahj/DataGenerator | https://github.com/standahj/DataGenerator | 1596f06530c52f6b674ef9336c9d98145e1150bc | d63472b19111e246ba9d574e9b646eec8d6ffa0c | refs/heads/master | 2020-03-23T16:36:58.148000 | 2018-07-22T10:24:27 | 2018-07-22T10:24:27 | 141,820,201 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chute.parser.source;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.EventDrivenSource;
import org.apache.flume.conf.Configurable;
import org.apache.flume.source.AbstractSource;
import org.slf4j.LoggerFactory;
import com.chute.parser.event.EventParser;
import com.chute.parser.event.config.EventParserConfig;
/**
*
* @author shejny
*
* CustomEventSource provides equivalent functionality as NetcatSource but instead just copying the input line by line as event to a channel,
* it calls an EventParser, which is able to join multiple lines into one event based on regExp criteria for event boundaries
*
* This is event driven source though it can also be converted to poll-able source by un-commenting process(), getBackOffSleepIncrement(), getBackOffSleepInterval() and
* changing implemented interface from EventDrivenSource to PollableSource
*/
public class CustomEventSource extends AbstractSource implements Configurable, EventDrivenSource {
public CustomEventSource() {}
private int port = -1; // listening port this source binds to
private ServerSocket serverSocket; // Server socket that will listen on the above port for client connections
private BlockingQueue<Event> distributedQueue; // used for PollableSource implementation only. Not used in EventDrivenImplementation
private boolean keepListening = true; // allows for graceful exit from socket listening loop on shutdown
/**
* Read configuration values for this source from flume-ng configuration properties file
*
* All values except 'port' have default value provided in EventParserConfig class.
* This method is called by Flume-ng framework in the Source initialization phase.
*
*/
@Override
public void configure(Context context) {
/*
port = context.getInteger("port");
String regexp = context.getString("BREAK_ONLY_BEFORE");
if (regexp != null) {
EventParserConfig.BREAK_ONLY_BEFORE = regexp;
}
System.out.println("Regexp BREAK_ONLY_BEFORE: "+EventParserConfig.BREAK_ONLY_BEFORE);
regexp = context.getString("MUST_BREAK_AFTER");
if (regexp != null) {
EventParserConfig.MUST_BREAK_AFTER = regexp;
}
System.out.println("Regexp MUST_BREAK_AFTER: "+EventParserConfig.MUST_BREAK_AFTER);
regexp = context.getString("MUST_NOT_BREAK_AFTER");
if (regexp != null) {
EventParserConfig.MUST_NOT_BREAK_AFTER = regexp;
}
System.out.println("Regexp MUST_NOT_BREAK_AFTER: "+EventParserConfig.MUST_NOT_BREAK_AFTER);
regexp = context.getString("MUST_NOT_BREAK_BEFORE");
if (regexp != null) {
EventParserConfig.MUST_NOT_BREAK_BEFORE = regexp;
}
System.out.println("Regexp MUST_NOT_BREAK_BEFORE: "+EventParserConfig.MUST_NOT_BREAK_BEFORE);
regexp = context.getString("EVENT_BREAKER");
if (regexp != null) {
EventParserConfig.EVENT_BREAKER = regexp;
}
System.out.println("Regexp EVENT_BREAKER: "+EventParserConfig.EVENT_BREAKER);
regexp = context.getString("LINE_BREAKER");
if (regexp != null) {
EventParserConfig.LINE_BREAKER = regexp;
}
System.out.println("Regexp LINE_BREAKER: "+EventParserConfig.LINE_BREAKER);
Boolean flag = context.getBoolean("BREAK_ONLY_BEFORE_DATE");
if (flag != null) {
EventParserConfig.BREAK_ONLY_BEFORE_DATE = flag;
}
System.out.println("Flag BREAK_ONLY_BEFORE_DATE: "+EventParserConfig.BREAK_ONLY_BEFORE_DATE);
flag = context.getBoolean("SHOULD_LINEMERGE");
if (flag != null) {
EventParserConfig.SHOULD_LINEMERGE = flag;
}
System.out.println("Flag SHOULD_LINEMERGE: "+EventParserConfig.SHOULD_LINEMERGE);
Integer limit = context.getInteger("LINE_BREAKER_LOOKBEHIND");
if (limit != null) {
EventParserConfig.LINE_BREAKER_LOOKBEHIND = limit;
}
System.out.println("Value LINE_BREAKER_LOOKBEHIND: "+EventParserConfig.LINE_BREAKER_LOOKBEHIND);
limit = context.getInteger("MAX_EVENTS");
if (limit != null) {
EventParserConfig.MAX_EVENTS = limit;
}
limit = context.getInteger("TRUNCATE");
System.out.println("Value MAX_EVENTS: "+EventParserConfig.MAX_EVENTS);
if (limit != null) {
EventParserConfig.TRUNCATE = limit;
}
System.out.println("value TRUNCATE: "+EventParserConfig.TRUNCATE);
*/
// System.out.println("****** Configuring CustomEventSource on port: "+port);
}
/**
* This method is called by Flume-ng framework to start this source.
* The socket binds to the configured port and start listening for connections.
* The actual client connection to host:port is the event that triggers EventParser instantiation and it starts new thread
* to handle this client connection in parallel.
*
* keepListening facilitates graceful exist from the parallel thread and also from the socket listening loop on flume-ng shutdown
*/
@Override
public void start() {
distributedQueue = new ArrayBlockingQueue<Event>(3000, keepListening);
try {
// System.out.println("****** Starting CustomEventSource on port: "+port);
LoggerFactory.getLogger(CustomEventSource.class).info("****** Starting CustomEventSource on port: "+port);
serverSocket = new ServerSocket(port);
// the listener socket runs in a thread, because the start() method must actually finish, so cannot do a blocking operation like accept() here.
new Thread(new Runnable() {
@Override
public void run() {
/*
* Implement a Socket listener for events. Using closure rather then anonymous class for better performance
*/
while (keepListening) { // facilitate graceful exit by setting it to false
try {
// wait for a client connection
final Socket remote = serverSocket.accept();
// remote is now the connected socket
final EventParser multilineEventParser = new EventParser();
// run the client connection event parsing in separate thread to free this loop to accept another connection
new Thread(new Runnable() {
@Override
public void run() {
try {
// processing input line by line
List<Event> parsedEvents = new ArrayList<>();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(remote.getInputStream()));
char[] inputBuffer = new char[512];
int bytesRead = inputReader.read(inputBuffer, 0, inputBuffer.length);
while (bytesRead > 0 && keepListening) {
String datagram = new String(inputBuffer);
try {
// one line may contain multiple events, so always expect many events, thus prepare a List as the store
multilineEventParser.parseEventsString(datagram, parsedEvents); //
System.out.println("CustomNetcatSource: parsed events: "+parsedEvents.size());
if (parsedEvents.size() > 0) { // if event spans multiple lines, the List may be empty until event end is detected
getChannelProcessor().processEventBatch(parsedEvents); // send events to channel
}
parsedEvents.clear();
} catch (Exception ex) {
LoggerFactory.getLogger(CustomEventSource.class).error(null, ex);
}
bytesRead = inputReader.read(inputBuffer, 0, inputBuffer.length);
}
} catch (IOException ex) {
LoggerFactory.getLogger(CustomEventSource.class).error(null, ex);
}
}
}).start();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
}).start();
} catch (Exception x) {
LoggerFactory.getLogger(CustomEventSource.class).error(x.getMessage(), x);
}
}
/**
* Called by flume-ng on shutdown.
*/
@Override
public void stop () {
// Disconnect from external client and do any additional cleanup
// (e.g. releasing resources or nulling-out field values) ..
keepListening = false;
try {
serverSocket.close();
} catch (IOException ex) {
LoggerFactory.getLogger(CustomEventSource.class).error(ex.getMessage(), ex);
}
}
// the next method is needed to implement PollableSource interface. It was deprecated in favour of EventDrivenSource which has better performance
/*
@Deprecated
@Override
public Status process() throws EventDeliveryException {
Status status = Status.BACKOFF;
try {
// This try clause includes whatever Channel/Event operations you want to do
// Receive new data
// using event-driven source - do no processing here
List<Event> e = readEvents();
if (e != null) {
// Store the Event into this Source's associated Channel(s)
getChannelProcessor().processEventBatch(e);
status = Status.READY;
} else {
status = Status.BACKOFF;
}
} catch (Throwable t) {
// Log exception, handle individual exceptions as needed
status = Status.BACKOFF;
// re-throw all Errors
if (t instanceof Error) {
throw (Error)t;
}
} finally {
}
return status;
}
*/
/*
* readEvents() is part of PollableSource implementation and has been deprecated in favor of event driven handling due to performance reasons.
* Left here for for completeness sake.
*/
@SuppressWarnings("unused")
@Deprecated
private List<Event> readEvents() {
Event event = null;
try {
// System.out.println("CustomEventSource- readEvents(): "+distributedQueue+" keepListening="+keepListening);
event = distributedQueue.poll(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
event = null;
}
// System.out.println("CustomEventSource- readEvents(): "+distributedQueue+" keepListening="+keepListening+" got event: "+event);
if (event == null)
return null;
List<Event> events = new ArrayList<>();
events.add(event);
distributedQueue.drainTo(events);
return events;
}
/*
* PollableSource Implementation, deprecated.
@Deprecated
@Override
public long getBackOffSleepIncrement() {
return 1;
}
@Deprecated
@Override
public long getMaxBackOffSleepInterval() {
return 500;
}
*/
} | UTF-8 | Java | 10,487 | java | CustomEventSource.java | Java | [
{
"context": ".config.EventParserConfig;\r\n\r\n/**\r\n * \r\n * @author shejny\r\n *\r\n *\tCustomEventSource provides equivalent fun",
"end": 742,
"score": 0.9991253018379211,
"start": 736,
"tag": "USERNAME",
"value": "shejny"
}
] | null | [] | package com.chute.parser.source;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.EventDrivenSource;
import org.apache.flume.conf.Configurable;
import org.apache.flume.source.AbstractSource;
import org.slf4j.LoggerFactory;
import com.chute.parser.event.EventParser;
import com.chute.parser.event.config.EventParserConfig;
/**
*
* @author shejny
*
* CustomEventSource provides equivalent functionality as NetcatSource but instead just copying the input line by line as event to a channel,
* it calls an EventParser, which is able to join multiple lines into one event based on regExp criteria for event boundaries
*
* This is event driven source though it can also be converted to poll-able source by un-commenting process(), getBackOffSleepIncrement(), getBackOffSleepInterval() and
* changing implemented interface from EventDrivenSource to PollableSource
*/
public class CustomEventSource extends AbstractSource implements Configurable, EventDrivenSource {
public CustomEventSource() {}
private int port = -1; // listening port this source binds to
private ServerSocket serverSocket; // Server socket that will listen on the above port for client connections
private BlockingQueue<Event> distributedQueue; // used for PollableSource implementation only. Not used in EventDrivenImplementation
private boolean keepListening = true; // allows for graceful exit from socket listening loop on shutdown
/**
* Read configuration values for this source from flume-ng configuration properties file
*
* All values except 'port' have default value provided in EventParserConfig class.
* This method is called by Flume-ng framework in the Source initialization phase.
*
*/
@Override
public void configure(Context context) {
/*
port = context.getInteger("port");
String regexp = context.getString("BREAK_ONLY_BEFORE");
if (regexp != null) {
EventParserConfig.BREAK_ONLY_BEFORE = regexp;
}
System.out.println("Regexp BREAK_ONLY_BEFORE: "+EventParserConfig.BREAK_ONLY_BEFORE);
regexp = context.getString("MUST_BREAK_AFTER");
if (regexp != null) {
EventParserConfig.MUST_BREAK_AFTER = regexp;
}
System.out.println("Regexp MUST_BREAK_AFTER: "+EventParserConfig.MUST_BREAK_AFTER);
regexp = context.getString("MUST_NOT_BREAK_AFTER");
if (regexp != null) {
EventParserConfig.MUST_NOT_BREAK_AFTER = regexp;
}
System.out.println("Regexp MUST_NOT_BREAK_AFTER: "+EventParserConfig.MUST_NOT_BREAK_AFTER);
regexp = context.getString("MUST_NOT_BREAK_BEFORE");
if (regexp != null) {
EventParserConfig.MUST_NOT_BREAK_BEFORE = regexp;
}
System.out.println("Regexp MUST_NOT_BREAK_BEFORE: "+EventParserConfig.MUST_NOT_BREAK_BEFORE);
regexp = context.getString("EVENT_BREAKER");
if (regexp != null) {
EventParserConfig.EVENT_BREAKER = regexp;
}
System.out.println("Regexp EVENT_BREAKER: "+EventParserConfig.EVENT_BREAKER);
regexp = context.getString("LINE_BREAKER");
if (regexp != null) {
EventParserConfig.LINE_BREAKER = regexp;
}
System.out.println("Regexp LINE_BREAKER: "+EventParserConfig.LINE_BREAKER);
Boolean flag = context.getBoolean("BREAK_ONLY_BEFORE_DATE");
if (flag != null) {
EventParserConfig.BREAK_ONLY_BEFORE_DATE = flag;
}
System.out.println("Flag BREAK_ONLY_BEFORE_DATE: "+EventParserConfig.BREAK_ONLY_BEFORE_DATE);
flag = context.getBoolean("SHOULD_LINEMERGE");
if (flag != null) {
EventParserConfig.SHOULD_LINEMERGE = flag;
}
System.out.println("Flag SHOULD_LINEMERGE: "+EventParserConfig.SHOULD_LINEMERGE);
Integer limit = context.getInteger("LINE_BREAKER_LOOKBEHIND");
if (limit != null) {
EventParserConfig.LINE_BREAKER_LOOKBEHIND = limit;
}
System.out.println("Value LINE_BREAKER_LOOKBEHIND: "+EventParserConfig.LINE_BREAKER_LOOKBEHIND);
limit = context.getInteger("MAX_EVENTS");
if (limit != null) {
EventParserConfig.MAX_EVENTS = limit;
}
limit = context.getInteger("TRUNCATE");
System.out.println("Value MAX_EVENTS: "+EventParserConfig.MAX_EVENTS);
if (limit != null) {
EventParserConfig.TRUNCATE = limit;
}
System.out.println("value TRUNCATE: "+EventParserConfig.TRUNCATE);
*/
// System.out.println("****** Configuring CustomEventSource on port: "+port);
}
/**
* This method is called by Flume-ng framework to start this source.
* The socket binds to the configured port and start listening for connections.
* The actual client connection to host:port is the event that triggers EventParser instantiation and it starts new thread
* to handle this client connection in parallel.
*
* keepListening facilitates graceful exist from the parallel thread and also from the socket listening loop on flume-ng shutdown
*/
@Override
public void start() {
distributedQueue = new ArrayBlockingQueue<Event>(3000, keepListening);
try {
// System.out.println("****** Starting CustomEventSource on port: "+port);
LoggerFactory.getLogger(CustomEventSource.class).info("****** Starting CustomEventSource on port: "+port);
serverSocket = new ServerSocket(port);
// the listener socket runs in a thread, because the start() method must actually finish, so cannot do a blocking operation like accept() here.
new Thread(new Runnable() {
@Override
public void run() {
/*
* Implement a Socket listener for events. Using closure rather then anonymous class for better performance
*/
while (keepListening) { // facilitate graceful exit by setting it to false
try {
// wait for a client connection
final Socket remote = serverSocket.accept();
// remote is now the connected socket
final EventParser multilineEventParser = new EventParser();
// run the client connection event parsing in separate thread to free this loop to accept another connection
new Thread(new Runnable() {
@Override
public void run() {
try {
// processing input line by line
List<Event> parsedEvents = new ArrayList<>();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(remote.getInputStream()));
char[] inputBuffer = new char[512];
int bytesRead = inputReader.read(inputBuffer, 0, inputBuffer.length);
while (bytesRead > 0 && keepListening) {
String datagram = new String(inputBuffer);
try {
// one line may contain multiple events, so always expect many events, thus prepare a List as the store
multilineEventParser.parseEventsString(datagram, parsedEvents); //
System.out.println("CustomNetcatSource: parsed events: "+parsedEvents.size());
if (parsedEvents.size() > 0) { // if event spans multiple lines, the List may be empty until event end is detected
getChannelProcessor().processEventBatch(parsedEvents); // send events to channel
}
parsedEvents.clear();
} catch (Exception ex) {
LoggerFactory.getLogger(CustomEventSource.class).error(null, ex);
}
bytesRead = inputReader.read(inputBuffer, 0, inputBuffer.length);
}
} catch (IOException ex) {
LoggerFactory.getLogger(CustomEventSource.class).error(null, ex);
}
}
}).start();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
}).start();
} catch (Exception x) {
LoggerFactory.getLogger(CustomEventSource.class).error(x.getMessage(), x);
}
}
/**
* Called by flume-ng on shutdown.
*/
@Override
public void stop () {
// Disconnect from external client and do any additional cleanup
// (e.g. releasing resources or nulling-out field values) ..
keepListening = false;
try {
serverSocket.close();
} catch (IOException ex) {
LoggerFactory.getLogger(CustomEventSource.class).error(ex.getMessage(), ex);
}
}
// the next method is needed to implement PollableSource interface. It was deprecated in favour of EventDrivenSource which has better performance
/*
@Deprecated
@Override
public Status process() throws EventDeliveryException {
Status status = Status.BACKOFF;
try {
// This try clause includes whatever Channel/Event operations you want to do
// Receive new data
// using event-driven source - do no processing here
List<Event> e = readEvents();
if (e != null) {
// Store the Event into this Source's associated Channel(s)
getChannelProcessor().processEventBatch(e);
status = Status.READY;
} else {
status = Status.BACKOFF;
}
} catch (Throwable t) {
// Log exception, handle individual exceptions as needed
status = Status.BACKOFF;
// re-throw all Errors
if (t instanceof Error) {
throw (Error)t;
}
} finally {
}
return status;
}
*/
/*
* readEvents() is part of PollableSource implementation and has been deprecated in favor of event driven handling due to performance reasons.
* Left here for for completeness sake.
*/
@SuppressWarnings("unused")
@Deprecated
private List<Event> readEvents() {
Event event = null;
try {
// System.out.println("CustomEventSource- readEvents(): "+distributedQueue+" keepListening="+keepListening);
event = distributedQueue.poll(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
event = null;
}
// System.out.println("CustomEventSource- readEvents(): "+distributedQueue+" keepListening="+keepListening+" got event: "+event);
if (event == null)
return null;
List<Event> events = new ArrayList<>();
events.add(event);
distributedQueue.drainTo(events);
return events;
}
/*
* PollableSource Implementation, deprecated.
@Deprecated
@Override
public long getBackOffSleepIncrement() {
return 1;
}
@Deprecated
@Override
public long getMaxBackOffSleepInterval() {
return 500;
}
*/
} | 10,487 | 0.693335 | 0.691332 | 265 | 37.577358 | 35.939293 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.279245 | false | false | 2 |
8be42359016877f15cde7462a54db1895c440d9e | 4,535,485,472,059 | 14532d2593789bea63f4cfb2b3e8e75b07449da3 | /Rover_Ruckus_2018-2019/TestBot/TeamCode/src/main/java/TestBot/EmptyChassisDrive.java | d211ddd3483a04dd61f7288b1bb101e40bb7be03 | [] | no_license | Wowwer-wowamazing0com1wow/RoboHeroes-12861 | https://github.com/Wowwer-wowamazing0com1wow/RoboHeroes-12861 | 732ffc53e21a3663f2c1d232b13109c0babbb66f | 0bc816eefec42b6f3eac206c5636082b2e5248f8 | refs/heads/master | 2020-12-09T01:52:30.783000 | 2020-01-05T01:52:20 | 2020-01-05T01:52:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package TestBot;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import TestBot.Init.HardwareTestBot;
@TeleOp(name="Empty Chassis Drive", group="EmptyChassis")
public class EmptyChassisDrive extends OpMode {
double speed = 0;
double turn = 0;
protected HardwareTestBot robot = new HardwareTestBot();
public void init(){
robot.init(hardwareMap);
}
public void loop(){
turn = gamepad1.left_stick_x;
speed = gamepad1.left_stick_y;
if (turn < -0.1 || turn > 0.1) {
robot.frontright.setPower(-turn);
robot.frontleft.setPower(-turn);
robot.backright.setPower(turn);
robot.backleft.setPower(turn);
}
robot.frontright.setPower(speed);
robot.frontleft.setPower(speed);
robot.backright.setPower(speed);
robot.backleft.setPower(speed);
}
}
| UTF-8 | Java | 1,160 | java | EmptyChassisDrive.java | Java | [] | null | [] | package TestBot;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import TestBot.Init.HardwareTestBot;
@TeleOp(name="Empty Chassis Drive", group="EmptyChassis")
public class EmptyChassisDrive extends OpMode {
double speed = 0;
double turn = 0;
protected HardwareTestBot robot = new HardwareTestBot();
public void init(){
robot.init(hardwareMap);
}
public void loop(){
turn = gamepad1.left_stick_x;
speed = gamepad1.left_stick_y;
if (turn < -0.1 || turn > 0.1) {
robot.frontright.setPower(-turn);
robot.frontleft.setPower(-turn);
robot.backright.setPower(turn);
robot.backleft.setPower(turn);
}
robot.frontright.setPower(speed);
robot.frontleft.setPower(speed);
robot.backright.setPower(speed);
robot.backleft.setPower(speed);
}
}
| 1,160 | 0.650862 | 0.643966 | 40 | 28 | 21.794495 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 2 |
c20eb595519a8235efab10d485bb3be0ee407407 | 13,340,168,467,666 | d6fd7ca6fed166e2ce21250c0a513ec3d086b36e | /src/main/java/at/creadoo/homematic/link/HMSerialLink.java | d9d914bbb53b494bbdc6a4dd3f76565250dfc629 | [] | no_license | crea-doo/homematic-java | https://github.com/crea-doo/homematic-java | b606094434dee1a6b5a2631891adcbdac4824662 | 5f6feda17782b77275eff3146d4fdf45ea09a888 | refs/heads/master | 2022-06-26T02:49:51.881000 | 2022-05-20T21:32:46 | 2022-05-20T21:32:46 | 51,786,475 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2017 crea-doo.at
*
* 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 at.creadoo.homematic.link;
import at.creadoo.homematic.IHomeMaticLinkListener;
import at.creadoo.homematic.impl.LinkBaseImpl;
import at.creadoo.homematic.packet.HomeMaticPacket;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.hid4java.HidDevice;
import org.hid4java.HidManager;
import org.hid4java.HidServices;
import org.hid4java.HidServicesListener;
import org.hid4java.event.HidServicesEvent;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* {@link HMSerialLink} manages the connection to the HomeMatic HM-MOD_RPI_PCB.
*/
public class HMSerialLink extends LinkBaseImpl {
private static final Logger log = Logger.getLogger(HMSerialLink.class);
private String device = null;
public HMSerialLink() {
this(null);
}
public HMSerialLink(final IHomeMaticLinkListener listener) {
super(listener);
log.debug("Initializing... ");
}
@Override
public String getName() {
return this.getClass().getSimpleName();
}
@Override
public boolean isReconnectSupported() {
return true;
}
@Override
protected boolean startLink(final boolean reconnecting) {
/*
boolean result = true;
synchronized (connectionsBySerial) {
for (Map.Entry<String, HidConnection> entry : connectionsBySerial.entrySet()) {
if (!entry.getValue().isOpened() && !entry.getValue().open()) {
result = false;
}
}
}
return result;
*/
return true;
}
@Override
protected boolean closeLink() {
/*
boolean result = true;
synchronized (connectionsBySerial) {
for (Map.Entry<String, HidConnection> entry : connectionsBySerial.entrySet()) {
if (entry.getValue().isOpened()) {
if (!entry.getValue().close()) {
result = false;
}
}
}
}
return result;
*/
return true;
}
@Override
protected boolean setupAES() {
return true;
}
@Override
protected void cleanUpAES() {
//
}
@Override
public boolean send(final HomeMaticPacket packet) throws SocketException, IOException {
/*
packet.setMessageCounter(getNextMessageCounter(packet.getDestinationAddress()));
boolean result = false;
synchronized (connectionsBySerial) {
for (String serial: connectionsBySerial.keySet()) {
final HidConnection connection = connectionsBySerial.get(serial);
if (connection.isOpened()) {
if (connection.sendPacketToDevice(packet.getData())) {
result = true;
} else {
log.debug("Error while sending packet via connection '" + serial + "'");
}
} else {
log.debug("Connection '" + serial + "' currently closed");
}
}
}
return result;
*/
return true;
}
public HidConnection getHidConnectionByDeviceSerial(final String serial) {
/*
synchronized (connectionsBySerial) {
for (String key: connectionsBySerial.keySet()) {
if (key.equals(serial)) {
return connectionsBySerial.get(key);
}
}
}
*/
return null;
}
/**
* Getter for the serial device.
*/
private String getDevice() {
return device;
}
/**
* Setter for the serial device.
*
* @param device
*/
public void setDevice(final String device) {
/*
if (StringUtils.isBlank(device)) {
return;
}
try {
// vids in the config file can start with '0x' -> interpret those as
// hexadecimal numbers
final int vid = vendorId.trim().startsWith("0x") ? Integer.parseInt(vendorId.trim().substring(2), 16) : Integer.parseInt(vendorId.trim());
if (vid != this.vendorId) {
this.vendorId = vid;
updateDevices();
}
} catch (Throwable e) {
log.warn("Unable to parse vendor id '" + vendorId + "'");
}
*/
}
}
| UTF-8 | Java | 4,369 | java | HMSerialLink.java | Java | [] | null | [] | /*
* Copyright 2017 crea-doo.at
*
* 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 at.creadoo.homematic.link;
import at.creadoo.homematic.IHomeMaticLinkListener;
import at.creadoo.homematic.impl.LinkBaseImpl;
import at.creadoo.homematic.packet.HomeMaticPacket;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.hid4java.HidDevice;
import org.hid4java.HidManager;
import org.hid4java.HidServices;
import org.hid4java.HidServicesListener;
import org.hid4java.event.HidServicesEvent;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* {@link HMSerialLink} manages the connection to the HomeMatic HM-MOD_RPI_PCB.
*/
public class HMSerialLink extends LinkBaseImpl {
private static final Logger log = Logger.getLogger(HMSerialLink.class);
private String device = null;
public HMSerialLink() {
this(null);
}
public HMSerialLink(final IHomeMaticLinkListener listener) {
super(listener);
log.debug("Initializing... ");
}
@Override
public String getName() {
return this.getClass().getSimpleName();
}
@Override
public boolean isReconnectSupported() {
return true;
}
@Override
protected boolean startLink(final boolean reconnecting) {
/*
boolean result = true;
synchronized (connectionsBySerial) {
for (Map.Entry<String, HidConnection> entry : connectionsBySerial.entrySet()) {
if (!entry.getValue().isOpened() && !entry.getValue().open()) {
result = false;
}
}
}
return result;
*/
return true;
}
@Override
protected boolean closeLink() {
/*
boolean result = true;
synchronized (connectionsBySerial) {
for (Map.Entry<String, HidConnection> entry : connectionsBySerial.entrySet()) {
if (entry.getValue().isOpened()) {
if (!entry.getValue().close()) {
result = false;
}
}
}
}
return result;
*/
return true;
}
@Override
protected boolean setupAES() {
return true;
}
@Override
protected void cleanUpAES() {
//
}
@Override
public boolean send(final HomeMaticPacket packet) throws SocketException, IOException {
/*
packet.setMessageCounter(getNextMessageCounter(packet.getDestinationAddress()));
boolean result = false;
synchronized (connectionsBySerial) {
for (String serial: connectionsBySerial.keySet()) {
final HidConnection connection = connectionsBySerial.get(serial);
if (connection.isOpened()) {
if (connection.sendPacketToDevice(packet.getData())) {
result = true;
} else {
log.debug("Error while sending packet via connection '" + serial + "'");
}
} else {
log.debug("Connection '" + serial + "' currently closed");
}
}
}
return result;
*/
return true;
}
public HidConnection getHidConnectionByDeviceSerial(final String serial) {
/*
synchronized (connectionsBySerial) {
for (String key: connectionsBySerial.keySet()) {
if (key.equals(serial)) {
return connectionsBySerial.get(key);
}
}
}
*/
return null;
}
/**
* Getter for the serial device.
*/
private String getDevice() {
return device;
}
/**
* Setter for the serial device.
*
* @param device
*/
public void setDevice(final String device) {
/*
if (StringUtils.isBlank(device)) {
return;
}
try {
// vids in the config file can start with '0x' -> interpret those as
// hexadecimal numbers
final int vid = vendorId.trim().startsWith("0x") ? Integer.parseInt(vendorId.trim().substring(2), 16) : Integer.parseInt(vendorId.trim());
if (vid != this.vendorId) {
this.vendorId = vid;
updateDevices();
}
} catch (Throwable e) {
log.warn("Unable to parse vendor id '" + vendorId + "'");
}
*/
}
}
| 4,369 | 0.681392 | 0.676814 | 182 | 23.005495 | 24.887108 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.807692 | false | false | 2 |
4e3fe2ccd6883ea7239a63ded2f0111a30798ea1 | 30,039,001,331,928 | 675322b05086850e754124ef5a7b156daff1076b | /src/stepF/StepF5.java | 19c9eedf120f640ba904fe85b5f2e98fdf50ddff | [] | no_license | to2915ny/JavaWorkbook_2018 | https://github.com/to2915ny/JavaWorkbook_2018 | a86fb06dff312091f14b550e63f2da996ba2551d | 09c2e598cb3381c7d7a4a22f37dc4040dabf8430 | refs/heads/master | 2020-04-11T16:25:16.786000 | 2019-01-06T15:05:15 | 2019-01-06T15:05:15 | 161,921,720 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package stepF;
import java.util.Scanner;
public class StepF5 {
private int number[][]= new int[5][3];
private int total;
public StepF5() {
input();
}
void input() {
int i,j;
Scanner s = new Scanner(System.in);
for(i=0;i<5;i++) {
for(j=0;j<3;j++) {
System.out.print((i+1)+"0"+(j+1)+"호에 살고 있는 사람의 숫자를 입력하시오.");
number[i][j] = s.nextInt();
this.total =this.total + number[i][j];
}
}
System.out.print("이 아파트에 사는 거주자는 모두 "+this.total+" 입니다.");
}
}
| UTF-8 | Java | 554 | java | StepF5.java | Java | [] | null | [] | package stepF;
import java.util.Scanner;
public class StepF5 {
private int number[][]= new int[5][3];
private int total;
public StepF5() {
input();
}
void input() {
int i,j;
Scanner s = new Scanner(System.in);
for(i=0;i<5;i++) {
for(j=0;j<3;j++) {
System.out.print((i+1)+"0"+(j+1)+"호에 살고 있는 사람의 숫자를 입력하시오.");
number[i][j] = s.nextInt();
this.total =this.total + number[i][j];
}
}
System.out.print("이 아파트에 사는 거주자는 모두 "+this.total+" 입니다.");
}
}
| 554 | 0.571721 | 0.54918 | 26 | 17.76923 | 17.925718 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.153846 | false | false | 2 |
9891585619bcea3c27dffdf06839ad1c51e253a4 | 30,039,001,333,358 | d9cd4f8a1052f902cb01a7dce88ae8070810bb4f | /src/ci/java/com/VampireNumbersUsingStrings.java | ffffe887614052d8be3c27083b79bb6b13da9bd9 | [] | no_license | robinjha/java_problems | https://github.com/robinjha/java_problems | 2b7c46b659411564ecc8790dc1ca9c518b41cecb | 8291f2b049504be73e1d94479b42a94c528af276 | refs/heads/master | 2021-01-22T14:38:59.687000 | 2015-02-09T05:30:58 | 2015-02-09T05:30:58 | 12,232,057 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ci.java.com;
import java.io.*;
import java.util.*;
import java.awt.geom.*;
/**
* Solution to Vampire Numbers.
*
*/
public class VampireNumbersUsingStrings
{
public Scanner sc;
public PrintStream ps;
/**
* Compute a "signature" for a string.
* That's just another string with the characters sorted.
* If two strings are anagrams of each other, then they'll have the same signature.
*
* @param s A String
* @return The "Signature" of String s
*/
public static String signature( String s )
{
char a[] = s.toCharArray();
Arrays.sort( a );
return new String( a );
}
/**
* Determine if x is a Vampire Number
*
* @param x An integer
* @return true if x is a Vampire Number, false otherwise
*/
public boolean isvampire( int x )
{
boolean result = false;
// Get x's signature
String vsig = signature( "" + x );
// Find factors
for( int i=2; i*i<=x; i++ ) if( x%i==0 )
{
// Get the signature of the two factors put together
String isig = signature( "" + i + "" + (x/i));
// If the signatures are equal, it's a Vampire Number!
if( isig.equals( vsig ) )
{
result = true;
break;
}
}
return result;
}
/**
* Driver.
* @throws Exception
*/
public void doit() throws Exception
{
// sc = new Scanner( new File( "/Users/robin/Documents/workspace/java_problems/src/ci/java/com/vampires.txt" ) );
// ps = System.out; //new PrintStream( new FileOutputStream( "vampirenumbers.solution" ) );
//
// for(;;)
// {
// int x = sc.nextInt();
// if( x==0 ) break;
//
// // Keep looking until we find a Vampire Number
// while( !isvampire( x ) ) ++x;
//
// ps.println( x );
// }
System.out.println(isvampire(1359));
}
public static void main( String[] args ) throws Exception
{
new VampireNumbersUsingStrings().doit();
}
}
| UTF-8 | Java | 2,240 | java | VampireNumbersUsingStrings.java | Java | [
{
"context": " {\n// sc = new Scanner( new File( \"/Users/robin/Documents/workspace/java_problems/src/ci/java/com",
"end": 1597,
"score": 0.9987486600875854,
"start": 1592,
"tag": "USERNAME",
"value": "robin"
}
] | null | [] | package ci.java.com;
import java.io.*;
import java.util.*;
import java.awt.geom.*;
/**
* Solution to Vampire Numbers.
*
*/
public class VampireNumbersUsingStrings
{
public Scanner sc;
public PrintStream ps;
/**
* Compute a "signature" for a string.
* That's just another string with the characters sorted.
* If two strings are anagrams of each other, then they'll have the same signature.
*
* @param s A String
* @return The "Signature" of String s
*/
public static String signature( String s )
{
char a[] = s.toCharArray();
Arrays.sort( a );
return new String( a );
}
/**
* Determine if x is a Vampire Number
*
* @param x An integer
* @return true if x is a Vampire Number, false otherwise
*/
public boolean isvampire( int x )
{
boolean result = false;
// Get x's signature
String vsig = signature( "" + x );
// Find factors
for( int i=2; i*i<=x; i++ ) if( x%i==0 )
{
// Get the signature of the two factors put together
String isig = signature( "" + i + "" + (x/i));
// If the signatures are equal, it's a Vampire Number!
if( isig.equals( vsig ) )
{
result = true;
break;
}
}
return result;
}
/**
* Driver.
* @throws Exception
*/
public void doit() throws Exception
{
// sc = new Scanner( new File( "/Users/robin/Documents/workspace/java_problems/src/ci/java/com/vampires.txt" ) );
// ps = System.out; //new PrintStream( new FileOutputStream( "vampirenumbers.solution" ) );
//
// for(;;)
// {
// int x = sc.nextInt();
// if( x==0 ) break;
//
// // Keep looking until we find a Vampire Number
// while( !isvampire( x ) ) ++x;
//
// ps.println( x );
// }
System.out.println(isvampire(1359));
}
public static void main( String[] args ) throws Exception
{
new VampireNumbersUsingStrings().doit();
}
}
| 2,240 | 0.508036 | 0.504911 | 87 | 24.735632 | 23.162325 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.367816 | false | false | 2 |
ac77ac46783d54cc14f1a0b2f76b68c3d34eb515 | 8,589,934,624,364 | cc511ceb3194cfdd51f591e50e52385ba46a91b3 | /example/source_code/jackrabbit/jackrabbit-core/src/main/java/org/apache/jackrabbit/core/security/authorization/PrivilegeBits.java | 3e6502828c7b422c8d8f756761712c66faa6d7db | [] | no_license | huox-lamda/testing_hw | https://github.com/huox-lamda/testing_hw | a86cdce8d92983e31e653dd460abf38b94a647e4 | d41642c1e3ffa298684ec6f0196f2094527793c3 | refs/heads/master | 2020-04-16T19:24:49.643000 | 2019-01-16T15:47:13 | 2019-01-16T15:47:13 | 165,858,365 | 3 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | org apach jackrabbit core secur author
java util arrai
java util hash map hashmap
java util map
code privilegebit code
privileg bit privilegebit
privileg bit privilegebit empti privileg bit privilegebit unmodifi data unmodifiabledata empti
read privat static final long read privilegeregistri read
map long privileg bit privilegebit built built hash map hashmap long privileg bit privilegebit
built built put empti long longvalu empti
data
privat constructor
param
privileg bit privilegebit data
packag privat method code privilegeregistri code handl
built privileg calcul intern permiss
return long represent instanc
privilegeregistri calculatepermiss privilegebit privilegebit boolean boolean
long longvalu
long longvalu
packag privat method code privilegeregistri code calcul
privileg bit built custom privileg
definit
return instanc code privilegebit code
privileg bit privilegebit bit nextbit
empti
empti
privileg bit privilegebit privileg bit privilegebit
simpl issimpl
built built put long longvalu
packag privat method code privilegeregistri code
creat instanc privileg bit long
param bit
return instanc code privilegebit code
privileg bit privilegebit instanc getinst bit
bit privileg registri privilegeregistri privileg privileg
empti
bit privileg registri privilegeregistri privileg privileg
illeg argument except illegalargumentexcept
privileg bit privilegebit built built bit
privileg bit privilegebit unmodifi data unmodifiabledata bit
built built put bit
intern method creat instanc code privilegebit code
param bit
return instanc code privilegebit code
privileg bit privilegebit instanc getinst bit
bt bit length
system arraycopi bit bt bit length
privileg bit privilegebit unmodifi data unmodifiabledata bt
creat mutabl instanc privileg bit
return instanc privileg bit
privileg bit privilegebit instanc getinst
privileg bit privilegebit modifi data modifiabledata
creat mutabl instanc privileg bit
param base
return instanc privileg bit
privileg bit privilegebit instanc getinst privileg bit privilegebit base
privileg bit privilegebit modifi data modifiabledata base
return code true code privileg bit includ privileg
return code true code privileg bit includ privileg
code fals code
privilegeregistri privileg
empti isempti
empti isempti
return unmodifi instanc
return unmodifi code privilegebit code instanc
privileg bit privilegebit unmodifi
modifi data modifiabledata
simpl issimpl instanc getinst long longvalu instanc getinst long valu longvalu
return code true code privileg bit instanc alter
return true privileg bit instanc alter
modifi ismodifi
modifi data modifiabledata
return code true code instanc includ jcr read
privileg shortcut call link privilegebit includ privilegebit
bit repres jcr read privileg
return code true code instanc includ jcr read
privileg code fals code
includ read includesread
empti
includ read includesread
return code true code privileg defin
code otherbit code present instanc
param otherbit
return code true code privileg defin
code otherbit code includ instanc code fals code
includ privileg bit privilegebit bit otherbit
includ bit otherbit
add privileg bit instanc
param privileg bit ad
throw unsupportedoperationexcept instanc immut
add privileg bit privilegebit
modifi data modifiabledata
modifi data modifiabledata add
unsupport oper except unsupportedoperationexcept immut privileg bit
subtract privilegebit
bit intersect modifi
code code includ code code link empti empti
privileg bit return
param privileg bit substract instanc
throw unsupportedoperationexcept instanc immut
diff privileg bit privilegebit
modifi data modifiabledata
modifi data modifiabledata diff
unsupport oper except unsupportedoperationexcept immut privileg bit
subtract code code code code add result diff
instanc
param instanc privileg bit
param instanc privileg bit
throw unsupportedoperationexcept instanc immut
add differ adddiffer privileg bit privilegebit privileg bit privilegebit
modifi data modifiabledata
modifi data modifiabledata add differ adddiffer
unsupport oper except unsupportedoperationexcept immut privileg bit
object
overrid
hash code hashcod
hash code hashcod
overrid
equal object
privileg bit privilegebit
equal privileg bit privilegebit
overrid
string string tostr
string builder stringbuild string builder stringbuild privilegebit
simpl issimpl
append long longvalu
append arrai string tostr long valu longvalu
string tostr
class
base class intern privileg bit represent handl
data
empti isempti
long longvalu
long valu longvalu
simpl issimpl
data
includ data
includ read includesread
equal data equaldata data
simpl issimpl simpl issimpl
simpl issimpl
long longvalu long longvalu
arrai equal long valu longvalu long valu longvalu
includ bit bit otherbit
bit bit otherbit
includ bit bit otherbit
bit otherbit length bit length
test long includ
bit otherbit length
bit bit otherbit
otherbit arrai longer includ bit
immut data object
unmodifi data unmodifiabledata data
max long max max
unmodifi data unmodifiabledata empti unmodifi data unmodifiabledata privileg registri privilegeregistri privileg privileg
bit
bit arr bitsarr
simpl issimpl
includ read includesread
unmodifi data unmodifiabledata bit
bit bit
bit arr bitsarr bit
simpl issimpl
includ read includesread bit read read
unmodifi data unmodifiabledata bit arr bitsarr
bit privileg registri privilegeregistri privileg privileg
bit arr bitsarr bit arr bitsarr
simpl issimpl
includ read includesread bit arr bitsarr read read
overrid
empti isempti
empti
overrid
long longvalu
bit
overrid
long valu longvalu
bit arr bitsarr
overrid
simpl issimpl
simpl issimpl
overrid
data
empti
empti
simpl issimpl
bit max
bit
unmodifi data unmodifiabledata
unmodifi data unmodifiabledata bit
bt
bit arr bitsarr bit arr bitsarr length
max
bt bit arr bitsarr length
system arraycopi bit arr bitsarr bt bit arr bitsarr length
bt bt length
bt bit arr bitsarr length
bt bt length
unmodifi data unmodifiabledata bt
overrid
includ data
simpl issimpl
simpl issimpl includ bit long longvalu
includ bit arr bitsarr long valu longvalu
overrid
includ read includesread
includ read includesread
object
overrid
hash code hashcod
simpl issimpl long bit hash code hashcod arrai hash code hashcod bit arr bitsarr
overrid
equal object
unmodifi data unmodifiabledata
unmodifi data unmodifiabledata unmodifi data unmodifiabledata
simpl issimpl simpl issimpl
simpl issimpl
bit bit
arrai equal bit arr bitsarr bit arr bitsarr
modifi data modifiabledata
equal data equaldata data
mutabl implement data base class
modifi data modifiabledata data
bit
modifi data modifiabledata
bit privileg registri privilegeregistri privileg privileg
modifi data modifiabledata data base
base long valu longvalu
length
empti
bit privileg registri privilegeregistri privileg privileg
singl long
bit
copi
bit length
system arraycopi bit length
overrid
empti isempti
bit length bit privileg registri privilegeregistri privileg privileg
overrid
long longvalu
bit length bit privileg registri privilegeregistri privileg privileg
overrid
long valu longvalu
bit
overrid
simpl issimpl
bit length
overrid
data
unsupport oper except unsupportedoperationexcept implement
overrid
includ data
bit length
simpl issimpl includ bit long longvalu
includ bit long valu longvalu
overrid
includ read includesread
bit read read
add data instanc
param
add data
bit length simpl issimpl
bit long longvalu
long valu longvalu
subtract data instanc
param
diff data
bit length simpl issimpl
bit bit long longvalu
bit diff bit long valu longvalu
add diff data
param
param
add differ adddiffer data data
simpl issimpl simpl issimpl
bit long longvalu long longvalu
diff diff long valu longvalu long valu longvalu
diff
length bit length
enlarg arrai
re length
system arraycopi bit re bit length
bit re
length
bit
diff
index
re length length length length
re length
length length
re
re length
rememb start trail arrai entri
re
index
index
index
index
remov trail long arrai
re
arrai consist multipl
privileg registri privilegeregistri privileg privileg
remov trail long entri arrai
index
system arraycopi re index
object
overrid
hash code hashcod
note mutabl object hashcod implement
overrid
equal object
modifi data modifiabledata
modifi data modifiabledata modifi data modifiabledata
arrai equal bit bit
unmodifi data unmodifiabledata
equal data equaldata data
| UTF-8 | Java | 8,297 | java | PrivilegeBits.java | Java | [] | null | [] | org apach jackrabbit core secur author
java util arrai
java util hash map hashmap
java util map
code privilegebit code
privileg bit privilegebit
privileg bit privilegebit empti privileg bit privilegebit unmodifi data unmodifiabledata empti
read privat static final long read privilegeregistri read
map long privileg bit privilegebit built built hash map hashmap long privileg bit privilegebit
built built put empti long longvalu empti
data
privat constructor
param
privileg bit privilegebit data
packag privat method code privilegeregistri code handl
built privileg calcul intern permiss
return long represent instanc
privilegeregistri calculatepermiss privilegebit privilegebit boolean boolean
long longvalu
long longvalu
packag privat method code privilegeregistri code calcul
privileg bit built custom privileg
definit
return instanc code privilegebit code
privileg bit privilegebit bit nextbit
empti
empti
privileg bit privilegebit privileg bit privilegebit
simpl issimpl
built built put long longvalu
packag privat method code privilegeregistri code
creat instanc privileg bit long
param bit
return instanc code privilegebit code
privileg bit privilegebit instanc getinst bit
bit privileg registri privilegeregistri privileg privileg
empti
bit privileg registri privilegeregistri privileg privileg
illeg argument except illegalargumentexcept
privileg bit privilegebit built built bit
privileg bit privilegebit unmodifi data unmodifiabledata bit
built built put bit
intern method creat instanc code privilegebit code
param bit
return instanc code privilegebit code
privileg bit privilegebit instanc getinst bit
bt bit length
system arraycopi bit bt bit length
privileg bit privilegebit unmodifi data unmodifiabledata bt
creat mutabl instanc privileg bit
return instanc privileg bit
privileg bit privilegebit instanc getinst
privileg bit privilegebit modifi data modifiabledata
creat mutabl instanc privileg bit
param base
return instanc privileg bit
privileg bit privilegebit instanc getinst privileg bit privilegebit base
privileg bit privilegebit modifi data modifiabledata base
return code true code privileg bit includ privileg
return code true code privileg bit includ privileg
code fals code
privilegeregistri privileg
empti isempti
empti isempti
return unmodifi instanc
return unmodifi code privilegebit code instanc
privileg bit privilegebit unmodifi
modifi data modifiabledata
simpl issimpl instanc getinst long longvalu instanc getinst long valu longvalu
return code true code privileg bit instanc alter
return true privileg bit instanc alter
modifi ismodifi
modifi data modifiabledata
return code true code instanc includ jcr read
privileg shortcut call link privilegebit includ privilegebit
bit repres jcr read privileg
return code true code instanc includ jcr read
privileg code fals code
includ read includesread
empti
includ read includesread
return code true code privileg defin
code otherbit code present instanc
param otherbit
return code true code privileg defin
code otherbit code includ instanc code fals code
includ privileg bit privilegebit bit otherbit
includ bit otherbit
add privileg bit instanc
param privileg bit ad
throw unsupportedoperationexcept instanc immut
add privileg bit privilegebit
modifi data modifiabledata
modifi data modifiabledata add
unsupport oper except unsupportedoperationexcept immut privileg bit
subtract privilegebit
bit intersect modifi
code code includ code code link empti empti
privileg bit return
param privileg bit substract instanc
throw unsupportedoperationexcept instanc immut
diff privileg bit privilegebit
modifi data modifiabledata
modifi data modifiabledata diff
unsupport oper except unsupportedoperationexcept immut privileg bit
subtract code code code code add result diff
instanc
param instanc privileg bit
param instanc privileg bit
throw unsupportedoperationexcept instanc immut
add differ adddiffer privileg bit privilegebit privileg bit privilegebit
modifi data modifiabledata
modifi data modifiabledata add differ adddiffer
unsupport oper except unsupportedoperationexcept immut privileg bit
object
overrid
hash code hashcod
hash code hashcod
overrid
equal object
privileg bit privilegebit
equal privileg bit privilegebit
overrid
string string tostr
string builder stringbuild string builder stringbuild privilegebit
simpl issimpl
append long longvalu
append arrai string tostr long valu longvalu
string tostr
class
base class intern privileg bit represent handl
data
empti isempti
long longvalu
long valu longvalu
simpl issimpl
data
includ data
includ read includesread
equal data equaldata data
simpl issimpl simpl issimpl
simpl issimpl
long longvalu long longvalu
arrai equal long valu longvalu long valu longvalu
includ bit bit otherbit
bit bit otherbit
includ bit bit otherbit
bit otherbit length bit length
test long includ
bit otherbit length
bit bit otherbit
otherbit arrai longer includ bit
immut data object
unmodifi data unmodifiabledata data
max long max max
unmodifi data unmodifiabledata empti unmodifi data unmodifiabledata privileg registri privilegeregistri privileg privileg
bit
bit arr bitsarr
simpl issimpl
includ read includesread
unmodifi data unmodifiabledata bit
bit bit
bit arr bitsarr bit
simpl issimpl
includ read includesread bit read read
unmodifi data unmodifiabledata bit arr bitsarr
bit privileg registri privilegeregistri privileg privileg
bit arr bitsarr bit arr bitsarr
simpl issimpl
includ read includesread bit arr bitsarr read read
overrid
empti isempti
empti
overrid
long longvalu
bit
overrid
long valu longvalu
bit arr bitsarr
overrid
simpl issimpl
simpl issimpl
overrid
data
empti
empti
simpl issimpl
bit max
bit
unmodifi data unmodifiabledata
unmodifi data unmodifiabledata bit
bt
bit arr bitsarr bit arr bitsarr length
max
bt bit arr bitsarr length
system arraycopi bit arr bitsarr bt bit arr bitsarr length
bt bt length
bt bit arr bitsarr length
bt bt length
unmodifi data unmodifiabledata bt
overrid
includ data
simpl issimpl
simpl issimpl includ bit long longvalu
includ bit arr bitsarr long valu longvalu
overrid
includ read includesread
includ read includesread
object
overrid
hash code hashcod
simpl issimpl long bit hash code hashcod arrai hash code hashcod bit arr bitsarr
overrid
equal object
unmodifi data unmodifiabledata
unmodifi data unmodifiabledata unmodifi data unmodifiabledata
simpl issimpl simpl issimpl
simpl issimpl
bit bit
arrai equal bit arr bitsarr bit arr bitsarr
modifi data modifiabledata
equal data equaldata data
mutabl implement data base class
modifi data modifiabledata data
bit
modifi data modifiabledata
bit privileg registri privilegeregistri privileg privileg
modifi data modifiabledata data base
base long valu longvalu
length
empti
bit privileg registri privilegeregistri privileg privileg
singl long
bit
copi
bit length
system arraycopi bit length
overrid
empti isempti
bit length bit privileg registri privilegeregistri privileg privileg
overrid
long longvalu
bit length bit privileg registri privilegeregistri privileg privileg
overrid
long valu longvalu
bit
overrid
simpl issimpl
bit length
overrid
data
unsupport oper except unsupportedoperationexcept implement
overrid
includ data
bit length
simpl issimpl includ bit long longvalu
includ bit long valu longvalu
overrid
includ read includesread
bit read read
add data instanc
param
add data
bit length simpl issimpl
bit long longvalu
long valu longvalu
subtract data instanc
param
diff data
bit length simpl issimpl
bit bit long longvalu
bit diff bit long valu longvalu
add diff data
param
param
add differ adddiffer data data
simpl issimpl simpl issimpl
bit long longvalu long longvalu
diff diff long valu longvalu long valu longvalu
diff
length bit length
enlarg arrai
re length
system arraycopi bit re bit length
bit re
length
bit
diff
index
re length length length length
re length
length length
re
re length
rememb start trail arrai entri
re
index
index
index
index
remov trail long arrai
re
arrai consist multipl
privileg registri privilegeregistri privileg privileg
remov trail long entri arrai
index
system arraycopi re index
object
overrid
hash code hashcod
note mutabl object hashcod implement
overrid
equal object
modifi data modifiabledata
modifi data modifiabledata modifi data modifiabledata
arrai equal bit bit
unmodifi data unmodifiabledata
equal data equaldata data
| 8,297 | 0.86007 | 0.86007 | 318 | 25.091194 | 19.193024 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | false | false | 2 |
80b43e76b79069b08bf162fef9ba49db6989040b | 20,607,253,098,883 | 2cad3b1a8d51702c14a440cf14dcd1eb9ec74c87 | /src/main/java/com/example/api/service/OcrService.java | a8d825c6dbbcbe1c50eb4de5e7bc9ceebfbe842b | [] | no_license | sz4m4n/OpticalCharacterRecognition | https://github.com/sz4m4n/OpticalCharacterRecognition | 5f025b757d393c077f827913fbfccfb40fc57441 | d74f84c19a3f5eae4ebdae63d3f79daea3d4af6f | refs/heads/master | 2020-09-11T04:12:31.304000 | 2019-11-15T14:28:04 | 2019-11-15T14:28:04 | 221,935,404 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.api.service;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class OcrService {
public String scanGraphic (String url){
try {
URL imageFile =new URL(url);
BufferedImage bufferedImage = ImageIO.read(imageFile);
ITesseract instance = new Tesseract();
instance.setDatapath("C:\\Users\\Public");
instance.setLanguage("pol");
return instance.doOCR(bufferedImage);
} catch (IOException | TesseractException e) {
e.printStackTrace();
log.error("error from scanGraphic Service");
return null;
}
}
}
| UTF-8 | Java | 963 | java | OcrService.java | Java | [] | null | [] | package com.example.api.service;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class OcrService {
public String scanGraphic (String url){
try {
URL imageFile =new URL(url);
BufferedImage bufferedImage = ImageIO.read(imageFile);
ITesseract instance = new Tesseract();
instance.setDatapath("C:\\Users\\Public");
instance.setLanguage("pol");
return instance.doOCR(bufferedImage);
} catch (IOException | TesseractException e) {
e.printStackTrace();
log.error("error from scanGraphic Service");
return null;
}
}
}
| 963 | 0.677051 | 0.67082 | 35 | 26.514286 | 20.316597 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 2 |
659dbfc4018d6634f68256c012f654652e7eae1a | 8,486,855,420,790 | 5559c4bf1a359c20144811c335947fecaae0f860 | /uikit/src/main/java/com/lzp/baseui/recyclerview/BaseRecycleViewAdapter.java | 56ccb5970b89997a036557c0be0c274539f3007b | [] | no_license | li504799868/BaseUI | https://github.com/li504799868/BaseUI | 7b6c063648492fad787955d527fe3431e1307487 | c75f10dd613d601fa6447dc08aa9dad9985a5cd1 | refs/heads/master | 2020-03-27T03:08:53.003000 | 2018-12-12T06:27:15 | 2018-12-12T06:27:15 | 145,841,393 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lzp.baseui.recyclerview;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Created by li.zhipeng on 2018/08/23.
* <p>
* 封装的RecyclerView.Adapter的基类
*/
public abstract class BaseRecycleViewAdapter<T> extends RecyclerView.Adapter<RecyclerViewHolder> {
private static final int TYPE_VIEW = 100000;
/**
* header集合
*/
private ArrayList<View> mHeaderViews = new ArrayList<>();
/**
* footer集合
*/
private ArrayList<View> mFooterViews = new ArrayList<>();
private ArrayList<Integer> mHeaderViewTypes = new ArrayList<>();
private ArrayList<Integer> mFooterViewTypes = new ArrayList<>();
private Context mContext;
private List<T> mDatas;
private OnItemClickListener<T> onItemClickListener;
private OnItemLongClickListener<T> onItemLongClickListener;
/**
* 构造器
*/
protected BaseRecycleViewAdapter(Context context) {
this.mContext = context;
}
/**
* 构造器
*/
protected BaseRecycleViewAdapter(Context context, List<T> mDatas) {
this(context);
this.mDatas = mDatas;
}
/**
* 返回指定的item的layoutId
*/
protected abstract int getLayoutId(int viewType);
/**
* 添加header
*/
public void addHeaderView(View headerView) {
if (mHeaderViews.contains(headerView)) {
return;
}
mHeaderViews.add(headerView);
}
/**
* 指定位置添加header
*/
public void addHeaderView(View headerView, int position) {
if (mHeaderViews.contains(headerView)) {
return;
}
mHeaderViews.add(position, headerView);
}
/**
* 移除所有headers
*/
public void removeAllHeaders() {
mHeaderViews.clear();
}
/**
* 可以添加多个尾视图
*
* @param footerView 尾视图
*/
public void addFooterView(View footerView) {
mFooterViews.add(footerView);
}
/**
* 可以添加多个尾视图
*
* @param footerView 尾视图
*/
public void addFooterView(View footerView, int position) {
mFooterViews.add(position, footerView);
}
public void removeHeaderView(View headerView) {
mHeaderViews.remove(headerView);
}
public void removeFooterView(View headerView) {
mFooterViews.remove(headerView);
}
/**
* Grid header footer占据位图
*/
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
if (manager instanceof GridLayoutManager) {
final GridLayoutManager gridManager = ((GridLayoutManager) manager);
gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
return getItemViewType(position) == position * TYPE_VIEW
? getHeaderAndFooterSpan(gridManager) : 1;
}
});
}
}
/**
* 获取GridLayoutManager的列数
*/
private int getHeaderAndFooterSpan(GridLayoutManager gridManager) {
return gridManager.getSpanCount();
}
/**
* StaggeredGrid header footer占据位图
*/
@Override
public void onViewAttachedToWindow(@NonNull RecyclerViewHolder holder) {
super.onViewAttachedToWindow(holder);
ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
if (lp != null
&& lp instanceof StaggeredGridLayoutManager.LayoutParams
&& (holder.getLayoutPosition() < mHeaderViews.size() || holder.getLayoutPosition() >= getItemCount() - mFooterViews.size())) {
StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
//占据全部空间
p.setFullSpan(true);
}
}
@Override
public int getItemViewType(int position) {
if (mHeaderViews.size() > 0 && position < mHeaderViews.size()) {
//用position作为HeaderView的ViewType标记
//记录每个ViewType标记
mHeaderViewTypes.add(position * TYPE_VIEW);
return position * TYPE_VIEW;
}
if (mFooterViews.size() > 0 && position > getListCount() - 1 + mHeaderViews.size()) {
//用position作为FooterView的ViewType标记
//记录每个ViewType标记
mFooterViewTypes.add(position * TYPE_VIEW);
return position * TYPE_VIEW;
}
if (mHeaderViews.size() > 0) {
return getListViewType(position - mHeaderViews.size());
}
return getListViewType(position);
}
/**
* Item页布局类型个数,默认为1
*/
protected int getListViewType(int position) {
return 1;
}
public int getListCount() {
if (mDatas != null) {
return mDatas.size();
}
return 0;
}
@NonNull
@Override
public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// 返回header
if (mHeaderViewTypes.contains(viewType)) {
return new HeaderHolder(mHeaderViews.get(viewType / TYPE_VIEW));
}
// 返回footer
if (mFooterViewTypes.contains(viewType)) {
int index = viewType / TYPE_VIEW - getListCount() - mHeaderViews.size();
return new FooterHolder(mFooterViews.get(index));
}
return onCreateBaseViewHolder(parent, viewType);
}
/**
* 创建ViewHolder
*
* @param parent RecycleView对象
* @param viewType item的类型
* @return Holder对象
*/
private RecyclerViewHolder onCreateBaseViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext).inflate(getLayoutId(viewType), parent,
false);
// 此处可以自定义ViewHolder,优先使用自定义的holder,请重写createViewHolder
RecyclerViewHolder customHolder = createViewHolder(itemView, parent, viewType);
if (customHolder != null) {
return customHolder;
} else {
// 使用通过的ViewHolder
return RecyclerViewHolder.get(mContext, itemView, viewType);
}
}
/**
* 如果希望有新的viewholder
*
* @param itemView
* @param parent
* @param viewType
* @return
*/
private RecyclerViewHolder createViewHolder(View itemView, ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
// 判断是否是footer,不处理
if (mFooterViews.size() > 0 && (position > getListCount() - 1 + mHeaderViews.size())) {
return;
}
// 判断是否是header,不处理
if (mHeaderViews.size() > 0) {
if (position < mHeaderViews.size()) {
return;
}
}
onBindBaseViewHolder(holder, position - mHeaderViews.size());
}
private void onBindBaseViewHolder(final RecyclerViewHolder holder, final int position) {
if (onItemClickListener != null) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClickListener.onItemClick(holder.itemView, mDatas.get(position), position);
}
});
}
if (onItemLongClickListener != null) {
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return onItemLongClickListener.onItemLongClick(holder.itemView, mDatas.get(position), position);
}
});
}
convert(holder, mDatas.get(position), position);
}
/**
* 设置每个页面显示的内容
*
* @param holder itemHolder
* @param item 每一Item显示的数据ø
*/
protected abstract void convert(RecyclerViewHolder holder, T item, int position);
public void setOnItemClickListener(OnItemClickListener<T> onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public void setOnItemLongClickListener(OnItemLongClickListener<T> onItemLongClickListener) {
this.onItemLongClickListener = onItemLongClickListener;
}
@Override
public int getItemCount() {
if (mHeaderViews.size() > 0 && mFooterViews.size() > 0) {
return getListCount() + mHeaderViews.size() + mFooterViews.size();
}
if (mHeaderViews.size() > 0) {
return getListCount() + mHeaderViews.size();
}
if (mFooterViews.size() > 0) {
return getListCount() + mFooterViews.size();
}
return getListCount();
}
/**
* 获取所有数据
*/
public List<T> getLists() {
return mDatas;
}
/**
* 根据位置插入
*
* @param position
* @param t
*/
public void addData(int position, T t) {
mDatas.add(position, t);
notifyItemInserted(position);
}
/**
* 插入一组list
*/
public void setList(List<T> list) {
mDatas.addAll(list);
notifyDataSetChanged();
}
/**
* 插入一组list
*/
public void setData(List<T> list) {
mDatas = list;
}
/**
* 单独移除某一个
*/
public void removeData(int position) {
if (!mDatas.isEmpty()) {
mDatas.remove(position);
notifyItemRemoved(position);
}
}
/**
* 全部移除
*/
public void removeAllData() {
if (!mDatas.isEmpty()) {
mDatas.clear();
this.notifyDataSetChanged();
}
}
public int getHeaderViewsCount() {
return mHeaderViews.size();
}
public int getFooterViewsCount() {
return mFooterViews.size();
}
/**
* 判断指定位置是否是header
*/
public boolean isHeader(int position) {
return getHeaderViewsCount() > 0 && position < mHeaderViews.size();
}
/**
* 判断指定位置是否是footer
*/
public boolean isFooter(int position) {
int lastPosition = getItemCount() - mFooterViews.size();
return getFooterViewsCount() > 0 && position >= lastPosition;
}
public interface OnItemClickListener<T> {
void onItemClick(View itemView, T t, int position);
}
public interface OnItemLongClickListener<T> {
boolean onItemLongClick(View itemView, T t, int position);
}
/**
* header的ViewHolder
*/
private class HeaderHolder extends RecyclerViewHolder {
HeaderHolder(View itemView) {
super(itemView);
}
}
/**
* footer的ViewHolder
*/
private class FooterHolder extends RecyclerViewHolder {
FooterHolder(View itemView) {
super(itemView);
}
}
}
| UTF-8 | Java | 11,680 | java | BaseRecycleViewAdapter.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by li.zhipeng on 2018/08/23.\n * <p>\n * 封装的RecyclerView.Adapter的",
"end": 447,
"score": 0.9939668774604797,
"start": 437,
"tag": "USERNAME",
"value": "li.zhipeng"
}
] | null | [] | package com.lzp.baseui.recyclerview;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Created by li.zhipeng on 2018/08/23.
* <p>
* 封装的RecyclerView.Adapter的基类
*/
public abstract class BaseRecycleViewAdapter<T> extends RecyclerView.Adapter<RecyclerViewHolder> {
private static final int TYPE_VIEW = 100000;
/**
* header集合
*/
private ArrayList<View> mHeaderViews = new ArrayList<>();
/**
* footer集合
*/
private ArrayList<View> mFooterViews = new ArrayList<>();
private ArrayList<Integer> mHeaderViewTypes = new ArrayList<>();
private ArrayList<Integer> mFooterViewTypes = new ArrayList<>();
private Context mContext;
private List<T> mDatas;
private OnItemClickListener<T> onItemClickListener;
private OnItemLongClickListener<T> onItemLongClickListener;
/**
* 构造器
*/
protected BaseRecycleViewAdapter(Context context) {
this.mContext = context;
}
/**
* 构造器
*/
protected BaseRecycleViewAdapter(Context context, List<T> mDatas) {
this(context);
this.mDatas = mDatas;
}
/**
* 返回指定的item的layoutId
*/
protected abstract int getLayoutId(int viewType);
/**
* 添加header
*/
public void addHeaderView(View headerView) {
if (mHeaderViews.contains(headerView)) {
return;
}
mHeaderViews.add(headerView);
}
/**
* 指定位置添加header
*/
public void addHeaderView(View headerView, int position) {
if (mHeaderViews.contains(headerView)) {
return;
}
mHeaderViews.add(position, headerView);
}
/**
* 移除所有headers
*/
public void removeAllHeaders() {
mHeaderViews.clear();
}
/**
* 可以添加多个尾视图
*
* @param footerView 尾视图
*/
public void addFooterView(View footerView) {
mFooterViews.add(footerView);
}
/**
* 可以添加多个尾视图
*
* @param footerView 尾视图
*/
public void addFooterView(View footerView, int position) {
mFooterViews.add(position, footerView);
}
public void removeHeaderView(View headerView) {
mHeaderViews.remove(headerView);
}
public void removeFooterView(View headerView) {
mFooterViews.remove(headerView);
}
/**
* Grid header footer占据位图
*/
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
if (manager instanceof GridLayoutManager) {
final GridLayoutManager gridManager = ((GridLayoutManager) manager);
gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
return getItemViewType(position) == position * TYPE_VIEW
? getHeaderAndFooterSpan(gridManager) : 1;
}
});
}
}
/**
* 获取GridLayoutManager的列数
*/
private int getHeaderAndFooterSpan(GridLayoutManager gridManager) {
return gridManager.getSpanCount();
}
/**
* StaggeredGrid header footer占据位图
*/
@Override
public void onViewAttachedToWindow(@NonNull RecyclerViewHolder holder) {
super.onViewAttachedToWindow(holder);
ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
if (lp != null
&& lp instanceof StaggeredGridLayoutManager.LayoutParams
&& (holder.getLayoutPosition() < mHeaderViews.size() || holder.getLayoutPosition() >= getItemCount() - mFooterViews.size())) {
StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
//占据全部空间
p.setFullSpan(true);
}
}
@Override
public int getItemViewType(int position) {
if (mHeaderViews.size() > 0 && position < mHeaderViews.size()) {
//用position作为HeaderView的ViewType标记
//记录每个ViewType标记
mHeaderViewTypes.add(position * TYPE_VIEW);
return position * TYPE_VIEW;
}
if (mFooterViews.size() > 0 && position > getListCount() - 1 + mHeaderViews.size()) {
//用position作为FooterView的ViewType标记
//记录每个ViewType标记
mFooterViewTypes.add(position * TYPE_VIEW);
return position * TYPE_VIEW;
}
if (mHeaderViews.size() > 0) {
return getListViewType(position - mHeaderViews.size());
}
return getListViewType(position);
}
/**
* Item页布局类型个数,默认为1
*/
protected int getListViewType(int position) {
return 1;
}
public int getListCount() {
if (mDatas != null) {
return mDatas.size();
}
return 0;
}
@NonNull
@Override
public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// 返回header
if (mHeaderViewTypes.contains(viewType)) {
return new HeaderHolder(mHeaderViews.get(viewType / TYPE_VIEW));
}
// 返回footer
if (mFooterViewTypes.contains(viewType)) {
int index = viewType / TYPE_VIEW - getListCount() - mHeaderViews.size();
return new FooterHolder(mFooterViews.get(index));
}
return onCreateBaseViewHolder(parent, viewType);
}
/**
* 创建ViewHolder
*
* @param parent RecycleView对象
* @param viewType item的类型
* @return Holder对象
*/
private RecyclerViewHolder onCreateBaseViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext).inflate(getLayoutId(viewType), parent,
false);
// 此处可以自定义ViewHolder,优先使用自定义的holder,请重写createViewHolder
RecyclerViewHolder customHolder = createViewHolder(itemView, parent, viewType);
if (customHolder != null) {
return customHolder;
} else {
// 使用通过的ViewHolder
return RecyclerViewHolder.get(mContext, itemView, viewType);
}
}
/**
* 如果希望有新的viewholder
*
* @param itemView
* @param parent
* @param viewType
* @return
*/
private RecyclerViewHolder createViewHolder(View itemView, ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
// 判断是否是footer,不处理
if (mFooterViews.size() > 0 && (position > getListCount() - 1 + mHeaderViews.size())) {
return;
}
// 判断是否是header,不处理
if (mHeaderViews.size() > 0) {
if (position < mHeaderViews.size()) {
return;
}
}
onBindBaseViewHolder(holder, position - mHeaderViews.size());
}
private void onBindBaseViewHolder(final RecyclerViewHolder holder, final int position) {
if (onItemClickListener != null) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClickListener.onItemClick(holder.itemView, mDatas.get(position), position);
}
});
}
if (onItemLongClickListener != null) {
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return onItemLongClickListener.onItemLongClick(holder.itemView, mDatas.get(position), position);
}
});
}
convert(holder, mDatas.get(position), position);
}
/**
* 设置每个页面显示的内容
*
* @param holder itemHolder
* @param item 每一Item显示的数据ø
*/
protected abstract void convert(RecyclerViewHolder holder, T item, int position);
public void setOnItemClickListener(OnItemClickListener<T> onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public void setOnItemLongClickListener(OnItemLongClickListener<T> onItemLongClickListener) {
this.onItemLongClickListener = onItemLongClickListener;
}
@Override
public int getItemCount() {
if (mHeaderViews.size() > 0 && mFooterViews.size() > 0) {
return getListCount() + mHeaderViews.size() + mFooterViews.size();
}
if (mHeaderViews.size() > 0) {
return getListCount() + mHeaderViews.size();
}
if (mFooterViews.size() > 0) {
return getListCount() + mFooterViews.size();
}
return getListCount();
}
/**
* 获取所有数据
*/
public List<T> getLists() {
return mDatas;
}
/**
* 根据位置插入
*
* @param position
* @param t
*/
public void addData(int position, T t) {
mDatas.add(position, t);
notifyItemInserted(position);
}
/**
* 插入一组list
*/
public void setList(List<T> list) {
mDatas.addAll(list);
notifyDataSetChanged();
}
/**
* 插入一组list
*/
public void setData(List<T> list) {
mDatas = list;
}
/**
* 单独移除某一个
*/
public void removeData(int position) {
if (!mDatas.isEmpty()) {
mDatas.remove(position);
notifyItemRemoved(position);
}
}
/**
* 全部移除
*/
public void removeAllData() {
if (!mDatas.isEmpty()) {
mDatas.clear();
this.notifyDataSetChanged();
}
}
public int getHeaderViewsCount() {
return mHeaderViews.size();
}
public int getFooterViewsCount() {
return mFooterViews.size();
}
/**
* 判断指定位置是否是header
*/
public boolean isHeader(int position) {
return getHeaderViewsCount() > 0 && position < mHeaderViews.size();
}
/**
* 判断指定位置是否是footer
*/
public boolean isFooter(int position) {
int lastPosition = getItemCount() - mFooterViews.size();
return getFooterViewsCount() > 0 && position >= lastPosition;
}
public interface OnItemClickListener<T> {
void onItemClick(View itemView, T t, int position);
}
public interface OnItemLongClickListener<T> {
boolean onItemLongClick(View itemView, T t, int position);
}
/**
* header的ViewHolder
*/
private class HeaderHolder extends RecyclerViewHolder {
HeaderHolder(View itemView) {
super(itemView);
}
}
/**
* footer的ViewHolder
*/
private class FooterHolder extends RecyclerViewHolder {
FooterHolder(View itemView) {
super(itemView);
}
}
}
| 11,680 | 0.601823 | 0.598785 | 417 | 25.836931 | 26.138027 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.311751 | false | false | 2 |
3006bb6dcbaf6edab2f6d8ff55d66fd123819315 | 33,732,673,166,378 | 35d51cb3a9c390ad16b2b6ed9f13f4f84028b04b | /Finals/src/finals/EditMeeting.java | d0099a7d489403a02b46e5857e6069bb2d2e67b9 | [] | no_license | chittaksh/CS320-Fall-2015-Lease-Management-System | https://github.com/chittaksh/CS320-Fall-2015-Lease-Management-System | 58f3758f1864278ad4f97051ef59d04b1860fd75 | 9bd4c34781fff5fd8e2db8a625a67cb2d94fdce2 | refs/heads/master | 2020-12-14T09:43:07.897000 | 2017-09-14T20:59:58 | 2017-09-14T20:59:58 | 55,467,456 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package finals;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.DataLink;
import model.Meeting;
/**
* Servlet implementation class EditMeeting
*/
@WebServlet("/EditMeeting")
public class EditMeeting extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public EditMeeting()
{
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
// response.getWriter().append("Served at:
// ").append(request.getContextPath());
try
{
if (request.getParameter("meetID") != null)
{
request.setAttribute("meetID", request.getParameter("meetID"));
request.setAttribute("Days", DataLink.getDays());
request.setAttribute("TimeSlots", DataLink.getTimeSlots());
request.setAttribute("Meetings", DataLink.getMeetings());
request.getRequestDispatcher("EditMeeting.jsp").include(request,
response);
}
else
{
request.setAttribute("errorMessage",
"Something went terrible wrong. Please try again.");
request.getRequestDispatcher("EditMeeting.jsp").include(request,
response);
}
}
catch (Exception e)
{
request.setAttribute("errorMessage", e.getMessage());
request.getRequestDispatcher("EditMeeting.jsp").include(request,
response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
// doGet(request, response);
try
{
int id = Integer.parseInt(request.getParameter("meetID"));
if (request.getParameter("Edit") != null)
{
boolean a = true;
String day = request.getParameter("day");
String time = request.getParameter("time");
String note = request.getParameter("note");
int iday = Integer.parseInt(day);
int itime = Integer.parseInt(time);
ArrayList<Meeting> Meetings = DataLink.getMeetings();
for (Meeting temp : Meetings)
{
if (temp.getDayID() == iday && temp.getTimeID() == itime
&& temp.getId() != id)
{
a = false;
}
}
if (time != null && a)
{
DataLink.updateMeeting(id, iday, itime, note);
response.sendRedirect("Final");
}
else
{
request.setAttribute("errorMessage",
"A meeting for same time already exists. Please Choose another time.");
request.setAttribute("meetID", id);
request.setAttribute("Days", DataLink.getDays());
request.setAttribute("TimeSlots", DataLink.getTimeSlots());
request.setAttribute("Meetings", DataLink.getMeetings());
request.getRequestDispatcher("EditMeeting.jsp")
.include(request, response);
}
}
else if (request.getParameter("Delete") != null)
{
DataLink.deleteMeeting(id);
response.sendRedirect("Final");
}
}
catch (Exception e)
{
request.setAttribute("errorMessage", e.getMessage());
request.getRequestDispatcher("EditMeeting.jsp").include(request,
response);
}
}
}
| UTF-8 | Java | 3,572 | java | EditMeeting.java | Java | [] | null | [] | package finals;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.DataLink;
import model.Meeting;
/**
* Servlet implementation class EditMeeting
*/
@WebServlet("/EditMeeting")
public class EditMeeting extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public EditMeeting()
{
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
// response.getWriter().append("Served at:
// ").append(request.getContextPath());
try
{
if (request.getParameter("meetID") != null)
{
request.setAttribute("meetID", request.getParameter("meetID"));
request.setAttribute("Days", DataLink.getDays());
request.setAttribute("TimeSlots", DataLink.getTimeSlots());
request.setAttribute("Meetings", DataLink.getMeetings());
request.getRequestDispatcher("EditMeeting.jsp").include(request,
response);
}
else
{
request.setAttribute("errorMessage",
"Something went terrible wrong. Please try again.");
request.getRequestDispatcher("EditMeeting.jsp").include(request,
response);
}
}
catch (Exception e)
{
request.setAttribute("errorMessage", e.getMessage());
request.getRequestDispatcher("EditMeeting.jsp").include(request,
response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
// doGet(request, response);
try
{
int id = Integer.parseInt(request.getParameter("meetID"));
if (request.getParameter("Edit") != null)
{
boolean a = true;
String day = request.getParameter("day");
String time = request.getParameter("time");
String note = request.getParameter("note");
int iday = Integer.parseInt(day);
int itime = Integer.parseInt(time);
ArrayList<Meeting> Meetings = DataLink.getMeetings();
for (Meeting temp : Meetings)
{
if (temp.getDayID() == iday && temp.getTimeID() == itime
&& temp.getId() != id)
{
a = false;
}
}
if (time != null && a)
{
DataLink.updateMeeting(id, iday, itime, note);
response.sendRedirect("Final");
}
else
{
request.setAttribute("errorMessage",
"A meeting for same time already exists. Please Choose another time.");
request.setAttribute("meetID", id);
request.setAttribute("Days", DataLink.getDays());
request.setAttribute("TimeSlots", DataLink.getTimeSlots());
request.setAttribute("Meetings", DataLink.getMeetings());
request.getRequestDispatcher("EditMeeting.jsp")
.include(request, response);
}
}
else if (request.getParameter("Delete") != null)
{
DataLink.deleteMeeting(id);
response.sendRedirect("Final");
}
}
catch (Exception e)
{
request.setAttribute("errorMessage", e.getMessage());
request.getRequestDispatcher("EditMeeting.jsp").include(request,
response);
}
}
}
| 3,572 | 0.68897 | 0.68869 | 137 | 25.072992 | 23.603054 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.89781 | false | false | 2 |
c9295cf507dbc37a657a68e2d1cceab68b58ffea | 27,006,754,380,681 | 27835b326965575e47e91e7089b918b642a91247 | /src/by/it/seroglazov/project/java/controller/CmdChangeRecipe.java | 6a3b85b613bb2a5a3267d27f52432b4ba5d3c262 | [] | no_license | s-karpovich/JD2018-11-13 | https://github.com/s-karpovich/JD2018-11-13 | c3bc03dc6268d52fd8372641b12c341aa3a3e11f | 5f5be48cb1619810950a629c47e46d186bf1ad93 | refs/heads/master | 2020-04-07T19:54:15.964000 | 2019-04-01T00:37:29 | 2019-04-01T00:37:29 | 158,667,895 | 2 | 0 | null | true | 2018-11-22T08:40:16 | 2018-11-22T08:40:16 | 2018-11-21T20:28:04 | 2018-11-21T20:28:02 | 323 | 0 | 0 | 0 | null | false | null | package by.it.seroglazov.project.java.controller;
import by.it.seroglazov.project.java.beans.*;
import by.it.seroglazov.project.java.dao.Dao;
import by.it.seroglazov.project.java.dao.MyDao;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
class CmdChangeRecipe extends Cmd {
private static final int ingrCount = 5;
@Override
Action execute(HttpServletRequest req) throws Exception {
if (Form.isPost(req)) {
User user = Util.findUserInSession(req);
if (user != null) {
String str = req.getParameter("changed_recipe_id");
if (str != null) {
Dao<Rtype> rtDao = new MyDao<>(new Rtype());
Dao<Ingredient> ingDao = new MyDao<>(new Ingredient());
Dao<Unit> unitDao = new MyDao<>(new Unit());
Dao<Amount> amDao = new MyDao<>(new Amount());
Dao<Recipe> recDao = new MyDao<>(new Recipe());
// Take cocktail name from form
String name = null;
try {
name = Form.getParameterMatchesPattern(req, "recipe_name", Patterns.cocktailName);
} catch (SiteException e) {
req.setAttribute("error_message", "Cocktail name is incorrect");
return Action.ADDRECIPE;
}
// Take cocktail type from form
String type = Form.getParameterMatchesPattern(req, "recipe_type", Patterns.cocktailType);
// If that type is already in DB then take it otherwise create new type in DB
Rtype rtype = rtDao.findFirstByFieldValue("text", type);
if (rtype == null) {
rtype = new Rtype(type);
rtDao.create(rtype);
}
// Now we should create ingredients, units
boolean bIngs[] = new boolean[ingrCount]; // true - ingredients exists, false - doesn't
Ingredient ings[] = new Ingredient[ingrCount];
Unit units[] = new Unit[ingrCount];
String sIng[] = new String[ingrCount];
String sUnit[] = new String[ingrCount];
for (int i = 0; i < ingrCount; i++) {
// Get Ingredient from BD, if not exist - create
sIng[i] = Form.getParameterMatchesPattern(req, "ingredient_" + String.valueOf(i + 1), Patterns.ingredientName);
bIngs[i] = (sIng[i].length() > 0);
if (bIngs[i]) {
ings[i] = ingDao.findFirstByFieldValue("name", sIng[i]);
if (ings[i] == null) {
ings[i] = new Ingredient(sIng[i]);
ingDao.create(ings[i]);
}
// Get Unit from BD, if not exist - create
sUnit[i] = Form.getParameterMatchesPattern(req, "unit_" + String.valueOf(i + 1), Patterns.unit);
units[i] = unitDao.findFirstByFieldValue("name", sUnit[i]);
if (units[i] == null) {
units[i] = new Unit(sUnit[i]);
unitDao.create(units[i]);
}
}
}
// Take description from form
String description = Form.getParameterMatchesPattern(req, "description", Patterns.description);
// Add new recipe to DB
long recipe_id = Form.getLong(req, "changed_recipe_id");
Recipe recipe = new Recipe(recipe_id, name, rtype.getId(), description);
if (!recDao.update(recipe)) {
throw new SiteException("Can't add new cocktail recipe to database");
}
//
for (int i = 0; i < ingrCount; i++) {
Ingredient ing = (Ingredient) req.getSession().getAttribute("ingredient" + String.valueOf(i + 1));
if (ing != null) {
String sqlSuffix = String.format("WHERE recipe_id='%d' and ingredient_id='%d'", recipe_id, ing.getId());
amDao.delete(sqlSuffix);
}
}
for (int i = 0; i < ingrCount; i++) {
if (bIngs[i]) {
String sAmount = Form.getParameterMatchesPattern(req, "amount_" + String.valueOf(i + 1), Patterns.amount);
amDao.create(new Amount(recipe.getId(), ings[i].getId(), sAmount, units[i].getId()));
}
}
return Action.RECIPESLIST;
}
long recipe_id = Form.getLong(req, "recipe_id");
Dao<Rtype> rtDao = new MyDao<>(new Rtype());
Dao<Ingredient> ingDao = new MyDao<>(new Ingredient());
Dao<Unit> unitDao = new MyDao<>(new Unit());
Dao<Amount> amDao = new MyDao<>(new Amount());
Dao<Recipe> recDao = new MyDao<>(new Recipe());
Recipe recipe = recDao.read(recipe_id);
req.setAttribute("recipe", recipe);
Rtype rtype = rtDao.read(recipe.getRtype_id());
req.setAttribute("rtype", rtype);
List<Amount> amounts = amDao.getAll("WHERE recipe_id=" + recipe.getId());
for (int i = 0; i < ingrCount; i++) {
req.getSession().removeAttribute("ingredient" + i);
req.getSession().removeAttribute("amount" + i);
req.getSession().removeAttribute("unit" + i);
}
int i = 1;
for (Amount amount : amounts) {
Ingredient ing = ingDao.read(amount.getIngredient_id());
Unit unit = unitDao.read(amount.getUnit_id());
req.getSession().setAttribute("ingredient" + i, ing);
req.getSession().setAttribute("amount" + i, amount);
req.getSession().setAttribute("unit" + i, unit);
i++;
}
return Action.CHANGERECIPE;
} else {
req.getSession().setAttribute("error_message", "You must be log-in to change cocktail recipe");
}
}
return Action.RECIPESLIST;
}
}
| UTF-8 | Java | 6,729 | java | CmdChangeRecipe.java | Java | [] | null | [] | package by.it.seroglazov.project.java.controller;
import by.it.seroglazov.project.java.beans.*;
import by.it.seroglazov.project.java.dao.Dao;
import by.it.seroglazov.project.java.dao.MyDao;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
class CmdChangeRecipe extends Cmd {
private static final int ingrCount = 5;
@Override
Action execute(HttpServletRequest req) throws Exception {
if (Form.isPost(req)) {
User user = Util.findUserInSession(req);
if (user != null) {
String str = req.getParameter("changed_recipe_id");
if (str != null) {
Dao<Rtype> rtDao = new MyDao<>(new Rtype());
Dao<Ingredient> ingDao = new MyDao<>(new Ingredient());
Dao<Unit> unitDao = new MyDao<>(new Unit());
Dao<Amount> amDao = new MyDao<>(new Amount());
Dao<Recipe> recDao = new MyDao<>(new Recipe());
// Take cocktail name from form
String name = null;
try {
name = Form.getParameterMatchesPattern(req, "recipe_name", Patterns.cocktailName);
} catch (SiteException e) {
req.setAttribute("error_message", "Cocktail name is incorrect");
return Action.ADDRECIPE;
}
// Take cocktail type from form
String type = Form.getParameterMatchesPattern(req, "recipe_type", Patterns.cocktailType);
// If that type is already in DB then take it otherwise create new type in DB
Rtype rtype = rtDao.findFirstByFieldValue("text", type);
if (rtype == null) {
rtype = new Rtype(type);
rtDao.create(rtype);
}
// Now we should create ingredients, units
boolean bIngs[] = new boolean[ingrCount]; // true - ingredients exists, false - doesn't
Ingredient ings[] = new Ingredient[ingrCount];
Unit units[] = new Unit[ingrCount];
String sIng[] = new String[ingrCount];
String sUnit[] = new String[ingrCount];
for (int i = 0; i < ingrCount; i++) {
// Get Ingredient from BD, if not exist - create
sIng[i] = Form.getParameterMatchesPattern(req, "ingredient_" + String.valueOf(i + 1), Patterns.ingredientName);
bIngs[i] = (sIng[i].length() > 0);
if (bIngs[i]) {
ings[i] = ingDao.findFirstByFieldValue("name", sIng[i]);
if (ings[i] == null) {
ings[i] = new Ingredient(sIng[i]);
ingDao.create(ings[i]);
}
// Get Unit from BD, if not exist - create
sUnit[i] = Form.getParameterMatchesPattern(req, "unit_" + String.valueOf(i + 1), Patterns.unit);
units[i] = unitDao.findFirstByFieldValue("name", sUnit[i]);
if (units[i] == null) {
units[i] = new Unit(sUnit[i]);
unitDao.create(units[i]);
}
}
}
// Take description from form
String description = Form.getParameterMatchesPattern(req, "description", Patterns.description);
// Add new recipe to DB
long recipe_id = Form.getLong(req, "changed_recipe_id");
Recipe recipe = new Recipe(recipe_id, name, rtype.getId(), description);
if (!recDao.update(recipe)) {
throw new SiteException("Can't add new cocktail recipe to database");
}
//
for (int i = 0; i < ingrCount; i++) {
Ingredient ing = (Ingredient) req.getSession().getAttribute("ingredient" + String.valueOf(i + 1));
if (ing != null) {
String sqlSuffix = String.format("WHERE recipe_id='%d' and ingredient_id='%d'", recipe_id, ing.getId());
amDao.delete(sqlSuffix);
}
}
for (int i = 0; i < ingrCount; i++) {
if (bIngs[i]) {
String sAmount = Form.getParameterMatchesPattern(req, "amount_" + String.valueOf(i + 1), Patterns.amount);
amDao.create(new Amount(recipe.getId(), ings[i].getId(), sAmount, units[i].getId()));
}
}
return Action.RECIPESLIST;
}
long recipe_id = Form.getLong(req, "recipe_id");
Dao<Rtype> rtDao = new MyDao<>(new Rtype());
Dao<Ingredient> ingDao = new MyDao<>(new Ingredient());
Dao<Unit> unitDao = new MyDao<>(new Unit());
Dao<Amount> amDao = new MyDao<>(new Amount());
Dao<Recipe> recDao = new MyDao<>(new Recipe());
Recipe recipe = recDao.read(recipe_id);
req.setAttribute("recipe", recipe);
Rtype rtype = rtDao.read(recipe.getRtype_id());
req.setAttribute("rtype", rtype);
List<Amount> amounts = amDao.getAll("WHERE recipe_id=" + recipe.getId());
for (int i = 0; i < ingrCount; i++) {
req.getSession().removeAttribute("ingredient" + i);
req.getSession().removeAttribute("amount" + i);
req.getSession().removeAttribute("unit" + i);
}
int i = 1;
for (Amount amount : amounts) {
Ingredient ing = ingDao.read(amount.getIngredient_id());
Unit unit = unitDao.read(amount.getUnit_id());
req.getSession().setAttribute("ingredient" + i, ing);
req.getSession().setAttribute("amount" + i, amount);
req.getSession().setAttribute("unit" + i, unit);
i++;
}
return Action.CHANGERECIPE;
} else {
req.getSession().setAttribute("error_message", "You must be log-in to change cocktail recipe");
}
}
return Action.RECIPESLIST;
}
}
| 6,729 | 0.476445 | 0.474811 | 136 | 48.47794 | 32.889961 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.838235 | false | false | 2 |
ae568c3c2b73dd6d532c2e332d77764ff4f0c4d7 | 29,205,777,654,675 | 63c5557a43f1fcd4dbc2100f045eea1add5305e0 | /commons/manage-trigger-lifecycle/src/main/java/com/enablix/trigger/lifecycle/impl/LaterCheckpointExecTimeInterpreter.java | ad7ca15752ed36008139a51c0859ebfca1ef52e4 | [] | no_license | dikshitluthra/enablix | https://github.com/dikshitluthra/enablix | 409758260002d371dac88ad88b73a084e932034d | 990e162b66efbc0199c01a84bcc441ca802da15f | refs/heads/master | 2018-12-25T22:23:11.120000 | 2018-12-21T19:39:50 | 2018-12-21T19:39:50 | 31,672,399 | 1 | 3 | null | false | 2016-12-14T07:21:02 | 2015-03-04T18:19:40 | 2016-10-25T10:37:13 | 2016-12-11T11:49:00 | 97,494 | 0 | 0 | 0 | Java | null | null | package com.enablix.trigger.lifecycle.impl;
import java.util.Calendar;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.enablix.core.commons.xsdtopojo.CheckpointType;
import com.enablix.core.commons.xsdtopojo.ExecTimeType;
import com.enablix.core.commons.xsdtopojo.LaterExecutionTimeType;
import com.enablix.core.domain.trigger.Trigger;
import com.enablix.trigger.lifecycle.CheckpointExecutionTimeInterpreter;
@Component
public class LaterCheckpointExecTimeInterpreter implements CheckpointExecutionTimeInterpreter {
private static final Logger LOGGER = LoggerFactory.getLogger(LaterCheckpointExecTimeInterpreter.class);
@Override
public <T extends Trigger> Date getCheckpointExecutionTime(CheckpointType checkpointDef, T trigger) {
Calendar refDate = Calendar.getInstance();
refDate.setTime(trigger.getTriggerTime());
LaterExecutionTimeType laterTimeDef = checkpointDef.getExecutionTime().getAfter();
if (laterTimeDef == null) {
LOGGER.error("Checkpoint later execution time not defined");
return null;
} else {
switch (laterTimeDef.getTimeUnit()) {
case MIN:
refDate.add(Calendar.MINUTE, laterTimeDef.getTimeValue().intValue());
break;
case DAY:
refDate.add(Calendar.DAY_OF_YEAR, laterTimeDef.getTimeValue().intValue());
break;
case WEEK:
refDate.add(Calendar.WEEK_OF_YEAR, laterTimeDef.getTimeValue().intValue());
break;
default:
break;
}
}
return refDate.getTime();
}
@Override
public boolean canHandle(CheckpointType checkpointDef) {
return checkpointDef.getExecutionTime().getType() == ExecTimeType.LATER;
}
}
| UTF-8 | Java | 1,740 | java | LaterCheckpointExecTimeInterpreter.java | Java | [] | null | [] | package com.enablix.trigger.lifecycle.impl;
import java.util.Calendar;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.enablix.core.commons.xsdtopojo.CheckpointType;
import com.enablix.core.commons.xsdtopojo.ExecTimeType;
import com.enablix.core.commons.xsdtopojo.LaterExecutionTimeType;
import com.enablix.core.domain.trigger.Trigger;
import com.enablix.trigger.lifecycle.CheckpointExecutionTimeInterpreter;
@Component
public class LaterCheckpointExecTimeInterpreter implements CheckpointExecutionTimeInterpreter {
private static final Logger LOGGER = LoggerFactory.getLogger(LaterCheckpointExecTimeInterpreter.class);
@Override
public <T extends Trigger> Date getCheckpointExecutionTime(CheckpointType checkpointDef, T trigger) {
Calendar refDate = Calendar.getInstance();
refDate.setTime(trigger.getTriggerTime());
LaterExecutionTimeType laterTimeDef = checkpointDef.getExecutionTime().getAfter();
if (laterTimeDef == null) {
LOGGER.error("Checkpoint later execution time not defined");
return null;
} else {
switch (laterTimeDef.getTimeUnit()) {
case MIN:
refDate.add(Calendar.MINUTE, laterTimeDef.getTimeValue().intValue());
break;
case DAY:
refDate.add(Calendar.DAY_OF_YEAR, laterTimeDef.getTimeValue().intValue());
break;
case WEEK:
refDate.add(Calendar.WEEK_OF_YEAR, laterTimeDef.getTimeValue().intValue());
break;
default:
break;
}
}
return refDate.getTime();
}
@Override
public boolean canHandle(CheckpointType checkpointDef) {
return checkpointDef.getExecutionTime().getType() == ExecTimeType.LATER;
}
}
| 1,740 | 0.75977 | 0.758621 | 64 | 26.1875 | 30.077438 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.234375 | false | false | 2 |
c4156c27f3b179b73327a9d1dc0de9cacd703bdb | 1,185,411,042,812 | b5a28bef8941095e6a10cd8c774e417864285f74 | /Metro_Version_Soap_Rest/src/main/java/me/uvmetro/metrov2_1/MostrarComprasResponse.java | 631dba8e3e23381c016db1c555d861a48d7bdec8 | [] | no_license | PrimalAngel/ServicioWeb_Metro | https://github.com/PrimalAngel/ServicioWeb_Metro | 9e78c5aa3c9b9929ad83a9756eaf396a44f0373b | 1085c8f3a385177a3d0c80cecfbbd4fddb5354ed | refs/heads/master | 2022-11-14T12:04:40.426000 | 2020-07-11T00:38:41 | 2020-07-11T00:38:41 | 249,624,731 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
// Este archivo ha sido generado por la arquitectura JavaTM para la implantación de la referencia de enlace (JAXB) XML v2.2.7
// Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Todas las modificaciones realizadas en este archivo se perderán si se vuelve a compilar el esquema de origen.
// Generado el: 2020.06.16 a las 09:01:46 PM CDT
//
package me.uvmetro.metrov2_1;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="compra" maxOccurs="unbounded">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Compra" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Usuario" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="TypeVagon" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Origen" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="NombreLinea" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="TypePago" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Fecha" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Precio" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"compra"
})
@XmlRootElement(name = "MostrarComprasResponse")
public class MostrarComprasResponse {
@XmlElement(required = true)
protected List<MostrarComprasResponse.Compra> compra;
/**
* Gets the value of the compra property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the compra property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCompra().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link MostrarComprasResponse.Compra }
*
*
*/
public List<MostrarComprasResponse.Compra> getCompra() {
if (compra == null) {
compra = new ArrayList<MostrarComprasResponse.Compra>();
}
return this.compra;
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Compra" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Usuario" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="TypeVagon" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Origen" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="NombreLinea" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="TypePago" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Fecha" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Precio" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"compra",
"usuario",
"typeVagon",
"origen",
"nombreLinea",
"typePago",
"fecha",
"precio"
})
public static class Compra {
@XmlElement(name = "Compra", required = true)
protected Object compra;
@XmlElement(name = "Usuario", required = true)
protected Object usuario;
@XmlElement(name = "TypeVagon", required = true)
protected Object typeVagon;
@XmlElement(name = "Origen", required = true)
protected Object origen;
@XmlElement(name = "NombreLinea", required = true)
protected Object nombreLinea;
@XmlElement(name = "TypePago", required = true)
protected Object typePago;
@XmlElement(name = "Fecha", required = true)
protected Object fecha;
@XmlElement(name = "Precio", required = true)
protected Object precio;
/**
* Obtiene el valor de la propiedad compra.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getCompra() {
return compra;
}
/**
* Define el valor de la propiedad compra.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setCompra(Object value) {
this.compra = value;
}
/**
* Obtiene el valor de la propiedad usuario.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getUsuario() {
return usuario;
}
/**
* Define el valor de la propiedad usuario.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setUsuario(Object value) {
this.usuario = value;
}
/**
* Obtiene el valor de la propiedad typeVagon.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getTypeVagon() {
return typeVagon;
}
/**
* Define el valor de la propiedad typeVagon.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setTypeVagon(Object value) {
this.typeVagon = value;
}
/**
* Obtiene el valor de la propiedad origen.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getOrigen() {
return origen;
}
/**
* Define el valor de la propiedad origen.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setOrigen(Object value) {
this.origen = value;
}
/**
* Obtiene el valor de la propiedad nombreLinea.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getNombreLinea() {
return nombreLinea;
}
/**
* Define el valor de la propiedad nombreLinea.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setNombreLinea(Object value) {
this.nombreLinea = value;
}
/**
* Obtiene el valor de la propiedad typePago.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getTypePago() {
return typePago;
}
/**
* Define el valor de la propiedad typePago.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setTypePago(Object value) {
this.typePago = value;
}
/**
* Obtiene el valor de la propiedad fecha.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getFecha() {
return fecha;
}
/**
* Define el valor de la propiedad fecha.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setFecha(Object value) {
this.fecha = value;
}
/**
* Obtiene el valor de la propiedad precio.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getPrecio() {
return precio;
}
/**
* Define el valor de la propiedad precio.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setPrecio(Object value) {
this.precio = value;
}
}
}
| UTF-8 | Java | 10,442 | java | MostrarComprasResponse.java | Java | [] | null | [] | //
// Este archivo ha sido generado por la arquitectura JavaTM para la implantación de la referencia de enlace (JAXB) XML v2.2.7
// Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Todas las modificaciones realizadas en este archivo se perderán si se vuelve a compilar el esquema de origen.
// Generado el: 2020.06.16 a las 09:01:46 PM CDT
//
package me.uvmetro.metrov2_1;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="compra" maxOccurs="unbounded">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Compra" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Usuario" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="TypeVagon" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Origen" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="NombreLinea" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="TypePago" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Fecha" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Precio" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"compra"
})
@XmlRootElement(name = "MostrarComprasResponse")
public class MostrarComprasResponse {
@XmlElement(required = true)
protected List<MostrarComprasResponse.Compra> compra;
/**
* Gets the value of the compra property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the compra property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCompra().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link MostrarComprasResponse.Compra }
*
*
*/
public List<MostrarComprasResponse.Compra> getCompra() {
if (compra == null) {
compra = new ArrayList<MostrarComprasResponse.Compra>();
}
return this.compra;
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Compra" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Usuario" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="TypeVagon" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Origen" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="NombreLinea" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="TypePago" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Fecha" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="Precio" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"compra",
"usuario",
"typeVagon",
"origen",
"nombreLinea",
"typePago",
"fecha",
"precio"
})
public static class Compra {
@XmlElement(name = "Compra", required = true)
protected Object compra;
@XmlElement(name = "Usuario", required = true)
protected Object usuario;
@XmlElement(name = "TypeVagon", required = true)
protected Object typeVagon;
@XmlElement(name = "Origen", required = true)
protected Object origen;
@XmlElement(name = "NombreLinea", required = true)
protected Object nombreLinea;
@XmlElement(name = "TypePago", required = true)
protected Object typePago;
@XmlElement(name = "Fecha", required = true)
protected Object fecha;
@XmlElement(name = "Precio", required = true)
protected Object precio;
/**
* Obtiene el valor de la propiedad compra.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getCompra() {
return compra;
}
/**
* Define el valor de la propiedad compra.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setCompra(Object value) {
this.compra = value;
}
/**
* Obtiene el valor de la propiedad usuario.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getUsuario() {
return usuario;
}
/**
* Define el valor de la propiedad usuario.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setUsuario(Object value) {
this.usuario = value;
}
/**
* Obtiene el valor de la propiedad typeVagon.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getTypeVagon() {
return typeVagon;
}
/**
* Define el valor de la propiedad typeVagon.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setTypeVagon(Object value) {
this.typeVagon = value;
}
/**
* Obtiene el valor de la propiedad origen.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getOrigen() {
return origen;
}
/**
* Define el valor de la propiedad origen.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setOrigen(Object value) {
this.origen = value;
}
/**
* Obtiene el valor de la propiedad nombreLinea.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getNombreLinea() {
return nombreLinea;
}
/**
* Define el valor de la propiedad nombreLinea.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setNombreLinea(Object value) {
this.nombreLinea = value;
}
/**
* Obtiene el valor de la propiedad typePago.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getTypePago() {
return typePago;
}
/**
* Define el valor de la propiedad typePago.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setTypePago(Object value) {
this.typePago = value;
}
/**
* Obtiene el valor de la propiedad fecha.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getFecha() {
return fecha;
}
/**
* Define el valor de la propiedad fecha.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setFecha(Object value) {
this.fecha = value;
}
/**
* Obtiene el valor de la propiedad precio.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getPrecio() {
return precio;
}
/**
* Define el valor de la propiedad precio.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setPrecio(Object value) {
this.precio = value;
}
}
}
| 10,442 | 0.493678 | 0.482759 | 346 | 28.17341 | 24.690664 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.283237 | false | false | 2 |
847fcb79c3408830071ae1db96b1ebf9d3541180 | 30,004,641,551,934 | 3bf186002a5d04ee89b6922abe3556e518c6455b | /TestCamera/app/src/main/java/com/zk/testcamera/activity/Test4Activity.java | 5d81c2b5dc170732c6aa15a53d7549d5b3adbcbb | [] | no_license | 63966367/MyProject | https://github.com/63966367/MyProject | cb0bbb53a67137c0c028f0eca3e44e2c0307646a | f2298ff2c866887e0254e308cc37c4c652f51b66 | refs/heads/master | 2022-01-29T11:17:42.280000 | 2019-07-03T06:16:33 | 2019-07-03T06:16:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zk.testcamera.activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import com.zk.testcamera.R;
import com.zk.testcamera.view.MatrixView;
import java.io.File;
import java.io.FileOutputStream;
public class Test4Activity extends AppCompatActivity {
private MatrixView v;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test4);
v = (MatrixView) findViewById(R.id.v);
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
int screenwidth = wm.getDefaultDisplay().getWidth();
int screenheight = wm.getDefaultDisplay().getHeight();
String file = getIntent().getStringExtra("snapshot");
Bitmap bitmap = BitmapFactory.decodeFile(file);
//initview
float x1 = getIntent().getFloatExtra("x1", 0.1f);
float y1 = getIntent().getFloatExtra("y1", 0.1f);
float x2 = getIntent().getFloatExtra("x2", 0.9f);
float y2 = getIntent().getFloatExtra("y2", 0.1f);
float x3 = getIntent().getFloatExtra("x3", 0.9f);
float y3 = getIntent().getFloatExtra("y3", 0.9f);
float x4 = getIntent().getFloatExtra("x4", 0.1f);
float y4 = getIntent().getFloatExtra("y4", 0.9f);
v.setParam(screenwidth, screenheight, bitmap, x1, y1, x2, y2, x3, y3, x4, y4);
}
public void clickOK(View view) {
// 获取屏幕
View dView = v; //getRootView();//getWindow().getDecorView();
dView.setDrawingCacheEnabled(true);
dView.buildDrawingCache();
Bitmap bmp = dView.getDrawingCache();
String name = "xxx.jpg";
String filePath = "/mnt/sdcard/" + name;
if (bmp != null) {
try {
// 图片文件路径
File file = new File(filePath);
FileOutputStream os = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| UTF-8 | Java | 2,418 | java | Test4Activity.java | Java | [] | null | [] | package com.zk.testcamera.activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import com.zk.testcamera.R;
import com.zk.testcamera.view.MatrixView;
import java.io.File;
import java.io.FileOutputStream;
public class Test4Activity extends AppCompatActivity {
private MatrixView v;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test4);
v = (MatrixView) findViewById(R.id.v);
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
int screenwidth = wm.getDefaultDisplay().getWidth();
int screenheight = wm.getDefaultDisplay().getHeight();
String file = getIntent().getStringExtra("snapshot");
Bitmap bitmap = BitmapFactory.decodeFile(file);
//initview
float x1 = getIntent().getFloatExtra("x1", 0.1f);
float y1 = getIntent().getFloatExtra("y1", 0.1f);
float x2 = getIntent().getFloatExtra("x2", 0.9f);
float y2 = getIntent().getFloatExtra("y2", 0.1f);
float x3 = getIntent().getFloatExtra("x3", 0.9f);
float y3 = getIntent().getFloatExtra("y3", 0.9f);
float x4 = getIntent().getFloatExtra("x4", 0.1f);
float y4 = getIntent().getFloatExtra("y4", 0.9f);
v.setParam(screenwidth, screenheight, bitmap, x1, y1, x2, y2, x3, y3, x4, y4);
}
public void clickOK(View view) {
// 获取屏幕
View dView = v; //getRootView();//getWindow().getDecorView();
dView.setDrawingCacheEnabled(true);
dView.buildDrawingCache();
Bitmap bmp = dView.getDrawingCache();
String name = "xxx.jpg";
String filePath = "/mnt/sdcard/" + name;
if (bmp != null) {
try {
// 图片文件路径
File file = new File(filePath);
FileOutputStream os = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 2,418 | 0.608007 | 0.588824 | 67 | 33.791046 | 23.021429 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.955224 | false | false | 2 |
9d14596f935998c0b99c36c4a49a51bfd688b3fb | 27,951,647,182,531 | 66d19fb59331f32520362c8478c5a7c19000e2ce | /mes-root/mes-auto-core/src/main/java/com/hengyi/japp/mes/auto/application/LineMachineService.java | 58521d1387da88206ef091ca8999ceda6f891396 | [] | no_license | ixtf/mes | https://github.com/ixtf/mes | d5008c03e383780b7b3bc85ea3cce7afec4b9d71 | 713c50add9e6cc4ba919a2c5a3a61fe5690d411d | refs/heads/master | 2023-01-07T08:10:16.505000 | 2019-11-11T20:35:12 | 2019-11-11T20:35:12 | 195,050,351 | 1 | 1 | null | false | 2023-01-07T07:27:21 | 2019-07-03T12:36:28 | 2019-12-05T00:25:34 | 2023-01-07T07:27:21 | 3,526 | 1 | 0 | 33 | Java | false | false | package com.hengyi.japp.mes.auto.application;
import com.hengyi.japp.mes.auto.application.command.LineMachineUpdateCommand;
import com.hengyi.japp.mes.auto.domain.LineMachine;
import com.hengyi.japp.mes.auto.domain.LineMachineProductPlan;
import java.security.Principal;
import java.util.List;
/**
* @author jzb 2018-06-22
*/
public interface LineMachineService {
LineMachine create(Principal principal, LineMachineUpdateCommand command);
LineMachine update(Principal principal, String id, LineMachineUpdateCommand command);
List<LineMachineProductPlan> listTimeline(String id, String currentId, int size);
}
| UTF-8 | Java | 629 | java | LineMachineService.java | Java | [
{
"context": ".Principal;\nimport java.util.List;\n\n/**\n * @author jzb 2018-06-22\n */\npublic interface LineMachineServic",
"end": 315,
"score": 0.9996030330657959,
"start": 312,
"tag": "USERNAME",
"value": "jzb"
}
] | null | [] | package com.hengyi.japp.mes.auto.application;
import com.hengyi.japp.mes.auto.application.command.LineMachineUpdateCommand;
import com.hengyi.japp.mes.auto.domain.LineMachine;
import com.hengyi.japp.mes.auto.domain.LineMachineProductPlan;
import java.security.Principal;
import java.util.List;
/**
* @author jzb 2018-06-22
*/
public interface LineMachineService {
LineMachine create(Principal principal, LineMachineUpdateCommand command);
LineMachine update(Principal principal, String id, LineMachineUpdateCommand command);
List<LineMachineProductPlan> listTimeline(String id, String currentId, int size);
}
| 629 | 0.804452 | 0.791733 | 20 | 30.450001 | 32.049141 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 2 |
1a75f5acffb26792a470791336656f28bdf503c1 | 27,839,978,032,168 | b8e6670705fa24331a14c9fd1fbfe8fe4b92be6b | /代跑侠项目20190102/runner/src/com/jerrymice/runner/changePayPassword/service/PayPasswordServiceImpl.java | e72d766273858becb13340c38207fe287f044db7 | [] | no_license | HBSDLJZ/Runner | https://github.com/HBSDLJZ/Runner | 24cd5424b6f1a6af0eb4f4c9d404176d10c298aa | f08bb5383d635abd04bf664ac80def30d6074bb5 | refs/heads/master | 2020-04-07T15:48:13.972000 | 2019-01-02T00:39:53 | 2019-01-02T00:39:53 | 158,501,549 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jerrymice.runner.changePayPassword.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jerrymice.runner.changePayPassword.dao.PayPasswordDao;
import com.jerrymice.runner.entity.Information;
@Service(value="payPasswordServiceId")
public class PayPasswordServiceImpl implements PayPasswordService {
@Resource(name="payPasswordId")
private PayPasswordDao payPasswordDao;
@Transactional(readOnly=false)
@Override
public void updateInformation(Information info) {
payPasswordDao.update(info);
}
}
| UTF-8 | Java | 634 | java | PayPasswordServiceImpl.java | Java | [] | null | [] | package com.jerrymice.runner.changePayPassword.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jerrymice.runner.changePayPassword.dao.PayPasswordDao;
import com.jerrymice.runner.entity.Information;
@Service(value="payPasswordServiceId")
public class PayPasswordServiceImpl implements PayPasswordService {
@Resource(name="payPasswordId")
private PayPasswordDao payPasswordDao;
@Transactional(readOnly=false)
@Override
public void updateInformation(Information info) {
payPasswordDao.update(info);
}
}
| 634 | 0.834385 | 0.834385 | 23 | 26.565218 | 24.203531 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.73913 | false | false | 2 |
022217c64df2a54ee393f853b0bb80ea6e2105c2 | 29,798,483,141,083 | acfbc78f2a455fd6349f594157f878a57b712fc4 | /src/main/java/uz/xtreme/example/repository/auth/PermissionRepository.java | bd6ac9e5719c88dd1ed3caf9eddff2b003da8db9 | [] | no_license | xtreme-uz/spring-web-app | https://github.com/xtreme-uz/spring-web-app | f0ee644a50dfb4eb46c22e9def0985ec1b6c233a | 8d8e09ce5ddbed5e78be76dde7ad881a4ef35dd2 | refs/heads/master | 2021-08-07T23:17:25.275000 | 2020-09-06T07:08:21 | 2020-09-06T07:08:21 | 216,811,643 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uz.xtreme.example.repository.auth;
import org.springframework.stereotype.Repository;
import uz.xtreme.example.criteria.auth.PermissionCriteria;
import uz.xtreme.example.dao.GenericDao;
import uz.xtreme.example.domain.auth.Permission;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;
/**
* Author: Rustambekov Avazbek
* Date: 23/10/19
* Time: 16:46
*/
@Repository
public class PermissionRepository extends GenericDao<Permission, PermissionCriteria> implements IPermissionRepository {
@Override
protected void defineCriteriaOnQuerying(PermissionCriteria criteria, List<String> whereCause, Map<String, Object> params, StringBuilder queryBuilder) {
if (!utils.isEmpty(criteria.getSelfId())) {
whereCause.add("t.id = :selfId");
params.put("selfId", criteria.getSelfId());
}
if (!utils.isEmpty(criteria.getName())) {
whereCause.add("t.name = :name");
params.put("name", criteria.getName());
}
if (!utils.isEmpty(criteria.getCodeName())) {
whereCause.add("t.codeName = :codeName");
params.put("codeName", criteria.getCodeName());
}
onDefineWhereCause(criteria, whereCause, params, queryBuilder);
}
@Override
protected Query defineQuerySelect(PermissionCriteria criteria, StringBuilder queryBuilder, boolean onDefineCount) {
String queryStr = " SELECT" + (onDefineCount ? " COUNT(t) " : " t ") + " FROM Permission t " +
joinStringOnQuerying(criteria) +
" WHERE t.deleted = 0 " + queryBuilder.toString() + onSortBy(criteria).toString();
return onDefineCount ? entityManager.createQuery(queryStr, Long.class) : entityManager.createQuery(queryStr);
}
@Override
protected void onDefineWhereCause(PermissionCriteria criteria, List<String> whereCause, Map<String, Object> params, StringBuilder queryBuilder) {
super.onDefineWhereCause(criteria, whereCause, params, queryBuilder);
}
}
| UTF-8 | Java | 2,041 | java | PermissionRepository.java | Java | [
{
"context": "a.util.List;\nimport java.util.Map;\n\n/**\n * Author: Rustambekov Avazbek\n * Date: 23/10/19\n * Time: 16:46\n */\n\n@Repository",
"end": 356,
"score": 0.9998641014099121,
"start": 337,
"tag": "NAME",
"value": "Rustambekov Avazbek"
}
] | null | [] | package uz.xtreme.example.repository.auth;
import org.springframework.stereotype.Repository;
import uz.xtreme.example.criteria.auth.PermissionCriteria;
import uz.xtreme.example.dao.GenericDao;
import uz.xtreme.example.domain.auth.Permission;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;
/**
* Author: <NAME>
* Date: 23/10/19
* Time: 16:46
*/
@Repository
public class PermissionRepository extends GenericDao<Permission, PermissionCriteria> implements IPermissionRepository {
@Override
protected void defineCriteriaOnQuerying(PermissionCriteria criteria, List<String> whereCause, Map<String, Object> params, StringBuilder queryBuilder) {
if (!utils.isEmpty(criteria.getSelfId())) {
whereCause.add("t.id = :selfId");
params.put("selfId", criteria.getSelfId());
}
if (!utils.isEmpty(criteria.getName())) {
whereCause.add("t.name = :name");
params.put("name", criteria.getName());
}
if (!utils.isEmpty(criteria.getCodeName())) {
whereCause.add("t.codeName = :codeName");
params.put("codeName", criteria.getCodeName());
}
onDefineWhereCause(criteria, whereCause, params, queryBuilder);
}
@Override
protected Query defineQuerySelect(PermissionCriteria criteria, StringBuilder queryBuilder, boolean onDefineCount) {
String queryStr = " SELECT" + (onDefineCount ? " COUNT(t) " : " t ") + " FROM Permission t " +
joinStringOnQuerying(criteria) +
" WHERE t.deleted = 0 " + queryBuilder.toString() + onSortBy(criteria).toString();
return onDefineCount ? entityManager.createQuery(queryStr, Long.class) : entityManager.createQuery(queryStr);
}
@Override
protected void onDefineWhereCause(PermissionCriteria criteria, List<String> whereCause, Map<String, Object> params, StringBuilder queryBuilder) {
super.onDefineWhereCause(criteria, whereCause, params, queryBuilder);
}
}
| 2,028 | 0.692798 | 0.687408 | 54 | 36.796295 | 40.334427 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.722222 | false | false | 2 |
8ec1fa1f08ef3e608878539c71a3c77cf965d590 | 20,770,461,860,399 | 55b80a498fadd18c7882f96ce7fa2ac5d54def12 | /Objects/src/Objects/CrazyObject.java | 56fc0600e97fa5e43f77aac40815042955c3e474 | [] | no_license | mijaelro/-Java-822-119 | https://github.com/mijaelro/-Java-822-119 | 783dc5eec5e61cef46b4393c4f46fac24892aa60 | 882a7f6533ee730abfc9e16746b8b49f45b91fda | refs/heads/master | 2021-01-03T06:59:58.534000 | 2020-01-31T11:15:59 | 2020-01-31T11:15:59 | 239,970,457 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Objects;
public class CrazyObject {
public String name = "Yaniv";
@Override
public String toString() {
return "Shalom " + name;
}
}
| UTF-8 | Java | 150 | java | CrazyObject.java | Java | [
{
"context": "ublic class CrazyObject {\n\n\tpublic String name = \"Yaniv\";\n\t\n\t@Override\n\tpublic String toString() {\n\t\tretu",
"end": 74,
"score": 0.9991207718849182,
"start": 69,
"tag": "NAME",
"value": "Yaniv"
},
{
"context": "\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Shalom \" + name;\n\t}\n}\n",
"end": 134,
"score": 0.9950418472290039,
"start": 128,
"tag": "NAME",
"value": "Shalom"
}
] | null | [] | package Objects;
public class CrazyObject {
public String name = "Yaniv";
@Override
public String toString() {
return "Shalom " + name;
}
}
| 150 | 0.673333 | 0.673333 | 11 | 12.636364 | 12.009638 | 30 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.909091 | false | false | 2 |
6c258e774654cee8438e0a2db44f249af3500df0 | 12,893,491,881,894 | 65c9061f5c722f6407825e55f008b5e6c1c1d819 | /rpa-application/src/main/java/com/szcinda/express/controller/netty/NettyChannelInitializer.java | de11a51df65efe6886b611fea9764c68c367bb66 | [] | no_license | miamiby557/netty | https://github.com/miamiby557/netty | ab9d65d35c99689e7d48631e1541dbee9295a665 | 5abb501f2e59fcce8bb20474f75a3631d463fbad | refs/heads/master | 2023-03-21T14:10:38.979000 | 2021-03-11T03:29:02 | 2021-03-11T03:29:02 | 346,566,188 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.szcinda.express.controller.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class NettyChannelInitializer extends ChannelInitializer<SocketChannel> {
// @Override
// protected void initChannel(Channel ch) throws Exception {
// // ChannelOutboundHandler,依照逆序执行
// ch.pipeline().addLast("encoder", new StringEncoder());
//
// // 属于ChannelInboundHandler,依照顺序执行
// ch.pipeline().addLast("decoder", new StringDecoder());
// ChannelPipeline pipeline = ch.pipeline();
// // 处理粘包问题
// ByteBuf delimiter = Unpooled.copiedBuffer("$$".getBytes());
// pipeline.addLast("framer", new DelimiterBasedFrameDecoder(2048,delimiter));
// /**
// * 自定义ChannelInboundHandlerAdapter
// */
// ch.pipeline().addLast(new NettyChannelInboundHandlerAdapter());
//
// }
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// ChannelOutboundHandler,依照逆序执行
ch.pipeline().addLast("encoder", new StringEncoder(StandardCharsets.UTF_8));
// 属于ChannelInboundHandler,依照顺序执行
ch.pipeline().addLast("decoder", new StringDecoder(StandardCharsets.UTF_8));
ChannelPipeline pipeline = ch.pipeline();
// 请求路径
// pipeline.addLast(new HttpRequestHandler("/chrome"));
// pipeline.addLast(new WebSocketServerProtocolHandler("/chrome"));
// 处理粘包问题
// ByteBuf delimiter = Unpooled.copiedBuffer("$$".getBytes());
// pipeline.addLast(new DelimiterBasedFrameDecoder(2048,delimiter));
/**
* 自定义ChannelInboundHandlerAdapter
*/
ch.pipeline().addLast(new NettyChannelInboundHandlerAdapter());
}
}
| UTF-8 | Java | 2,479 | java | NettyChannelInitializer.java | Java | [] | null | [] | package com.szcinda.express.controller.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class NettyChannelInitializer extends ChannelInitializer<SocketChannel> {
// @Override
// protected void initChannel(Channel ch) throws Exception {
// // ChannelOutboundHandler,依照逆序执行
// ch.pipeline().addLast("encoder", new StringEncoder());
//
// // 属于ChannelInboundHandler,依照顺序执行
// ch.pipeline().addLast("decoder", new StringDecoder());
// ChannelPipeline pipeline = ch.pipeline();
// // 处理粘包问题
// ByteBuf delimiter = Unpooled.copiedBuffer("$$".getBytes());
// pipeline.addLast("framer", new DelimiterBasedFrameDecoder(2048,delimiter));
// /**
// * 自定义ChannelInboundHandlerAdapter
// */
// ch.pipeline().addLast(new NettyChannelInboundHandlerAdapter());
//
// }
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// ChannelOutboundHandler,依照逆序执行
ch.pipeline().addLast("encoder", new StringEncoder(StandardCharsets.UTF_8));
// 属于ChannelInboundHandler,依照顺序执行
ch.pipeline().addLast("decoder", new StringDecoder(StandardCharsets.UTF_8));
ChannelPipeline pipeline = ch.pipeline();
// 请求路径
// pipeline.addLast(new HttpRequestHandler("/chrome"));
// pipeline.addLast(new WebSocketServerProtocolHandler("/chrome"));
// 处理粘包问题
// ByteBuf delimiter = Unpooled.copiedBuffer("$$".getBytes());
// pipeline.addLast(new DelimiterBasedFrameDecoder(2048,delimiter));
/**
* 自定义ChannelInboundHandlerAdapter
*/
ch.pipeline().addLast(new NettyChannelInboundHandlerAdapter());
}
}
| 2,479 | 0.716154 | 0.711936 | 58 | 39.879311 | 25.736782 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655172 | false | false | 2 |
f2169c80745bd93567b413c61097ec44f7b31589 | 17,660,905,581,761 | 32724159f9ecae76c59a57549d461243746fbb41 | /AP_CSA/src/labAssessment/Runner.java | b3f13f3b137d949e884f7e8e268d91d5972ddad1 | [] | no_license | renj3065/AP_CSA | https://github.com/renj3065/AP_CSA | a2e064c88413da7eb4f472ef42c8189363f0f5b5 | 2a953e6d1ee9eac7926c45266bd43746c273ccb4 | refs/heads/master | 2021-05-08T13:47:23.049000 | 2018-05-11T21:57:54 | 2018-05-11T21:57:54 | 120,034,956 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package labAssessment;
public class Runner {
public static void main(String[] args) {
DuffelBag bag1=new DuffelBag();
bag1.addBall(new SoccerBall("Nike",true));
bag1.addBall(new SoccerBall("Adidas",false));
bag1.addBall(new SoccerBall("Puma",true));
DuffelBag bag2=new DuffelBag();
bag2.addBall(new SoccerBall(false));
bag2.addBall(new SoccerBall("Adidas"));
DuffelBag bag3=new DuffelBag();
bag3.addBall(new SoccerBall("Adidas",true));
bag3.addBall(new SoccerBall("Adidas",true));
SoccerPlayer player1=new SoccerPlayer("Sam",bag1);
SoccerPlayer player2=new SoccerPlayer("Bill",bag2);
SoccerPlayer player3=new SoccerPlayer("Jillian", bag3);
SoccerTeam temp=new SoccerTeam("Barcalona");
temp.recruit(player1);
temp.recruit(player2);
temp.recruit(player3);
System.out.println(temp);
temp.playGame();
System.out.println("Team after game:");
System.out.println(temp);
temp.viewBags();
temp.heal();
System.out.println(temp);
}
}
| UTF-8 | Java | 1,004 | java | Runner.java | Java | [
{
"context": "ue));\r\n\t\r\n\tSoccerPlayer player1=new SoccerPlayer(\"Sam\",bag1);\r\n\tSoccerPlayer player2=new SoccerPlayer(\"",
"end": 559,
"score": 0.9998584389686584,
"start": 556,
"tag": "NAME",
"value": "Sam"
},
{
"context": "\",bag1);\r\n\tSoccerPlayer player2=new SoccerPlayer(\"Bill\",bag2);\r\n\tSoccerPlayer player3=new SoccerPlayer(\"",
"end": 613,
"score": 0.999877393245697,
"start": 609,
"tag": "NAME",
"value": "Bill"
},
{
"context": "\",bag2);\r\n\tSoccerPlayer player3=new SoccerPlayer(\"Jillian\", bag3);\r\n\t\r\n\tSoccerTeam temp=new SoccerTeam(\"Bar",
"end": 670,
"score": 0.9997990727424622,
"start": 663,
"tag": "NAME",
"value": "Jillian"
},
{
"context": "ian\", bag3);\r\n\t\r\n\tSoccerTeam temp=new SoccerTeam(\"Barcalona\");\r\n\ttemp.recruit(player1);\r\n\ttemp.recruit(player",
"end": 726,
"score": 0.9841968417167664,
"start": 717,
"tag": "NAME",
"value": "Barcalona"
}
] | null | [] | package labAssessment;
public class Runner {
public static void main(String[] args) {
DuffelBag bag1=new DuffelBag();
bag1.addBall(new SoccerBall("Nike",true));
bag1.addBall(new SoccerBall("Adidas",false));
bag1.addBall(new SoccerBall("Puma",true));
DuffelBag bag2=new DuffelBag();
bag2.addBall(new SoccerBall(false));
bag2.addBall(new SoccerBall("Adidas"));
DuffelBag bag3=new DuffelBag();
bag3.addBall(new SoccerBall("Adidas",true));
bag3.addBall(new SoccerBall("Adidas",true));
SoccerPlayer player1=new SoccerPlayer("Sam",bag1);
SoccerPlayer player2=new SoccerPlayer("Bill",bag2);
SoccerPlayer player3=new SoccerPlayer("Jillian", bag3);
SoccerTeam temp=new SoccerTeam("Barcalona");
temp.recruit(player1);
temp.recruit(player2);
temp.recruit(player3);
System.out.println(temp);
temp.playGame();
System.out.println("Team after game:");
System.out.println(temp);
temp.viewBags();
temp.heal();
System.out.println(temp);
}
}
| 1,004 | 0.704183 | 0.685259 | 39 | 23.743589 | 18.231726 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 2 |
ababba2d5bccf69b04a777c8dacb2ee28b656be2 | 8,435,315,803,598 | cf330d52b346d58595aa14b337d2e5c2181fa73e | /app/src/main/java/com/jetLee/customviewpractice/ui/property/PropertyAnimatorActivity.java | 47042c044b8b3d181378bccc7384de03f0695a39 | [] | no_license | jetLee92/CustomViewPractice | https://github.com/jetLee92/CustomViewPractice | 3769ab8c2eace537900a749a0c63bf1f519562b7 | 30c1ae3c7f40fab0904dcd59df8205e4817f7742 | refs/heads/master | 2020-03-23T21:55:23.974000 | 2018-08-22T10:04:04 | 2018-08-22T10:04:04 | 142,141,529 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jetLee.customviewpractice.ui.property;
import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.jetLee.customviewpractice.R;
import com.jetLee.customviewpractice.view.property.PropertyView;
/**
* ObjectAnimator使用
*
* @author:Jet啟思
* @date:2018/7/26 14:49
*/
public class PropertyAnimatorActivity extends AppCompatActivity {
PropertyView view;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_property_animator);
view = findViewById(R.id.propertyView);
// view.animate()
//// .translationY(Utils.dpToPx(200))
// .scaleX(0.5f)
// .setStartDelay(800);
// ObjectAnimator objectAnimator = ObjectAnimator.ofInt(view, "progress", 0, 70);
// objectAnimator.setDuration(800);
// objectAnimator.setStartDelay(500);
// objectAnimator.start();
Keyframe keyframe1 = Keyframe.ofInt(0, 0);
Keyframe keyframe2 = Keyframe.ofInt(0.5f, 80);
Keyframe keyframe3 = Keyframe.ofInt(1, 60);
PropertyValuesHolder propertyValuesHolder = PropertyValuesHolder.ofKeyframe("progress", keyframe1, keyframe2, keyframe3);
ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(view, propertyValuesHolder);
objectAnimator.setDuration(1200);
objectAnimator.setStartDelay(800);
objectAnimator.start();
}
}
| UTF-8 | Java | 1,550 | java | PropertyAnimatorActivity.java | Java | [
{
"context": "pertyView;\n\n/**\n * ObjectAnimator使用\n *\n * @author:Jet啟思\n * @date:2018/7/26 14:49\n */\npublic class Propert",
"end": 444,
"score": 0.9997615218162537,
"start": 439,
"tag": "NAME",
"value": "Jet啟思"
}
] | null | [] | package com.jetLee.customviewpractice.ui.property;
import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.jetLee.customviewpractice.R;
import com.jetLee.customviewpractice.view.property.PropertyView;
/**
* ObjectAnimator使用
*
* @author:Jet啟思
* @date:2018/7/26 14:49
*/
public class PropertyAnimatorActivity extends AppCompatActivity {
PropertyView view;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_property_animator);
view = findViewById(R.id.propertyView);
// view.animate()
//// .translationY(Utils.dpToPx(200))
// .scaleX(0.5f)
// .setStartDelay(800);
// ObjectAnimator objectAnimator = ObjectAnimator.ofInt(view, "progress", 0, 70);
// objectAnimator.setDuration(800);
// objectAnimator.setStartDelay(500);
// objectAnimator.start();
Keyframe keyframe1 = Keyframe.ofInt(0, 0);
Keyframe keyframe2 = Keyframe.ofInt(0.5f, 80);
Keyframe keyframe3 = Keyframe.ofInt(1, 60);
PropertyValuesHolder propertyValuesHolder = PropertyValuesHolder.ofKeyframe("progress", keyframe1, keyframe2, keyframe3);
ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(view, propertyValuesHolder);
objectAnimator.setDuration(1200);
objectAnimator.setStartDelay(800);
objectAnimator.start();
}
}
| 1,550 | 0.77987 | 0.746753 | 50 | 29.799999 | 27.166155 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.68 | false | false | 2 |
8d791bf4ccdd9204d2dbc8490be4f86169d152e2 | 7,576,322,352,263 | 8681e73fa3da78977346db10e9790dc049acae14 | /src/main/java/hust/tool/SpringBean.java | 531e191d7e914abf2fe7fddec5cacdde099ce2b0 | [] | no_license | lab702-flyme/sweo | https://github.com/lab702-flyme/sweo | 2a607116ee6a4fce3edc627643f697d7fe090c07 | 5ed3a6c82144a9c9aa158490cac242bc5a108feb | refs/heads/master | 2018-01-10T02:24:06.716000 | 2015-10-26T02:03:26 | 2015-10-26T02:03:26 | 44,105,449 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hust.tool;
import javax.servlet.ServletContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class SpringBean {
/**
* 获取spring中bean的实例
* @param beanName
* @param sc
* @return
*/
public static Object getBean (String beanName, ServletContext sc) {
return WebApplicationContextUtils.getWebApplicationContext(sc).getBean(beanName);
}
/**
* 获取spring中bean的实例
* @param beanName
* @param sc
* @return
*/
public static Object getBean (String beanName) {
return getBean(beanName, ApplicationContainer.sc);
}
}
| UTF-8 | Java | 606 | java | SpringBean.java | Java | [] | null | [] | package hust.tool;
import javax.servlet.ServletContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class SpringBean {
/**
* 获取spring中bean的实例
* @param beanName
* @param sc
* @return
*/
public static Object getBean (String beanName, ServletContext sc) {
return WebApplicationContextUtils.getWebApplicationContext(sc).getBean(beanName);
}
/**
* 获取spring中bean的实例
* @param beanName
* @param sc
* @return
*/
public static Object getBean (String beanName) {
return getBean(beanName, ApplicationContainer.sc);
}
}
| 606 | 0.737113 | 0.737113 | 28 | 19.785715 | 23.56959 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.035714 | false | false | 2 |
5221c3a6994553ffb99d7c134899ed61cae0c78a | 10,264,971,882,053 | b44a102cd20146a858e004476e64da30842a1019 | /app/src/main/java/org/sunbird/telemetry/TelemetryPageId.java | ba130b808bdf6c447a440568e6252075c2ff185f | [
"MIT"
] | permissive | G33tha/sunbird-android | https://github.com/G33tha/sunbird-android | 25fe082c0ec77e5f0eeb199a01dc9f65c672c874 | 10e56a9b67826ee96560fb8a38714218dc71c1c1 | refs/heads/master | 2020-04-10T03:53:47.323000 | 2018-12-07T06:44:12 | 2018-12-07T06:44:12 | 160,782,287 | 0 | 0 | MIT | true | 2018-12-07T06:39:23 | 2018-12-07T06:39:23 | 2018-09-28T07:13:20 | 2018-06-21T06:07:49 | 10,109 | 0 | 0 | 0 | null | false | null | package org.sunbird.telemetry;
/**
* Created on 5/17/2016.
*
* @author anil
*/
public interface TelemetryPageId {
String SPLASH_SCREEN = "splash";
String LOGIN = "login";
String LOGOUT = "logout";
String SIGNUP = "signup";
String HOME = "home";
String COURSES = "courses";
String LIBRARY = "library";
String GROUPS = "groups";
String PROFILE = "profile";
String COURSE_PAGE_FILTER = "course-page-filter";
String LIBRARY_PAGE_FILTER = "library-page-filter";
String COURSE_DETAIL = "course-detail";
String COLLECTION_DETAIL = "collection-detail";
String CONTENT_DETAIL = "content-detail";
String FLAG_CONTENT = "flag-content";
String SHARE_CONTENT = "share-content";
String SHARE_ANNOUCEMENT = "share-announcement";
String QRCodeScanner = "QRCode-Scanner";
String SETTINGS = "Settings";
String SETTINGS_LANGUAGE = "settings-language";
String SETTINGS_DATASYNC = "settings-datasync";
String SETTINGS_DEVICE_TAGS = "settings-device-tags";
String ABOUT_APP = "about-app";
String SIGNIN_OVERLAY = "signin-overlay";
String SERVER_NOTIFICATION = "server-notifiaction";
String ANNOUNCEMENT_LIST = "announcement-list";
String ANNOUNCEMENT_DETAIL = "announcement-detail";
String USER_TYPE_SELECTION = "user-type-selection";
String ONBOARD = "onboard";
String RECEIVED = "received";
String DISPLAYED = "displayed";
String CONTENT_RATING = "content-rating";
String ONBOARDING = "onboarding";
}
| UTF-8 | Java | 1,523 | java | TelemetryPageId.java | Java | [
{
"context": "metry;\n\n/**\n * Created on 5/17/2016.\n *\n * @author anil\n */\npublic interface TelemetryPageId {\n\n Strin",
"end": 79,
"score": 0.9591971635818481,
"start": 75,
"tag": "USERNAME",
"value": "anil"
}
] | null | [] | package org.sunbird.telemetry;
/**
* Created on 5/17/2016.
*
* @author anil
*/
public interface TelemetryPageId {
String SPLASH_SCREEN = "splash";
String LOGIN = "login";
String LOGOUT = "logout";
String SIGNUP = "signup";
String HOME = "home";
String COURSES = "courses";
String LIBRARY = "library";
String GROUPS = "groups";
String PROFILE = "profile";
String COURSE_PAGE_FILTER = "course-page-filter";
String LIBRARY_PAGE_FILTER = "library-page-filter";
String COURSE_DETAIL = "course-detail";
String COLLECTION_DETAIL = "collection-detail";
String CONTENT_DETAIL = "content-detail";
String FLAG_CONTENT = "flag-content";
String SHARE_CONTENT = "share-content";
String SHARE_ANNOUCEMENT = "share-announcement";
String QRCodeScanner = "QRCode-Scanner";
String SETTINGS = "Settings";
String SETTINGS_LANGUAGE = "settings-language";
String SETTINGS_DATASYNC = "settings-datasync";
String SETTINGS_DEVICE_TAGS = "settings-device-tags";
String ABOUT_APP = "about-app";
String SIGNIN_OVERLAY = "signin-overlay";
String SERVER_NOTIFICATION = "server-notifiaction";
String ANNOUNCEMENT_LIST = "announcement-list";
String ANNOUNCEMENT_DETAIL = "announcement-detail";
String USER_TYPE_SELECTION = "user-type-selection";
String ONBOARD = "onboard";
String RECEIVED = "received";
String DISPLAYED = "displayed";
String CONTENT_RATING = "content-rating";
String ONBOARDING = "onboarding";
}
| 1,523 | 0.680893 | 0.676297 | 47 | 31.404255 | 18.564047 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.723404 | false | false | 2 |
cdbc0d8a2ed90811d3a3a8b5026e4e17665d1489 | 10,264,971,884,345 | c7bcf7e7409457bf9c6e679c6ba7c1596aeae4a7 | /plugins/de.cau.cs.kieler.synccharts.kivi/src/de/cau/cs/kieler/synccharts/kivi/ManualFocusCombination.java | 2a298a5d726f0613883257027e3143174a0a29ff | [] | no_license | flymolon/de.cau.cs.kieler | https://github.com/flymolon/de.cau.cs.kieler | 9a4a91251c84b112f472ded83595de77e5380027 | ead1a8fba7fca2072b36d931f62df735f818b94e | refs/heads/master | 2021-01-18T11:08:18.636000 | 2012-08-09T12:28:23 | 2012-08-09T12:28:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* KIELER - Kiel Integrated Environment for Layout Eclipse RichClient
*
* http://www.informatik.uni-kiel.de/rtsys/kieler/
*
* Copyright 2011 by
* + Christian-Albrechts-University of Kiel
* + Department of Computer Science
* + Real-Time and Embedded Systems Group
*
* This code is provided under the terms of the Eclipse Public License (EPL).
* See the file epl-v10.html for the license text.
*/
package de.cau.cs.kieler.synccharts.kivi;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import com.google.common.collect.Lists;
import de.cau.cs.kieler.core.kivi.AbstractCombination;
import de.cau.cs.kieler.core.kivi.menu.ButtonTrigger.ButtonState;
import de.cau.cs.kieler.core.kivi.menu.KiviMenuContributionService.LocationScheme;
import de.cau.cs.kieler.core.kivi.menu.KiviMenuContributionService;
import de.cau.cs.kieler.core.kivi.menu.MenuItemEnableStateEffect;
import de.cau.cs.kieler.core.model.gmf.effects.FocusContextEffect;
import de.cau.cs.kieler.core.model.triggers.DiagramTrigger.DiagramState;
import de.cau.cs.kieler.core.model.triggers.SelectionTrigger.DiagramSelectionState;
import de.cau.cs.kieler.kiml.kivi.LayoutEffect;
/**
* A Kieler Viewmanagement Combination that lets the user manually select a focus in a diagram and
* then configures Focus&Context accordingly by collapsing and expanding compartments. Elements in
* the focus are shown with most details and elements in the context with the least details, e.g.
* their compartments get collapsed. Zoom buttons allow to change the hierarchy level for which the
* contents of the focus should be shown.
*
* @author haf
* @kieler.ignore (excluded from review process)
*/
public class ManualFocusCombination extends AbstractCombination {
private static final String FOCUS_BUTTON_ID = "de.cau.cs.kieler.core.kivi.selectionFocus";
private static final String PLUS_BUTTON_ID = "de.cau.cs.kieler.core.kivi.focusPlus";
private static final String MINUS_BUTTON_ID = "de.cau.cs.kieler.core.kivi.focusMinus";
private static final String ALL_BUTTON_ID = "de.cau.cs.kieler.core.kivi.focusAll";
/*
* Add editor ID here to enable this button also for other editors.
*/
private static final ArrayList<String> EDITOR_IDS = Lists.newArrayList(
"de.cau.cs.kieler.synccharts.diagram.part.SyncchartsDiagramEditorID",
"de.cau.cs.kieler.kaom.diagram.part.KaomDiagramEditorID");
private static final int DEFAULT_ZOOM_LEVEL = 1;
private int zoomLevel = DEFAULT_ZOOM_LEVEL;
private boolean enabled = false;
/**
* Default Constructor defining some Buttons.
*/
public ManualFocusCombination() {
// KiVi.getInstance().setDebug(true);
ImageDescriptor iconFC = Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID,
"icons/focusContext.png");
ImageDescriptor iconPlus = Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID,
"icons/focusContextPlus.png");
ImageDescriptor iconPlusPlus = Activator.imageDescriptorFromPlugin(
Activator.PLUGIN_ID, "icons/focusContextPlusPlus.png");
ImageDescriptor iconMinus = Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID,
"icons/focusContextMinus.png");
KiviMenuContributionService.INSTANCE.addToolbarButton(this, FOCUS_BUTTON_ID,
"Manual Focus", "Focus selected model objects and do a semantic zooming.", iconFC,
SWT.CHECK, LocationScheme.MENU_POPUP_TOOLBAR, null, null, null,
EDITOR_IDS.toArray(new String[2]));
KiviMenuContributionService.INSTANCE.addToolbarButton(this, PLUS_BUTTON_ID, "Focus more",
"Increase Focus/Context zoom level.", iconPlus, SWT.PUSH,
LocationScheme.MENU_POPUP_TOOLBAR, null, null, null, EDITOR_IDS.toArray(new String[2]));
KiviMenuContributionService.INSTANCE.addToolbarButton(this, MINUS_BUTTON_ID, "Focus less",
"Decrease Focus/Context zoom level.", iconMinus, SWT.PUSH,
LocationScheme.MENU_POPUP_TOOLBAR, null, null, null, EDITOR_IDS.toArray(new String[2]));
KiviMenuContributionService.INSTANCE.addToolbarButton(this, ALL_BUTTON_ID, "Focus all",
"Show all hierarchy levels.", iconPlusPlus, SWT.PUSH,
LocationScheme.MENU_POPUP_TOOLBAR, null, null, null, EDITOR_IDS.toArray(new String[2]));
}
/**
* Main Combination logic.
*
* @param button
* listens to ButtonTriggers
* @param selection
* listens to a SelectionTrigger
* @param diagram
* listens to a DiagramTrigger
*/
public void execute(final ButtonState button, final DiagramSelectionState selection,
final DiagramState diagram) {
// first check buttons
boolean showAll = false;
if (button == latestState()) {
if (button.getButtonId().equals(PLUS_BUTTON_ID)) {
zoomLevel++;
} else if (button.getButtonId().equals(MINUS_BUTTON_ID)) {
zoomLevel--;
} else if (button.getButtonId().equals(ALL_BUTTON_ID)) {
showAll = true;
}
}
this.enable(button.isPushedIn(FOCUS_BUTTON_ID), diagram);
// if enabled, do something
if (this.enabled) {
// if bridge is null the DiagramState is uninitialized so don't do
// anything as it will fail anyway
// if the workbenchparts are different we are likely in the transition
// between diagrams don't do anything then
if ((diagram.getGraphicalFrameworkBridge() != null)
&& (diagram.getDiagramPart() == selection.getWorkbenchPart())) {
int level = zoomLevel;
List<EObject> focus = selection.getSelectedObjects();
// if we want to see everything, select root element and do a full child focus
if (showAll) {
focus.add(diagram.getSemanticModel());
level = Integer.MAX_VALUE;
} else {
// if nothing is selected, use the model root as the focus
if (focus.isEmpty()) {
focus.add(diagram.getSemanticModel());
}
}
FocusContextEffect focusEffect = new FocusContextEffect(diagram.getDiagramPart());
focusEffect.addFocus(focus, level);
this.schedule(focusEffect);
this.schedule(new LayoutEffect(selection.getWorkbenchPart(), null, true, false, true));
}
}
}
/**
* Enable or disable this functionality by graying out buttons.
*
* @param enable
* true if enabled
* @param diagram
*/
private void enable(final boolean enable, final DiagramState diagram) {
boolean validDiagram = EDITOR_IDS.contains(diagram.getDiagramType());
if (!validDiagram) {
this.enabled = false;
return;
}
if (this.enabled && !enable) {
this.schedule(new MenuItemEnableStateEffect(PLUS_BUTTON_ID, false));
this.schedule(new MenuItemEnableStateEffect(MINUS_BUTTON_ID, false));
this.enabled = enable;
} else if (!this.enabled && enable) {
this.schedule(new MenuItemEnableStateEffect(PLUS_BUTTON_ID, true));
this.schedule(new MenuItemEnableStateEffect(MINUS_BUTTON_ID, true));
// reset zoom level
zoomLevel = DEFAULT_ZOOM_LEVEL;
this.enabled = enable;
}
}
}
| UTF-8 | Java | 7,818 | java | ManualFocusCombination.java | Java | [
{
"context": "iel.de/rtsys/kieler/\n * \n * Copyright 2011 by\n * + Christian-Albrechts-University of Kiel\n * + Department of",
"end": 166,
"score": 0.866011381149292,
"start": 157,
"tag": "NAME",
"value": "Christian"
},
{
"context": "s/kieler/\n * \n * Copyright 2011 by\n * + Christian-Albrechts-University of Kiel\n * + Department of Computer ",
"end": 176,
"score": 0.8558950424194336,
"start": 167,
"tag": "NAME",
"value": "Albrechts"
},
{
"context": "tents of the focus should be shown.\n * \n * @author haf\n * @kieler.ignore (excluded from review process)\n",
"end": 1742,
"score": 0.9992600679397583,
"start": 1739,
"tag": "USERNAME",
"value": "haf"
},
{
"context": "the focus should be shown.\n * \n * @author haf\n * @kieler.ignore (excluded from review process)\n */\npublic class M",
"end": 1760,
"score": 0.9681092500686646,
"start": 1747,
"tag": "USERNAME",
"value": "kieler.ignore"
}
] | null | [] | /*
* KIELER - Kiel Integrated Environment for Layout Eclipse RichClient
*
* http://www.informatik.uni-kiel.de/rtsys/kieler/
*
* Copyright 2011 by
* + Christian-Albrechts-University of Kiel
* + Department of Computer Science
* + Real-Time and Embedded Systems Group
*
* This code is provided under the terms of the Eclipse Public License (EPL).
* See the file epl-v10.html for the license text.
*/
package de.cau.cs.kieler.synccharts.kivi;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import com.google.common.collect.Lists;
import de.cau.cs.kieler.core.kivi.AbstractCombination;
import de.cau.cs.kieler.core.kivi.menu.ButtonTrigger.ButtonState;
import de.cau.cs.kieler.core.kivi.menu.KiviMenuContributionService.LocationScheme;
import de.cau.cs.kieler.core.kivi.menu.KiviMenuContributionService;
import de.cau.cs.kieler.core.kivi.menu.MenuItemEnableStateEffect;
import de.cau.cs.kieler.core.model.gmf.effects.FocusContextEffect;
import de.cau.cs.kieler.core.model.triggers.DiagramTrigger.DiagramState;
import de.cau.cs.kieler.core.model.triggers.SelectionTrigger.DiagramSelectionState;
import de.cau.cs.kieler.kiml.kivi.LayoutEffect;
/**
* A Kieler Viewmanagement Combination that lets the user manually select a focus in a diagram and
* then configures Focus&Context accordingly by collapsing and expanding compartments. Elements in
* the focus are shown with most details and elements in the context with the least details, e.g.
* their compartments get collapsed. Zoom buttons allow to change the hierarchy level for which the
* contents of the focus should be shown.
*
* @author haf
* @kieler.ignore (excluded from review process)
*/
public class ManualFocusCombination extends AbstractCombination {
private static final String FOCUS_BUTTON_ID = "de.cau.cs.kieler.core.kivi.selectionFocus";
private static final String PLUS_BUTTON_ID = "de.cau.cs.kieler.core.kivi.focusPlus";
private static final String MINUS_BUTTON_ID = "de.cau.cs.kieler.core.kivi.focusMinus";
private static final String ALL_BUTTON_ID = "de.cau.cs.kieler.core.kivi.focusAll";
/*
* Add editor ID here to enable this button also for other editors.
*/
private static final ArrayList<String> EDITOR_IDS = Lists.newArrayList(
"de.cau.cs.kieler.synccharts.diagram.part.SyncchartsDiagramEditorID",
"de.cau.cs.kieler.kaom.diagram.part.KaomDiagramEditorID");
private static final int DEFAULT_ZOOM_LEVEL = 1;
private int zoomLevel = DEFAULT_ZOOM_LEVEL;
private boolean enabled = false;
/**
* Default Constructor defining some Buttons.
*/
public ManualFocusCombination() {
// KiVi.getInstance().setDebug(true);
ImageDescriptor iconFC = Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID,
"icons/focusContext.png");
ImageDescriptor iconPlus = Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID,
"icons/focusContextPlus.png");
ImageDescriptor iconPlusPlus = Activator.imageDescriptorFromPlugin(
Activator.PLUGIN_ID, "icons/focusContextPlusPlus.png");
ImageDescriptor iconMinus = Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID,
"icons/focusContextMinus.png");
KiviMenuContributionService.INSTANCE.addToolbarButton(this, FOCUS_BUTTON_ID,
"Manual Focus", "Focus selected model objects and do a semantic zooming.", iconFC,
SWT.CHECK, LocationScheme.MENU_POPUP_TOOLBAR, null, null, null,
EDITOR_IDS.toArray(new String[2]));
KiviMenuContributionService.INSTANCE.addToolbarButton(this, PLUS_BUTTON_ID, "Focus more",
"Increase Focus/Context zoom level.", iconPlus, SWT.PUSH,
LocationScheme.MENU_POPUP_TOOLBAR, null, null, null, EDITOR_IDS.toArray(new String[2]));
KiviMenuContributionService.INSTANCE.addToolbarButton(this, MINUS_BUTTON_ID, "Focus less",
"Decrease Focus/Context zoom level.", iconMinus, SWT.PUSH,
LocationScheme.MENU_POPUP_TOOLBAR, null, null, null, EDITOR_IDS.toArray(new String[2]));
KiviMenuContributionService.INSTANCE.addToolbarButton(this, ALL_BUTTON_ID, "Focus all",
"Show all hierarchy levels.", iconPlusPlus, SWT.PUSH,
LocationScheme.MENU_POPUP_TOOLBAR, null, null, null, EDITOR_IDS.toArray(new String[2]));
}
/**
* Main Combination logic.
*
* @param button
* listens to ButtonTriggers
* @param selection
* listens to a SelectionTrigger
* @param diagram
* listens to a DiagramTrigger
*/
public void execute(final ButtonState button, final DiagramSelectionState selection,
final DiagramState diagram) {
// first check buttons
boolean showAll = false;
if (button == latestState()) {
if (button.getButtonId().equals(PLUS_BUTTON_ID)) {
zoomLevel++;
} else if (button.getButtonId().equals(MINUS_BUTTON_ID)) {
zoomLevel--;
} else if (button.getButtonId().equals(ALL_BUTTON_ID)) {
showAll = true;
}
}
this.enable(button.isPushedIn(FOCUS_BUTTON_ID), diagram);
// if enabled, do something
if (this.enabled) {
// if bridge is null the DiagramState is uninitialized so don't do
// anything as it will fail anyway
// if the workbenchparts are different we are likely in the transition
// between diagrams don't do anything then
if ((diagram.getGraphicalFrameworkBridge() != null)
&& (diagram.getDiagramPart() == selection.getWorkbenchPart())) {
int level = zoomLevel;
List<EObject> focus = selection.getSelectedObjects();
// if we want to see everything, select root element and do a full child focus
if (showAll) {
focus.add(diagram.getSemanticModel());
level = Integer.MAX_VALUE;
} else {
// if nothing is selected, use the model root as the focus
if (focus.isEmpty()) {
focus.add(diagram.getSemanticModel());
}
}
FocusContextEffect focusEffect = new FocusContextEffect(diagram.getDiagramPart());
focusEffect.addFocus(focus, level);
this.schedule(focusEffect);
this.schedule(new LayoutEffect(selection.getWorkbenchPart(), null, true, false, true));
}
}
}
/**
* Enable or disable this functionality by graying out buttons.
*
* @param enable
* true if enabled
* @param diagram
*/
private void enable(final boolean enable, final DiagramState diagram) {
boolean validDiagram = EDITOR_IDS.contains(diagram.getDiagramType());
if (!validDiagram) {
this.enabled = false;
return;
}
if (this.enabled && !enable) {
this.schedule(new MenuItemEnableStateEffect(PLUS_BUTTON_ID, false));
this.schedule(new MenuItemEnableStateEffect(MINUS_BUTTON_ID, false));
this.enabled = enable;
} else if (!this.enabled && enable) {
this.schedule(new MenuItemEnableStateEffect(PLUS_BUTTON_ID, true));
this.schedule(new MenuItemEnableStateEffect(MINUS_BUTTON_ID, true));
// reset zoom level
zoomLevel = DEFAULT_ZOOM_LEVEL;
this.enabled = enable;
}
}
}
| 7,818 | 0.655794 | 0.654387 | 177 | 43.169491 | 32.303551 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672316 | false | false | 2 |
09e90c16147f84ae9723ae105cec58129314180d | 6,622,839,610,300 | 2283c4564aa812a1fd1356d56e15f9d58b6b4eb2 | /service/src/main/java/by/itacademy/jd2/th/messenger/service/ISmileService.java | fd21ea6b7d83608bc9a9fa762ee1682ea17e2639 | [] | no_license | TimHaidel/messenger | https://github.com/TimHaidel/messenger | 224975212a84e31bd22b59c433e00886e7027300 | bdf916ba74da7a40a736e801b0e17a21b7d4cd4b | refs/heads/master | 2020-06-15T05:47:57.361000 | 2019-09-16T15:16:08 | 2019-09-16T15:16:08 | 195,218,248 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.itacademy.jd2.th.messenger.service;
import java.util.List;
import javax.transaction.Transactional;
import by.itacademy.jd2.th.messenger.dao.api.entity.table.ISmile;
import by.itacademy.jd2.th.messenger.dao.api.filter.SmileFilter;
public interface ISmileService {
long getCount(final SmileFilter filter);
List<ISmile> find(final SmileFilter filter);
List<ISmile> getAll();
@Transactional
void deleteAll();
@Transactional
void delete(final Integer id);
@Transactional
void save(final ISmile entity);
ISmile createEntity();
ISmile getFullInfo(Integer id);
Object get(Integer id);
@Transactional
List<ISmile> search(String string);
}
| UTF-8 | Java | 670 | java | ISmileService.java | Java | [] | null | [] | package by.itacademy.jd2.th.messenger.service;
import java.util.List;
import javax.transaction.Transactional;
import by.itacademy.jd2.th.messenger.dao.api.entity.table.ISmile;
import by.itacademy.jd2.th.messenger.dao.api.filter.SmileFilter;
public interface ISmileService {
long getCount(final SmileFilter filter);
List<ISmile> find(final SmileFilter filter);
List<ISmile> getAll();
@Transactional
void deleteAll();
@Transactional
void delete(final Integer id);
@Transactional
void save(final ISmile entity);
ISmile createEntity();
ISmile getFullInfo(Integer id);
Object get(Integer id);
@Transactional
List<ISmile> search(String string);
}
| 670 | 0.773134 | 0.768657 | 36 | 17.611111 | 19.127174 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.805556 | false | false | 2 |
c0fb29afaa8a20fc21a82bf5cf4003031783f692 | 19,335,942,807,942 | 9cbc7d449d3ec290ae38ff0daaba01b514c39e76 | /src/main/java/com/inter/controller/paper/ViewController.java | 1fce1580a154915598a849dcd3276a35c790f8f7 | [] | no_license | zhangDemoSeven/- | https://github.com/zhangDemoSeven/- | bc8f7d8875d3498a29f9cc05b02996a85c0d4368 | 41668dda73e7cfa076cbd47d90c8550f0763ebd3 | refs/heads/master | 2020-04-11T01:44:55.075000 | 2018-12-12T02:57:16 | 2018-12-12T02:57:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.inter.controller.paper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ViewController {
/**
* @Title: monthPage
* @Description: TODO:月度考试页面跳转
* @param @return 参数
* @return String 返回类型
* @throws
*/
@RequestMapping("/paper/month/s/view.do")
public String monthPage() {
return "/paper/month/month";
}
}
| UTF-8 | Java | 478 | java | ViewController.java | Java | [] | null | [] | package com.inter.controller.paper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ViewController {
/**
* @Title: monthPage
* @Description: TODO:月度考试页面跳转
* @param @return 参数
* @return String 返回类型
* @throws
*/
@RequestMapping("/paper/month/s/view.do")
public String monthPage() {
return "/paper/month/month";
}
}
| 478 | 0.686667 | 0.686667 | 20 | 20.5 | 17.729918 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 2 |
09afd21ced15ddbab3361a566c9cb9392d18ae37 | 37,675,453,146,657 | c04d753dc0479ca544bffdecacb8f2f3d731fcf3 | /src/VerleihProtokollierer.java | 54fde1d2751570cc630c7dad1907e7660e58a888 | [] | no_license | NiklasFinzel/MediathekWoche4 | https://github.com/NiklasFinzel/MediathekWoche4 | 4f87f2dc01e027447578b4ceca8746ef7b6378b8 | 66b5818756899ad3bc43647fd3078555504bf9d3 | refs/heads/master | 2021-01-20T06:19:33.646000 | 2017-05-07T15:13:42 | 2017-05-07T15:13:42 | 89,864,520 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.FileWriter;
import java.io.IOException;
public class VerleihProtokollierer {
/**
* Speichert in einem Textfile alle Ausleihen und Rueckgaben ab.
*
* @require ereignis == "Ausleihe" || ereignis == "Rueckgabe"
* @require verleihkarte != null
* @param ereignis Gibt and ob es sich um eine Ausleihe oder Rueckgabe handelt
* @param verleihkarte Gibt an welche Verleihkarte protokolliert werden soll
*/
public static void protokolliere(String ereignis, Verleihkarte verleihkarte) throws ProtokollierException{
assert ereignis.equals("Ausleihe") || ereignis.equals("Rueckgabe");
assert verleihkarte != null;
try(FileWriter writer = new FileWriter("./protokoll.txt",true))
{
if(ereignis.equals("Ausleihe")){
writer.write(verleihkarte.getFormatiertenString());
}
else{
writer.write(verleihkarte.getFormatiertenString() + "und Rücknahme am:" + Datum.heute() +"\n");
}
}
catch(IOException e){
throw new ProtokollierException(e.toString());
}
}
}
| UTF-8 | Java | 1,045 | java | VerleihProtokollierer.java | Java | [] | null | [] | import java.io.FileWriter;
import java.io.IOException;
public class VerleihProtokollierer {
/**
* Speichert in einem Textfile alle Ausleihen und Rueckgaben ab.
*
* @require ereignis == "Ausleihe" || ereignis == "Rueckgabe"
* @require verleihkarte != null
* @param ereignis Gibt and ob es sich um eine Ausleihe oder Rueckgabe handelt
* @param verleihkarte Gibt an welche Verleihkarte protokolliert werden soll
*/
public static void protokolliere(String ereignis, Verleihkarte verleihkarte) throws ProtokollierException{
assert ereignis.equals("Ausleihe") || ereignis.equals("Rueckgabe");
assert verleihkarte != null;
try(FileWriter writer = new FileWriter("./protokoll.txt",true))
{
if(ereignis.equals("Ausleihe")){
writer.write(verleihkarte.getFormatiertenString());
}
else{
writer.write(verleihkarte.getFormatiertenString() + "und Rücknahme am:" + Datum.heute() +"\n");
}
}
catch(IOException e){
throw new ProtokollierException(e.toString());
}
}
}
| 1,045 | 0.698276 | 0.698276 | 34 | 28.705883 | 31.81521 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.735294 | false | false | 2 |
587dc69cc51356ad80f530fd52da8b6cf647a385 | 39,608,188,422,308 | 7e60e18dbde2e37b16201cfc0c30048efc9a32cb | /src/main/java/per/jm/demo/pojo/bo/GameUserInfor.java | 1622791af1af8f4d859319bfd79fc97470815c24 | [] | no_license | our16/the_spy | https://github.com/our16/the_spy | 7657ef4b3d021a6dd512a494b6b1d0be4576884a | ca19cf139156598fe75154027b129c93aee6c765 | refs/heads/master | 2022-07-02T18:52:40.944000 | 2020-09-19T15:12:20 | 2020-09-19T15:12:20 | 201,954,573 | 2 | 0 | null | false | 2022-06-17T03:28:29 | 2019-08-12T15:11:09 | 2022-02-14T11:33:20 | 2022-06-17T03:28:29 | 67 | 2 | 0 | 2 | Java | false | false | package per.jm.demo.pojo.bo;
public class GameUserInfor {
private int gameId; // 本局游戏的id
private String openId;
private String wxName;
private boolean status;//是否存活
private boolean isTheSpy; //是不是卧底
private boolean notPoll; //投过票没有
private int poll;//每轮的票数
private String content; //说的话
private int pollWho; //本轮投给谁
private boolean isReciveInfor; //是否接收消息,阵亡后可选择
private String antistop;//关键字
private boolean thisTurnIsSpoken; //标志本轮已经说过话了
public boolean isThisTurnIsSpoken() {
return thisTurnIsSpoken;
}
public void setThisTurnIsSpoken(boolean thisTurnIsSpoken) {
this.thisTurnIsSpoken = thisTurnIsSpoken;
}
public String getAntistop() {
return antistop;
}
public void setAntistop(String antistop) {
this.antistop = antistop;
}
public boolean isNotPoll() {
return notPoll;
}
public void setNotPoll(boolean notPoll) {
this.notPoll = notPoll;
}
public boolean isTheSpy() {
return isTheSpy;
}
public void setTheSpy(boolean theSpy) {
isTheSpy = theSpy;
}
public int getGameId() {
return gameId;
}
public void setGameId(int gameId) {
this.gameId = gameId;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getWxName() {
return wxName;
}
public void setWxName(String wxName) {
this.wxName = wxName;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public int getPoll() {
return poll;
}
public void setPoll(int poll) {
this.poll = poll;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getPollWho() {
return pollWho;
}
public void setPollWho(int pollWho) {
this.pollWho = pollWho;
}
public boolean isReciveInfor() {
return isReciveInfor;
}
public void setReciveInfor(boolean reciveInfor) {
isReciveInfor = reciveInfor;
}
}
| UTF-8 | Java | 2,407 | java | GameUserInfor.java | Java | [] | null | [] | package per.jm.demo.pojo.bo;
public class GameUserInfor {
private int gameId; // 本局游戏的id
private String openId;
private String wxName;
private boolean status;//是否存活
private boolean isTheSpy; //是不是卧底
private boolean notPoll; //投过票没有
private int poll;//每轮的票数
private String content; //说的话
private int pollWho; //本轮投给谁
private boolean isReciveInfor; //是否接收消息,阵亡后可选择
private String antistop;//关键字
private boolean thisTurnIsSpoken; //标志本轮已经说过话了
public boolean isThisTurnIsSpoken() {
return thisTurnIsSpoken;
}
public void setThisTurnIsSpoken(boolean thisTurnIsSpoken) {
this.thisTurnIsSpoken = thisTurnIsSpoken;
}
public String getAntistop() {
return antistop;
}
public void setAntistop(String antistop) {
this.antistop = antistop;
}
public boolean isNotPoll() {
return notPoll;
}
public void setNotPoll(boolean notPoll) {
this.notPoll = notPoll;
}
public boolean isTheSpy() {
return isTheSpy;
}
public void setTheSpy(boolean theSpy) {
isTheSpy = theSpy;
}
public int getGameId() {
return gameId;
}
public void setGameId(int gameId) {
this.gameId = gameId;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getWxName() {
return wxName;
}
public void setWxName(String wxName) {
this.wxName = wxName;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public int getPoll() {
return poll;
}
public void setPoll(int poll) {
this.poll = poll;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getPollWho() {
return pollWho;
}
public void setPollWho(int pollWho) {
this.pollWho = pollWho;
}
public boolean isReciveInfor() {
return isReciveInfor;
}
public void setReciveInfor(boolean reciveInfor) {
isReciveInfor = reciveInfor;
}
}
| 2,407 | 0.613706 | 0.613706 | 114 | 19.096491 | 16.743141 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.324561 | false | false | 2 |
d89ba4ef52e6fbc29215c04305b5e19531b4d85a | 39,591,008,555,176 | 919d8ee3eb46c28195d07b7d9a734e4643babda3 | /src/main/java/com/getprobe/www/waterfall/vertx/JsonConfigElements.java | 1988f5b2bcb4ea5e7d670cbc5a01986ee82c4bc3 | [] | no_license | sinowl/waterfall | https://github.com/sinowl/waterfall | b91d1591e70343105a6d47a2756e88aa70085c31 | ed9b6e4209b7674d66fada46ba415e6a8f6c39c9 | refs/heads/master | 2020-05-29T11:43:17.247000 | 2014-11-10T13:49:11 | 2014-11-10T13:49:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.getprobe.www.scope.vertx;
public enum JsonConfigElements {
;
public static enum MASTER{
PHASE_NAME, ADDRESS
}
public static enum WORKER{
PHASE_NAME, ADDRESS
}
}
| UTF-8 | Java | 221 | java | JsonConfigElements.java | Java | [] | null | [] | package com.getprobe.www.scope.vertx;
public enum JsonConfigElements {
;
public static enum MASTER{
PHASE_NAME, ADDRESS
}
public static enum WORKER{
PHASE_NAME, ADDRESS
}
}
| 221 | 0.61086 | 0.61086 | 14 | 14.785714 | 13.883076 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 2 |
bdd19d54dba8cfcaf93a45992b6e042c53eec695 | 35,055,523,127,480 | 547d0027b812cf0d3c865a6dcd3f4293c41b098f | /src/Addition.java | 74abd64b6f59c44e20ebd1ba3c907b29dd1c64e8 | [] | no_license | Joel-George-Panicker/Practicals | https://github.com/Joel-George-Panicker/Practicals | 8b84821d0225a8e1a37703bb9b86fb23b33c2ef8 | 7594b3e2d5c8e2771a662ecd8d835726f8ecfca7 | refs/heads/master | 2023-08-11T10:59:50.734000 | 2021-10-01T10:02:22 | 2021-10-01T10:02:22 | 412,415,182 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Addition {
public static void main(String[] args) {
int x = 100;
int y = 50;
int z = x+y;
System.out.println("Result of the sum is "+z);
}
}
| UTF-8 | Java | 194 | java | Addition.java | Java | [] | null | [] | public class Addition {
public static void main(String[] args) {
int x = 100;
int y = 50;
int z = x+y;
System.out.println("Result of the sum is "+z);
}
}
| 194 | 0.520619 | 0.494845 | 8 | 23.25 | 16.746267 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
522d1ca69e3be4b61bb92b05ea48d9e3597aab61 | 35,321,811,094,622 | 9243af29d2837e6c821d526f1d6450e6a8d778ac | /ICG_TERM_PROJECT/src/Cymatics.java | 6e80f1ec8c5b57fa1a95b5874c2d2ac5a4a08374 | [] | no_license | Likisee/ICG2014_TERM_PROJECT | https://github.com/Likisee/ICG2014_TERM_PROJECT | 766261e4625ef0339c3de4b78becd1f7a8b38de8 | 6494ae7906d7d7c8a2436595126fd36bf2aaeb53 | refs/heads/master | 2021-01-22T06:45:20.046000 | 2015-09-28T23:20:52 | 2015-09-28T23:20:52 | 28,914,197 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.*;
import java.applet.Applet;
import java.util.Vector;
import java.util.Random;
import java.awt.image.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Math;
import java.awt.event.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.StringTokenizer;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Track;
class CymaticsCanvas extends Canvas {
CymaticsFrame cf;
CymaticsCanvas(CymaticsFrame f) {
cf = f;
}
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
public void update(Graphics g) {
cf.updateCymatics(g);
}
public void paint(Graphics g) {
cf.updateCymatics(g);
}
};
class CymaticsLayout implements LayoutManager {
public CymaticsLayout() {
}
public void addLayoutComponent(String name, Component c) {
}
public void removeLayoutComponent(Component c) {
}
public Dimension preferredLayoutSize(Container target) {
return new Dimension(500, 500);
}
public Dimension minimumLayoutSize(Container target) {
return new Dimension(100, 100);
}
public void layoutContainer(Container target) {
Insets insets = target.insets();
// targetw, targeth -> getComponent(0)
int targetw = target.size().width - (insets.left + insets.right);
int cw = targetw * 7 / 10;
if (target.getComponentCount() == 1) {
cw = targetw;
}
int targeth = target.size().height - (insets.top + insets.bottom);
target.getComponent(0).move(insets.left, insets.top);
target.getComponent(0).resize(cw, targeth);
// barwidth -> the rest of the getComponent(>0)
int barwidth = targetw - cw; // (ratio: 3 / 10)
cw = cw + insets.left;
int i;
int h = insets.top;
for (i = 1; i < target.getComponentCount(); i++) { // For each Component
Component m = target.getComponent(i);
if (m.isVisible()) {
Dimension d = m.getPreferredSize();
if (m instanceof Scrollbar) {
d.width = barwidth;
}
if (m instanceof Choice && d.width > barwidth) {
d.width = barwidth;
}
if (m instanceof Label) {
h += d.height / 5;
d.width = barwidth;
}
m.move(cw, h);
m.resize(d.width, d.height);
h = h + d.height;
}
}
}
};
public class Cymatics extends Applet implements ComponentListener {
boolean started = false;
static CymaticsFrame cf;
void destroyFrame() {
if (cf != null) {
cf.dispose();
}
cf = null;
repaint();
}
void showFrame() {
if (cf == null) {
started = true;
cf = new CymaticsFrame(this);
cf.init();
repaint();
}
}
public void paint(Graphics g) {
String s = "Applet is open in a separate window.";
if (!started) {
s = "Applet is starting.";
} else if (cf == null) {
s = "Applet is finished.";
} else if (cf.useFrame) {
cf.triggerShow();
}
g.drawString(s, 10, 30);
}
public void init() {
addComponentListener(this);
}
public static void main(String args[]) {
cf = new CymaticsFrame(null);
cf.init();
}
/**************************************************************************
* ComponentEvent
*************************************************************************/
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {
showFrame();
}
public void componentResized(ComponentEvent e) {
}
public void destroy() {
if (cf != null) {
cf.dispose();
}
cf = null;
repaint();
}
};
class CymaticsFrame extends Frame implements ComponentListener, ActionListener, AdjustmentListener, MouseMotionListener, MouseListener, ItemListener {
CymaticsCanvas cv;
Cymatics applet;
CymaticsFrame(Cymatics c) {
super("CYMATICS Music Player by CSu (D02944006@ntu.edu.tw)");
applet = c;
useFrame = true;
showControls = true;
adjustResolution = true;
}
/**************************************************************************
* Variable Initial
*************************************************************************/
Dimension windowSize;
Image dbimage;
Random random;
int gridSizeX;
int gridSizeY;
int gridSizeXY;
int gw;
int windowWidth = 50;
int windowHeight = 50;
int windowOffsetX = 0;
int windowOffsetY = 0;
int windowBottom = 0;
int windowRight = 0;
Container main;
Choice musicChooser;
Choice setupChooser;
Choice sourceChooser;
Choice colorChooser;
Button clearWaveButton;
Button clearBorderButton;
Button setBorderButton;
Button view3dButton;
Button stopButton;
Scrollbar speedBar;
Scrollbar resBar;
Scrollbar freqBar;
Scrollbar brightnessBar;
double brightMult = 1;
Scrollbar auxBar;
Label auxLabel;
int auxFunction;
static final double pi = 3.14159265358979323846;
public static final int sourceRadius = 5;
public static final double freqMult = .0233333;
static final int SWF_SIN = 0;
static final int AUX_NONE = 0;
static final int AUX_SPEED = 1;
static final int SRC_NONE = 0;
static final int SRC_1S = 1;
static final int SRC_2S = 2;
static final int SRC_4S = 3;
static final int SRC_1S_MOVING = 4;
static final int SRC_1S_PLANE = 5;
static final int SRC_2S_PLANE = 6;
static final int MODE_SETFUNC = 0;
static final int MODE_WALLS = 1;
OscillationSource sources[];
float func[];
float funci[];
boolean walls[];
boolean exception[];
int pixels[];
Color wallColor, posColor, negColor, zeroColor, sourceColor;
Color schemeColors[][];
long startTime;
Method timerMethod;
int timerDiv;
MemoryImageSource imageSource;
public boolean useFrame;
boolean showControls;
boolean useBufferedImage = false;
Vector setupList;
Setup setup;
boolean adjustResolution = true;
boolean increaseResolution = false;
boolean sourcePlane = false;
boolean sourceMoving = false;
double movingSourcePos = 0;
int sourceCount = -1;
int selectedSource = -1;
int sourceFreqCount = -1;
int sourceWaveform = SWF_SIN;
int sourceIndex;
boolean dragging;
boolean dragClear;
boolean dragSet;
int dragX, dragY, dragStartX = -1, dragStartY;
int freqBarValue;
double freqTimeZero;
double timeT;
boolean is3dView = false;
boolean isStop = false;
double dampcoef = 1;
/**************************************************************************
* Applet Main
*************************************************************************/
public void init() {
// useFrame? showControls? main!!
try {
if (applet != null) {
// useFrame: Default true
String param = applet.getParameter("useFrame");
if (param != null && param.equalsIgnoreCase("false")) {
useFrame = false;
}
// showControls: Default false
param = applet.getParameter("showControls");
if (param != null && param.equalsIgnoreCase("false")) {
showControls = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (useFrame) {
main = this;
} else {
main = applet;
}
// useBufferedImage
String jv = System.getProperty("java.class.version");
double jvf = new Double(jv).doubleValue();
if (jvf >= 48) { // Java 1.4
useBufferedImage = true;
}
// timerMethod & timerDiv (nano vs milli)
try {
Class sysclass = Class.forName("java.lang.System");
timerMethod = sysclass.getMethod("nanoTime", null);
timerDiv = 1000000;
if (timerMethod == null) {
timerMethod = sysclass.getMethod("currentTimeMillis", null);
timerDiv = 1;
}
} catch (Exception ee) {
ee.printStackTrace();
}
main.setLayout(new CymaticsLayout());
cv = new CymaticsCanvas(this);
cv.addComponentListener(this);
cv.addMouseMotionListener(this);
cv.addMouseListener(this);
main.add(cv);
// Initial musicSource & musicChooser
musicSource = new String [999];
musicChooser = new Choice();
File musicFolder = new File(musicFolderPath);
File [] musicFiles = musicFolder.listFiles();
for(int i = 0; i < musicFiles.length; i++) {
musicChooser.add(musicFiles[i].getName());
musicSource[i] = musicFiles[i].getName();
}
musicChooser.addItemListener(this);
if (showControls) {
main.add(musicChooser);
}
// Initial setupList -> setupChooser
setupList = new Vector();
Setup s = new SingleSourceSetup(); // Default SingleSourceSetup
while (s != null) {
setupList.addElement(s);
s = s.createNext();
}
setupChooser = new Choice();
int i;
for (i = 0; i != setupList.size(); i++) {
setupChooser.add("預設主題: " + ((Setup) setupList.elementAt(i)).getName());
}
setupChooser.addItemListener(this);
if (showControls) {
main.add(setupChooser);
}
// Initial OscillationSource & sourceChooser
sources = new OscillationSource[20];
sourceChooser = new Choice();
sourceChooser.add("無"); // 0
sourceChooser.add("1點波源"); // 1
sourceChooser.add("2點波源"); // 2
sourceChooser.add("4點波源"); // 3
sourceChooser.add("移動波源"); // 4
sourceChooser.add("1線波源"); // 5
sourceChooser.add("2線波源"); // 6
sourceChooser.select(SRC_1S);
sourceChooser.addItemListener(this);
if (showControls) {
// main.add(sourceChooser);
}
// Initial colorChooser
colorChooser = new Choice();
colorChooser.addItemListener(this);
if (showControls) {
main.add(colorChooser);
}
// Initial clearWaveButton
clearWaveButton = new Button("清空水波");
clearWaveButton.setFont(new Font( "Arial" , Font.BOLD , 40 ));
if (showControls) {
main.add(clearWaveButton);
}
clearWaveButton.addActionListener(this);
// Initial clearBorderButton
clearBorderButton = new Button("清空邊界");
clearBorderButton.setFont(new Font( "Arial" , Font.BOLD , 40 ));
if (showControls) {
main.add(clearBorderButton);
}
clearBorderButton.addActionListener(this);
// Initial setBorderButton
setBorderButton = new Button("新增邊界");
setBorderButton.setFont(new Font( "Arial" , Font.BOLD , 40 ));
if (showControls) {
main.add(setBorderButton);
}
setBorderButton.addActionListener(this);
// Initial view3DButton
view3dButton = new Button("切3D視角");
view3dButton.setFont(new Font( "Arial" , Font.BOLD , 40 ));
view3dButton.setPreferredSize(new Dimension(178, 50));
if (showControls) {
main.add(view3dButton);
}
view3dButton.addActionListener(this);
// Initial stopButton
stopButton = new Button("暫停");
stopButton.setFont(new Font( "Arial" , Font.BOLD , 40 ));
stopButton.setPreferredSize(new Dimension(178, 50));
if (showControls) {
main.add(stopButton);
}
stopButton.addActionListener(this);
// Initial speedBar
Label l = new Label("模擬速度", Label.CENTER);
l.setFont(new Font( "Arial" , Font.BOLD , 40 ));
speedBar = new Scrollbar(Scrollbar.HORIZONTAL, 8, 1, 1, 100); // Default: 8/100
speedBar.addAdjustmentListener(this);
if (showControls) {
// main.add(l);
// main.add(speedBar);
}
// Initial resBar
l = new Label("解析度", Label.CENTER);
l.setFont(new Font( "Arial" , Font.BOLD , 40 ));
resBar = new Scrollbar(Scrollbar.HORIZONTAL, 110, 5, 5, 400); // Default: 110/400
resBar.addAdjustmentListener(this);
if (showControls) {
// main.add(l);
// main.add(resBar);
}
setResolution();
// Initial freqBar
l = new Label("水波頻率", Label.CENTER);
l.setFont(new Font( "Arial" , Font.BOLD , 40 ));
freqBar = new Scrollbar(Scrollbar.HORIZONTAL, freqBarValue = 15, 1, 1, 30); // Default: 15/30
freqBar.addAdjustmentListener(this);
if (showControls) {
main.add(l);
main.add(freqBar);
}
// Initial brightnessBar
l = new Label("對比色差", Label.CENTER);
l.setFont(new Font( "Arial" , Font.BOLD , 40 ));
brightnessBar = new Scrollbar(Scrollbar.HORIZONTAL, 27, 1, 1, 1200); // Default: 27/1200
brightnessBar.addAdjustmentListener(this);
if (showControls) {
main.add(l);
main.add(brightnessBar);
}
// Initial auxBar
auxLabel = new Label("", Label.CENTER);
auxBar = new Scrollbar(Scrollbar.HORIZONTAL, 1, 1, 1, 30); // Default: 1/30
auxBar.addAdjustmentListener(this);
if (showControls) {
main.add(auxLabel);
main.add(auxBar);
}
schemeColors = new Color[20][8];
try {
String param;
param = applet.getParameter("setup");
if (param != null) {
setupChooser.select(Integer.parseInt(param));
}
param = applet.getParameter("setupClass");
if (param != null) {
for (i = 0; i != setupList.size(); i++) {
if (setupList.elementAt(i).getClass().getName().equalsIgnoreCase("CymaticsFrame$" + param)) {
setupChooser.select(i);
break;
}
}
}
} catch (Exception e) {
if (applet != null) {
e.printStackTrace();
}
}
if (colorChooser.getItemCount() == 0) {
addDefaultColorScheme();
}
doColor();
setup = (Setup) setupList.elementAt(setupChooser.getSelectedIndex());
reinit();
cv.setBackground(Color.black);
cv.setForeground(Color.lightGray);
startTime = getTimeMillis();
if (useFrame) {
resize(800, 640);
handleResize();
Dimension x = getSize();
Dimension screen = getToolkit().getScreenSize();
setLocation((screen.width - x.width) / 2, (screen.height - x.height) / 2);
show();
} else {
hide();
handleResize();
applet.validate();
}
main.requestFocus();
}
void reinit() {
reinit(true);
}
void reinit(boolean setup) {
sourceCount = -1;
System.out.print("reinit " + gridSizeX + " " + gridSizeY + "\n");
gridSizeXY = gridSizeX * gridSizeY;
gw = gridSizeY;
func = new float[gridSizeXY];
funci = new float[gridSizeXY];
walls = new boolean[gridSizeXY];
exception = new boolean[gridSizeXY];
int i, j;
if (setup) {
doSetup();
}
}
boolean shown = false;
public void triggerShow() {
if (!shown)
show();
shown = true;
}
void handleResize() {
Dimension d = windowSize = cv.getSize();
if (windowSize.width == 0) {
return;
}
pixels = null;
if (useBufferedImage) {
try {
Class biclass = Class.forName("java.awt.image.BufferedImage");
Class dbiclass = Class.forName("java.awt.image.DataBufferInt");
Class rasclass = Class.forName("java.awt.image.Raster");
Constructor cstr = biclass.getConstructor(new Class[] { int.class, int.class, int.class });
dbimage = (Image) cstr.newInstance(new Object[] { new Integer(d.width), new Integer(d.height), new Integer(BufferedImage.TYPE_INT_RGB) });
Method m = biclass.getMethod("getRaster", null);
Object ras = m.invoke(dbimage, null);
Object db = rasclass.getMethod("getDataBuffer", null).invoke(ras, null);
pixels = (int[]) dbiclass.getMethod("getData", null).invoke(db, null);
} catch (Exception ee) {
System.out.println("BufferedImage failed");
}
}
if (pixels == null) {
pixels = new int[d.width * d.height];
int i;
for (i = 0; i != d.width * d.height; i++)
pixels[i] = 0xFF000000;
imageSource = new MemoryImageSource(d.width, d.height, pixels, 0, d.width);
imageSource.setAnimated(true);
imageSource.setFullBufferUpdates(true);
dbimage = cv.createImage(imageSource);
}
}
public boolean handleEvent(Event ev) {
if (ev.id == Event.WINDOW_DESTROY) {
destroyFrame();
return true;
}
return super.handleEvent(ev);
}
void destroyFrame() {
if (applet == null) {
dispose();
} else {
applet.destroyFrame();
}
}
int frames = 0;
int steps = 0;
boolean moveRight = true;
boolean moveDown = true;
public void updateCymatics(Graphics realg) {
if (windowSize == null || windowSize.width == 0) {
handleResize();
return;
}
long sysTime = getTimeMillis();
if (increaseResolution) {
increaseResolution = false;
if (resBar.getValue() < 495) {
setResolution(resBar.getValue() + 10);
}
}
double tadd = 0;
if (!isStop) {
int val = 5; // speedBar.getValue();
tadd = val * .05;
}
boolean stopFunc = dragging && selectedSource == -1 && is3dView == false;
if (isStop) {
stopFunc = true;
}
int iterCount = speedBar.getValue();
if (!stopFunc) {
int iter;
int mxx = gridSizeX - 1;
int mxy = gridSizeY - 1;
for (iter = 0; iter != iterCount; iter++) {
int jstart, jend, jinc;
if (moveDown) {
jstart = 1;
jend = mxy;
jinc = 1;
moveDown = false;
} else {
jstart = mxy - 1;
jend = 0;
jinc = -1;
moveDown = true;
}
moveRight = moveDown;
float sinhalfth = 0;
float sinth = 0;
float scaleo = 0;
for (int j = jstart; j != jend; j += jinc) {
int istart, iend, iinc;
if (moveRight) {
iinc = 1;
istart = 1;
iend = mxx;
moveRight = false;
} else {
iinc = -1;
istart = mxx - 1;
iend = 0;
moveRight = true;
}
int gi = j * gw + istart;
int giEnd = j * gw + iend;
for (; gi != giEnd; gi += iinc) {
// the equilibrium point
float previ = func[gi - 1];
float nexti = func[gi + 1];
float prevj = func[gi - gw];
float nextj = func[gi + gw];
float basis = (nexti + previ + nextj + prevj) * .25f;
if (exception[gi]) {
sinhalfth = (float) Math.sin(tadd / 2);
sinth = (float) (Math.sin(tadd) * dampcoef);
scaleo = (float) (1 - Math.sqrt(4 * sinhalfth * sinhalfth - sinth * sinth));
if (walls[gi]) {
continue;
}
if (walls[gi - 1]) previ = 0;
if (walls[gi + 1]) nexti = 0;
if (walls[gi - gw]) prevj = 0;
if (walls[gi + gw]) nextj = 0;
basis = (nexti + previ + nextj + prevj) * .25f;
}
float a = 0;
float b = 0;
a = func[gi] - basis;
b = funci[gi];
func[gi] = basis + a * scaleo - b * sinth;
funci[gi] = b * scaleo + a * sinth;
}
}
timeT += tadd;
if (sourceCount > 0) {
double w = freqBar.getValue() * (timeT - freqTimeZero) * freqMult;
double w2 = w;
double v = 0;
double v2 = 0;
v = Math.cos(w);
if (sourceCount >= (sourcePlane ? 4 : 2)) {
v2 = Math.cos(w2);
} else if (sourceFreqCount == 2) {
v = (v + Math.cos(w2)) * .5;
}
for (int j = 0; j != sourceCount; j++) {
if ((j % 2) == 0) {
sources[j].v = (float) (v * setup.sourceStrength());
} else{
sources[j].v = (float) (v2 * setup.sourceStrength());
}
}
if (sourcePlane) {
for (int j = 0; j != sourceCount / 2; j++) {
OscillationSource src1 = sources[j * 2];
OscillationSource src2 = sources[j * 2 + 1];
OscillationSource src3 = sources[j];
drawPlaneSource(src1.x, src1.y, src2.x, src2.y, src3.v, w);
}
} else {
if (sourceMoving) {
int sy;
movingSourcePos += tadd * .02 * auxBar.getValue();
double wm = movingSourcePos;
int h = windowHeight - 3;
wm %= h * 2;
sy = (int) wm;
if (sy > h) {
sy = 2 * h - sy;
}
sy += windowOffsetY + 1;
sources[0].y = sy;
}
for (int i = 0; i != sourceCount; i++) {
OscillationSource src = sources[i];
func[src.x + gw * src.y] = src.v;
funci[src.x + gw * src.y] = 0;
}
}
}
setup.eachFrame();
steps++;
filterGrid();
}
}
brightMult = Math.exp(brightnessBar.getValue() / 100. - 5.);
if (is3dView) {
draw3dView();
} else {
draw2dView();
}
if (imageSource != null) {
imageSource.newPixels();
}
realg.drawImage(dbimage, 0, 0, this);
if (dragStartX >= 0 && !is3dView) {
// POSITION
int x = dragStartX * windowWidth / windowSize.width;
int y = windowHeight - 1 - (dragStartY * windowHeight / windowSize.height);
String s = "(" + x + "," + y + ")";
realg.setColor(Color.white);
FontMetrics fm = realg.getFontMetrics();
int h = 5 + fm.getAscent();
realg.fillRect(0, windowSize.height - h, fm.stringWidth(s) + 10, h);
realg.setColor(Color.black);
realg.drawString(s, 5, windowSize.height - 5);
} else {
// NOTE // TODO
int midiNoteIndex = Long.valueOf(getTimeMillis() - timeMidiStart).intValue() * musicMult / 1000;
String s = "";
try{
String note = musicMainNote[midiNoteIndex];
setFreqBarByNote(note);
s = "midiNoteIndex: " + midiNoteIndex;
if(midiNoteIndex < musicLength * musicMult) {
s = "NOTE: " + musicMainNote[midiNoteIndex];
}
} catch (Exception e) {
//
}
realg.setColor(Color.white);
FontMetrics fm = realg.getFontMetrics();
int h = 5 + fm.getAscent();
realg.fillRect(0, windowSize.height - h, fm.stringWidth(s) + 10, h);
realg.setColor(Color.black);
realg.drawString(s, 5, windowSize.height - 5);
}
if (!isStop) {
long diff = getTimeMillis() - sysTime;
if (adjustResolution && diff > 0 && sysTime < startTime + 1000 && windowOffsetX * diff / iterCount < 55) {
increaseResolution = true;
startTime = sysTime;
}
cv.repaint(0);
}
}
void drawPlaneSource(int x1, int y1, int x2, int y2, float v, double w) {
// correct x1, x2
if (y1 == y2) {
if (x1 == windowOffsetX) {
x1 = 0;
}
if (x2 == windowOffsetX) {
x2 = 0;
}
if (x1 == windowOffsetX + windowWidth - 1) {
x1 = gridSizeX - 1;
}
if (x2 == windowOffsetX + windowWidth - 1) {
x2 = gridSizeX - 1;
}
}
// correct y1, y2
if (x1 == x2) {
if (y1 == windowOffsetY) {
y1 = 0;
}
if (y2 == windowOffsetY) {
y2 = 0;
}
if (y1 == windowOffsetY + windowHeight - 1) {
y1 = gridSizeY - 1;
}
if (y2 == windowOffsetY + windowHeight - 1) {
y2 = gridSizeY - 1;
}
}
// need to draw a line from x1,y1 to x2,y2 smoothly by interpolation
if (x1 == x2 && y1 == y2) { // a straight line
func[x1 + gw * y1] = v;
funci[x1 + gw * y1] = 0;
} else if (abs(y2 - y1) > abs(x2 - x1)) { // y difference is greater, cutting y to calculate x
double sgn = sign(y2 - y1);
int x, y;
for (y = y1; y != y2 + sgn; y += sgn) {
x = x1 + (x2 - x1) * (y - y1) / (y2 - y1);
double ph = sgn * (y - y1) / (y2 - y1);
int gi = x + gw * y;
func[gi] = setup.calcSourcePhase(ph, v, w);
funci[gi] = 0;
}
} else { // x difference is greater, cutting x to calculate y
double sgn = sign(x2 - x1);
int x, y;
for (x = x1; x != x2 + sgn; x += sgn) {
y = y1 + (y2 - y1) * (x - x1) / (x2 - x1);
double ph = sgn * (x - x1) / (x2 - x1);
int gi = x + gw * y;
func[gi] = setup.calcSourcePhase(ph, v, w);
funci[gi] = 0;
}
}
}
/**************************************************************************
* Draw 2D
*************************************************************************/
void draw2dView() {
int ix = 0;
int i, j, k, l;
for (j = 0; j != windowHeight; j++) {
ix = windowSize.width * (j * windowSize.height / windowHeight);
int j2 = j + windowOffsetY;
int gi = j2 * gw + windowOffsetX;
int y = j * windowSize.height / windowHeight;
int y2 = (j + 1) * windowSize.height / windowHeight;
for (i = 0; i != windowWidth; i++, gi++) {
int x = i * windowSize.width / windowWidth;
int x2 = (i + 1) * windowSize.width / windowWidth;
int i2 = i + windowOffsetX;
double dy = func[gi] * brightMult;
if (dy < -1)
dy = -1;
if (dy > 1)
dy = 1;
int col = 0;
int colR = 0, colG = 0, colB = 0;
if (walls[gi]) {
colR = wallColor.getRed();
colG = wallColor.getGreen();
colB = wallColor.getBlue();
}
else if (dy < 0) {
double d1 = -dy;
double d2 = 1 - d1;
colR = (int) (negColor.getRed() * d1 + zeroColor.getRed() * d2);
colG = (int) (negColor.getGreen() * d1 + zeroColor.getGreen() * d2);
colB = (int) (negColor.getBlue() * d1 + zeroColor.getBlue() * d2);
} else {
double d1 = dy;
double d2 = 1 - dy;
colR = (int) (posColor.getRed() * d1 + zeroColor.getRed() * d2);
colG = (int) (posColor.getGreen() * d1 + zeroColor.getGreen() * d2);
colB = (int) (posColor.getBlue() * d1 + zeroColor.getBlue() * d2);
}
col = (255 << 24) | (colR << 16) | (colG << 8) | (colB);
for (k = 0; k != x2 - x; k++, ix++) {
for (l = 0; l != y2 - y; l++) {
pixels[ix + l * windowSize.width] = col;
}
}
}
}
for (i = 0; i != sourceCount; i++) {
OscillationSource src = sources[i];
int xx = src.getScreenX();
int yy = src.getScreenY();
plotSource(i, xx, yy);
}
}
// draw a circle
void plotSource(int n, int xx, int yy) {
int rad = sourceRadius;
int j;
int col = (sourceColor.getRed() << 16) | (sourceColor.getGreen() << 8) | (sourceColor.getBlue()) | 0xFF000000;
if (n == selectedSource) {
col ^= 0xFFFFFF;
}
for (j = 0; j <= rad; j++) {
int k = (int) (Math.sqrt(rad * rad - j * j) + .5);
plotPixel(xx + j, yy + k, col);
plotPixel(xx + k, yy + j, col);
plotPixel(xx + j, yy - k, col);
plotPixel(xx - k, yy + j, col);
plotPixel(xx - j, yy + k, col);
plotPixel(xx + k, yy - j, col);
plotPixel(xx - j, yy - k, col);
plotPixel(xx - k, yy - j, col);
plotPixel(xx, yy + j, col);
plotPixel(xx, yy - j, col);
plotPixel(xx + j, yy, col);
plotPixel(xx - j, yy, col);
}
}
void plotPixel(int x, int y, int pix) {
if (x < 0 || x >= windowSize.width) {
return;
}
try {
pixels[x + y * windowSize.width] = pix;
} catch (Exception e) {
}
}
// filter the high-frequency bug
int filterCount;
void filterGrid() {
int x, y;
if (sourceCount > 0 && freqBarValue > 23) {
return;
}
if (sourceFreqCount >= 2 && auxBar.getValue() > 23) {
return;
}
if (++filterCount < 10) {
return;
}
filterCount = 0;
for (y = windowOffsetY; y < windowBottom; y++)
for (x = windowOffsetX; x < windowRight; x++) {
int gi = x + y * gw;
if (walls[gi]) {
continue;
}
if (func[gi - 1] < 0 && func[gi] > 0 && func[gi + 1] < 0 && !walls[gi + 1] && !walls[gi - 1]) {
func[gi] = (func[gi - 1] + func[gi + 1]) / 2;
}
if (func[gi - gw] < 0 && func[gi] > 0 && func[gi + gw] < 0 && !walls[gi - gw] && !walls[gi + gw]) {
func[gi] = (func[gi - gw] + func[gi + gw]) / 2;
}
if (func[gi - 1] > 0 && func[gi] < 0 && func[gi + 1] > 0 && !walls[gi + 1] && !walls[gi - 1]) {
func[gi] = (func[gi - 1] + func[gi + 1]) / 2;
}
if (func[gi - gw] > 0 && func[gi] < 0 && func[gi + gw] > 0 && !walls[gi - gw] && !walls[gi + gw]) {
func[gi] = (func[gi - gw] + func[gi + gw]) / 2;
}
}
}
/**************************************************************************
* Draw 3D
*************************************************************************/
double realxmx, realxmy, realymz, realzmy, realzmx, realymadd, realzmadd;
double viewAngle = pi, viewAngleDragStart;
double viewZoom = .775, viewZoomDragStart;
double viewAngleCos = -1, viewAngleSin = 0;
double viewHeight = -38, viewHeightDragStart;
double scalex, scaley;
int centerX3d, centerY3d;
int xpoints[] = new int[4], ypoints[] = new int[4];
final double viewDistance = 66;
void draw3dView() {
int half = gridSizeX / 2;
scaleworld();
int x, y;
int xdir, xstart, xend;
int ydir, ystart, yend;
int sc = windowRight - 1;
// which side render first
if (viewAngleCos > 0) {
ystart = sc;
yend = windowOffsetY - 1;
ydir = -1;
} else {
ystart = windowOffsetY;
yend = sc + 1;
ydir = 1;
}
if (viewAngleSin < 0) {
xstart = windowOffsetX;
xend = sc + 1;
xdir = 1;
} else {
xstart = sc;
xend = windowOffsetX - 1;
xdir = -1;
}
boolean xFirst = (viewAngleSin * xdir < viewAngleCos * ydir);
for (x = 0; x != windowSize.width * windowSize.height; x++) {
pixels[x] = 0xFF000000;
}
double zval = .1;
double zval2 = zval * zval;
for (x = xstart; x != xend; x += xdir) {
for (y = ystart; y != yend; y += ydir) {
if (!xFirst) {
x = xstart;
}
for (; x != xend; x += xdir) {
int gi = x + gw * y;
map3d(x - half, y - half, func[gi], xpoints, ypoints, 0);
map3d(x + 1 - half, y - half, func[gi + 1], xpoints, ypoints, 1);
map3d(x - half, y + 1 - half, func[gi + gw], xpoints, ypoints, 2);
map3d(x + 1 - half, y + 1 - half, func[gi + gw + 1], xpoints, ypoints, 3);
double qx = func[gi + 1] - func[gi];
double qy = func[gi + gw] - func[gi];
// calculate light
double normdot = (qx + qy + zval) * (1 / 1.73) / Math.sqrt(qx * qx + qy * qy + zval2);
int col = computeColor(gi, normdot);
fillTriangle(xpoints[0], ypoints[0], xpoints[1], ypoints[1], xpoints[3], ypoints[3], col);
fillTriangle(xpoints[0], ypoints[0], xpoints[2], ypoints[2], xpoints[3], ypoints[3], col);
if (xFirst) {
break;
}
}
}
if (!xFirst)
break;
}
}
double scaleMult;
void scaleworld() {
scalex = viewZoom * (windowSize.width / 4) * viewDistance / 8;
scaley = -scalex;
int y = (int) (scaley * viewHeight / viewDistance);
centerX3d = windowSize.width / 2;
centerY3d = windowSize.height / 2 - y;
scaleMult = 16. / (windowWidth / 2);
realxmx = -viewAngleCos * scaleMult * scalex;
realxmy = viewAngleSin * scaleMult * scalex;
realymz = -brightMult * scaley;
realzmy = viewAngleCos * scaleMult;
realzmx = viewAngleSin * scaleMult;
realymadd = -viewHeight * scaley;
realzmadd = viewDistance;
}
void map3d(double x, double y, double z, int xpoints[], int ypoints[], int pt) {
double realx = realxmx * x + realxmy * y;
double realy = realymz * z + realymadd;
double realz = realzmx * x + realzmy * y + realzmadd;
xpoints[pt] = centerX3d + (int) (realx / realz);
ypoints[pt] = centerY3d - (int) (realy / realz);
}
int computeColor(int gix, double c) {
double h = func[gix] * brightMult;
if (c < 0) c = 0;
if (c > 1) c = 1;
c = .5 + c * .5;
double redness = (h < 0) ? -h : 0;
double grnness = (h > 0) ? h : 0;
if (redness > 1) redness = 1;
if (grnness > 1) grnness = 1;
if (grnness < 0) grnness = 0;
if (redness < 0) redness = 0;
double grayness = (1 - (redness + grnness)) * c;
double gray = .6;
int bi = (int) ((gray * grayness) * 255);
return 0xFF000000 | bi;
}
void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3, int col) {
if (x1 > x2) {
if (x2 > x3) {
// x1 > x2 > x3
int ay = interp(x1, y1, x3, y3, x2);
fillTriangle1(x3, y3, x2, y2, ay, col);
fillTriangle1(x1, y1, x2, y2, ay, col);
} else if (x1 > x3) {
// x1 > x3 > x2
int ay = interp(x1, y1, x2, y2, x3);
fillTriangle1(x2, y2, x3, y3, ay, col);
fillTriangle1(x1, y1, x3, y3, ay, col);
} else {
// x3 > x1 > x2
int ay = interp(x3, y3, x2, y2, x1);
fillTriangle1(x2, y2, x1, y1, ay, col);
fillTriangle1(x3, y3, x1, y1, ay, col);
}
} else {
if (x1 > x3) {
// x2 > x1 > x3
int ay = interp(x2, y2, x3, y3, x1);
fillTriangle1(x3, y3, x1, y1, ay, col);
fillTriangle1(x2, y2, x1, y1, ay, col);
} else if (x2 > x3) {
// x2 > x3 > x1
int ay = interp(x2, y2, x1, y1, x3);
fillTriangle1(x1, y1, x3, y3, ay, col);
fillTriangle1(x2, y2, x3, y3, ay, col);
} else {
// x3 > x2 > x1
int ay = interp(x3, y3, x1, y1, x2);
fillTriangle1(x1, y1, x2, y2, ay, col);
fillTriangle1(x3, y3, x2, y2, ay, col);
}
}
}
void fillTriangle1(int x1, int y1, int x2, int y2, int y3, int col) {
// x2 == x3
int dir = (x1 > x2) ? -1 : 1;
int x = x1;
if (x < 0) {
x = 0;
if (x2 < 0) {
return;
}
}
if (x >= windowSize.width) {
x = windowSize.width - 1;
if (x2 >= windowSize.width) {
return;
}
}
if (y2 > y3) {
int q = y2;
y2 = y3;
y3 = q;
}
// y2 < y3
while (x != x2 + dir) {
int ya = interp(x1, y1, x2, y2, x);
int yb = interp(x1, y1, x2, y3, x);
if (ya < 0) {
ya = 0;
}
if (yb >= windowSize.height) {
yb = windowSize.height - 1;
}
for (; ya <= yb; ya++) {
pixels[x + ya * windowSize.width] = col;
}
x += dir;
if (x < 0 || x >= windowSize.width) {
return;
}
}
}
int interp(int x1, int y1, int x2, int y2, int x) {
if (x1 == x2) {
return y1;
}
if (x < x1 && x < x2 || x > x1 && x > x2) {
System.out.print("interp out of bounds\n");
}
return (int) (y1 + ((double) x - x1) * (y2 - y1) / (x2 - x1));
}
/**************************************************************************
* ColorScheme Setup
*************************************************************************/
void addDefaultColorScheme() {
decodeColorScheme(0, "#000000 #3333D6 #0000A3 #0000CC #CC0000", "Water");
decodeColorScheme(1, "#800000 #ffffff #ffffff #808080 #CC0000", "Cymatics1: White Plate");
decodeColorScheme(2, "#800000 #000000 #000000 #808080 #CC0000", "Cymatics2: Black Plate");
}
void decodeColorScheme(int cn, String s, String name) {
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
int i;
for (i = 0; i != 5; i++)
schemeColors[cn][i] = Color.decode(st.nextToken());
}
colorChooser.add(name);
}
/**************************************************************************
* WaveSource Setup
*************************************************************************/
abstract class Setup {
abstract String getName();
abstract void select();
void doSetupSources() {
setSources();
}
void deselect() {
}
double sourceStrength() {
return 1;
}
abstract Setup createNext();
void eachFrame() {
}
float calcSourcePhase(double ph, float v, double w) {
return v;
}
};
class SingleSourceSetup extends Setup {
String getName() {
return "1點波源";
}
void select() {
// setFreqBar(15);
}
Setup createNext() {
return new DoubleSourceSetup();
}
}
class DoubleSourceSetup extends Setup {
String getName() {
return "2點波源";
}
void select() {
// setFreqBar(15);
}
void doSetupSources() {
sourceChooser.select(SRC_2S);
setSources();
sources[0].y = gridSizeY / 2 - 8;
sources[1].y = gridSizeY / 2 + 8;
sources[0].x = sources[1].x = gridSizeX / 2;
}
Setup createNext() {
return new QuadrupleSourceSetup();
}
}
class QuadrupleSourceSetup extends Setup {
String getName() {
return "4點波源";
}
void select() {
// setFreqBar(15);
}
void doSetupSources() {
sourceChooser.select(SRC_4S);
setSources();
}
Setup createNext() {
return new PlaneWaveSetup();
}
}
class PlaneWaveSetup extends Setup {
String getName() {
return "1線波源";
}
void select() {
// setFreqBar(15);
}
void doSetupSources() {
sourceChooser.select(SRC_1S_PLANE);
setSources();
}
Setup createNext() {
return new IntersectingPlaneWavesSetup();
}
}
class IntersectingPlaneWavesSetup extends Setup {
String getName() {
return "交錯線波源";
}
void select() {
// setFreqBar(15);
}
void doSetupSources() {
sourceChooser.select(SRC_2S_PLANE);
setSources();
sources[0].y = sources[1].y = windowOffsetY;
sources[0].x = windowOffsetX + 1;
sources[2].x = sources[3].x = windowOffsetX;
sources[2].y = windowOffsetY + 1;
sources[3].y = windowOffsetY + windowHeight - 1;
}
Setup createNext() {
return new DopplerSetup();
}
}
class DopplerSetup extends Setup {
String getName() {
return "都普勒效應";
}
void select() {
// setFreqBar(15);
}
void doSetupSources() {
sourceChooser.select(SRC_1S_MOVING);
setSources();
}
Setup createNext() {
return null;
}
}
/**************************************************************************
* Event
*************************************************************************/
/**************************************************************************
* ComponentEvent
*************************************************************************/
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {
cv.repaint();
}
public void componentResized(ComponentEvent e) {
handleResize();
cv.repaint(100);
}
/**************************************************************************
* ItemEvent
*************************************************************************/
public void itemStateChanged(ItemEvent e) {
if (e.getItemSelectable() == musicChooser) {
doMusic();
}
if (e.getItemSelectable() == sourceChooser) {
if (sourceChooser.getSelectedIndex() != sourceIndex) {
setSources();
}
}
if (e.getItemSelectable() == setupChooser) {
doSetup();
}
if (e.getItemSelectable() == colorChooser) {
doColor();
}
}
void doMusic() {
int musicIndex = musicChooser.getSelectedIndex();
try {
this.doPlaySequencer(musicFolderPath + musicSource[musicIndex]);
} catch (MidiUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidMidiDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void setSources() {
int oldSCount = sourceCount;
boolean oldPlane = sourcePlane;
sourceIndex = sourceChooser.getSelectedIndex();
sourcePlane = (sourceChooser.getSelectedIndex() >= SRC_1S_PLANE && sourceChooser.getSelectedIndex() <= SRC_2S_PLANE );
sourceCount = 1;
sourceFreqCount = 1;
sourceMoving = false;
sourceWaveform = SWF_SIN;
switch (sourceChooser.getSelectedIndex()) {
case 0:
sourceCount = 0;
break;
case 2:
sourceCount = 2;
break;
case 3:
sourceCount = 4;
break;
case 4:
sourceMoving = true;
break;
case 6:
sourceCount = 2;
break;
}
if (sourceMoving) {
auxFunction = AUX_SPEED;
auxBar.setValue(7);
auxLabel.setText("移動速度");
auxLabel.setFont(new Font( "Arial" , Font.BOLD , 40 ));
} else {
auxFunction = AUX_NONE;
auxBar.hide();
auxLabel.hide();
}
if (auxFunction != AUX_NONE) {
auxBar.show();
auxLabel.show();
}
validate();
if (sourcePlane) {
sourceCount *= 2;
if (!(oldPlane && oldSCount == sourceCount)) {
int x2 = windowOffsetX + windowWidth - 1;
int y2 = windowOffsetY + windowHeight - 1;
sources[0] = new OscillationSource(windowOffsetX, windowOffsetY + 1);
sources[1] = new OscillationSource(x2, windowOffsetY + 1);
sources[2] = new OscillationSource(windowOffsetX, y2);
sources[3] = new OscillationSource(x2, y2);
}
} else if (!(!oldPlane && oldSCount == sourceCount)) {
sources[0] = new OscillationSource(gridSizeX / 2, windowOffsetY + 1);
sources[1] = new OscillationSource(gridSizeX / 2, gridSizeY - windowOffsetY - 2);
sources[2] = new OscillationSource(windowOffsetX + 1, gridSizeY / 2);
sources[3] = new OscillationSource(gridSizeX - windowOffsetX - 2, gridSizeY / 2);
for (int i = 4; i < sourceCount; i++) {
sources[i] = new OscillationSource(windowOffsetX + 1 + i * 2, gridSizeY / 2);
}
}
}
void doSetup() {
timeT = 0;
if (resBar.getValue() < 32) {
setResolution(32);
}
doClearWave();
doClearBorder();
// don't use previous source positions, use defaults
sourceCount = -1;
sourceChooser.select(SRC_1S);
setFreqBar(5);
setBrightness(15);
auxBar.setValue(1);
setup = (Setup) setupList.elementAt(setupChooser.getSelectedIndex());
setup.select();
setup.doSetupSources();
calculateExceptions();
}
void setBrightness(int x) {
double m = x / 5.;
m = (Math.log(m) + 5.) * 100;
brightnessBar.setValue((int) m);
}
void doColor() {
int cn = colorChooser.getSelectedIndex();
wallColor = schemeColors[cn][0];
posColor = schemeColors[cn][1];
negColor = schemeColors[cn][2];
zeroColor = schemeColors[cn][3];
sourceColor = schemeColors[cn][4];
}
/**************************************************************************
* ActionEvent
*************************************************************************/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clearWaveButton) {
doClearWave();
cv.repaint();
}
if (e.getSource() == clearBorderButton) {
doClearBorder();
cv.repaint();
}
if (e.getSource() == setBorderButton) {
doSetBorder();
cv.repaint();
}
if (e.getSource() == view3dButton) {
do3dView();
cv.repaint();
}
if (e.getSource() == stopButton) {
doStop();
cv.repaint();
}
}
void doClearWave() {
int x, y;
for (x = 0; x != gridSizeXY; x++) {
func[x] = funci[x] = 1e-10f;
}
}
void doClearBorder() {
int x, y;
for (x = 0; x != gridSizeXY; x++) {
walls[x] = false;
}
calculateExceptions();
}
void doSetBorder() {
int x, y;
for (x = 0; x < gridSizeX; x++) {
setWall(x, windowOffsetY);
setWall(x, windowBottom);
}
for (y = 0; y < gridSizeY; y++) {
setWall(windowOffsetX, y);
setWall(windowRight, y);
}
calculateExceptions();
}
void do3dView() {
is3dView = !is3dView;
if(is3dView) {
view3dButton.setLabel("切2D視角");
} else {
view3dButton.setLabel("切3D視角");
}
}
void doStop() {
isStop = !isStop;
if(isStop) {
stopButton.setLabel("開始");
} else {
stopButton.setLabel("暫停");
}
}
/**************************************************************************
* AdjustmentEvent
*************************************************************************/
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.print(((Scrollbar) e.getSource()).getValue() + "\n");
if (e.getSource() == brightnessBar) {
cv.repaint(0);
}
if (e.getSource() == freqBar) {
setFreq();
}
}
void setFreqBar(int x) {
freqBar.setValue(x);
freqBarValue = x;
freqTimeZero = 0;
}
void setFreq() {
// adjust time zero to maintain continuity in the freq func even though the frequency has changed.
double oldfreq = freqBarValue * freqMult;
freqBarValue = freqBar.getValue();
double newfreq = freqBarValue * freqMult;
freqTimeZero = timeT - oldfreq * (timeT - freqTimeZero) / newfreq; // newfreq * (timeT - freqTimeZero) = oldfreq * (timeT - freqTimeZero);
}
/**************************************************************************
* MouseEvent
*************************************************************************/
void edit(MouseEvent e) {
if (is3dView) {
return;
}
int x = e.getX();
int y = e.getY();
if (selectedSource != -1) {
x = x * windowWidth / windowSize.width;
y = y * windowHeight / windowSize.height;
if (x >= 0 && y >= 0 && x < windowWidth && y < windowHeight) {
sources[selectedSource].x = x + windowOffsetX;
sources[selectedSource].y = y + windowOffsetY;
}
return;
}
if (dragX == x && dragY == y)
editWavePoint(x, y);
else {
// need to draw a line from old x,y to new x,y and
// call editFuncPoint for each point on that line. yuck.
if (abs(y - dragY) > abs(x - dragX)) {
// y difference is greater, so we step along y's from min to max y and calculate x for each step
int x1 = (y < dragY) ? x : dragX;
int y1 = (y < dragY) ? y : dragY;
int x2 = (y > dragY) ? x : dragX;
int y2 = (y > dragY) ? y : dragY;
dragX = x;
dragY = y;
for (y = y1; y <= y2; y++) {
x = x1 + (x2 - x1) * (y - y1) / (y2 - y1);
editWavePoint(x, y);
}
} else {
// x difference is greater, so we step along x's from min to max x and calculate y for each step
int x1 = (x < dragX) ? x : dragX;
int y1 = (x < dragX) ? y : dragY;
int x2 = (x > dragX) ? x : dragX;
int y2 = (x > dragX) ? y : dragY;
dragX = x;
dragY = y;
for (x = x1; x <= x2; x++) {
y = y1 + (y2 - y1) * (x - x1) / (x2 - x1);
editWavePoint(x, y);
}
}
}
}
void editWavePoint(int x, int y) {
int xp = x * windowWidth / windowSize.width + windowOffsetX;
int yp = y * windowHeight / windowSize.height + windowOffsetY;
int gi = xp + yp * gw;
if (!dragSet && !dragClear) {
dragClear = func[gi] > .1;
dragSet = !dragClear;
}
func[gi] = (dragSet) ? 1 : -1;
funci[gi] = 0;
cv.repaint(0);
}
void selectSource(MouseEvent me) {
int x = me.getX();
int y = me.getY();
int i;
for (i = 0; i != sourceCount; i++) {
OscillationSource src = sources[i];
int sx = src.getScreenX();
int sy = src.getScreenY();
int r2 = (sx - x) * (sx - x) + (sy - y) * (sy - y);
if (sourceRadius * sourceRadius > r2) {
selectedSource = i;
return;
}
}
selectedSource = -1;
}
public void mouseDragged(MouseEvent e) {
if (is3dView) {
view3dDrag(e);
}
if (!dragging) {
selectSource(e);
}
dragging = true;
edit(e);
adjustResolution = false;
cv.repaint(0);
}
public void mouseMoved(MouseEvent e) {
if (dragging) {
return;
}
int x = e.getX();
int y = e.getY();
dragStartX = dragX = x;
dragStartY = dragY = y;
viewAngleDragStart = viewAngle;
viewHeightDragStart = viewHeight;
selectSource(e);
if (isStop) {
cv.repaint(0);
}
}
void view3dDrag(MouseEvent e) {
int x = e.getX();
int y = e.getY();
viewAngle = (dragStartX - x) / 40. + viewAngleDragStart;
while (viewAngle < 0) {
viewAngle += 2 * pi;
}
while (viewAngle >= 2 * pi) {
viewAngle -= 2 * pi;
}
viewAngleCos = Math.cos(viewAngle);
viewAngleSin = Math.sin(viewAngle);
viewHeight = (dragStartY - y) / 10. + viewHeightDragStart;
cv.repaint();
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {
dragStartX = -1;
}
public void mousePressed(MouseEvent e) {
adjustResolution = false;
mouseMoved(e);
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == 0) {
return;
}
dragging = true;
edit(e);
}
public void mouseReleased(MouseEvent e) {
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == 0) {
return;
}
dragging = false;
dragSet = dragClear = false;
cv.repaint();
}
/**************************************************************************
* Global Variable Setting Function
*************************************************************************/
void setResolution(int x) {
resBar.setValue(x);
setResolution();
reinit();
}
void setResolution() {
windowWidth = windowHeight = resBar.getValue();
int border = windowWidth / 9;
if (border < 20) {
border = 20;
}
windowOffsetX = windowOffsetY = border;
gridSizeX = windowWidth + windowOffsetX * 2;
gridSizeY = windowHeight + windowOffsetY * 2;
windowBottom = windowOffsetY + windowHeight - 1;
windowRight = windowOffsetX + windowWidth - 1;
}
void setWall(int x, int y) {
walls[x + gw * y] = true;
}
/**************************************************************************
* Global Variable Calculating Function
*************************************************************************/
void calculateExceptions() {
int x, y;
// if walls are in place on border, need to extend that through hidden area to avoid "leaks"
for (x = 0; x != gridSizeX; x++) {
for (y = 0; y < windowOffsetY; y++) {
walls[x + gw * y] = walls[x + gw * windowOffsetY];
walls[x + gw * (gridSizeY - y - 1)] = walls[x + gw * (gridSizeY - windowOffsetY - 1)];
}
}
for (y = 0; y < gridSizeY; y++) {
for (x = 0; x < windowOffsetX; x++) {
walls[x + gw * y] = walls[windowOffsetX + gw * y];
walls[gridSizeX - x - 1 + gw * y] = walls[gridSizeX - windowOffsetX - 1 + gw * y];
}
}
// generate exceptional array, which is useful for doing special handling of elements
for (x = 1; x < gridSizeX - 1; x++) {
for (y = 1; y < gridSizeY - 1; y++) {
int gi = x + gw * y;
exception[gi] = walls[gi - 1] || walls[gi + 1] || walls[gi - gw] || walls[gi + gw] || walls[gi];
}
}
// put some extra exceptions at the corners to ensure tadd2, sinth and etc to get calculated
exception[1 + gw] = exception[gridSizeX - 2 + gw] = exception[1 + (gridSizeY - 2) * gw] = exception[gridSizeX - 2 + (gridSizeY - 2) * gw] = true;
}
/**************************************************************************
* Calculating Function
*************************************************************************/
int abs(int x) {
return x < 0 ? -x : x;
}
int sign(int x) {
return (x < 0) ? -1 : (x == 0) ? 0 : 1;
}
long getTimeMillis() {
try {
Long time = (Long) timerMethod.invoke(null, new Object[] {});
return time.longValue() / timerDiv;
} catch (Exception ee) {
ee.printStackTrace();
return 0;
}
}
/**************************************************************************
* Object OscillationSource
*************************************************************************/
class OscillationSource {
int x;
int y;
float v;
OscillationSource(int xx, int yy) {
x = xx;
y = yy;
}
int getScreenX() {
return ((x - windowOffsetX) * windowSize.width + windowSize.width / 2) / windowWidth;
}
int getScreenY() {
return ((y - windowOffsetY) * windowSize.height + windowSize.height / 2) / windowHeight;
}
};
/**************************************************************************
* MUSIC
*************************************************************************/
String musicFolderPath = "D:\\ICG2014_TERM_PROJECT_MIDI\\";
String [] musicSource = null;
Sequence sequence = null;
Sequencer sequencer = null;
int maxTick;
int musicLength = 0;
double eachTickSec = 0.0;
int musicMult = 4;
String [] musicMainNote = null;
int [][] musicNoteCount = null; // {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}
Long timeMidiStart = new Long(0);
void doCloseSequencer() throws MidiUnavailableException, IOException, InvalidMidiDataException {
if(sequencer != null) {
sequencer.close();
sequencer = null;
}
}
void doCalMusicNoteCount(String filepath) throws InvalidMidiDataException, IOException {
// maxTick
maxTick = Long.valueOf(sequencer.getTickLength()).intValue();
System.out.println(sequencer.getTickLength());
// calculate musicMainNote[]
musicLength = Long.valueOf(sequencer.getMicrosecondLength() / 1000000).intValue();
System.out.println(sequencer.getMicrosecondLength());
eachTickSec = Double.valueOf(musicLength) / Double.valueOf(maxTick);
System.out.println(eachTickSec);
musicMainNote = new String[musicLength * musicMult + 1];
musicNoteCount = new int[musicLength * musicMult + 1][12];
sequence = MidiSystem.getSequence(new File(filepath));
for (Track track : sequence.getTracks()) {
for (int i=0; i < track.size(); i++) {
MidiEvent event = track.get(i);
int currentBase = Double.valueOf(Math.floor(event.getTick() * eachTickSec * musicMult)).intValue();
MidiMessage message = event.getMessage();
if (message instanceof ShortMessage) {
ShortMessage sm = (ShortMessage) message;
int key = sm.getData1();
int note = key % 12;
musicNoteCount[currentBase][note]++;
}
}
}
this.doCalMainNote();
}
void doCalMainNote() {
for(int index = 0; index < musicLength * musicMult; index ++) {
int max = 0;
int maxI = 0;
for(int i = 0; i < musicNoteCount[index].length; i++) {
if(musicNoteCount[index][i] > max) {
max = musicNoteCount[index][i];
maxI = i;
}
}
switch (maxI) { // {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}
case 0:
musicMainNote[index] = "C";
break;
case 1:
musicMainNote[index] = "C#";
break;
case 2:
musicMainNote[index] = "D";
break;
case 3:
musicMainNote[index] = "D#";
break;
case 4:
musicMainNote[index] = "E";
break;
case 5:
musicMainNote[index] = "F";
break;
case 6:
musicMainNote[index] = "F#";
break;
case 7:
musicMainNote[index] = "G";
break;
case 8:
musicMainNote[index] = "G#";
break;
case 9:
musicMainNote[index] = "A";
break;
case 10:
musicMainNote[index] = "A#";
break;
case 11:
musicMainNote[index] = "B";
break;
}
System.out.println(index + ": " + musicMainNote[index]);
}
}
void doPlaySequencer(String filepath) throws MidiUnavailableException, IOException, InvalidMidiDataException { // doPlayMIDI
this.doCloseSequencer();
sequencer = MidiSystem.getSequencer();
// Opens the device, indicating that it should now acquire any
// system resources it requires and become operational.
sequencer.open();
// create a stream from a file
InputStream is = new BufferedInputStream(new FileInputStream(new File(filepath)));
// Sets the current sequence on which the sequencer operates.
// The stream must point to MIDI file data.
sequencer.setSequence(is);
// doCalSequence
this.doCalMusicNoteCount(filepath);
// Starts playback of the MIDI data in the currently loaded sequence.
sequencer.start();
// timeMidiStart
timeMidiStart = getTimeMillis();
}
void setFreqBarByNote(String note) {
// {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}
if(note.equals("C")) {
setFreqBar(1);
} else if(note.equals("C#")) {
setFreqBar(2);
} else if(note.equals("D")) {
setFreqBar(3);
} else if(note.equals("D#")) {
setFreqBar(4);
} else if(note.equals("E")) {
setFreqBar(5);
} else if(note.equals("F")) {
setFreqBar(6);
} else if(note.equals("F#")) {
setFreqBar(7);
} else if(note.equals("G")) {
setFreqBar(8);
} else if(note.equals("G#")) {
setFreqBar(9);
} else if(note.equals("A")) {
setFreqBar(10);
} else if(note.equals("A#")) {
setFreqBar(11);
} else if(note.equals("B")) {
setFreqBar(12);
}
setFreq();
}
} | BIG5 | Java | 54,128 | java | Cymatics.java | Java | [
{
"context": "me(Cymatics c) {\n\t\tsuper(\"CYMATICS Music Player by CSu (D02944006@ntu.edu.tw)\");\n\t\tapplet = c;\n\t\tuseFram",
"end": 4149,
"score": 0.9155434966087341,
"start": 4146,
"tag": "USERNAME",
"value": "CSu"
},
{
"context": "atics c) {\n\t\tsuper(\"CYMATICS Music Player by CSu (D02944006@ntu.edu.tw)\");\n\t\tapplet = c;\n\t\tuseFrame = true;\n\t\tshowContro",
"end": 4171,
"score": 0.9999297857284546,
"start": 4151,
"tag": "EMAIL",
"value": "D02944006@ntu.edu.tw"
}
] | null | [] | import java.awt.*;
import java.applet.Applet;
import java.util.Vector;
import java.util.Random;
import java.awt.image.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Math;
import java.awt.event.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.StringTokenizer;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Track;
class CymaticsCanvas extends Canvas {
CymaticsFrame cf;
CymaticsCanvas(CymaticsFrame f) {
cf = f;
}
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
public void update(Graphics g) {
cf.updateCymatics(g);
}
public void paint(Graphics g) {
cf.updateCymatics(g);
}
};
class CymaticsLayout implements LayoutManager {
public CymaticsLayout() {
}
public void addLayoutComponent(String name, Component c) {
}
public void removeLayoutComponent(Component c) {
}
public Dimension preferredLayoutSize(Container target) {
return new Dimension(500, 500);
}
public Dimension minimumLayoutSize(Container target) {
return new Dimension(100, 100);
}
public void layoutContainer(Container target) {
Insets insets = target.insets();
// targetw, targeth -> getComponent(0)
int targetw = target.size().width - (insets.left + insets.right);
int cw = targetw * 7 / 10;
if (target.getComponentCount() == 1) {
cw = targetw;
}
int targeth = target.size().height - (insets.top + insets.bottom);
target.getComponent(0).move(insets.left, insets.top);
target.getComponent(0).resize(cw, targeth);
// barwidth -> the rest of the getComponent(>0)
int barwidth = targetw - cw; // (ratio: 3 / 10)
cw = cw + insets.left;
int i;
int h = insets.top;
for (i = 1; i < target.getComponentCount(); i++) { // For each Component
Component m = target.getComponent(i);
if (m.isVisible()) {
Dimension d = m.getPreferredSize();
if (m instanceof Scrollbar) {
d.width = barwidth;
}
if (m instanceof Choice && d.width > barwidth) {
d.width = barwidth;
}
if (m instanceof Label) {
h += d.height / 5;
d.width = barwidth;
}
m.move(cw, h);
m.resize(d.width, d.height);
h = h + d.height;
}
}
}
};
public class Cymatics extends Applet implements ComponentListener {
boolean started = false;
static CymaticsFrame cf;
void destroyFrame() {
if (cf != null) {
cf.dispose();
}
cf = null;
repaint();
}
void showFrame() {
if (cf == null) {
started = true;
cf = new CymaticsFrame(this);
cf.init();
repaint();
}
}
public void paint(Graphics g) {
String s = "Applet is open in a separate window.";
if (!started) {
s = "Applet is starting.";
} else if (cf == null) {
s = "Applet is finished.";
} else if (cf.useFrame) {
cf.triggerShow();
}
g.drawString(s, 10, 30);
}
public void init() {
addComponentListener(this);
}
public static void main(String args[]) {
cf = new CymaticsFrame(null);
cf.init();
}
/**************************************************************************
* ComponentEvent
*************************************************************************/
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {
showFrame();
}
public void componentResized(ComponentEvent e) {
}
public void destroy() {
if (cf != null) {
cf.dispose();
}
cf = null;
repaint();
}
};
class CymaticsFrame extends Frame implements ComponentListener, ActionListener, AdjustmentListener, MouseMotionListener, MouseListener, ItemListener {
CymaticsCanvas cv;
Cymatics applet;
CymaticsFrame(Cymatics c) {
super("CYMATICS Music Player by CSu (<EMAIL>)");
applet = c;
useFrame = true;
showControls = true;
adjustResolution = true;
}
/**************************************************************************
* Variable Initial
*************************************************************************/
Dimension windowSize;
Image dbimage;
Random random;
int gridSizeX;
int gridSizeY;
int gridSizeXY;
int gw;
int windowWidth = 50;
int windowHeight = 50;
int windowOffsetX = 0;
int windowOffsetY = 0;
int windowBottom = 0;
int windowRight = 0;
Container main;
Choice musicChooser;
Choice setupChooser;
Choice sourceChooser;
Choice colorChooser;
Button clearWaveButton;
Button clearBorderButton;
Button setBorderButton;
Button view3dButton;
Button stopButton;
Scrollbar speedBar;
Scrollbar resBar;
Scrollbar freqBar;
Scrollbar brightnessBar;
double brightMult = 1;
Scrollbar auxBar;
Label auxLabel;
int auxFunction;
static final double pi = 3.14159265358979323846;
public static final int sourceRadius = 5;
public static final double freqMult = .0233333;
static final int SWF_SIN = 0;
static final int AUX_NONE = 0;
static final int AUX_SPEED = 1;
static final int SRC_NONE = 0;
static final int SRC_1S = 1;
static final int SRC_2S = 2;
static final int SRC_4S = 3;
static final int SRC_1S_MOVING = 4;
static final int SRC_1S_PLANE = 5;
static final int SRC_2S_PLANE = 6;
static final int MODE_SETFUNC = 0;
static final int MODE_WALLS = 1;
OscillationSource sources[];
float func[];
float funci[];
boolean walls[];
boolean exception[];
int pixels[];
Color wallColor, posColor, negColor, zeroColor, sourceColor;
Color schemeColors[][];
long startTime;
Method timerMethod;
int timerDiv;
MemoryImageSource imageSource;
public boolean useFrame;
boolean showControls;
boolean useBufferedImage = false;
Vector setupList;
Setup setup;
boolean adjustResolution = true;
boolean increaseResolution = false;
boolean sourcePlane = false;
boolean sourceMoving = false;
double movingSourcePos = 0;
int sourceCount = -1;
int selectedSource = -1;
int sourceFreqCount = -1;
int sourceWaveform = SWF_SIN;
int sourceIndex;
boolean dragging;
boolean dragClear;
boolean dragSet;
int dragX, dragY, dragStartX = -1, dragStartY;
int freqBarValue;
double freqTimeZero;
double timeT;
boolean is3dView = false;
boolean isStop = false;
double dampcoef = 1;
/**************************************************************************
* Applet Main
*************************************************************************/
public void init() {
// useFrame? showControls? main!!
try {
if (applet != null) {
// useFrame: Default true
String param = applet.getParameter("useFrame");
if (param != null && param.equalsIgnoreCase("false")) {
useFrame = false;
}
// showControls: Default false
param = applet.getParameter("showControls");
if (param != null && param.equalsIgnoreCase("false")) {
showControls = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (useFrame) {
main = this;
} else {
main = applet;
}
// useBufferedImage
String jv = System.getProperty("java.class.version");
double jvf = new Double(jv).doubleValue();
if (jvf >= 48) { // Java 1.4
useBufferedImage = true;
}
// timerMethod & timerDiv (nano vs milli)
try {
Class sysclass = Class.forName("java.lang.System");
timerMethod = sysclass.getMethod("nanoTime", null);
timerDiv = 1000000;
if (timerMethod == null) {
timerMethod = sysclass.getMethod("currentTimeMillis", null);
timerDiv = 1;
}
} catch (Exception ee) {
ee.printStackTrace();
}
main.setLayout(new CymaticsLayout());
cv = new CymaticsCanvas(this);
cv.addComponentListener(this);
cv.addMouseMotionListener(this);
cv.addMouseListener(this);
main.add(cv);
// Initial musicSource & musicChooser
musicSource = new String [999];
musicChooser = new Choice();
File musicFolder = new File(musicFolderPath);
File [] musicFiles = musicFolder.listFiles();
for(int i = 0; i < musicFiles.length; i++) {
musicChooser.add(musicFiles[i].getName());
musicSource[i] = musicFiles[i].getName();
}
musicChooser.addItemListener(this);
if (showControls) {
main.add(musicChooser);
}
// Initial setupList -> setupChooser
setupList = new Vector();
Setup s = new SingleSourceSetup(); // Default SingleSourceSetup
while (s != null) {
setupList.addElement(s);
s = s.createNext();
}
setupChooser = new Choice();
int i;
for (i = 0; i != setupList.size(); i++) {
setupChooser.add("預設主題: " + ((Setup) setupList.elementAt(i)).getName());
}
setupChooser.addItemListener(this);
if (showControls) {
main.add(setupChooser);
}
// Initial OscillationSource & sourceChooser
sources = new OscillationSource[20];
sourceChooser = new Choice();
sourceChooser.add("無"); // 0
sourceChooser.add("1點波源"); // 1
sourceChooser.add("2點波源"); // 2
sourceChooser.add("4點波源"); // 3
sourceChooser.add("移動波源"); // 4
sourceChooser.add("1線波源"); // 5
sourceChooser.add("2線波源"); // 6
sourceChooser.select(SRC_1S);
sourceChooser.addItemListener(this);
if (showControls) {
// main.add(sourceChooser);
}
// Initial colorChooser
colorChooser = new Choice();
colorChooser.addItemListener(this);
if (showControls) {
main.add(colorChooser);
}
// Initial clearWaveButton
clearWaveButton = new Button("清空水波");
clearWaveButton.setFont(new Font( "Arial" , Font.BOLD , 40 ));
if (showControls) {
main.add(clearWaveButton);
}
clearWaveButton.addActionListener(this);
// Initial clearBorderButton
clearBorderButton = new Button("清空邊界");
clearBorderButton.setFont(new Font( "Arial" , Font.BOLD , 40 ));
if (showControls) {
main.add(clearBorderButton);
}
clearBorderButton.addActionListener(this);
// Initial setBorderButton
setBorderButton = new Button("新增邊界");
setBorderButton.setFont(new Font( "Arial" , Font.BOLD , 40 ));
if (showControls) {
main.add(setBorderButton);
}
setBorderButton.addActionListener(this);
// Initial view3DButton
view3dButton = new Button("切3D視角");
view3dButton.setFont(new Font( "Arial" , Font.BOLD , 40 ));
view3dButton.setPreferredSize(new Dimension(178, 50));
if (showControls) {
main.add(view3dButton);
}
view3dButton.addActionListener(this);
// Initial stopButton
stopButton = new Button("暫停");
stopButton.setFont(new Font( "Arial" , Font.BOLD , 40 ));
stopButton.setPreferredSize(new Dimension(178, 50));
if (showControls) {
main.add(stopButton);
}
stopButton.addActionListener(this);
// Initial speedBar
Label l = new Label("模擬速度", Label.CENTER);
l.setFont(new Font( "Arial" , Font.BOLD , 40 ));
speedBar = new Scrollbar(Scrollbar.HORIZONTAL, 8, 1, 1, 100); // Default: 8/100
speedBar.addAdjustmentListener(this);
if (showControls) {
// main.add(l);
// main.add(speedBar);
}
// Initial resBar
l = new Label("解析度", Label.CENTER);
l.setFont(new Font( "Arial" , Font.BOLD , 40 ));
resBar = new Scrollbar(Scrollbar.HORIZONTAL, 110, 5, 5, 400); // Default: 110/400
resBar.addAdjustmentListener(this);
if (showControls) {
// main.add(l);
// main.add(resBar);
}
setResolution();
// Initial freqBar
l = new Label("水波頻率", Label.CENTER);
l.setFont(new Font( "Arial" , Font.BOLD , 40 ));
freqBar = new Scrollbar(Scrollbar.HORIZONTAL, freqBarValue = 15, 1, 1, 30); // Default: 15/30
freqBar.addAdjustmentListener(this);
if (showControls) {
main.add(l);
main.add(freqBar);
}
// Initial brightnessBar
l = new Label("對比色差", Label.CENTER);
l.setFont(new Font( "Arial" , Font.BOLD , 40 ));
brightnessBar = new Scrollbar(Scrollbar.HORIZONTAL, 27, 1, 1, 1200); // Default: 27/1200
brightnessBar.addAdjustmentListener(this);
if (showControls) {
main.add(l);
main.add(brightnessBar);
}
// Initial auxBar
auxLabel = new Label("", Label.CENTER);
auxBar = new Scrollbar(Scrollbar.HORIZONTAL, 1, 1, 1, 30); // Default: 1/30
auxBar.addAdjustmentListener(this);
if (showControls) {
main.add(auxLabel);
main.add(auxBar);
}
schemeColors = new Color[20][8];
try {
String param;
param = applet.getParameter("setup");
if (param != null) {
setupChooser.select(Integer.parseInt(param));
}
param = applet.getParameter("setupClass");
if (param != null) {
for (i = 0; i != setupList.size(); i++) {
if (setupList.elementAt(i).getClass().getName().equalsIgnoreCase("CymaticsFrame$" + param)) {
setupChooser.select(i);
break;
}
}
}
} catch (Exception e) {
if (applet != null) {
e.printStackTrace();
}
}
if (colorChooser.getItemCount() == 0) {
addDefaultColorScheme();
}
doColor();
setup = (Setup) setupList.elementAt(setupChooser.getSelectedIndex());
reinit();
cv.setBackground(Color.black);
cv.setForeground(Color.lightGray);
startTime = getTimeMillis();
if (useFrame) {
resize(800, 640);
handleResize();
Dimension x = getSize();
Dimension screen = getToolkit().getScreenSize();
setLocation((screen.width - x.width) / 2, (screen.height - x.height) / 2);
show();
} else {
hide();
handleResize();
applet.validate();
}
main.requestFocus();
}
void reinit() {
reinit(true);
}
void reinit(boolean setup) {
sourceCount = -1;
System.out.print("reinit " + gridSizeX + " " + gridSizeY + "\n");
gridSizeXY = gridSizeX * gridSizeY;
gw = gridSizeY;
func = new float[gridSizeXY];
funci = new float[gridSizeXY];
walls = new boolean[gridSizeXY];
exception = new boolean[gridSizeXY];
int i, j;
if (setup) {
doSetup();
}
}
boolean shown = false;
public void triggerShow() {
if (!shown)
show();
shown = true;
}
void handleResize() {
Dimension d = windowSize = cv.getSize();
if (windowSize.width == 0) {
return;
}
pixels = null;
if (useBufferedImage) {
try {
Class biclass = Class.forName("java.awt.image.BufferedImage");
Class dbiclass = Class.forName("java.awt.image.DataBufferInt");
Class rasclass = Class.forName("java.awt.image.Raster");
Constructor cstr = biclass.getConstructor(new Class[] { int.class, int.class, int.class });
dbimage = (Image) cstr.newInstance(new Object[] { new Integer(d.width), new Integer(d.height), new Integer(BufferedImage.TYPE_INT_RGB) });
Method m = biclass.getMethod("getRaster", null);
Object ras = m.invoke(dbimage, null);
Object db = rasclass.getMethod("getDataBuffer", null).invoke(ras, null);
pixels = (int[]) dbiclass.getMethod("getData", null).invoke(db, null);
} catch (Exception ee) {
System.out.println("BufferedImage failed");
}
}
if (pixels == null) {
pixels = new int[d.width * d.height];
int i;
for (i = 0; i != d.width * d.height; i++)
pixels[i] = 0xFF000000;
imageSource = new MemoryImageSource(d.width, d.height, pixels, 0, d.width);
imageSource.setAnimated(true);
imageSource.setFullBufferUpdates(true);
dbimage = cv.createImage(imageSource);
}
}
public boolean handleEvent(Event ev) {
if (ev.id == Event.WINDOW_DESTROY) {
destroyFrame();
return true;
}
return super.handleEvent(ev);
}
void destroyFrame() {
if (applet == null) {
dispose();
} else {
applet.destroyFrame();
}
}
int frames = 0;
int steps = 0;
boolean moveRight = true;
boolean moveDown = true;
public void updateCymatics(Graphics realg) {
if (windowSize == null || windowSize.width == 0) {
handleResize();
return;
}
long sysTime = getTimeMillis();
if (increaseResolution) {
increaseResolution = false;
if (resBar.getValue() < 495) {
setResolution(resBar.getValue() + 10);
}
}
double tadd = 0;
if (!isStop) {
int val = 5; // speedBar.getValue();
tadd = val * .05;
}
boolean stopFunc = dragging && selectedSource == -1 && is3dView == false;
if (isStop) {
stopFunc = true;
}
int iterCount = speedBar.getValue();
if (!stopFunc) {
int iter;
int mxx = gridSizeX - 1;
int mxy = gridSizeY - 1;
for (iter = 0; iter != iterCount; iter++) {
int jstart, jend, jinc;
if (moveDown) {
jstart = 1;
jend = mxy;
jinc = 1;
moveDown = false;
} else {
jstart = mxy - 1;
jend = 0;
jinc = -1;
moveDown = true;
}
moveRight = moveDown;
float sinhalfth = 0;
float sinth = 0;
float scaleo = 0;
for (int j = jstart; j != jend; j += jinc) {
int istart, iend, iinc;
if (moveRight) {
iinc = 1;
istart = 1;
iend = mxx;
moveRight = false;
} else {
iinc = -1;
istart = mxx - 1;
iend = 0;
moveRight = true;
}
int gi = j * gw + istart;
int giEnd = j * gw + iend;
for (; gi != giEnd; gi += iinc) {
// the equilibrium point
float previ = func[gi - 1];
float nexti = func[gi + 1];
float prevj = func[gi - gw];
float nextj = func[gi + gw];
float basis = (nexti + previ + nextj + prevj) * .25f;
if (exception[gi]) {
sinhalfth = (float) Math.sin(tadd / 2);
sinth = (float) (Math.sin(tadd) * dampcoef);
scaleo = (float) (1 - Math.sqrt(4 * sinhalfth * sinhalfth - sinth * sinth));
if (walls[gi]) {
continue;
}
if (walls[gi - 1]) previ = 0;
if (walls[gi + 1]) nexti = 0;
if (walls[gi - gw]) prevj = 0;
if (walls[gi + gw]) nextj = 0;
basis = (nexti + previ + nextj + prevj) * .25f;
}
float a = 0;
float b = 0;
a = func[gi] - basis;
b = funci[gi];
func[gi] = basis + a * scaleo - b * sinth;
funci[gi] = b * scaleo + a * sinth;
}
}
timeT += tadd;
if (sourceCount > 0) {
double w = freqBar.getValue() * (timeT - freqTimeZero) * freqMult;
double w2 = w;
double v = 0;
double v2 = 0;
v = Math.cos(w);
if (sourceCount >= (sourcePlane ? 4 : 2)) {
v2 = Math.cos(w2);
} else if (sourceFreqCount == 2) {
v = (v + Math.cos(w2)) * .5;
}
for (int j = 0; j != sourceCount; j++) {
if ((j % 2) == 0) {
sources[j].v = (float) (v * setup.sourceStrength());
} else{
sources[j].v = (float) (v2 * setup.sourceStrength());
}
}
if (sourcePlane) {
for (int j = 0; j != sourceCount / 2; j++) {
OscillationSource src1 = sources[j * 2];
OscillationSource src2 = sources[j * 2 + 1];
OscillationSource src3 = sources[j];
drawPlaneSource(src1.x, src1.y, src2.x, src2.y, src3.v, w);
}
} else {
if (sourceMoving) {
int sy;
movingSourcePos += tadd * .02 * auxBar.getValue();
double wm = movingSourcePos;
int h = windowHeight - 3;
wm %= h * 2;
sy = (int) wm;
if (sy > h) {
sy = 2 * h - sy;
}
sy += windowOffsetY + 1;
sources[0].y = sy;
}
for (int i = 0; i != sourceCount; i++) {
OscillationSource src = sources[i];
func[src.x + gw * src.y] = src.v;
funci[src.x + gw * src.y] = 0;
}
}
}
setup.eachFrame();
steps++;
filterGrid();
}
}
brightMult = Math.exp(brightnessBar.getValue() / 100. - 5.);
if (is3dView) {
draw3dView();
} else {
draw2dView();
}
if (imageSource != null) {
imageSource.newPixels();
}
realg.drawImage(dbimage, 0, 0, this);
if (dragStartX >= 0 && !is3dView) {
// POSITION
int x = dragStartX * windowWidth / windowSize.width;
int y = windowHeight - 1 - (dragStartY * windowHeight / windowSize.height);
String s = "(" + x + "," + y + ")";
realg.setColor(Color.white);
FontMetrics fm = realg.getFontMetrics();
int h = 5 + fm.getAscent();
realg.fillRect(0, windowSize.height - h, fm.stringWidth(s) + 10, h);
realg.setColor(Color.black);
realg.drawString(s, 5, windowSize.height - 5);
} else {
// NOTE // TODO
int midiNoteIndex = Long.valueOf(getTimeMillis() - timeMidiStart).intValue() * musicMult / 1000;
String s = "";
try{
String note = musicMainNote[midiNoteIndex];
setFreqBarByNote(note);
s = "midiNoteIndex: " + midiNoteIndex;
if(midiNoteIndex < musicLength * musicMult) {
s = "NOTE: " + musicMainNote[midiNoteIndex];
}
} catch (Exception e) {
//
}
realg.setColor(Color.white);
FontMetrics fm = realg.getFontMetrics();
int h = 5 + fm.getAscent();
realg.fillRect(0, windowSize.height - h, fm.stringWidth(s) + 10, h);
realg.setColor(Color.black);
realg.drawString(s, 5, windowSize.height - 5);
}
if (!isStop) {
long diff = getTimeMillis() - sysTime;
if (adjustResolution && diff > 0 && sysTime < startTime + 1000 && windowOffsetX * diff / iterCount < 55) {
increaseResolution = true;
startTime = sysTime;
}
cv.repaint(0);
}
}
void drawPlaneSource(int x1, int y1, int x2, int y2, float v, double w) {
// correct x1, x2
if (y1 == y2) {
if (x1 == windowOffsetX) {
x1 = 0;
}
if (x2 == windowOffsetX) {
x2 = 0;
}
if (x1 == windowOffsetX + windowWidth - 1) {
x1 = gridSizeX - 1;
}
if (x2 == windowOffsetX + windowWidth - 1) {
x2 = gridSizeX - 1;
}
}
// correct y1, y2
if (x1 == x2) {
if (y1 == windowOffsetY) {
y1 = 0;
}
if (y2 == windowOffsetY) {
y2 = 0;
}
if (y1 == windowOffsetY + windowHeight - 1) {
y1 = gridSizeY - 1;
}
if (y2 == windowOffsetY + windowHeight - 1) {
y2 = gridSizeY - 1;
}
}
// need to draw a line from x1,y1 to x2,y2 smoothly by interpolation
if (x1 == x2 && y1 == y2) { // a straight line
func[x1 + gw * y1] = v;
funci[x1 + gw * y1] = 0;
} else if (abs(y2 - y1) > abs(x2 - x1)) { // y difference is greater, cutting y to calculate x
double sgn = sign(y2 - y1);
int x, y;
for (y = y1; y != y2 + sgn; y += sgn) {
x = x1 + (x2 - x1) * (y - y1) / (y2 - y1);
double ph = sgn * (y - y1) / (y2 - y1);
int gi = x + gw * y;
func[gi] = setup.calcSourcePhase(ph, v, w);
funci[gi] = 0;
}
} else { // x difference is greater, cutting x to calculate y
double sgn = sign(x2 - x1);
int x, y;
for (x = x1; x != x2 + sgn; x += sgn) {
y = y1 + (y2 - y1) * (x - x1) / (x2 - x1);
double ph = sgn * (x - x1) / (x2 - x1);
int gi = x + gw * y;
func[gi] = setup.calcSourcePhase(ph, v, w);
funci[gi] = 0;
}
}
}
/**************************************************************************
* Draw 2D
*************************************************************************/
void draw2dView() {
int ix = 0;
int i, j, k, l;
for (j = 0; j != windowHeight; j++) {
ix = windowSize.width * (j * windowSize.height / windowHeight);
int j2 = j + windowOffsetY;
int gi = j2 * gw + windowOffsetX;
int y = j * windowSize.height / windowHeight;
int y2 = (j + 1) * windowSize.height / windowHeight;
for (i = 0; i != windowWidth; i++, gi++) {
int x = i * windowSize.width / windowWidth;
int x2 = (i + 1) * windowSize.width / windowWidth;
int i2 = i + windowOffsetX;
double dy = func[gi] * brightMult;
if (dy < -1)
dy = -1;
if (dy > 1)
dy = 1;
int col = 0;
int colR = 0, colG = 0, colB = 0;
if (walls[gi]) {
colR = wallColor.getRed();
colG = wallColor.getGreen();
colB = wallColor.getBlue();
}
else if (dy < 0) {
double d1 = -dy;
double d2 = 1 - d1;
colR = (int) (negColor.getRed() * d1 + zeroColor.getRed() * d2);
colG = (int) (negColor.getGreen() * d1 + zeroColor.getGreen() * d2);
colB = (int) (negColor.getBlue() * d1 + zeroColor.getBlue() * d2);
} else {
double d1 = dy;
double d2 = 1 - dy;
colR = (int) (posColor.getRed() * d1 + zeroColor.getRed() * d2);
colG = (int) (posColor.getGreen() * d1 + zeroColor.getGreen() * d2);
colB = (int) (posColor.getBlue() * d1 + zeroColor.getBlue() * d2);
}
col = (255 << 24) | (colR << 16) | (colG << 8) | (colB);
for (k = 0; k != x2 - x; k++, ix++) {
for (l = 0; l != y2 - y; l++) {
pixels[ix + l * windowSize.width] = col;
}
}
}
}
for (i = 0; i != sourceCount; i++) {
OscillationSource src = sources[i];
int xx = src.getScreenX();
int yy = src.getScreenY();
plotSource(i, xx, yy);
}
}
// draw a circle
void plotSource(int n, int xx, int yy) {
int rad = sourceRadius;
int j;
int col = (sourceColor.getRed() << 16) | (sourceColor.getGreen() << 8) | (sourceColor.getBlue()) | 0xFF000000;
if (n == selectedSource) {
col ^= 0xFFFFFF;
}
for (j = 0; j <= rad; j++) {
int k = (int) (Math.sqrt(rad * rad - j * j) + .5);
plotPixel(xx + j, yy + k, col);
plotPixel(xx + k, yy + j, col);
plotPixel(xx + j, yy - k, col);
plotPixel(xx - k, yy + j, col);
plotPixel(xx - j, yy + k, col);
plotPixel(xx + k, yy - j, col);
plotPixel(xx - j, yy - k, col);
plotPixel(xx - k, yy - j, col);
plotPixel(xx, yy + j, col);
plotPixel(xx, yy - j, col);
plotPixel(xx + j, yy, col);
plotPixel(xx - j, yy, col);
}
}
void plotPixel(int x, int y, int pix) {
if (x < 0 || x >= windowSize.width) {
return;
}
try {
pixels[x + y * windowSize.width] = pix;
} catch (Exception e) {
}
}
// filter the high-frequency bug
int filterCount;
void filterGrid() {
int x, y;
if (sourceCount > 0 && freqBarValue > 23) {
return;
}
if (sourceFreqCount >= 2 && auxBar.getValue() > 23) {
return;
}
if (++filterCount < 10) {
return;
}
filterCount = 0;
for (y = windowOffsetY; y < windowBottom; y++)
for (x = windowOffsetX; x < windowRight; x++) {
int gi = x + y * gw;
if (walls[gi]) {
continue;
}
if (func[gi - 1] < 0 && func[gi] > 0 && func[gi + 1] < 0 && !walls[gi + 1] && !walls[gi - 1]) {
func[gi] = (func[gi - 1] + func[gi + 1]) / 2;
}
if (func[gi - gw] < 0 && func[gi] > 0 && func[gi + gw] < 0 && !walls[gi - gw] && !walls[gi + gw]) {
func[gi] = (func[gi - gw] + func[gi + gw]) / 2;
}
if (func[gi - 1] > 0 && func[gi] < 0 && func[gi + 1] > 0 && !walls[gi + 1] && !walls[gi - 1]) {
func[gi] = (func[gi - 1] + func[gi + 1]) / 2;
}
if (func[gi - gw] > 0 && func[gi] < 0 && func[gi + gw] > 0 && !walls[gi - gw] && !walls[gi + gw]) {
func[gi] = (func[gi - gw] + func[gi + gw]) / 2;
}
}
}
/**************************************************************************
* Draw 3D
*************************************************************************/
double realxmx, realxmy, realymz, realzmy, realzmx, realymadd, realzmadd;
double viewAngle = pi, viewAngleDragStart;
double viewZoom = .775, viewZoomDragStart;
double viewAngleCos = -1, viewAngleSin = 0;
double viewHeight = -38, viewHeightDragStart;
double scalex, scaley;
int centerX3d, centerY3d;
int xpoints[] = new int[4], ypoints[] = new int[4];
final double viewDistance = 66;
void draw3dView() {
int half = gridSizeX / 2;
scaleworld();
int x, y;
int xdir, xstart, xend;
int ydir, ystart, yend;
int sc = windowRight - 1;
// which side render first
if (viewAngleCos > 0) {
ystart = sc;
yend = windowOffsetY - 1;
ydir = -1;
} else {
ystart = windowOffsetY;
yend = sc + 1;
ydir = 1;
}
if (viewAngleSin < 0) {
xstart = windowOffsetX;
xend = sc + 1;
xdir = 1;
} else {
xstart = sc;
xend = windowOffsetX - 1;
xdir = -1;
}
boolean xFirst = (viewAngleSin * xdir < viewAngleCos * ydir);
for (x = 0; x != windowSize.width * windowSize.height; x++) {
pixels[x] = 0xFF000000;
}
double zval = .1;
double zval2 = zval * zval;
for (x = xstart; x != xend; x += xdir) {
for (y = ystart; y != yend; y += ydir) {
if (!xFirst) {
x = xstart;
}
for (; x != xend; x += xdir) {
int gi = x + gw * y;
map3d(x - half, y - half, func[gi], xpoints, ypoints, 0);
map3d(x + 1 - half, y - half, func[gi + 1], xpoints, ypoints, 1);
map3d(x - half, y + 1 - half, func[gi + gw], xpoints, ypoints, 2);
map3d(x + 1 - half, y + 1 - half, func[gi + gw + 1], xpoints, ypoints, 3);
double qx = func[gi + 1] - func[gi];
double qy = func[gi + gw] - func[gi];
// calculate light
double normdot = (qx + qy + zval) * (1 / 1.73) / Math.sqrt(qx * qx + qy * qy + zval2);
int col = computeColor(gi, normdot);
fillTriangle(xpoints[0], ypoints[0], xpoints[1], ypoints[1], xpoints[3], ypoints[3], col);
fillTriangle(xpoints[0], ypoints[0], xpoints[2], ypoints[2], xpoints[3], ypoints[3], col);
if (xFirst) {
break;
}
}
}
if (!xFirst)
break;
}
}
double scaleMult;
void scaleworld() {
scalex = viewZoom * (windowSize.width / 4) * viewDistance / 8;
scaley = -scalex;
int y = (int) (scaley * viewHeight / viewDistance);
centerX3d = windowSize.width / 2;
centerY3d = windowSize.height / 2 - y;
scaleMult = 16. / (windowWidth / 2);
realxmx = -viewAngleCos * scaleMult * scalex;
realxmy = viewAngleSin * scaleMult * scalex;
realymz = -brightMult * scaley;
realzmy = viewAngleCos * scaleMult;
realzmx = viewAngleSin * scaleMult;
realymadd = -viewHeight * scaley;
realzmadd = viewDistance;
}
void map3d(double x, double y, double z, int xpoints[], int ypoints[], int pt) {
double realx = realxmx * x + realxmy * y;
double realy = realymz * z + realymadd;
double realz = realzmx * x + realzmy * y + realzmadd;
xpoints[pt] = centerX3d + (int) (realx / realz);
ypoints[pt] = centerY3d - (int) (realy / realz);
}
int computeColor(int gix, double c) {
double h = func[gix] * brightMult;
if (c < 0) c = 0;
if (c > 1) c = 1;
c = .5 + c * .5;
double redness = (h < 0) ? -h : 0;
double grnness = (h > 0) ? h : 0;
if (redness > 1) redness = 1;
if (grnness > 1) grnness = 1;
if (grnness < 0) grnness = 0;
if (redness < 0) redness = 0;
double grayness = (1 - (redness + grnness)) * c;
double gray = .6;
int bi = (int) ((gray * grayness) * 255);
return 0xFF000000 | bi;
}
void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3, int col) {
if (x1 > x2) {
if (x2 > x3) {
// x1 > x2 > x3
int ay = interp(x1, y1, x3, y3, x2);
fillTriangle1(x3, y3, x2, y2, ay, col);
fillTriangle1(x1, y1, x2, y2, ay, col);
} else if (x1 > x3) {
// x1 > x3 > x2
int ay = interp(x1, y1, x2, y2, x3);
fillTriangle1(x2, y2, x3, y3, ay, col);
fillTriangle1(x1, y1, x3, y3, ay, col);
} else {
// x3 > x1 > x2
int ay = interp(x3, y3, x2, y2, x1);
fillTriangle1(x2, y2, x1, y1, ay, col);
fillTriangle1(x3, y3, x1, y1, ay, col);
}
} else {
if (x1 > x3) {
// x2 > x1 > x3
int ay = interp(x2, y2, x3, y3, x1);
fillTriangle1(x3, y3, x1, y1, ay, col);
fillTriangle1(x2, y2, x1, y1, ay, col);
} else if (x2 > x3) {
// x2 > x3 > x1
int ay = interp(x2, y2, x1, y1, x3);
fillTriangle1(x1, y1, x3, y3, ay, col);
fillTriangle1(x2, y2, x3, y3, ay, col);
} else {
// x3 > x2 > x1
int ay = interp(x3, y3, x1, y1, x2);
fillTriangle1(x1, y1, x2, y2, ay, col);
fillTriangle1(x3, y3, x2, y2, ay, col);
}
}
}
void fillTriangle1(int x1, int y1, int x2, int y2, int y3, int col) {
// x2 == x3
int dir = (x1 > x2) ? -1 : 1;
int x = x1;
if (x < 0) {
x = 0;
if (x2 < 0) {
return;
}
}
if (x >= windowSize.width) {
x = windowSize.width - 1;
if (x2 >= windowSize.width) {
return;
}
}
if (y2 > y3) {
int q = y2;
y2 = y3;
y3 = q;
}
// y2 < y3
while (x != x2 + dir) {
int ya = interp(x1, y1, x2, y2, x);
int yb = interp(x1, y1, x2, y3, x);
if (ya < 0) {
ya = 0;
}
if (yb >= windowSize.height) {
yb = windowSize.height - 1;
}
for (; ya <= yb; ya++) {
pixels[x + ya * windowSize.width] = col;
}
x += dir;
if (x < 0 || x >= windowSize.width) {
return;
}
}
}
int interp(int x1, int y1, int x2, int y2, int x) {
if (x1 == x2) {
return y1;
}
if (x < x1 && x < x2 || x > x1 && x > x2) {
System.out.print("interp out of bounds\n");
}
return (int) (y1 + ((double) x - x1) * (y2 - y1) / (x2 - x1));
}
/**************************************************************************
* ColorScheme Setup
*************************************************************************/
void addDefaultColorScheme() {
decodeColorScheme(0, "#000000 #3333D6 #0000A3 #0000CC #CC0000", "Water");
decodeColorScheme(1, "#800000 #ffffff #ffffff #808080 #CC0000", "Cymatics1: White Plate");
decodeColorScheme(2, "#800000 #000000 #000000 #808080 #CC0000", "Cymatics2: Black Plate");
}
void decodeColorScheme(int cn, String s, String name) {
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
int i;
for (i = 0; i != 5; i++)
schemeColors[cn][i] = Color.decode(st.nextToken());
}
colorChooser.add(name);
}
/**************************************************************************
* WaveSource Setup
*************************************************************************/
abstract class Setup {
abstract String getName();
abstract void select();
void doSetupSources() {
setSources();
}
void deselect() {
}
double sourceStrength() {
return 1;
}
abstract Setup createNext();
void eachFrame() {
}
float calcSourcePhase(double ph, float v, double w) {
return v;
}
};
class SingleSourceSetup extends Setup {
String getName() {
return "1點波源";
}
void select() {
// setFreqBar(15);
}
Setup createNext() {
return new DoubleSourceSetup();
}
}
class DoubleSourceSetup extends Setup {
String getName() {
return "2點波源";
}
void select() {
// setFreqBar(15);
}
void doSetupSources() {
sourceChooser.select(SRC_2S);
setSources();
sources[0].y = gridSizeY / 2 - 8;
sources[1].y = gridSizeY / 2 + 8;
sources[0].x = sources[1].x = gridSizeX / 2;
}
Setup createNext() {
return new QuadrupleSourceSetup();
}
}
class QuadrupleSourceSetup extends Setup {
String getName() {
return "4點波源";
}
void select() {
// setFreqBar(15);
}
void doSetupSources() {
sourceChooser.select(SRC_4S);
setSources();
}
Setup createNext() {
return new PlaneWaveSetup();
}
}
class PlaneWaveSetup extends Setup {
String getName() {
return "1線波源";
}
void select() {
// setFreqBar(15);
}
void doSetupSources() {
sourceChooser.select(SRC_1S_PLANE);
setSources();
}
Setup createNext() {
return new IntersectingPlaneWavesSetup();
}
}
class IntersectingPlaneWavesSetup extends Setup {
String getName() {
return "交錯線波源";
}
void select() {
// setFreqBar(15);
}
void doSetupSources() {
sourceChooser.select(SRC_2S_PLANE);
setSources();
sources[0].y = sources[1].y = windowOffsetY;
sources[0].x = windowOffsetX + 1;
sources[2].x = sources[3].x = windowOffsetX;
sources[2].y = windowOffsetY + 1;
sources[3].y = windowOffsetY + windowHeight - 1;
}
Setup createNext() {
return new DopplerSetup();
}
}
class DopplerSetup extends Setup {
String getName() {
return "都普勒效應";
}
void select() {
// setFreqBar(15);
}
void doSetupSources() {
sourceChooser.select(SRC_1S_MOVING);
setSources();
}
Setup createNext() {
return null;
}
}
/**************************************************************************
* Event
*************************************************************************/
/**************************************************************************
* ComponentEvent
*************************************************************************/
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {
cv.repaint();
}
public void componentResized(ComponentEvent e) {
handleResize();
cv.repaint(100);
}
/**************************************************************************
* ItemEvent
*************************************************************************/
public void itemStateChanged(ItemEvent e) {
if (e.getItemSelectable() == musicChooser) {
doMusic();
}
if (e.getItemSelectable() == sourceChooser) {
if (sourceChooser.getSelectedIndex() != sourceIndex) {
setSources();
}
}
if (e.getItemSelectable() == setupChooser) {
doSetup();
}
if (e.getItemSelectable() == colorChooser) {
doColor();
}
}
void doMusic() {
int musicIndex = musicChooser.getSelectedIndex();
try {
this.doPlaySequencer(musicFolderPath + musicSource[musicIndex]);
} catch (MidiUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidMidiDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void setSources() {
int oldSCount = sourceCount;
boolean oldPlane = sourcePlane;
sourceIndex = sourceChooser.getSelectedIndex();
sourcePlane = (sourceChooser.getSelectedIndex() >= SRC_1S_PLANE && sourceChooser.getSelectedIndex() <= SRC_2S_PLANE );
sourceCount = 1;
sourceFreqCount = 1;
sourceMoving = false;
sourceWaveform = SWF_SIN;
switch (sourceChooser.getSelectedIndex()) {
case 0:
sourceCount = 0;
break;
case 2:
sourceCount = 2;
break;
case 3:
sourceCount = 4;
break;
case 4:
sourceMoving = true;
break;
case 6:
sourceCount = 2;
break;
}
if (sourceMoving) {
auxFunction = AUX_SPEED;
auxBar.setValue(7);
auxLabel.setText("移動速度");
auxLabel.setFont(new Font( "Arial" , Font.BOLD , 40 ));
} else {
auxFunction = AUX_NONE;
auxBar.hide();
auxLabel.hide();
}
if (auxFunction != AUX_NONE) {
auxBar.show();
auxLabel.show();
}
validate();
if (sourcePlane) {
sourceCount *= 2;
if (!(oldPlane && oldSCount == sourceCount)) {
int x2 = windowOffsetX + windowWidth - 1;
int y2 = windowOffsetY + windowHeight - 1;
sources[0] = new OscillationSource(windowOffsetX, windowOffsetY + 1);
sources[1] = new OscillationSource(x2, windowOffsetY + 1);
sources[2] = new OscillationSource(windowOffsetX, y2);
sources[3] = new OscillationSource(x2, y2);
}
} else if (!(!oldPlane && oldSCount == sourceCount)) {
sources[0] = new OscillationSource(gridSizeX / 2, windowOffsetY + 1);
sources[1] = new OscillationSource(gridSizeX / 2, gridSizeY - windowOffsetY - 2);
sources[2] = new OscillationSource(windowOffsetX + 1, gridSizeY / 2);
sources[3] = new OscillationSource(gridSizeX - windowOffsetX - 2, gridSizeY / 2);
for (int i = 4; i < sourceCount; i++) {
sources[i] = new OscillationSource(windowOffsetX + 1 + i * 2, gridSizeY / 2);
}
}
}
void doSetup() {
timeT = 0;
if (resBar.getValue() < 32) {
setResolution(32);
}
doClearWave();
doClearBorder();
// don't use previous source positions, use defaults
sourceCount = -1;
sourceChooser.select(SRC_1S);
setFreqBar(5);
setBrightness(15);
auxBar.setValue(1);
setup = (Setup) setupList.elementAt(setupChooser.getSelectedIndex());
setup.select();
setup.doSetupSources();
calculateExceptions();
}
void setBrightness(int x) {
double m = x / 5.;
m = (Math.log(m) + 5.) * 100;
brightnessBar.setValue((int) m);
}
void doColor() {
int cn = colorChooser.getSelectedIndex();
wallColor = schemeColors[cn][0];
posColor = schemeColors[cn][1];
negColor = schemeColors[cn][2];
zeroColor = schemeColors[cn][3];
sourceColor = schemeColors[cn][4];
}
/**************************************************************************
* ActionEvent
*************************************************************************/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clearWaveButton) {
doClearWave();
cv.repaint();
}
if (e.getSource() == clearBorderButton) {
doClearBorder();
cv.repaint();
}
if (e.getSource() == setBorderButton) {
doSetBorder();
cv.repaint();
}
if (e.getSource() == view3dButton) {
do3dView();
cv.repaint();
}
if (e.getSource() == stopButton) {
doStop();
cv.repaint();
}
}
void doClearWave() {
int x, y;
for (x = 0; x != gridSizeXY; x++) {
func[x] = funci[x] = 1e-10f;
}
}
void doClearBorder() {
int x, y;
for (x = 0; x != gridSizeXY; x++) {
walls[x] = false;
}
calculateExceptions();
}
void doSetBorder() {
int x, y;
for (x = 0; x < gridSizeX; x++) {
setWall(x, windowOffsetY);
setWall(x, windowBottom);
}
for (y = 0; y < gridSizeY; y++) {
setWall(windowOffsetX, y);
setWall(windowRight, y);
}
calculateExceptions();
}
void do3dView() {
is3dView = !is3dView;
if(is3dView) {
view3dButton.setLabel("切2D視角");
} else {
view3dButton.setLabel("切3D視角");
}
}
void doStop() {
isStop = !isStop;
if(isStop) {
stopButton.setLabel("開始");
} else {
stopButton.setLabel("暫停");
}
}
/**************************************************************************
* AdjustmentEvent
*************************************************************************/
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.print(((Scrollbar) e.getSource()).getValue() + "\n");
if (e.getSource() == brightnessBar) {
cv.repaint(0);
}
if (e.getSource() == freqBar) {
setFreq();
}
}
void setFreqBar(int x) {
freqBar.setValue(x);
freqBarValue = x;
freqTimeZero = 0;
}
void setFreq() {
// adjust time zero to maintain continuity in the freq func even though the frequency has changed.
double oldfreq = freqBarValue * freqMult;
freqBarValue = freqBar.getValue();
double newfreq = freqBarValue * freqMult;
freqTimeZero = timeT - oldfreq * (timeT - freqTimeZero) / newfreq; // newfreq * (timeT - freqTimeZero) = oldfreq * (timeT - freqTimeZero);
}
/**************************************************************************
* MouseEvent
*************************************************************************/
void edit(MouseEvent e) {
if (is3dView) {
return;
}
int x = e.getX();
int y = e.getY();
if (selectedSource != -1) {
x = x * windowWidth / windowSize.width;
y = y * windowHeight / windowSize.height;
if (x >= 0 && y >= 0 && x < windowWidth && y < windowHeight) {
sources[selectedSource].x = x + windowOffsetX;
sources[selectedSource].y = y + windowOffsetY;
}
return;
}
if (dragX == x && dragY == y)
editWavePoint(x, y);
else {
// need to draw a line from old x,y to new x,y and
// call editFuncPoint for each point on that line. yuck.
if (abs(y - dragY) > abs(x - dragX)) {
// y difference is greater, so we step along y's from min to max y and calculate x for each step
int x1 = (y < dragY) ? x : dragX;
int y1 = (y < dragY) ? y : dragY;
int x2 = (y > dragY) ? x : dragX;
int y2 = (y > dragY) ? y : dragY;
dragX = x;
dragY = y;
for (y = y1; y <= y2; y++) {
x = x1 + (x2 - x1) * (y - y1) / (y2 - y1);
editWavePoint(x, y);
}
} else {
// x difference is greater, so we step along x's from min to max x and calculate y for each step
int x1 = (x < dragX) ? x : dragX;
int y1 = (x < dragX) ? y : dragY;
int x2 = (x > dragX) ? x : dragX;
int y2 = (x > dragX) ? y : dragY;
dragX = x;
dragY = y;
for (x = x1; x <= x2; x++) {
y = y1 + (y2 - y1) * (x - x1) / (x2 - x1);
editWavePoint(x, y);
}
}
}
}
void editWavePoint(int x, int y) {
int xp = x * windowWidth / windowSize.width + windowOffsetX;
int yp = y * windowHeight / windowSize.height + windowOffsetY;
int gi = xp + yp * gw;
if (!dragSet && !dragClear) {
dragClear = func[gi] > .1;
dragSet = !dragClear;
}
func[gi] = (dragSet) ? 1 : -1;
funci[gi] = 0;
cv.repaint(0);
}
void selectSource(MouseEvent me) {
int x = me.getX();
int y = me.getY();
int i;
for (i = 0; i != sourceCount; i++) {
OscillationSource src = sources[i];
int sx = src.getScreenX();
int sy = src.getScreenY();
int r2 = (sx - x) * (sx - x) + (sy - y) * (sy - y);
if (sourceRadius * sourceRadius > r2) {
selectedSource = i;
return;
}
}
selectedSource = -1;
}
public void mouseDragged(MouseEvent e) {
if (is3dView) {
view3dDrag(e);
}
if (!dragging) {
selectSource(e);
}
dragging = true;
edit(e);
adjustResolution = false;
cv.repaint(0);
}
public void mouseMoved(MouseEvent e) {
if (dragging) {
return;
}
int x = e.getX();
int y = e.getY();
dragStartX = dragX = x;
dragStartY = dragY = y;
viewAngleDragStart = viewAngle;
viewHeightDragStart = viewHeight;
selectSource(e);
if (isStop) {
cv.repaint(0);
}
}
void view3dDrag(MouseEvent e) {
int x = e.getX();
int y = e.getY();
viewAngle = (dragStartX - x) / 40. + viewAngleDragStart;
while (viewAngle < 0) {
viewAngle += 2 * pi;
}
while (viewAngle >= 2 * pi) {
viewAngle -= 2 * pi;
}
viewAngleCos = Math.cos(viewAngle);
viewAngleSin = Math.sin(viewAngle);
viewHeight = (dragStartY - y) / 10. + viewHeightDragStart;
cv.repaint();
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {
dragStartX = -1;
}
public void mousePressed(MouseEvent e) {
adjustResolution = false;
mouseMoved(e);
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == 0) {
return;
}
dragging = true;
edit(e);
}
public void mouseReleased(MouseEvent e) {
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == 0) {
return;
}
dragging = false;
dragSet = dragClear = false;
cv.repaint();
}
/**************************************************************************
* Global Variable Setting Function
*************************************************************************/
void setResolution(int x) {
resBar.setValue(x);
setResolution();
reinit();
}
void setResolution() {
windowWidth = windowHeight = resBar.getValue();
int border = windowWidth / 9;
if (border < 20) {
border = 20;
}
windowOffsetX = windowOffsetY = border;
gridSizeX = windowWidth + windowOffsetX * 2;
gridSizeY = windowHeight + windowOffsetY * 2;
windowBottom = windowOffsetY + windowHeight - 1;
windowRight = windowOffsetX + windowWidth - 1;
}
void setWall(int x, int y) {
walls[x + gw * y] = true;
}
/**************************************************************************
* Global Variable Calculating Function
*************************************************************************/
void calculateExceptions() {
int x, y;
// if walls are in place on border, need to extend that through hidden area to avoid "leaks"
for (x = 0; x != gridSizeX; x++) {
for (y = 0; y < windowOffsetY; y++) {
walls[x + gw * y] = walls[x + gw * windowOffsetY];
walls[x + gw * (gridSizeY - y - 1)] = walls[x + gw * (gridSizeY - windowOffsetY - 1)];
}
}
for (y = 0; y < gridSizeY; y++) {
for (x = 0; x < windowOffsetX; x++) {
walls[x + gw * y] = walls[windowOffsetX + gw * y];
walls[gridSizeX - x - 1 + gw * y] = walls[gridSizeX - windowOffsetX - 1 + gw * y];
}
}
// generate exceptional array, which is useful for doing special handling of elements
for (x = 1; x < gridSizeX - 1; x++) {
for (y = 1; y < gridSizeY - 1; y++) {
int gi = x + gw * y;
exception[gi] = walls[gi - 1] || walls[gi + 1] || walls[gi - gw] || walls[gi + gw] || walls[gi];
}
}
// put some extra exceptions at the corners to ensure tadd2, sinth and etc to get calculated
exception[1 + gw] = exception[gridSizeX - 2 + gw] = exception[1 + (gridSizeY - 2) * gw] = exception[gridSizeX - 2 + (gridSizeY - 2) * gw] = true;
}
/**************************************************************************
* Calculating Function
*************************************************************************/
int abs(int x) {
return x < 0 ? -x : x;
}
int sign(int x) {
return (x < 0) ? -1 : (x == 0) ? 0 : 1;
}
long getTimeMillis() {
try {
Long time = (Long) timerMethod.invoke(null, new Object[] {});
return time.longValue() / timerDiv;
} catch (Exception ee) {
ee.printStackTrace();
return 0;
}
}
/**************************************************************************
* Object OscillationSource
*************************************************************************/
class OscillationSource {
int x;
int y;
float v;
OscillationSource(int xx, int yy) {
x = xx;
y = yy;
}
int getScreenX() {
return ((x - windowOffsetX) * windowSize.width + windowSize.width / 2) / windowWidth;
}
int getScreenY() {
return ((y - windowOffsetY) * windowSize.height + windowSize.height / 2) / windowHeight;
}
};
/**************************************************************************
* MUSIC
*************************************************************************/
String musicFolderPath = "D:\\ICG2014_TERM_PROJECT_MIDI\\";
String [] musicSource = null;
Sequence sequence = null;
Sequencer sequencer = null;
int maxTick;
int musicLength = 0;
double eachTickSec = 0.0;
int musicMult = 4;
String [] musicMainNote = null;
int [][] musicNoteCount = null; // {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}
Long timeMidiStart = new Long(0);
void doCloseSequencer() throws MidiUnavailableException, IOException, InvalidMidiDataException {
if(sequencer != null) {
sequencer.close();
sequencer = null;
}
}
void doCalMusicNoteCount(String filepath) throws InvalidMidiDataException, IOException {
// maxTick
maxTick = Long.valueOf(sequencer.getTickLength()).intValue();
System.out.println(sequencer.getTickLength());
// calculate musicMainNote[]
musicLength = Long.valueOf(sequencer.getMicrosecondLength() / 1000000).intValue();
System.out.println(sequencer.getMicrosecondLength());
eachTickSec = Double.valueOf(musicLength) / Double.valueOf(maxTick);
System.out.println(eachTickSec);
musicMainNote = new String[musicLength * musicMult + 1];
musicNoteCount = new int[musicLength * musicMult + 1][12];
sequence = MidiSystem.getSequence(new File(filepath));
for (Track track : sequence.getTracks()) {
for (int i=0; i < track.size(); i++) {
MidiEvent event = track.get(i);
int currentBase = Double.valueOf(Math.floor(event.getTick() * eachTickSec * musicMult)).intValue();
MidiMessage message = event.getMessage();
if (message instanceof ShortMessage) {
ShortMessage sm = (ShortMessage) message;
int key = sm.getData1();
int note = key % 12;
musicNoteCount[currentBase][note]++;
}
}
}
this.doCalMainNote();
}
void doCalMainNote() {
for(int index = 0; index < musicLength * musicMult; index ++) {
int max = 0;
int maxI = 0;
for(int i = 0; i < musicNoteCount[index].length; i++) {
if(musicNoteCount[index][i] > max) {
max = musicNoteCount[index][i];
maxI = i;
}
}
switch (maxI) { // {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}
case 0:
musicMainNote[index] = "C";
break;
case 1:
musicMainNote[index] = "C#";
break;
case 2:
musicMainNote[index] = "D";
break;
case 3:
musicMainNote[index] = "D#";
break;
case 4:
musicMainNote[index] = "E";
break;
case 5:
musicMainNote[index] = "F";
break;
case 6:
musicMainNote[index] = "F#";
break;
case 7:
musicMainNote[index] = "G";
break;
case 8:
musicMainNote[index] = "G#";
break;
case 9:
musicMainNote[index] = "A";
break;
case 10:
musicMainNote[index] = "A#";
break;
case 11:
musicMainNote[index] = "B";
break;
}
System.out.println(index + ": " + musicMainNote[index]);
}
}
void doPlaySequencer(String filepath) throws MidiUnavailableException, IOException, InvalidMidiDataException { // doPlayMIDI
this.doCloseSequencer();
sequencer = MidiSystem.getSequencer();
// Opens the device, indicating that it should now acquire any
// system resources it requires and become operational.
sequencer.open();
// create a stream from a file
InputStream is = new BufferedInputStream(new FileInputStream(new File(filepath)));
// Sets the current sequence on which the sequencer operates.
// The stream must point to MIDI file data.
sequencer.setSequence(is);
// doCalSequence
this.doCalMusicNoteCount(filepath);
// Starts playback of the MIDI data in the currently loaded sequence.
sequencer.start();
// timeMidiStart
timeMidiStart = getTimeMillis();
}
void setFreqBarByNote(String note) {
// {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}
if(note.equals("C")) {
setFreqBar(1);
} else if(note.equals("C#")) {
setFreqBar(2);
} else if(note.equals("D")) {
setFreqBar(3);
} else if(note.equals("D#")) {
setFreqBar(4);
} else if(note.equals("E")) {
setFreqBar(5);
} else if(note.equals("F")) {
setFreqBar(6);
} else if(note.equals("F#")) {
setFreqBar(7);
} else if(note.equals("G")) {
setFreqBar(8);
} else if(note.equals("G#")) {
setFreqBar(9);
} else if(note.equals("A")) {
setFreqBar(10);
} else if(note.equals("A#")) {
setFreqBar(11);
} else if(note.equals("B")) {
setFreqBar(12);
}
setFreq();
}
} | 54,115 | 0.573261 | 0.550775 | 2,082 | 24.910183 | 22.281948 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.027858 | false | false | 2 |
fe256de15470f848593182c6f9501df28c3096d6 | 34,230,889,410,890 | a13d3a1028eb05d41855b1d0c04f989ca477b31b | /Java/Basic/Annotation/src/com/small/reflect/ReflectorTest06.java | 00edd3c3c510c8c103b1b8b59340e2ba72ca4163 | [
"Apache-2.0"
] | permissive | Yjsmall/codeStudy | https://github.com/Yjsmall/codeStudy | 0c1ae5cc9bc419edb10cb4f63d2286f232c3a62f | 52d983e1444c135008916c6f2562acbd2711689b | refs/heads/main | 2023-02-23T11:53:41.025000 | 2021-01-30T16:42:07 | 2021-01-30T16:42:07 | 334,448,829 | 0 | 0 | Apache-2.0 | false | 2021-01-30T16:34:02 | 2021-01-30T15:44:17 | 2021-01-30T15:44:21 | 2021-01-30T16:34:02 | 0 | 0 | 0 | 0 | null | false | false | package com.small.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* 反编译,获取属性
* @author small
*/
public class ReflectorTest06 {
public static void main(String[] args) throws Exception{
//为了拼接字符串
StringBuilder s = new StringBuilder();
//Class stdClass = Class.forName("com.small.bean.Student");
Class stdClass = Class.forName("java.lang.Thread");
s.append(Modifier.toString(stdClass.getModifiers()) + "class" + stdClass.getSimpleName() + "{\n");
Field[] fields = stdClass.getDeclaredFields();
for(Field field : fields){
s.append("\t");
s.append(Modifier.toString(field.getModifiers()));
s.append(" ");
s.append(field.getType().getSimpleName());
s.append(" ");
s.append(field.getName());
s.append(";\n");
}
s.append("}");
System.out.println(s);
}
}
| UTF-8 | Java | 989 | java | ReflectorTest06.java | Java | [
{
"context": "lang.reflect.Modifier;\n\n/**\n * 反编译,获取属性\n * @author small\n */\npublic class ReflectorTest06 {\n public sta",
"end": 128,
"score": 0.9848880171775818,
"start": 123,
"tag": "USERNAME",
"value": "small"
}
] | null | [] | package com.small.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* 反编译,获取属性
* @author small
*/
public class ReflectorTest06 {
public static void main(String[] args) throws Exception{
//为了拼接字符串
StringBuilder s = new StringBuilder();
//Class stdClass = Class.forName("com.small.bean.Student");
Class stdClass = Class.forName("java.lang.Thread");
s.append(Modifier.toString(stdClass.getModifiers()) + "class" + stdClass.getSimpleName() + "{\n");
Field[] fields = stdClass.getDeclaredFields();
for(Field field : fields){
s.append("\t");
s.append(Modifier.toString(field.getModifiers()));
s.append(" ");
s.append(field.getType().getSimpleName());
s.append(" ");
s.append(field.getName());
s.append(";\n");
}
s.append("}");
System.out.println(s);
}
}
| 989 | 0.578564 | 0.576483 | 36 | 25.694445 | 24.812429 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527778 | false | false | 2 |
d47529cd4fa6e7b9d6389459ac102555b9fff081 | 38,852,274,213,026 | f8b1bbfad0c7408a23b76e2ada8899f31c212a79 | /PasingInsta/CONTROL/KeyWordDBfinder.java | c67041e2453337450faa1dc14d7b6a627dc4ab46 | [] | no_license | rubyou123/FashionInsta | https://github.com/rubyou123/FashionInsta | 4b13338639a1716346cc41780354eb8af8932001 | 8bbd3fa3e92d43d9ba1a7937915aaa93d090939b | refs/heads/develop | 2021-01-10T21:50:45.586000 | 2015-08-20T02:45:28 | 2015-08-20T02:45:28 | 39,673,053 | 0 | 0 | null | false | 2015-07-27T01:41:45 | 2015-07-25T04:53:40 | 2015-07-25T04:53:40 | 2015-07-27T01:41:45 | 0 | 0 | 0 | 0 | null | null | null | package CONTROL;
import DATA.InstaInfoDB;
public class KeyWordDBfinder {
InstaInfoDB instaDB;
public KeyWordDBfinder(String dbName)
{
instaDB = new InstaInfoDB(dbName);
}
public int getCreatedTime(int year, String season, String keyWord)
{
boolean check = true;
check = instaDB.checkKeyWord(year, season, keyWord);
if(check == false)
{
instaDB.insertKeyWord(year, season, keyWord);
System.out.println("======== 최근 마지막 게시글 : 없음 ");
return -1;
}
else
{
int createdTime = instaDB.searchEarlyCreatedTime(keyWord);
System.out.println("======== 최근 마지막 게시글 : " + createdTime);
return createdTime;
}
}
public void closeDB()
{
instaDB.closeDB();
}
}
| UTF-8 | Java | 740 | java | KeyWordDBfinder.java | Java | [] | null | [] | package CONTROL;
import DATA.InstaInfoDB;
public class KeyWordDBfinder {
InstaInfoDB instaDB;
public KeyWordDBfinder(String dbName)
{
instaDB = new InstaInfoDB(dbName);
}
public int getCreatedTime(int year, String season, String keyWord)
{
boolean check = true;
check = instaDB.checkKeyWord(year, season, keyWord);
if(check == false)
{
instaDB.insertKeyWord(year, season, keyWord);
System.out.println("======== 최근 마지막 게시글 : 없음 ");
return -1;
}
else
{
int createdTime = instaDB.searchEarlyCreatedTime(keyWord);
System.out.println("======== 최근 마지막 게시글 : " + createdTime);
return createdTime;
}
}
public void closeDB()
{
instaDB.closeDB();
}
}
| 740 | 0.667614 | 0.666193 | 37 | 18.027027 | 20.656111 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.891892 | false | false | 2 |
6919a43e8090ec0220c2a4e7ba8cf84eb57b4983 | 39,109,972,213,370 | 75e0bc8c8cf24c5ceb1d3d67bf7e76c05aef25b4 | /apt/src/main/java/com/example/GetMsg.java | f1599437899a9048ce8a9ca8e19ada486250d17d | [] | no_license | to686312/Demo | https://github.com/to686312/Demo | 823d32b36cf94806978be80555de86e52fe408fb | 5ec5202a9aaaf847ee6021cd2f0ecc8f10a1dd2f | refs/heads/master | 2021-01-16T23:18:52.123000 | 2017-06-29T02:20:09 | 2017-06-29T02:20:09 | 95,729,728 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 修饰 class等 .CLASS:在class文件中有效(即class保留)
* 对于方法
* 这个注解可以设置两个值。id和name。name是有默认值的,可以不设置
*/
//@Retention(RetentionPolicy.CLASS)
//@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface GetMsg {
int id();
String name() default "default";
}
| UTF-8 | Java | 580 | java | GetMsg.java | Java | [] | null | [] | package com.example;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 修饰 class等 .CLASS:在class文件中有效(即class保留)
* 对于方法
* 这个注解可以设置两个值。id和name。name是有默认值的,可以不设置
*/
//@Retention(RetentionPolicy.CLASS)
//@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface GetMsg {
int id();
String name() default "default";
}
| 580 | 0.765306 | 0.765306 | 21 | 22.333334 | 16.042603 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 2 |
53b67c77b23b7abe4d9ecf2af76e791c42816c74 | 3,410,204,101,085 | c006f1d59e600d12d9f310b6d0fc489411b31b0e | /topen/src/main/java/com/haizhi/sms/topen/MsgSend.java | 960f88c7e811bceb64571c82c7a84a450fe351f0 | [] | no_license | txfan/sms | https://github.com/txfan/sms | 94d924c3d887786f048d0997c57c959c305edf23 | c7e0ff4caeb436e1c7a7eba8f6f438be727057b7 | refs/heads/master | 2016-08-05T14:43:55.104000 | 2014-10-11T10:58:49 | 2014-10-11T10:58:49 | 24,974,442 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.haizhi.sms.topen;
import lombok.extern.slf4j.Slf4j;
import javax.xml.namespace.QName;
import javax.xml.ws.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.4-b01
* Generated source version: 2.2
*/
@Slf4j
@WebServiceClient(name = "MsgSend", targetNamespace = "http://tempuri.org/", wsdlLocation = "http://122.144.130.36:1210/Services/MsgSend.asmx?WSDL")
public class MsgSend extends Service {
private static URL MSGSEND_WSDL_LOCATION;
private static WebServiceException MSGSEND_EXCEPTION;
private static QName MSGSEND_QNAME = new QName("http://tempuri.org/", "MsgSend");
public static void init(String endpoint) {
URL url = null;
WebServiceException e = null;
try {
if (!endpoint.endsWith("/")) {
endpoint += "/";
}
url = new URL(endpoint + "Services/MsgSend.asmx?WSDL");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
MSGSEND_WSDL_LOCATION = url;
MSGSEND_EXCEPTION = e;
}
public MsgSend() {
super(__getWsdlLocation(), MSGSEND_QNAME);
}
public MsgSend(WebServiceFeature... features) {
super(__getWsdlLocation(), MSGSEND_QNAME, features);
}
public MsgSend(URL wsdlLocation) {
super(wsdlLocation, MSGSEND_QNAME);
}
public MsgSend(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, MSGSEND_QNAME, features);
}
public MsgSend(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public MsgSend(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
* @return returns MsgSendSoap
*/
@WebEndpoint(name = "MsgSendSoap")
public MsgSendSoap getMsgSendSoap() {
return super.getPort(new QName("http://tempuri.org/", "MsgSendSoap"), MsgSendSoap.class);
}
/**
* @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return returns MsgSendSoap
*/
@WebEndpoint(name = "MsgSendSoap")
public MsgSendSoap getMsgSendSoap(WebServiceFeature... features) {
return super.getPort(new QName("http://tempuri.org/", "MsgSendSoap"), MsgSendSoap.class, features);
}
private static URL __getWsdlLocation() {
if (MSGSEND_EXCEPTION != null) {
throw MSGSEND_EXCEPTION;
}
return MSGSEND_WSDL_LOCATION;
}
}
| UTF-8 | Java | 2,731 | java | MsgSend.java | Java | [
{
"context": "e = \"http://tempuri.org/\", wsdlLocation = \"http://122.144.130.36:1210/Services/MsgSend.asmx?WSDL\")\npublic class Ms",
"end": 445,
"score": 0.9985750913619995,
"start": 431,
"tag": "IP_ADDRESS",
"value": "122.144.130.36"
}
] | null | [] | package com.haizhi.sms.topen;
import lombok.extern.slf4j.Slf4j;
import javax.xml.namespace.QName;
import javax.xml.ws.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.4-b01
* Generated source version: 2.2
*/
@Slf4j
@WebServiceClient(name = "MsgSend", targetNamespace = "http://tempuri.org/", wsdlLocation = "http://172.16.17.32:1210/Services/MsgSend.asmx?WSDL")
public class MsgSend extends Service {
private static URL MSGSEND_WSDL_LOCATION;
private static WebServiceException MSGSEND_EXCEPTION;
private static QName MSGSEND_QNAME = new QName("http://tempuri.org/", "MsgSend");
public static void init(String endpoint) {
URL url = null;
WebServiceException e = null;
try {
if (!endpoint.endsWith("/")) {
endpoint += "/";
}
url = new URL(endpoint + "Services/MsgSend.asmx?WSDL");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
MSGSEND_WSDL_LOCATION = url;
MSGSEND_EXCEPTION = e;
}
public MsgSend() {
super(__getWsdlLocation(), MSGSEND_QNAME);
}
public MsgSend(WebServiceFeature... features) {
super(__getWsdlLocation(), MSGSEND_QNAME, features);
}
public MsgSend(URL wsdlLocation) {
super(wsdlLocation, MSGSEND_QNAME);
}
public MsgSend(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, MSGSEND_QNAME, features);
}
public MsgSend(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public MsgSend(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
* @return returns MsgSendSoap
*/
@WebEndpoint(name = "MsgSendSoap")
public MsgSendSoap getMsgSendSoap() {
return super.getPort(new QName("http://tempuri.org/", "MsgSendSoap"), MsgSendSoap.class);
}
/**
* @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return returns MsgSendSoap
*/
@WebEndpoint(name = "MsgSendSoap")
public MsgSendSoap getMsgSendSoap(WebServiceFeature... features) {
return super.getPort(new QName("http://tempuri.org/", "MsgSendSoap"), MsgSendSoap.class, features);
}
private static URL __getWsdlLocation() {
if (MSGSEND_EXCEPTION != null) {
throw MSGSEND_EXCEPTION;
}
return MSGSEND_WSDL_LOCATION;
}
}
| 2,729 | 0.652142 | 0.642988 | 88 | 30.03409 | 33.012203 | 193 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 2 |
9c3f20d7c3cc110d66819e68616a38737e9c7b07 | 16,192,026,771,378 | b12959fe0ea4606477f9ba4a6d9b5b8010b5fb6f | /Champlain College - Int. Project (Gregory Desrosiers)/Original Development Files/src/listeners/menuBarListeners/ProgramMenuListener.java | 2d724ed88d6ead587550db43c45d5deed5520624 | [] | no_license | GregPDesSCH/CEGEP-Int.-Project | https://github.com/GregPDesSCH/CEGEP-Int.-Project | 9124a92e4dd56a27a41218445d69a07e9b97e101 | 93e359ba06db08aa9708d62bd1e5a4af5421562b | refs/heads/master | 2021-01-10T17:41:23.916000 | 2015-10-31T00:34:39 | 2015-10-31T00:34:39 | 45,283,224 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Desrosiers Mechanics Teaching Tool
* Program Menu Listener
*
* This is the listener for the Program Menu in all menu bars of this program.
*
* @author Gregory Desrosiers
* @version 1.0 (April 21, 2014 - May 6, 2014)
*
* UPDATE (May 13, 2014) - Description added.
*
* DISCLAIMER: You may use this class at anytime, but be sure to credit me
* first as a programmer.
*
* © 2014 Gregory Desrosiers. All rights reserved.
*/
// Package Location
package listeners.menuBarListeners;
// Resource Packages
import java.awt.event.*;
import javax.swing.*;
// Interaction Class
import programCore.Application;
public class ProgramMenuListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
/*
* The menu is assigned to several menu bars. The listener is kept as
* a separate class than the listeners already assigned to the actions
* for the menu when created.
*/
JMenu menuOfEventTrigger = Application.frame.getJMenuBar().getMenu(0);
// When the user clicks on the button to display the performance utility.
if (e.getSource() == menuOfEventTrigger.getItem(0))
Application.performanceUtility.showDialog();
// When the user clicks on the button to quit the program.
else if (e.getSource() == menuOfEventTrigger.getItem(2))
Application.callingToQuitApplication();
}
}
| WINDOWS-1252 | Java | 1,350 | java | ProgramMenuListener.java | Java | [
{
"context": "u in all menu bars of this program.\n * \n * @author Gregory Desrosiers\n * @version 1.0 (April 21, 2014 - May 6, 2014)\n *",
"end": 183,
"score": 0.9998993277549744,
"start": 165,
"tag": "NAME",
"value": "Gregory Desrosiers"
},
{
"context": "credit me \n * first as a programmer.\n * \n * © 2014 Gregory Desrosiers. All rights reserved.\n */\n\n// Package Location\npa",
"end": 419,
"score": 0.9998974204063416,
"start": 401,
"tag": "NAME",
"value": "Gregory Desrosiers"
}
] | null | [] | /**
* Desrosiers Mechanics Teaching Tool
* Program Menu Listener
*
* This is the listener for the Program Menu in all menu bars of this program.
*
* @author <NAME>
* @version 1.0 (April 21, 2014 - May 6, 2014)
*
* UPDATE (May 13, 2014) - Description added.
*
* DISCLAIMER: You may use this class at anytime, but be sure to credit me
* first as a programmer.
*
* © 2014 <NAME>. All rights reserved.
*/
// Package Location
package listeners.menuBarListeners;
// Resource Packages
import java.awt.event.*;
import javax.swing.*;
// Interaction Class
import programCore.Application;
public class ProgramMenuListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
/*
* The menu is assigned to several menu bars. The listener is kept as
* a separate class than the listeners already assigned to the actions
* for the menu when created.
*/
JMenu menuOfEventTrigger = Application.frame.getJMenuBar().getMenu(0);
// When the user clicks on the button to display the performance utility.
if (e.getSource() == menuOfEventTrigger.getItem(0))
Application.performanceUtility.showDialog();
// When the user clicks on the button to quit the program.
else if (e.getSource() == menuOfEventTrigger.getItem(2))
Application.callingToQuitApplication();
}
}
| 1,326 | 0.727205 | 0.707932 | 47 | 27.702127 | 25.785461 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.93617 | false | false | 2 |
fefb5c08559ff0dae672760d2e7cdbfa3b974c6c | 35,098,472,798,962 | d68d6903b108b5d0c77b69645a0e192ec7b3cc24 | /app/src/main/java/com/rspitaliere/starwarscharacters/activitys/LoginActivity.java | 579031f0dfd7e23a71d810052f1fe89b0f3de9e8 | [] | no_license | rafaspita/StarWarsCharacters | https://github.com/rafaspita/StarWarsCharacters | 0ac888dbb0303e81689717de1ede3ec8c5a22478 | 6abd0736852e04214c80b7f7f9040a0c2e5f3567 | refs/heads/master | 2021-05-09T20:45:52.114000 | 2018-01-25T23:29:40 | 2018-01-25T23:29:40 | 118,705,416 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rspitaliere.starwarscharacters.activitys;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import com.rspitaliere.starwarscharacters.R;
import com.rspitaliere.starwarscharacters.application.MainApplication;
import com.rspitaliere.starwarscharacters.dao.SharedKey;
import com.rspitaliere.starwarscharacters.dao.SharedLocalDAO;
import com.rspitaliere.starwarscharacters.utils.FontUtils;
import com.rspitaliere.starwarscharacters.utils.Validator;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class LoginActivity extends AppCompatActivity {
@BindView(R.id.login_button)
Button button;
@BindView(R.id.login_name)
EditText editText;
@Inject SharedLocalDAO sharedLocalDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
MainApplication.getMyComponent().inject(this);
ButterKnife.bind(this);
setFont();
}
@OnClick(R.id.login_button)
public void saveUserName(){
if (Validator.validateEditTextNotNull(editText, "Nome não informado!")){
sharedLocalDAO.save(SharedKey.USER_NAME_KEY, editText.getText().toString());
goToMainActivity();
}
}
private void goToMainActivity(){
Intent it = new Intent(LoginActivity.this, MainActivity.class);
startActivity(it);
LoginActivity.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
finish();
}
private void setFont(){
editText.setTypeface(FontUtils.fontRegular(this));
button.setTypeface(FontUtils.fontRegular(this));
}
}
| UTF-8 | Java | 1,921 | java | LoginActivity.java | Java | [] | null | [] | package com.rspitaliere.starwarscharacters.activitys;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import com.rspitaliere.starwarscharacters.R;
import com.rspitaliere.starwarscharacters.application.MainApplication;
import com.rspitaliere.starwarscharacters.dao.SharedKey;
import com.rspitaliere.starwarscharacters.dao.SharedLocalDAO;
import com.rspitaliere.starwarscharacters.utils.FontUtils;
import com.rspitaliere.starwarscharacters.utils.Validator;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class LoginActivity extends AppCompatActivity {
@BindView(R.id.login_button)
Button button;
@BindView(R.id.login_name)
EditText editText;
@Inject SharedLocalDAO sharedLocalDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
MainApplication.getMyComponent().inject(this);
ButterKnife.bind(this);
setFont();
}
@OnClick(R.id.login_button)
public void saveUserName(){
if (Validator.validateEditTextNotNull(editText, "Nome não informado!")){
sharedLocalDAO.save(SharedKey.USER_NAME_KEY, editText.getText().toString());
goToMainActivity();
}
}
private void goToMainActivity(){
Intent it = new Intent(LoginActivity.this, MainActivity.class);
startActivity(it);
LoginActivity.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
finish();
}
private void setFont(){
editText.setTypeface(FontUtils.fontRegular(this));
button.setTypeface(FontUtils.fontRegular(this));
}
}
| 1,921 | 0.743229 | 0.742708 | 60 | 31 | 25.532986 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.616667 | false | false | 2 |
6d3442f21b91b4e12403c0a89d415f698b79f7d7 | 11,398,843,252,747 | abbe6a2e936bc08c1320c6aa21866b57ad06331f | /src/orderProcessor/OrderProcessor.java | 909289508a5496824594d0ee00ddce4350b3774f | [] | no_license | NicopandaLim/logistics-application | https://github.com/NicopandaLim/logistics-application | 6183bc6975cd489126ca3d741ecc4a8c18d7700b | 614163afceb324abe3dd16eb5b70a77ab5a0d44b | refs/heads/master | 2020-05-16T06:14:40.374000 | 2019-04-22T17:51:22 | 2019-04-22T17:51:22 | 182,839,152 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package orderProcessor;
import exceptions.*;
import facility.FacilityManager;
import items.ItemManager;
import order.Order;
import order.orderItem.OrderItem;
import shortestPath.ShortestProcessor;
import java.util.*;
public class OrderProcessor {
Order currOrder;
ShortestProcessor sp;
Solution currSolution;
FacilityManager facilityManager;
ItemManager itemManager = ItemManager.getInstance();
public void startToProcess(Order order)
throws NeighborsValidationException, DataValidationException,
NullFacilityException, NullVertexException{
facilityManager = FacilityManager.getInstance();
currOrder = order;
// Initialize current solution
currSolution = new Solution(currOrder.getOrderId(), currOrder.getOrderDay(),
currOrder.getDestination());
//currOrder.print();
for (OrderItem ordItem : currOrder.getOrderItems()){
if(itemManager.IsRealItem(ordItem.getItemId())) {
//If item is real, copy and add to solution.
OrderItem orderItem = new OrderItem(ordItem.getItemId(), ordItem.getQuantity());
currSolution.addItem(orderItem);
//pass the name list to createFacRecord()
List<String> nameList = facilityManager.getIdentifiedFacs(ordItem.getItemId(), currOrder.getDestination());
createFacRecord(nameList, ordItem);
}
}
}
public void createFacRecord(List<String> nameList, OrderItem ordItem)
throws NeighborsValidationException, DataValidationException,
NullFacilityException, NullVertexException{
LogisticsRecord currLogRecord = new LogisticsRecord(ordItem.getItemId(), ordItem.getQuantity());
while(ordItem.getQuantity()>0) {
ArrayList<FacilityRecord> facRecordList = new ArrayList<>();
sp = new ShortestProcessor();
if (!nameList.isEmpty()) {
for (String facility : nameList) {
double procDay;
double DaysToProc;
//the number of item in Identified facility
int processQuantity = facilityManager.getItemQuantity(facility, ordItem.getItemId());
//calculate the shortest path
String Day = sp.getTravelTime(facility, currOrder.getDestination());
double traDay = Double.parseDouble(Day);
//get processing day and days to process
if (processQuantity > ordItem.getQuantity()) {
procDay = facilityManager.checkProcessDay(facility, ordItem.getQuantity(), currOrder.getOrderDay());
DaysToProc = facilityManager.getProcessDays(facility, ordItem.getQuantity(), currOrder.getOrderDay());
} else {
procDay = facilityManager.checkProcessDay(facility, processQuantity, currOrder.getOrderDay());
DaysToProc = facilityManager.getProcessDays(facility, processQuantity, currOrder.getOrderDay());
}
FacilityRecord currRecord = new FacilityRecord(facility, processQuantity, procDay, DaysToProc, traDay);
facRecordList.add(currRecord);
}
} else {
//no facility has this item, Stored as back order in solution
currSolution.addString(Integer.toString(ordItem.getQuantity()) + " of " + ordItem.getItemId() + " is back-order.");
return;
}
//sort List to get the top facility
facRecordList.sort(Comparator.comparing(FacilityRecord::getArrDayInt));
FacilityRecord topRecord = facRecordList.get(0);
processRec(topRecord, ordItem);
currLogRecord.addFacRecord(topRecord);
if(topRecord == facRecordList.get(facRecordList.size()-1)){
currSolution.addString(Integer.toString(ordItem.getQuantity()) + " of "
+ ordItem.getItemId() + " is back-order.");
break;
}else {
//get the new name list
nameList.remove(topRecord.getFacHasItem());
}
}
currSolution.addLogRecord(currLogRecord);
}
public void processRec(FacilityRecord facRecord, OrderItem ordItem)
throws DataValidationException{
if(ordItem.getQuantity() > facRecord.getItemsNumber()){
//reduce quantity in Identified facility
facilityManager.reduceInventory(facRecord.facHasItem, ordItem.getItemId(),
facRecord.getItemsNumber());
//reduce quantity in copied Order
currOrder.decrQuantity(ordItem.getItemId(), facRecord.getItemsNumber());
//update facility Schedule
facilityManager.updateSchedule(facRecord.getFacHasItem(), facRecord.getItemsNumber(),
currOrder.getOrderDay());
}else{
//(ordItem.getQuantity() <= facRecord.getItemsNumber())
facRecord.setItemsNumber(ordItem.getQuantity());
//reduce quantity in Identified facility
facilityManager.reduceInventory(facRecord.facHasItem, ordItem.getItemId(),
ordItem.getQuantity());
//reduce quantity in copied Order
currOrder.decrQuantity(ordItem.getItemId(), ordItem.getQuantity());
//update facility Schedule
facilityManager.updateSchedule(facRecord.getFacHasItem(), facRecord.getItemsNumber(),
currOrder.getOrderDay());
}
}
public Solution getSolution(){
return currSolution;
}
}
| UTF-8 | Java | 5,998 | java | OrderProcessor.java | Java | [] | null | [] | package orderProcessor;
import exceptions.*;
import facility.FacilityManager;
import items.ItemManager;
import order.Order;
import order.orderItem.OrderItem;
import shortestPath.ShortestProcessor;
import java.util.*;
public class OrderProcessor {
Order currOrder;
ShortestProcessor sp;
Solution currSolution;
FacilityManager facilityManager;
ItemManager itemManager = ItemManager.getInstance();
public void startToProcess(Order order)
throws NeighborsValidationException, DataValidationException,
NullFacilityException, NullVertexException{
facilityManager = FacilityManager.getInstance();
currOrder = order;
// Initialize current solution
currSolution = new Solution(currOrder.getOrderId(), currOrder.getOrderDay(),
currOrder.getDestination());
//currOrder.print();
for (OrderItem ordItem : currOrder.getOrderItems()){
if(itemManager.IsRealItem(ordItem.getItemId())) {
//If item is real, copy and add to solution.
OrderItem orderItem = new OrderItem(ordItem.getItemId(), ordItem.getQuantity());
currSolution.addItem(orderItem);
//pass the name list to createFacRecord()
List<String> nameList = facilityManager.getIdentifiedFacs(ordItem.getItemId(), currOrder.getDestination());
createFacRecord(nameList, ordItem);
}
}
}
public void createFacRecord(List<String> nameList, OrderItem ordItem)
throws NeighborsValidationException, DataValidationException,
NullFacilityException, NullVertexException{
LogisticsRecord currLogRecord = new LogisticsRecord(ordItem.getItemId(), ordItem.getQuantity());
while(ordItem.getQuantity()>0) {
ArrayList<FacilityRecord> facRecordList = new ArrayList<>();
sp = new ShortestProcessor();
if (!nameList.isEmpty()) {
for (String facility : nameList) {
double procDay;
double DaysToProc;
//the number of item in Identified facility
int processQuantity = facilityManager.getItemQuantity(facility, ordItem.getItemId());
//calculate the shortest path
String Day = sp.getTravelTime(facility, currOrder.getDestination());
double traDay = Double.parseDouble(Day);
//get processing day and days to process
if (processQuantity > ordItem.getQuantity()) {
procDay = facilityManager.checkProcessDay(facility, ordItem.getQuantity(), currOrder.getOrderDay());
DaysToProc = facilityManager.getProcessDays(facility, ordItem.getQuantity(), currOrder.getOrderDay());
} else {
procDay = facilityManager.checkProcessDay(facility, processQuantity, currOrder.getOrderDay());
DaysToProc = facilityManager.getProcessDays(facility, processQuantity, currOrder.getOrderDay());
}
FacilityRecord currRecord = new FacilityRecord(facility, processQuantity, procDay, DaysToProc, traDay);
facRecordList.add(currRecord);
}
} else {
//no facility has this item, Stored as back order in solution
currSolution.addString(Integer.toString(ordItem.getQuantity()) + " of " + ordItem.getItemId() + " is back-order.");
return;
}
//sort List to get the top facility
facRecordList.sort(Comparator.comparing(FacilityRecord::getArrDayInt));
FacilityRecord topRecord = facRecordList.get(0);
processRec(topRecord, ordItem);
currLogRecord.addFacRecord(topRecord);
if(topRecord == facRecordList.get(facRecordList.size()-1)){
currSolution.addString(Integer.toString(ordItem.getQuantity()) + " of "
+ ordItem.getItemId() + " is back-order.");
break;
}else {
//get the new name list
nameList.remove(topRecord.getFacHasItem());
}
}
currSolution.addLogRecord(currLogRecord);
}
public void processRec(FacilityRecord facRecord, OrderItem ordItem)
throws DataValidationException{
if(ordItem.getQuantity() > facRecord.getItemsNumber()){
//reduce quantity in Identified facility
facilityManager.reduceInventory(facRecord.facHasItem, ordItem.getItemId(),
facRecord.getItemsNumber());
//reduce quantity in copied Order
currOrder.decrQuantity(ordItem.getItemId(), facRecord.getItemsNumber());
//update facility Schedule
facilityManager.updateSchedule(facRecord.getFacHasItem(), facRecord.getItemsNumber(),
currOrder.getOrderDay());
}else{
//(ordItem.getQuantity() <= facRecord.getItemsNumber())
facRecord.setItemsNumber(ordItem.getQuantity());
//reduce quantity in Identified facility
facilityManager.reduceInventory(facRecord.facHasItem, ordItem.getItemId(),
ordItem.getQuantity());
//reduce quantity in copied Order
currOrder.decrQuantity(ordItem.getItemId(), ordItem.getQuantity());
//update facility Schedule
facilityManager.updateSchedule(facRecord.getFacHasItem(), facRecord.getItemsNumber(),
currOrder.getOrderDay());
}
}
public Solution getSolution(){
return currSolution;
}
}
| 5,998 | 0.598366 | 0.597866 | 128 | 44.859375 | 33.896149 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.734375 | false | false | 2 |
e3f41fa0c80419e48b14a80e60fda86bfec81dd6 | 29,892,972,407,623 | c36456a2798e9a3ece56124e3daa975c5fe8cd8c | /app/src/main/java/com/yakgwa/kullow/map/Router.java | a90541082428f8c652f8ed2ae26170448e3644bc | [] | no_license | aeomhs/kullow | https://github.com/aeomhs/kullow | 0df05df98a970b528f7e531e13e486133b60c717 | e4027b1afb2f73f5652faf844a4f8ec31bfd3ff6 | refs/heads/master | 2020-09-07T02:50:30.510000 | 2019-11-15T07:38:14 | 2019-11-15T07:38:14 | 209,968,304 | 0 | 3 | null | false | 2019-09-22T16:11:51 | 2019-09-21T10:46:39 | 2019-09-22T15:50:03 | 2019-09-22T16:11:50 | 152 | 0 | 0 | 0 | Java | false | false | package com.yakgwa.kullow.map;
import android.util.Log;
import androidx.annotation.NonNull;
import com.yakgwa.kullow.map.Path.Path;
import com.yakgwa.kullow.map.Point.Point;
import java.util.List;
import java.util.Stack;
/**
* Router is only one functional module.
* using routing.
*/
public class Router {
private List<Point> allPoints;
private List<Path> allPaths;
private int pointNum;
private boolean[][] graph;
private Stack<Integer> routingStack;
private Route route;
public Router(@NonNull List<Point> allPoints,@NonNull List<Path> allPaths){
this.allPoints = allPoints;
this.allPaths = allPaths;
pointNum = this.allPoints.size();
Log.e("@Point NUM@",String.valueOf(pointNum));
}
public Route getRoute(@NonNull Point src,@NonNull Point dest) {
route = new Route(src);
routingStack = new Stack<>();
// 각 Point 연결 그래프
graph = new boolean[pointNum+1][pointNum+1];
for(Path path : allPaths){
graph[(int)path.getP1Id()][(int)path.getP2Id()] = true;
graph[(int)path.getP2Id()][(int)path.getP1Id()] = true;
}
// visit
routingStack.add((int)src.getPid());
visit((int)src.getPid(), (int)dest.getPid());
return route;
}
private void visit(int visitNode, int targetNode){
// Find Route!
if(visitNode == targetNode){
// _TODO: make route from Stack, if it has min distance, save it._
Stack<Integer> findRoute = (Stack<Integer>) routingStack.clone();
Route newRoute = new Route(allPoints.get(findRoute.pop()-1));
while(!findRoute.empty()){
int pid = findRoute.pop();
// Log.d("ROUTE_STACK", String.valueOf(pid));
newRoute.addPoint(allPoints.get(pid-1));
}
// Log.e("ROUTE", route.getDistanceSrcToDest() + " , " + newRoute.getDistanceSrcToDest());
if(route.getDistanceSrcToDest() == 0 || route.getDistanceSrcToDest() > newRoute.getDistanceSrcToDest()){
route = newRoute;
}
return;
}
/**
* Optimization, 경로 찾는 중 route를 하나 찾았고, route의 getDistanceSrcToDest 보다 크면 더 이상 찾지 않는다.
*/
if(route.getDistanceSrcToDest() != 0 && routingStack.size() > 1){
Stack<Integer> findRoute = (Stack<Integer>) routingStack.clone();
Route newRoute = new Route(allPoints.get(findRoute.pop()-1));
while(!findRoute.empty()){
int pid = findRoute.pop();
newRoute.addPoint(allPoints.get(pid-1));
}
if(newRoute.getDistanceSrcToDest() > route.getDistanceSrcToDest()){
return ;
}
}
// Was not visited
if(!graph[visitNode][0]){
// Visit
graph[visitNode][0] = true;
// Find Neighbor Point
for(int i = 1; i <= pointNum; i++){
if(graph[visitNode][i] || graph[i][visitNode]){
// Log.i("NEIGHBOR_NODE", String.valueOf(i));
register(i, targetNode);
}
}
graph[visitNode][0] = false;
}
}
private void register(int neighborNode, int targetNode){
routingStack.add(neighborNode);
visit(neighborNode, targetNode);
routingStack.pop();
}
}
| UTF-8 | Java | 3,512 | java | Router.java | Java | [] | null | [] | package com.yakgwa.kullow.map;
import android.util.Log;
import androidx.annotation.NonNull;
import com.yakgwa.kullow.map.Path.Path;
import com.yakgwa.kullow.map.Point.Point;
import java.util.List;
import java.util.Stack;
/**
* Router is only one functional module.
* using routing.
*/
public class Router {
private List<Point> allPoints;
private List<Path> allPaths;
private int pointNum;
private boolean[][] graph;
private Stack<Integer> routingStack;
private Route route;
public Router(@NonNull List<Point> allPoints,@NonNull List<Path> allPaths){
this.allPoints = allPoints;
this.allPaths = allPaths;
pointNum = this.allPoints.size();
Log.e("@Point NUM@",String.valueOf(pointNum));
}
public Route getRoute(@NonNull Point src,@NonNull Point dest) {
route = new Route(src);
routingStack = new Stack<>();
// 각 Point 연결 그래프
graph = new boolean[pointNum+1][pointNum+1];
for(Path path : allPaths){
graph[(int)path.getP1Id()][(int)path.getP2Id()] = true;
graph[(int)path.getP2Id()][(int)path.getP1Id()] = true;
}
// visit
routingStack.add((int)src.getPid());
visit((int)src.getPid(), (int)dest.getPid());
return route;
}
private void visit(int visitNode, int targetNode){
// Find Route!
if(visitNode == targetNode){
// _TODO: make route from Stack, if it has min distance, save it._
Stack<Integer> findRoute = (Stack<Integer>) routingStack.clone();
Route newRoute = new Route(allPoints.get(findRoute.pop()-1));
while(!findRoute.empty()){
int pid = findRoute.pop();
// Log.d("ROUTE_STACK", String.valueOf(pid));
newRoute.addPoint(allPoints.get(pid-1));
}
// Log.e("ROUTE", route.getDistanceSrcToDest() + " , " + newRoute.getDistanceSrcToDest());
if(route.getDistanceSrcToDest() == 0 || route.getDistanceSrcToDest() > newRoute.getDistanceSrcToDest()){
route = newRoute;
}
return;
}
/**
* Optimization, 경로 찾는 중 route를 하나 찾았고, route의 getDistanceSrcToDest 보다 크면 더 이상 찾지 않는다.
*/
if(route.getDistanceSrcToDest() != 0 && routingStack.size() > 1){
Stack<Integer> findRoute = (Stack<Integer>) routingStack.clone();
Route newRoute = new Route(allPoints.get(findRoute.pop()-1));
while(!findRoute.empty()){
int pid = findRoute.pop();
newRoute.addPoint(allPoints.get(pid-1));
}
if(newRoute.getDistanceSrcToDest() > route.getDistanceSrcToDest()){
return ;
}
}
// Was not visited
if(!graph[visitNode][0]){
// Visit
graph[visitNode][0] = true;
// Find Neighbor Point
for(int i = 1; i <= pointNum; i++){
if(graph[visitNode][i] || graph[i][visitNode]){
// Log.i("NEIGHBOR_NODE", String.valueOf(i));
register(i, targetNode);
}
}
graph[visitNode][0] = false;
}
}
private void register(int neighborNode, int targetNode){
routingStack.add(neighborNode);
visit(neighborNode, targetNode);
routingStack.pop();
}
}
| 3,512 | 0.563441 | 0.558517 | 113 | 29.548672 | 26.449146 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.59292 | false | false | 2 |
6572f2dbb806aa7bf087f046c5ae4af602521a03 | 29,892,972,405,243 | b1985487107b543ef30f29f6a09fec3c8938c78b | /src/cn/code/LeetCode/char1/TwoSum.java | edf7b26c9e454d13a088c5f7ee67dbdb12685541 | [] | no_license | carrymaniac/Algorithms | https://github.com/carrymaniac/Algorithms | 6db73946f6c9f6f3420b10882c92a97c786e6711 | d6d67c134087b657c0f2aa2ff80bc7145f16b109 | refs/heads/master | 2020-04-29T06:52:34.153000 | 2019-07-24T02:50:07 | 2019-07-24T02:50:07 | 175,933,165 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.code.LeetCode.char1;
/**
* 167. Two Sum II - Input array is sorted (Easy)
* 题目描述:在有序数组中找出两个数,使它们的和为 target。
*
* Input: numbers={2, 7, 11, 15}, target=9
* Output: index1=1, index2=2
*/
public class TwoSum {
public int[] twoSum(int[] numbers,int target){
int i = 0 ;
int j =numbers.length-1;
while(i<j){
int sum = numbers[i]+numbers[j];
if(sum>target){
j--;
}else if(sum<target){
i++;
}else {
return new int[]{i+1,j+1};
}
}
return null;
}
}
| UTF-8 | Java | 661 | java | TwoSum.java | Java | [] | null | [] | package cn.code.LeetCode.char1;
/**
* 167. Two Sum II - Input array is sorted (Easy)
* 题目描述:在有序数组中找出两个数,使它们的和为 target。
*
* Input: numbers={2, 7, 11, 15}, target=9
* Output: index1=1, index2=2
*/
public class TwoSum {
public int[] twoSum(int[] numbers,int target){
int i = 0 ;
int j =numbers.length-1;
while(i<j){
int sum = numbers[i]+numbers[j];
if(sum>target){
j--;
}else if(sum<target){
i++;
}else {
return new int[]{i+1,j+1};
}
}
return null;
}
}
| 661 | 0.476346 | 0.445351 | 26 | 22.576923 | 15.107749 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.576923 | false | false | 2 |
c7db1274680c6ff9153fbe40a630c8d2fa92c485 | 18,184,891,555,623 | 5d2741a66c48cb81a32442291c326176504b121f | /springcloud-app-system/src/main/java/com/jn/system/user/model/SysUserPostAdd.java | 7c69daf71cf458d2dcfaae97226948a96d880f8c | [] | no_license | moutainhigh/jn-springcloud | https://github.com/moutainhigh/jn-springcloud | 52b3213a46c1a1186803c34f5ecdd55572c5930f | 4a4ed682c7ce06383cd53c814622197e4c920a91 | refs/heads/master | 2023-07-12T05:32:25.625000 | 2019-07-02T03:18:48 | 2019-07-02T03:18:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jn.system.user.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* 用户及岗位
* @author: shaobao
* @date: Created on 2018/11/8 9:13
* @version: v1.0
* @modified By:
**/
@ApiModel(value = "SysUserPostAdd",description = "用户及岗位")
public class SysUserPostAdd implements Serializable {
private static final long serialVersionUID = 1144521838334957110L;
@ApiModelProperty("用户id")
private String userId;
@ApiModelProperty("岗位id")
private String postId;
public SysUserPostAdd() {
}
public SysUserPostAdd(String userId, String postId) {
this.userId = userId;
this.postId = postId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
@Override
public String toString() {
return "SysUserPostAdd{" +
"userId='" + userId + '\'' +
", postId='" + postId + '\'' +
'}';
}
}
| UTF-8 | Java | 1,242 | java | SysUserPostAdd.java | Java | [
{
"context": "rt java.io.Serializable;\n\n/**\n * 用户及岗位\n * @author: shaobao\n * @date: Created on 2018/11/8 9:13\n * @version: ",
"end": 186,
"score": 0.9915130734443665,
"start": 179,
"tag": "USERNAME",
"value": "shaobao"
}
] | null | [] | package com.jn.system.user.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* 用户及岗位
* @author: shaobao
* @date: Created on 2018/11/8 9:13
* @version: v1.0
* @modified By:
**/
@ApiModel(value = "SysUserPostAdd",description = "用户及岗位")
public class SysUserPostAdd implements Serializable {
private static final long serialVersionUID = 1144521838334957110L;
@ApiModelProperty("用户id")
private String userId;
@ApiModelProperty("岗位id")
private String postId;
public SysUserPostAdd() {
}
public SysUserPostAdd(String userId, String postId) {
this.userId = userId;
this.postId = postId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
@Override
public String toString() {
return "SysUserPostAdd{" +
"userId='" + userId + '\'' +
", postId='" + postId + '\'' +
'}';
}
}
| 1,242 | 0.614238 | 0.588576 | 54 | 21.370371 | 18.195742 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.314815 | false | false | 2 |
04d07ade3e4c9ce055bfe7bd57edbeae1933f5cc | 6,382,321,425,279 | 20177f33e82e19a215ee2ebc9be83014a15185a1 | /app/src/main/java/com/android/lahuhula/widget/MultiGridLayout.java | a0f035fed9edf12a784db05b58eef1904666fae4 | [] | no_license | DevinScarlet/Lahuhula2 | https://github.com/DevinScarlet/Lahuhula2 | fc08e946883b3e95997a10b2794607ded4e9f613 | ae4e99a2f912e84417f7f6149e50d6cd58e13732 | refs/heads/master | 2021-01-01T19:00:14.017000 | 2017-07-27T02:36:01 | 2017-07-27T02:36:01 | 98,485,707 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.android.lahuhula.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.android.lahuhula.util.ImageUtils;
import com.bumptech.glide.Glide;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by lenovo on 2017/1/3.
*/
public class MultiGridLayout extends LinearLayout {
private static final String TAG = MultiGridLayout.class.getSimpleName();
private static final int DEFAULT_MAX_COLUMNS = 3;
private static final int DEFAULT_GAP = 10;
private int mGap = DEFAULT_GAP;
;
private int mMaxColumns = DEFAULT_MAX_COLUMNS;
private int mRows = 1;
private int mColumns = 2;
private String mOwner;
private ArrayList<String> mImageList = new ArrayList<String>();
private OnItemClickListener mItemClickListener = null;
public interface OnItemClickListener {
public void onItemClick(View v, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mItemClickListener = listener;
}
public MultiGridLayout(Context context) {
super(context);
}
public MultiGridLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MultiGridLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MultiGridLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setMaxColumns(int maxColumns) {
mMaxColumns = maxColumns;
}
public void setDataList(ArrayList<String> resList, String owner) {
mOwner = owner;
mImageList.clear();
mImageList.addAll(resList);
setupView();
calculateColumnRows();
}
private void setupView() {
for (int i = 0; i < mImageList.size() && i < Math.pow(mMaxColumns, 2); i++) {
ImageView iv = new ImageView(getContext());
iv.setId(i);
try {
Glide.with(getContext()).load(new URL(ImageUtils.PICTURE_URL + mOwner + "/" + mImageList.get(i))).thumbnail(0.2f).centerCrop().into(iv);
} catch (MalformedURLException e) {
//
}
iv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(view, view.getId());
}
}
});
addView(iv, generateDefaultLayoutParams());
}
}
public int getDataListSize() {
return mImageList.size();
}
private void calculateColumnRows() {
int length = getDataListSize();
if (length <= 0) {
return;
}
//低于2张图片
if (length <= 2) {
//两列
mColumns = length;
//1行
mRows = 1;
} else {
//大于两张图片
for (int i = 2; i <= mMaxColumns; i++) {
if (Math.pow(i, 2) == length) {
mColumns = mRows = i;
break;
} else if (Math.pow(i, 2) < length) {
mColumns = i;
mRows = length / i + (length % i > 0 ? 1 : 0);
break;
} else {
if (i == mMaxColumns) {
mColumns = mRows = i;
break;
}
}
}
}
Log.d(TAG, "length:" + length + ", mColumns:" + mColumns + ", mRows:" + mRows);
}
private int[] findPosition(int childNum) {
int[] position = new int[2];
for (int i = 0; i < mRows; i++) {
for (int j = 0; j < mColumns; j++) {
if ((i * mColumns + j) == childNum) {
position[0] = i;
position[1] = j;
break;
}
}
}
return position;
}
private void layoutChildrenView(int width) {
int childrenCount = getChildCount();
Log.d(TAG, "layoutChildrenView.childrenCount:" + childrenCount);
if (childrenCount <= 0) {
return;
}
int singleWidth = (width - mGap * (mColumns - 1)) / mColumns;
int singleHeight = singleWidth;
ViewGroup.LayoutParams params = getLayoutParams();
params.height = singleHeight * mRows + mGap * (mRows - 1);
setLayoutParams(params);
for (int i = 0; i < childrenCount; i++) {
ImageView childrenView = (ImageView) getChildAt(i);
int[] position = findPosition(i);
int left = (singleWidth + mGap) * position[1];
int top = (singleHeight + mGap) * position[0];
int right = left + singleWidth;
int bottom = top + singleHeight;
childrenView.layout(left, top, right, bottom);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d(TAG, "onLayout->left:" + l + ", top:" + t + ", right:" + r + ", bottom:" + b);
Log.d(TAG, "onLayout.getChildCount():" + getChildCount());
int width = r - l;
layoutChildrenView(width);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.d(TAG, "onMeasure.getChildCount():" + getChildCount());
final int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
int realWidth = getChildCount() > 1 ? width : width / 2;
setMeasuredDimension(realWidth, realWidth);
}
}
| UTF-8 | Java | 6,028 | java | MultiGridLayout.java | Java | [
{
"context": "RL;\nimport java.util.ArrayList;\n\n/**\n * Created by lenovo on 2017/1/3.\n */\n\npublic class MultiGridLayout ex",
"end": 448,
"score": 0.9995263814926147,
"start": 442,
"tag": "USERNAME",
"value": "lenovo"
}
] | null | [] | package com.android.lahuhula.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.android.lahuhula.util.ImageUtils;
import com.bumptech.glide.Glide;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by lenovo on 2017/1/3.
*/
public class MultiGridLayout extends LinearLayout {
private static final String TAG = MultiGridLayout.class.getSimpleName();
private static final int DEFAULT_MAX_COLUMNS = 3;
private static final int DEFAULT_GAP = 10;
private int mGap = DEFAULT_GAP;
;
private int mMaxColumns = DEFAULT_MAX_COLUMNS;
private int mRows = 1;
private int mColumns = 2;
private String mOwner;
private ArrayList<String> mImageList = new ArrayList<String>();
private OnItemClickListener mItemClickListener = null;
public interface OnItemClickListener {
public void onItemClick(View v, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mItemClickListener = listener;
}
public MultiGridLayout(Context context) {
super(context);
}
public MultiGridLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MultiGridLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MultiGridLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setMaxColumns(int maxColumns) {
mMaxColumns = maxColumns;
}
public void setDataList(ArrayList<String> resList, String owner) {
mOwner = owner;
mImageList.clear();
mImageList.addAll(resList);
setupView();
calculateColumnRows();
}
private void setupView() {
for (int i = 0; i < mImageList.size() && i < Math.pow(mMaxColumns, 2); i++) {
ImageView iv = new ImageView(getContext());
iv.setId(i);
try {
Glide.with(getContext()).load(new URL(ImageUtils.PICTURE_URL + mOwner + "/" + mImageList.get(i))).thumbnail(0.2f).centerCrop().into(iv);
} catch (MalformedURLException e) {
//
}
iv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(view, view.getId());
}
}
});
addView(iv, generateDefaultLayoutParams());
}
}
public int getDataListSize() {
return mImageList.size();
}
private void calculateColumnRows() {
int length = getDataListSize();
if (length <= 0) {
return;
}
//低于2张图片
if (length <= 2) {
//两列
mColumns = length;
//1行
mRows = 1;
} else {
//大于两张图片
for (int i = 2; i <= mMaxColumns; i++) {
if (Math.pow(i, 2) == length) {
mColumns = mRows = i;
break;
} else if (Math.pow(i, 2) < length) {
mColumns = i;
mRows = length / i + (length % i > 0 ? 1 : 0);
break;
} else {
if (i == mMaxColumns) {
mColumns = mRows = i;
break;
}
}
}
}
Log.d(TAG, "length:" + length + ", mColumns:" + mColumns + ", mRows:" + mRows);
}
private int[] findPosition(int childNum) {
int[] position = new int[2];
for (int i = 0; i < mRows; i++) {
for (int j = 0; j < mColumns; j++) {
if ((i * mColumns + j) == childNum) {
position[0] = i;
position[1] = j;
break;
}
}
}
return position;
}
private void layoutChildrenView(int width) {
int childrenCount = getChildCount();
Log.d(TAG, "layoutChildrenView.childrenCount:" + childrenCount);
if (childrenCount <= 0) {
return;
}
int singleWidth = (width - mGap * (mColumns - 1)) / mColumns;
int singleHeight = singleWidth;
ViewGroup.LayoutParams params = getLayoutParams();
params.height = singleHeight * mRows + mGap * (mRows - 1);
setLayoutParams(params);
for (int i = 0; i < childrenCount; i++) {
ImageView childrenView = (ImageView) getChildAt(i);
int[] position = findPosition(i);
int left = (singleWidth + mGap) * position[1];
int top = (singleHeight + mGap) * position[0];
int right = left + singleWidth;
int bottom = top + singleHeight;
childrenView.layout(left, top, right, bottom);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d(TAG, "onLayout->left:" + l + ", top:" + t + ", right:" + r + ", bottom:" + b);
Log.d(TAG, "onLayout.getChildCount():" + getChildCount());
int width = r - l;
layoutChildrenView(width);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.d(TAG, "onMeasure.getChildCount():" + getChildCount());
final int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
int realWidth = getChildCount() > 1 ? width : width / 2;
setMeasuredDimension(realWidth, realWidth);
}
}
| 6,028 | 0.559667 | 0.553167 | 185 | 31.432432 | 25.451534 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.724324 | false | false | 2 |
4b31190a440d4819c781b858cc05f1f6e08af6bb | 644,245,124,386 | 2e5eb0d9be12c7ab57e7c72de91086357c1ff7d1 | /src/lesson2/FahrenheitToCelsius.java | 72aabaa9609111867de6ad44a63816315132e5d5 | [] | no_license | bob302/DUTRep | https://github.com/bob302/DUTRep | 4bb7e0620725caf8b4c1c71268e648181d637e69 | 9c8b11ed73f44e03acd6f149d3117aea53a91ac8 | refs/heads/master | 2021-01-02T12:33:22.697000 | 2020-04-13T15:56:00 | 2020-04-13T15:56:00 | 239,626,805 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lesson2;
import java.util.Scanner;
public class FahrenheitToCelsius {
public static void main(String[] args) {
float fahrenheit, celsius;
Scanner in = new Scanner(System.in);
System.out.println("Введите температуру в градусах Фаренгейта:");
fahrenheit = in.nextInt();
celsius = fahrenheit;
celsius = ((celsius - 32) * 5) / 9;
System.out.println(fahrenheit + " градусов по Фаренгейту = " + celsius + " градусов по Цельсию");
}
}
| UTF-8 | Java | 580 | java | FahrenheitToCelsius.java | Java | [] | null | [] | package lesson2;
import java.util.Scanner;
public class FahrenheitToCelsius {
public static void main(String[] args) {
float fahrenheit, celsius;
Scanner in = new Scanner(System.in);
System.out.println("Введите температуру в градусах Фаренгейта:");
fahrenheit = in.nextInt();
celsius = fahrenheit;
celsius = ((celsius - 32) * 5) / 9;
System.out.println(fahrenheit + " градусов по Фаренгейту = " + celsius + " градусов по Цельсию");
}
}
| 580 | 0.634387 | 0.624506 | 19 | 25.631578 | 27.917568 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 2 |
357530734ecfd32a18cb868f1b5861214ffc3c1f | 27,504,970,629,960 | 9fe5e080d2c75e39d5033cbfcab494c2b9fef16e | /algaworks-jpa2/algaworks-jpa2-locadora-veiculo-web/src/test/java/br/com/jkavdev/algaworks/jpa2/test/criteria/motorista/MotoristaFiltro.java | a110d5b6b4cb161ceeaa8ac9c93bb7d3105a20b4 | [] | no_license | jkavdev/algaworks_cursos | https://github.com/jkavdev/algaworks_cursos | 6d0afa351967e25a1a5af817c85c7c438fb5b848 | 65d0d2f40797ba6599ef4344e0bfa07d36d32b63 | refs/heads/master | 2023-04-17T13:19:14.109000 | 2023-04-04T02:08:49 | 2023-04-04T02:08:49 | 73,874,465 | 0 | 0 | null | false | 2022-12-16T06:31:26 | 2016-11-16T02:12:31 | 2021-09-07T18:58:12 | 2022-12-16T06:31:23 | 1,692 | 0 | 0 | 40 | Java | false | false | package br.com.jkavdev.algaworks.jpa2.test.criteria.motorista;
public class MotoristaFiltro {
private String nome;
private Integer totalAlugueis;
public MotoristaFiltro(String nome, Number totalAlugueis) {
this.nome = nome;
this.totalAlugueis = Integer.valueOf(totalAlugueis.intValue());
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Integer getTotalAlugueis() {
return totalAlugueis;
}
public void setTotalAlugueis(Integer totalAlugueis) {
this.totalAlugueis = totalAlugueis;
}
}
| UTF-8 | Java | 572 | java | MotoristaFiltro.java | Java | [] | null | [] | package br.com.jkavdev.algaworks.jpa2.test.criteria.motorista;
public class MotoristaFiltro {
private String nome;
private Integer totalAlugueis;
public MotoristaFiltro(String nome, Number totalAlugueis) {
this.nome = nome;
this.totalAlugueis = Integer.valueOf(totalAlugueis.intValue());
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Integer getTotalAlugueis() {
return totalAlugueis;
}
public void setTotalAlugueis(Integer totalAlugueis) {
this.totalAlugueis = totalAlugueis;
}
}
| 572 | 0.75 | 0.748252 | 29 | 18.724138 | 20.971075 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.172414 | false | false | 2 |
429e4535812bbc521e58529aa477eeab26c7cdb2 | 9,612,136,844,337 | 5461f7e402254fdaf039c35ef7c3093ad6ff77b2 | /src/org/model/Teacher.java | 2690e7567d45f46fb4f365032eaf6bc20654abd9 | [] | no_license | httv52/PaperManager | https://github.com/httv52/PaperManager | 7e7db27831529b04dc4af5a9ceeb34bd192e9bb6 | b39d17de41262b20ce25a6f28701b1b16775dbd2 | refs/heads/master | 2021-07-13T02:32:45.999000 | 2017-10-11T00:45:00 | 2017-10-11T00:45:00 | 106,481,218 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.model;
public class Teacher {
private int teacherNo;
private String teacherName;
private String teacherPassword;
private int departmentNo;
private String tel;
private String content;
private int paperNumber;
private int paperAuNumber;
private String departmentName;
private String departmentTel;
public int getTeacherNo() {
return teacherNo;
}
public void setTeacherNo(int teacherNo) {
this.teacherNo = teacherNo;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public String getTeacherPassword() {
return teacherPassword;
}
public void setTeacherPassword(String teacherPassword) {
this.teacherPassword = teacherPassword;
}
public int getDepartmentNo() {
return departmentNo;
}
public void setDepartmentNo(int departmentNo) {
this.departmentNo = departmentNo;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getPaperNumber() {
return paperNumber;
}
public void setPaperNumber(int paperNumber) {
this.paperNumber = paperNumber;
}
public int getPaperAuNumber() {
return paperAuNumber;
}
public void setPaperAuNumber(int paperAuNumber) {
this.paperAuNumber = paperAuNumber;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getDepartmentTel() {
return departmentTel;
}
public void setDepartmentTel(String departmentTel) {
this.departmentTel = departmentTel;
}
}
| UTF-8 | Java | 1,749 | java | Teacher.java | Java | [
{
"context": "String teacherPassword) {\n\t\tthis.teacherPassword = teacherPassword;\n\t}\n\tpublic int getDepartmentNo() {\n\t\tret",
"end": 752,
"score": 0.5037521123886108,
"start": 745,
"tag": "PASSWORD",
"value": "teacher"
}
] | null | [] | package org.model;
public class Teacher {
private int teacherNo;
private String teacherName;
private String teacherPassword;
private int departmentNo;
private String tel;
private String content;
private int paperNumber;
private int paperAuNumber;
private String departmentName;
private String departmentTel;
public int getTeacherNo() {
return teacherNo;
}
public void setTeacherNo(int teacherNo) {
this.teacherNo = teacherNo;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public String getTeacherPassword() {
return teacherPassword;
}
public void setTeacherPassword(String teacherPassword) {
this.teacherPassword = <PASSWORD>Password;
}
public int getDepartmentNo() {
return departmentNo;
}
public void setDepartmentNo(int departmentNo) {
this.departmentNo = departmentNo;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getPaperNumber() {
return paperNumber;
}
public void setPaperNumber(int paperNumber) {
this.paperNumber = paperNumber;
}
public int getPaperAuNumber() {
return paperAuNumber;
}
public void setPaperAuNumber(int paperAuNumber) {
this.paperAuNumber = paperAuNumber;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getDepartmentTel() {
return departmentTel;
}
public void setDepartmentTel(String departmentTel) {
this.departmentTel = departmentTel;
}
}
| 1,752 | 0.756432 | 0.756432 | 76 | 22.013159 | 16.165667 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.618421 | false | false | 2 |
2905471621c0e5eb9fdf47790567c1cc6f9cf8cd | 6,811,818,174,448 | ea0725c08a78222f11fcd7373e58c428fe1f3fc0 | /src/main/java/com/xh/examination/service/impl/AssessmentServiceImpl.java | 121c532bcdf016a4f46568aa0cdf1afa9a1f0b93 | [] | no_license | carbule-bar/examination | https://github.com/carbule-bar/examination | c5c43582d78c6461121d6e033be5bc44b3de3f35 | bf300075dd703ce6b77d5fc98d63dba6fc1bfed9 | refs/heads/master | 2020-08-31T09:06:05.853000 | 2019-10-31T01:10:19 | 2019-10-31T01:10:19 | 218,655,324 | 0 | 0 | null | false | 2020-10-13T17:06:55 | 2019-10-31T00:58:15 | 2019-10-31T01:10:22 | 2020-10-13T17:06:53 | 13,525 | 0 | 0 | 4 | JavaScript | false | false | package com.xh.examination.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xh.examination.dto.CalcaulateList;
import com.xh.examination.mapper.TbAssessmentMapper;
import com.xh.examination.mapper.TbTeacherMapper;
import com.xh.examination.pojo.*;
import com.xh.examination.service.AssessmentService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* 服务实现层
*
* @author Administrator
*/
@Service
public class AssessmentServiceImpl implements AssessmentService {
@Autowired
private TbAssessmentMapper assessmentMapper;
@Autowired
private TbTeacherMapper tbTeacherMapper;
@Autowired
private AdminServiceImpl adminService;
/**
* 查询全部
*/
@Override
public List<TbAssessment> findAll() {
return assessmentMapper.selectByExample(null);
}
/**
* 按分页查询
*/
// @Override
// public PageResult findPage(int pageNum, int pageSize) {
// PageHelper.startPage(pageNum, pageSize);
//
// Page<TbAssessment> page = (Page<TbAssessment>) assessmentMapper.selectByExample(null);
//
// return new PageResult(page.getTotal(), page.getResult());
// }
@Override
public PageResult findPage(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
Page<TbAssessment> page = (Page<TbAssessment>) assessmentMapper.selectByExample(null);
return new PageResult(page.getTotal(), page.getResult());
}
/**
* 增加
*/
@Override
public void add(TbAssessment assessment) {
try {
if(assessment !=null){
//设置管理员id
TbAdmin tbAdmin = adminService.selectAdminByName(SecurityUtils.getSubject().getPrincipal().toString());
assessment.setManagerId(tbAdmin.getId().intValue());
//设置创建时间
assessment.setCreatetime(new Date());
//解析值
parseParam(assessment);
}
assessmentMapper.insert(assessment);
}catch (Exception e){
e.printStackTrace();
}
}
private void parseParam(TbAssessment assessment){
if (assessment.getAttendance() == null) {
assessment.setAttendance(0f);
}
if (assessment.getSatisfaction() == null) {
assessment.setSatisfaction(0f);
}
if (assessment.getWorkCollect() == null) {
assessment.setWorkCollect(0f);
}
if (assessment.getClassControl() == null) {
assessment.setClassControl(0f);
}
if (assessment.getTeachingAccident() == null) {
assessment.setTeachingAccident(0f);
}
if (assessment.getCoursesTaught() == null) {
assessment.setCoursesTaught(0f);
}
if (assessment.getCloudClassroom() == null) {
assessment.setCloudClassroom(0f);
}
if (assessment.getProjectDevelopment() == null) {
assessment.setProjectDevelopment(0f);
}
if (assessment.getTeachingLog() == null) {
assessment.setTeachingLog(0f);
}
if (assessment.getPassRate() == null) {
assessment.setPassRate(0f);
}
if (assessment.getFinalReply() == null) {
assessment.setFinalReply(0f);
}
if (assessment.getAdditionalPoints() == null) {
assessment.setAdditionalPoints(0f);
}
}
/**
* 修改
*/
@Override
public void update(TbAssessment assessment) {
assessment.setCreatetime(new Date());
parseParam(assessment);
assessmentMapper.updateByPrimaryKey(assessment);
}
/**
* 根据ID获取实体
*
* @param id
* @return
*/
@Override
public TbAssessment findOne(Long id) {
return assessmentMapper.selectByPrimaryKey(id);
}
/**
* 批量删除
*/
@Override
public void delete(Long[] ids) {
for (Long id : ids) {
assessmentMapper.deleteByPrimaryKey(id);
}
}
@Override
public PageResult findPage(TbAssessment assessment, int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
TbAssessmentExample example = new TbAssessmentExample();
TbAssessmentExample.Criteria criteria = example.createCriteria();
if (assessment != null) {
if(assessment.getTeacherId()!=null){
criteria.andTeacherIdEqualTo(assessment.getTeacherId());
}
}
example.setOrderByClause("createtime desc");
Page<TbAssessment> page = (Page<TbAssessment>) assessmentMapper.selectByExample(example);
return new PageResult(page.getTotal(), page.getResult());
}
@Override
public PageResult findTeacherScorePage(TbAssessment assessment, int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
TbAssessmentExample example = new TbAssessmentExample();
TbAssessmentExample.Criteria criteria = example.createCriteria();
example.setOrderByClause("createtime desc");
if (assessment != null) {
if(assessment.getTeacherId()!=null){
criteria.andTeacherIdEqualTo(assessment.getTeacherId());
}
}
Page<TbAssessment> page = (Page<TbAssessment>)assessmentMapper.selectByExample(example);
return new PageResult(page.getTotal(), page.getResult());
}
@Override
public CalcaulateList totalScore(Long id) {
List<TbAssessment> calculates = assessmentMapper.totalScore(id);
float count = 0;
for (int i = 0 ;i < calculates.size();i++){
count +=calculates.get(i).getAttendance();
count +=calculates.get(i).getSatisfaction();
count +=calculates.get(i).getWorkCollect();
count +=calculates.get(i).getClassControl();
count +=calculates.get(i).getTeachingAccident();
count +=calculates.get(i).getCoursesTaught();
count +=calculates.get(i).getCloudClassroom();
count +=calculates.get(i).getProjectDevelopment();
count +=calculates.get(i).getTeachingLog();
count +=calculates.get(i).getPassRate();
count +=calculates.get(i).getFinalReply();
count +=calculates.get(i).getAdditionalPoints();
}
CalcaulateList calcaulateList = new CalcaulateList();
calcaulateList.setCalculates(calculates);
calcaulateList.setScore(count);
calcaulateList.setTbTeacher(tbTeacherMapper.selectByPrimaryKey(id));
return calcaulateList;
}
@Override
public PageResult findPage(TbAssessmentCustom assessmentCustom, int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
// 如果检索条件内教师姓名和教师工号同时存在时 以教师工号优先
username:if (assessmentCustom.getUsername() != null) {
if (assessmentCustom.getTeacherId() != null) {
break username;
}
Page<TbAssessmentCustom> customPage = (Page<TbAssessmentCustom>) assessmentMapper.selectTbAssessmentCustom(assessmentCustom);
return new PageResult(customPage.getTotal(), customPage.getResult());
}
TbAssessmentExample example = new TbAssessmentExample();
TbAssessmentExample.Criteria criteria = example.createCriteria();
if (assessmentCustom != null) {
if(assessmentCustom.getTeacherId()!=null){
criteria.andTeacherIdEqualTo(assessmentCustom.getTeacherId());
}
if (assessmentCustom.getCreatetime() != null) {
criteria.andCreatetimeGreaterThanOrEqualTo(assessmentCustom.getCreatetime());
}
}
example.setOrderByClause("createtime desc");
Page<TbAssessment> page = (Page<TbAssessment>) assessmentMapper.selectByExample(example);
return new PageResult(page.getTotal(), page.getResult());
}
}
| UTF-8 | Java | 8,267 | java | AssessmentServiceImpl.java | Java | [
{
"context": "mport java.util.List;\n\n\n/**\n * 服务实现层\n *\n * @author Administrator\n */\n@Service\npublic class AssessmentServiceImpl i",
"end": 592,
"score": 0.7786822319030762,
"start": 579,
"tag": "USERNAME",
"value": "Administrator"
}
] | null | [] | package com.xh.examination.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xh.examination.dto.CalcaulateList;
import com.xh.examination.mapper.TbAssessmentMapper;
import com.xh.examination.mapper.TbTeacherMapper;
import com.xh.examination.pojo.*;
import com.xh.examination.service.AssessmentService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* 服务实现层
*
* @author Administrator
*/
@Service
public class AssessmentServiceImpl implements AssessmentService {
@Autowired
private TbAssessmentMapper assessmentMapper;
@Autowired
private TbTeacherMapper tbTeacherMapper;
@Autowired
private AdminServiceImpl adminService;
/**
* 查询全部
*/
@Override
public List<TbAssessment> findAll() {
return assessmentMapper.selectByExample(null);
}
/**
* 按分页查询
*/
// @Override
// public PageResult findPage(int pageNum, int pageSize) {
// PageHelper.startPage(pageNum, pageSize);
//
// Page<TbAssessment> page = (Page<TbAssessment>) assessmentMapper.selectByExample(null);
//
// return new PageResult(page.getTotal(), page.getResult());
// }
@Override
public PageResult findPage(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
Page<TbAssessment> page = (Page<TbAssessment>) assessmentMapper.selectByExample(null);
return new PageResult(page.getTotal(), page.getResult());
}
/**
* 增加
*/
@Override
public void add(TbAssessment assessment) {
try {
if(assessment !=null){
//设置管理员id
TbAdmin tbAdmin = adminService.selectAdminByName(SecurityUtils.getSubject().getPrincipal().toString());
assessment.setManagerId(tbAdmin.getId().intValue());
//设置创建时间
assessment.setCreatetime(new Date());
//解析值
parseParam(assessment);
}
assessmentMapper.insert(assessment);
}catch (Exception e){
e.printStackTrace();
}
}
private void parseParam(TbAssessment assessment){
if (assessment.getAttendance() == null) {
assessment.setAttendance(0f);
}
if (assessment.getSatisfaction() == null) {
assessment.setSatisfaction(0f);
}
if (assessment.getWorkCollect() == null) {
assessment.setWorkCollect(0f);
}
if (assessment.getClassControl() == null) {
assessment.setClassControl(0f);
}
if (assessment.getTeachingAccident() == null) {
assessment.setTeachingAccident(0f);
}
if (assessment.getCoursesTaught() == null) {
assessment.setCoursesTaught(0f);
}
if (assessment.getCloudClassroom() == null) {
assessment.setCloudClassroom(0f);
}
if (assessment.getProjectDevelopment() == null) {
assessment.setProjectDevelopment(0f);
}
if (assessment.getTeachingLog() == null) {
assessment.setTeachingLog(0f);
}
if (assessment.getPassRate() == null) {
assessment.setPassRate(0f);
}
if (assessment.getFinalReply() == null) {
assessment.setFinalReply(0f);
}
if (assessment.getAdditionalPoints() == null) {
assessment.setAdditionalPoints(0f);
}
}
/**
* 修改
*/
@Override
public void update(TbAssessment assessment) {
assessment.setCreatetime(new Date());
parseParam(assessment);
assessmentMapper.updateByPrimaryKey(assessment);
}
/**
* 根据ID获取实体
*
* @param id
* @return
*/
@Override
public TbAssessment findOne(Long id) {
return assessmentMapper.selectByPrimaryKey(id);
}
/**
* 批量删除
*/
@Override
public void delete(Long[] ids) {
for (Long id : ids) {
assessmentMapper.deleteByPrimaryKey(id);
}
}
@Override
public PageResult findPage(TbAssessment assessment, int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
TbAssessmentExample example = new TbAssessmentExample();
TbAssessmentExample.Criteria criteria = example.createCriteria();
if (assessment != null) {
if(assessment.getTeacherId()!=null){
criteria.andTeacherIdEqualTo(assessment.getTeacherId());
}
}
example.setOrderByClause("createtime desc");
Page<TbAssessment> page = (Page<TbAssessment>) assessmentMapper.selectByExample(example);
return new PageResult(page.getTotal(), page.getResult());
}
@Override
public PageResult findTeacherScorePage(TbAssessment assessment, int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
TbAssessmentExample example = new TbAssessmentExample();
TbAssessmentExample.Criteria criteria = example.createCriteria();
example.setOrderByClause("createtime desc");
if (assessment != null) {
if(assessment.getTeacherId()!=null){
criteria.andTeacherIdEqualTo(assessment.getTeacherId());
}
}
Page<TbAssessment> page = (Page<TbAssessment>)assessmentMapper.selectByExample(example);
return new PageResult(page.getTotal(), page.getResult());
}
@Override
public CalcaulateList totalScore(Long id) {
List<TbAssessment> calculates = assessmentMapper.totalScore(id);
float count = 0;
for (int i = 0 ;i < calculates.size();i++){
count +=calculates.get(i).getAttendance();
count +=calculates.get(i).getSatisfaction();
count +=calculates.get(i).getWorkCollect();
count +=calculates.get(i).getClassControl();
count +=calculates.get(i).getTeachingAccident();
count +=calculates.get(i).getCoursesTaught();
count +=calculates.get(i).getCloudClassroom();
count +=calculates.get(i).getProjectDevelopment();
count +=calculates.get(i).getTeachingLog();
count +=calculates.get(i).getPassRate();
count +=calculates.get(i).getFinalReply();
count +=calculates.get(i).getAdditionalPoints();
}
CalcaulateList calcaulateList = new CalcaulateList();
calcaulateList.setCalculates(calculates);
calcaulateList.setScore(count);
calcaulateList.setTbTeacher(tbTeacherMapper.selectByPrimaryKey(id));
return calcaulateList;
}
@Override
public PageResult findPage(TbAssessmentCustom assessmentCustom, int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
// 如果检索条件内教师姓名和教师工号同时存在时 以教师工号优先
username:if (assessmentCustom.getUsername() != null) {
if (assessmentCustom.getTeacherId() != null) {
break username;
}
Page<TbAssessmentCustom> customPage = (Page<TbAssessmentCustom>) assessmentMapper.selectTbAssessmentCustom(assessmentCustom);
return new PageResult(customPage.getTotal(), customPage.getResult());
}
TbAssessmentExample example = new TbAssessmentExample();
TbAssessmentExample.Criteria criteria = example.createCriteria();
if (assessmentCustom != null) {
if(assessmentCustom.getTeacherId()!=null){
criteria.andTeacherIdEqualTo(assessmentCustom.getTeacherId());
}
if (assessmentCustom.getCreatetime() != null) {
criteria.andCreatetimeGreaterThanOrEqualTo(assessmentCustom.getCreatetime());
}
}
example.setOrderByClause("createtime desc");
Page<TbAssessment> page = (Page<TbAssessment>) assessmentMapper.selectByExample(example);
return new PageResult(page.getTotal(), page.getResult());
}
}
| 8,267 | 0.631844 | 0.630122 | 241 | 32.721992 | 27.572189 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.460581 | false | false | 2 |
8bae52c2af9f451135cc64a3740910f3de5b858a | 27,857,157,917,193 | 09ed09135e4a41c82cd2cb2a28e22a07de9483cb | /src/com/kiran/common/ProblemSolver.java | 66b573a81bc911e21c8301abe742ec43654f1410 | [] | no_license | rkiranchowdhary/projecteuler | https://github.com/rkiranchowdhary/projecteuler | bb914524df9f3b13275ce7bb291df473aeabf342 | 9139a8721b57e7d0c3fb8e5d3f31dc28456d56b0 | refs/heads/master | 2020-06-14T21:19:17.510000 | 2017-07-26T14:39:00 | 2017-07-26T14:39:00 | 75,409,988 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kiran.common;
import java.util.List;
import com.kiran.project.euler.Problem;
public class ProblemSolver {
public static void solve(Problem problem){
problem.start();
}
public static void solveAll(List<Problem> problems){
for(Problem problem:problems){
solve(problem);
}
}
}
| UTF-8 | Java | 303 | java | ProblemSolver.java | Java | [] | null | [] | package com.kiran.common;
import java.util.List;
import com.kiran.project.euler.Problem;
public class ProblemSolver {
public static void solve(Problem problem){
problem.start();
}
public static void solveAll(List<Problem> problems){
for(Problem problem:problems){
solve(problem);
}
}
}
| 303 | 0.735974 | 0.735974 | 17 | 16.82353 | 17.064705 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.058824 | false | false | 2 |
46f44b376c5ee8474de86a0d623abe73f53dda30 | 3,667,902,114,815 | bd4de51c2c19f7371503bc302c0b7d49c6bce02d | /GoJack/src/ciopper90/gojack/Generali.java | 665fd187d2286bcf07b657e8a440ea669fe49763 | [] | no_license | Git-Host/gojack | https://github.com/Git-Host/gojack | 8b1b647e0896bdd3d56f626598da67a2d863af68 | 5a386ba4fd1b787d847bbbe683ec01f5c66afa70 | refs/heads/master | 2021-01-10T17:43:29.852000 | 2013-03-04T19:18:59 | 2013-03-04T19:18:59 | 43,601,211 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ciopper90.gojack;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
public class Generali extends Activity{
private SharedPreferences prefs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.setting_2);
setContentView(R.layout.setting);
prefs=this.getSharedPreferences("Setting", Context.MODE_PRIVATE);
int stat = prefs.getInt("lastnum",0);
final CheckBox c=(CheckBox)findViewById(R.id.checkBox1);
if(stat==1)
c.setChecked(true);
else
c.setChecked(false);
c.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
SharedPreferences.Editor editor = prefs.edit();
if(c.isChecked())
editor.putInt("lastnum", 1);
else
editor.putInt("lastnum", 0);
editor.commit();
//Toast.makeText(getApplicationContext(), "Salvate Impostazioni", Toast.LENGTH_SHORT).show();
//finish();
}
});
stat = prefs.getInt("salvasmsinviati",0);
final CheckBox d=(CheckBox)findViewById(R.id.checkBox2);
if(stat==1)
d.setChecked(true);
else
d.setChecked(false);
d.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
SharedPreferences.Editor editor = prefs.edit();
if(d.isChecked())
editor.putInt("salvasmsinviati", 1);
else
editor.putInt("salvasmsinviati", 0);
editor.commit();
//Toast.makeText(getApplicationContext(), "Salvate Impostazioni", Toast.LENGTH_SHORT).show();
//finish();
}
});
}
}
| UTF-8 | Java | 1,766 | java | Generali.java | Java | [
{
"context": "package ciopper90.gojack;\r\n\r\nimport android.app.Activity;\r\nimport a",
"end": 17,
"score": 0.9895004034042358,
"start": 8,
"tag": "USERNAME",
"value": "ciopper90"
}
] | null | [] | package ciopper90.gojack;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
public class Generali extends Activity{
private SharedPreferences prefs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.setting_2);
setContentView(R.layout.setting);
prefs=this.getSharedPreferences("Setting", Context.MODE_PRIVATE);
int stat = prefs.getInt("lastnum",0);
final CheckBox c=(CheckBox)findViewById(R.id.checkBox1);
if(stat==1)
c.setChecked(true);
else
c.setChecked(false);
c.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
SharedPreferences.Editor editor = prefs.edit();
if(c.isChecked())
editor.putInt("lastnum", 1);
else
editor.putInt("lastnum", 0);
editor.commit();
//Toast.makeText(getApplicationContext(), "Salvate Impostazioni", Toast.LENGTH_SHORT).show();
//finish();
}
});
stat = prefs.getInt("salvasmsinviati",0);
final CheckBox d=(CheckBox)findViewById(R.id.checkBox2);
if(stat==1)
d.setChecked(true);
else
d.setChecked(false);
d.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
SharedPreferences.Editor editor = prefs.edit();
if(d.isChecked())
editor.putInt("salvasmsinviati", 1);
else
editor.putInt("salvasmsinviati", 0);
editor.commit();
//Toast.makeText(getApplicationContext(), "Salvate Impostazioni", Toast.LENGTH_SHORT).show();
//finish();
}
});
}
}
| 1,766 | 0.689694 | 0.6812 | 61 | 26.950819 | 21.893503 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.901639 | false | false | 2 |
640c2361d9e50dba82f7b6b9b61baac82eb4f0c2 | 3,667,902,115,327 | 5e9acabe5e14d846d46342d4d9907a8ba2623013 | /src/main/java/com/ly/daoImpl/OrderItemDaoImpl.java | 726f6fd08c20cec8b0533ce4ed19fdfbb5455778 | [] | no_license | bys-levi-lu/luyang | https://github.com/bys-levi-lu/luyang | 11fc76ecb62460c711e2b204af5be161b64a1437 | 3d73479741383cd28de1615886dda920be39dca5 | refs/heads/master | 2016-09-06T14:23:21.700000 | 2015-04-11T08:47:22 | 2015-04-11T08:47:22 | 32,446,516 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Author:Administrator
* Create time:下午2:11:04
*/
package com.ly.daoImpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.ly.dao.OrderItemDao;
import com.ly.framework.QueryPageInfo;
import com.ly.framework.db.DataProccessor;
import com.ly.framework.db.JdbcSupport;
import com.ly.model.OrderItemModel;
/**
* @author Administrator
*
*/
@Repository
public class OrderItemDaoImpl extends JdbcSupport implements OrderItemDao, DataProccessor<OrderItemModel>
{
public static final String SELECTSQL = "SELECT ORDER_NO, ORDER_DESC, ORDER_ADDRESS, ORDER_PHONE FROM ORDER_ITEM";
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#getOrderItemByPk(int)
*/
@Override
public OrderItemModel getOrderItemByPk(int orderNo)
{
StringBuilder sql = new StringBuilder(SELECTSQL);
sql.append(" WHERE ORDER_NO = ?");
List<OrderItemModel> list = select(sql.toString(), new Object[]{orderNo}, this);
if (list != null && list.size() > 0)
{
return list.get(0);
}
return null;
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#getOrderItemByAddress(java.lang.String)
*/
@Override
public List<OrderItemModel> getOrderItemByAddress(String address)
{
StringBuilder sql = new StringBuilder(SELECTSQL);
sql.append(" WHERE ORDER_ADDRESS LIKE ?");
return select(sql.toString(), new Object[]{"%" + address+ "%"}, this);
}
@Override
public List<OrderItemModel> getOrderItemByAddress(String address, QueryPageInfo pageInfo)
{
StringBuilder sql = new StringBuilder(SELECTSQL);
sql.append(" WHERE ORDER_ADDRESS LIKE ?");
return select(sql.toString(), new Object[]{"%" + address+ "%"}, pageInfo, this);
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#getOrderItemByDesc(java.lang.String)
*/
@Override
public List<OrderItemModel> getOrderItemByDesc(String orderDesc)
{
StringBuilder sql = new StringBuilder(SELECTSQL);
sql.append(" WHERE ORDER_DESC = ?");
return select(sql.toString(), new Object[]{orderDesc}, this);
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#createOrderItem(com.ly.model.OrderItemModel)
*/
@Override
public void createOrderItem(OrderItemModel orderItem)
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#updateOrderItem(com.ly.model.OrderItemModel)
*/
@Override
public void updateOrderItem(OrderItemModel orderItem)
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#deleteOrderItemByPk(int)
*/
@Override
public void deleteOrderItemByPk(int orderNo)
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#deleteOrderItemByAddress(java.lang.String)
*/
@Override
public void deleteOrderItemByAddress(String address)
{
// TODO Auto-generated method stub
}
@Override
public OrderItemModel populate(ResultSet rs) throws SQLException
{
OrderItemModel model = new OrderItemModel();
model.setOrderNo(rs.getInt("ORDER_NO"));
model.setOrderDesc(rs.getString("ORDER_DESC"));
model.setOrderAddress(rs.getString("ORDER_ADDRESS"));
model.setOrderPhone(rs.getString("ORDER_PHONE"));
return model;
}
@Override
public List<OrderItemModel> getOrderItemByDesc(String orderDesc,
QueryPageInfo pageInfo)
{
StringBuilder sql = new StringBuilder(SELECTSQL);
sql.append(" WHERE ORDER_DESC = ?");
return select(sql.toString(), new Object[]{orderDesc}, pageInfo, this);
}
}
| UTF-8 | Java | 3,713 | java | OrderItemDaoImpl.java | Java | [
{
"context": "/**\r\n * Author:Administrator\r\n * Create time:下午2:11:04\r\n */\r\npackage com.ly.da",
"end": 28,
"score": 0.5823811292648315,
"start": 15,
"tag": "NAME",
"value": "Administrator"
},
{
"context": "rt com.ly.model.OrderItemModel;\r\n\r\n/**\r\n * @author Administrator\r\n *\r\n */\r\n@Repository\r\npublic class OrderItemDaoI",
"end": 452,
"score": 0.7336729168891907,
"start": 439,
"tag": "USERNAME",
"value": "Administrator"
}
] | null | [] | /**
* Author:Administrator
* Create time:下午2:11:04
*/
package com.ly.daoImpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.ly.dao.OrderItemDao;
import com.ly.framework.QueryPageInfo;
import com.ly.framework.db.DataProccessor;
import com.ly.framework.db.JdbcSupport;
import com.ly.model.OrderItemModel;
/**
* @author Administrator
*
*/
@Repository
public class OrderItemDaoImpl extends JdbcSupport implements OrderItemDao, DataProccessor<OrderItemModel>
{
public static final String SELECTSQL = "SELECT ORDER_NO, ORDER_DESC, ORDER_ADDRESS, ORDER_PHONE FROM ORDER_ITEM";
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#getOrderItemByPk(int)
*/
@Override
public OrderItemModel getOrderItemByPk(int orderNo)
{
StringBuilder sql = new StringBuilder(SELECTSQL);
sql.append(" WHERE ORDER_NO = ?");
List<OrderItemModel> list = select(sql.toString(), new Object[]{orderNo}, this);
if (list != null && list.size() > 0)
{
return list.get(0);
}
return null;
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#getOrderItemByAddress(java.lang.String)
*/
@Override
public List<OrderItemModel> getOrderItemByAddress(String address)
{
StringBuilder sql = new StringBuilder(SELECTSQL);
sql.append(" WHERE ORDER_ADDRESS LIKE ?");
return select(sql.toString(), new Object[]{"%" + address+ "%"}, this);
}
@Override
public List<OrderItemModel> getOrderItemByAddress(String address, QueryPageInfo pageInfo)
{
StringBuilder sql = new StringBuilder(SELECTSQL);
sql.append(" WHERE ORDER_ADDRESS LIKE ?");
return select(sql.toString(), new Object[]{"%" + address+ "%"}, pageInfo, this);
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#getOrderItemByDesc(java.lang.String)
*/
@Override
public List<OrderItemModel> getOrderItemByDesc(String orderDesc)
{
StringBuilder sql = new StringBuilder(SELECTSQL);
sql.append(" WHERE ORDER_DESC = ?");
return select(sql.toString(), new Object[]{orderDesc}, this);
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#createOrderItem(com.ly.model.OrderItemModel)
*/
@Override
public void createOrderItem(OrderItemModel orderItem)
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#updateOrderItem(com.ly.model.OrderItemModel)
*/
@Override
public void updateOrderItem(OrderItemModel orderItem)
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#deleteOrderItemByPk(int)
*/
@Override
public void deleteOrderItemByPk(int orderNo)
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see com.ly.dao.OrderItemDao#deleteOrderItemByAddress(java.lang.String)
*/
@Override
public void deleteOrderItemByAddress(String address)
{
// TODO Auto-generated method stub
}
@Override
public OrderItemModel populate(ResultSet rs) throws SQLException
{
OrderItemModel model = new OrderItemModel();
model.setOrderNo(rs.getInt("ORDER_NO"));
model.setOrderDesc(rs.getString("ORDER_DESC"));
model.setOrderAddress(rs.getString("ORDER_ADDRESS"));
model.setOrderPhone(rs.getString("ORDER_PHONE"));
return model;
}
@Override
public List<OrderItemModel> getOrderItemByDesc(String orderDesc,
QueryPageInfo pageInfo)
{
StringBuilder sql = new StringBuilder(SELECTSQL);
sql.append(" WHERE ORDER_DESC = ?");
return select(sql.toString(), new Object[]{orderDesc}, pageInfo, this);
}
}
| 3,713 | 0.689404 | 0.687517 | 148 | 23.06081 | 26.459358 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.304054 | false | false | 2 |
252e9489fc5ac40804a27591318a0d777ecc730f | 3,667,902,114,192 | fc1eb85277d647d6b10de23c91116ec66e21e91f | /src/StraightInsertionSort.java | d5db5941fc9133fef10f197b96f7277d6bea11a2 | [] | no_license | ddpound/javaTestProject | https://github.com/ddpound/javaTestProject | 868e2796cc0f8d6cb65912510d90e97ca7720a50 | 295861aabc2411c5728f446f637fa5f072979183 | refs/heads/master | 2023-07-09T03:50:25.992000 | 2021-08-20T18:00:24 | 2021-08-20T18:00:24 | 397,541,572 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
public class StraightInsertionSort {
public ArrayList<Integer> straightInsertionSort(ArrayList<Integer> arrayList){
int targetIndexNum = 0;
for(int i=0; i < arrayList.size();i++){
if(targetIndexNum==0){
targetIndexNum++;
}else {
int temp = arrayList.get(targetIndexNum);
for(int j =1; j < i; j++){
// target index
if(targetIndexNum-j < 0){
break;
}
// 타겟 인덱스의 값이 더 작으면 왼쪽으로 교환해줘야함
if(arrayList.get(targetIndexNum-j) > temp){
int chtemp = arrayList.get(targetIndexNum-j);
arrayList.set(targetIndexNum-j, temp);
arrayList.set(targetIndexNum, chtemp);
}else {
break;
}
targetIndexNum++;
}
}
}
return arrayList;
}
}
| UTF-8 | Java | 1,113 | java | StraightInsertionSort.java | Java | [] | null | [] | import java.util.ArrayList;
public class StraightInsertionSort {
public ArrayList<Integer> straightInsertionSort(ArrayList<Integer> arrayList){
int targetIndexNum = 0;
for(int i=0; i < arrayList.size();i++){
if(targetIndexNum==0){
targetIndexNum++;
}else {
int temp = arrayList.get(targetIndexNum);
for(int j =1; j < i; j++){
// target index
if(targetIndexNum-j < 0){
break;
}
// 타겟 인덱스의 값이 더 작으면 왼쪽으로 교환해줘야함
if(arrayList.get(targetIndexNum-j) > temp){
int chtemp = arrayList.get(targetIndexNum-j);
arrayList.set(targetIndexNum-j, temp);
arrayList.set(targetIndexNum, chtemp);
}else {
break;
}
targetIndexNum++;
}
}
}
return arrayList;
}
}
| 1,113 | 0.438728 | 0.434051 | 38 | 27.131578 | 22.829081 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.447368 | false | false | 2 |
57556f8cc0374019ac7c04f38c691f2282f00cc4 | 24,670,292,191,843 | 24f322ba857688709c787658306c50f0f3a19ad1 | /Eg_July_7AM/src/com/str/StrConcatTest.java | d9db88796d227a8c371ba7960100cf91564fbfdd | [] | no_license | Abby-Hub/Eg_July_2021_7am | https://github.com/Abby-Hub/Eg_July_2021_7am | 620041a71a504955b084fed58826db25beb8a28b | 64c270a1457e45a2589a919a9e8d27c0c9b82d88 | refs/heads/master | 2023-06-27T08:46:04.217000 | 2021-07-29T02:25:51 | 2021-07-29T02:25:51 | 386,154,647 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.str;
public class StrConcatTest {
public static void main(String[] args) {
String s1 = "Java";
System.out.println(s1); // Java
s1 = s1.concat("Developer");
System.out.println(s1);
}
}
| UTF-8 | Java | 210 | java | StrConcatTest.java | Java | [] | null | [] | package com.str;
public class StrConcatTest {
public static void main(String[] args) {
String s1 = "Java";
System.out.println(s1); // Java
s1 = s1.concat("Developer");
System.out.println(s1);
}
}
| 210 | 0.657143 | 0.633333 | 12 | 16.5 | 14.620192 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false | 2 |
894ec8cb11f00ed11980d12b10553404331cce1f | 26,113,401,182,021 | ba551837420ab34aecd7552ad5071be04965b866 | /src/main/java/cn/cnr/admin/base/util/PageSqlUtil.java | 3c98db192da35726da3d2a810a3b607763c0ac56 | [] | no_license | ycssh/cnrserver | https://github.com/ycssh/cnrserver | 7d5c9db73ff33a0aafb2283336aa17b75edb1a08 | 307dbb70f3ee2d8c8b9c9657753e180f8e68dcaa | refs/heads/master | 2021-01-02T23:08:42.166000 | 2017-08-08T02:27:06 | 2017-08-08T02:27:06 | 99,474,173 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.cnr.admin.base.util;
/**
* @author 作者姓名 yc E-mail: ycssh2@163.com
* @version 创建时间:2014-5-14 下午04:44:58 类说明
*/
public class PageSqlUtil {
public static String getPageSql(String sql, Pagination pagination) {
int page = pagination.getPage();
int rows = pagination.getRows();
if(page<=1){
page=1;
}
if(rows<=1){
rows=10;
}
return "SELECT * FROM (SELECT tab.*, ROWNUM RN FROM ("+sql+")tab ) WHERE RN >= "+((page - 1) * rows+1)+" and RN<="+page * rows;
}
public static String getCountSql(String sql) {
return "select count(*) from (" + sql + ") count_table";
}
}
| UTF-8 | Java | 627 | java | PageSqlUtil.java | Java | [
{
"context": "r.admin.base.util;\n\n/**\n * @author 作者姓名 yc E-mail: ycssh2@163.com\n * @version 创建时间:2014-5-14 下午04:44:58 类说明\n */\npub",
"end": 78,
"score": 0.9999240636825562,
"start": 64,
"tag": "EMAIL",
"value": "ycssh2@163.com"
}
] | null | [] | package cn.cnr.admin.base.util;
/**
* @author 作者姓名 yc E-mail: <EMAIL>
* @version 创建时间:2014-5-14 下午04:44:58 类说明
*/
public class PageSqlUtil {
public static String getPageSql(String sql, Pagination pagination) {
int page = pagination.getPage();
int rows = pagination.getRows();
if(page<=1){
page=1;
}
if(rows<=1){
rows=10;
}
return "SELECT * FROM (SELECT tab.*, ROWNUM RN FROM ("+sql+")tab ) WHERE RN >= "+((page - 1) * rows+1)+" and RN<="+page * rows;
}
public static String getCountSql(String sql) {
return "select count(*) from (" + sql + ") count_table";
}
}
| 620 | 0.634391 | 0.594324 | 23 | 25.043478 | 29.868521 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.521739 | false | false | 2 |
af77993f96891be2e2f42aec416c7945cd0e8a41 | 32,332,513,853,345 | 50e947ea04e2411743a68e848a8206dfe4722194 | /src/onid3/OnID3.java | fcf059d4759b357c0c3e8409c4f32ba5664fd9c6 | [] | no_license | azon04/ID3_ML | https://github.com/azon04/ID3_ML | 6b4ee3fc8bd6801c9887e70680f0a9b834e81d1e | dd0432c9acea306bbd76170bbc6dccc4f36db0b2 | refs/heads/master | 2020-05-29T23:16:03.429000 | 2015-01-16T04:37:03 | 2015-01-16T04:37:03 | 12,674,342 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package onid3;
import com.on.Alg.ANN.Sig;
import com.on.Alg.ANN.Sign;
import com.on.Alg.ANN.Step;
import com.on.Alg.ANNClassifier;
import com.on.Alg.ANNMultiLayer;
import com.on.Alg.ID3;
import com.on.clustering.BisectingKMeans;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
*
* @author Nurul Fithria
*/
public class OnID3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
Parser _parser = new Parser();
Dataset trainset = _parser.loadDataset("pengawasan_1atr.arff");
//Dataset answerset = _parser.loadDataset("PlayTennis_Cluster_ans.arff");
BisectingKMeans bisectingKMeans = new BisectingKMeans(7, trainset);
bisectingKMeans.doCluster();
bisectingKMeans.printResult();
//System.out.println("Accuracy : " + bisectingKMeans.accuracy(answerset)*100 + "%" );
// Parser _parser = new Parser();
// Dataset trainset = _parser.loadDataset("trainingUTS.arff");
// Dataset testset = _parser.loadDataset("test.arff");
// ID3 id3 = new ID3(trainset);
// System.out.println("ID3");
// id3.GenerateModel();
// System.out.println("Accuracy Test set : " + id3.accuration(trainset.getData()));
//
// System.out.println("");
// System.out.println("ANN");
// ANNClassifier ann = new ANNClassifier(trainset, ANNClassifier.Mode.INCREMENTAL);
// ann.setLearningRate(0.25f);
// ann.setMaxIteration(100);
// ann.GenerateModel();
// System.out.println("Accuracy Test set : " + ann.accuration(trainset.getData()));
//
/*Dataset _dataset = _parser.loadDataset("and.arff");
System.out.println("(A)");
System.out.println("INCREMENTAL");
System.out.println("ANN for AND dataset with Linear Function : ");
ANNClassifier ann = new ANNClassifier(_dataset, ANNClassifier.Mode.INCREMENTAL);
ann.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Sigmoid Function : ");
ANNClassifier ann2 = new ANNClassifier(_dataset, ANNClassifier.Mode.INCREMENTAL, new Sig());
ann2.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann2.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Sign Function : ");
ANNClassifier ann3 = new ANNClassifier(_dataset, ANNClassifier.Mode.INCREMENTAL, new Sign());
ann3.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann3.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Step Function : ");
ANNClassifier ann4 = new ANNClassifier(_dataset, ANNClassifier.Mode.INCREMENTAL, new Step(0.0f));
ann4.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann4.GenerateModel();
System.out.println("");
System.out.println("BATCH");
System.out.println("ANN for AND dataset with Linear Function : ");
ANNClassifier ann5 = new ANNClassifier(_dataset, ANNClassifier.Mode.BATCH);
ann5.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann5.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Sigmoid Function : ");
ANNClassifier ann6 = new ANNClassifier(_dataset, ANNClassifier.Mode.BATCH, new Sig());
ann6.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann6.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Sign Function : ");
ANNClassifier ann7 = new ANNClassifier(_dataset, ANNClassifier.Mode.BATCH, new Sign());
ann7.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann7.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Step Function : ");
ANNClassifier ann8 = new ANNClassifier(_dataset, ANNClassifier.Mode.BATCH, new Step(0.0f));
ann8.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann8.GenerateModel();
System.out.println("");
System.out.println("(B)");
Dataset xnor_dataset = _parser.loadDataset("xnor.arff");
System.out.println("ANN for XNOR Incremental, Sigmoid");
ANNClassifier ann9 = new ANNClassifier(xnor_dataset, ANNClassifier.Mode.INCREMENTAL, new Sig());
ann9.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f,1.0f});
ann9.setMinMSE(0.001f);
ann9.GenerateModel();
System.out.println("ANN for XNOR Batch, Sigmoid");
ANNClassifier ann10 = new ANNClassifier(xnor_dataset, ANNClassifier.Mode.BATCH, new Sig());
ann10.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f,1.0f});
ann10.setMinMSE(0.001f);
ann10.GenerateModel();
System.out.println("");
System.out.println("(C)");
System.out.println("ANN Multilayer XNOR with Backpropagation Algorithm");
ANNMultiLayer annMultiLayer = new ANNMultiLayer(xnor_dataset, new int[]{2,1}, new Sig());
annMultiLayer.GenerateModel();
System.out.println("");
System.out.println("(D)");
System.out.println("Playtennis Step Incremental");
Dataset playtennis = _parser.loadDataset("data1.arff");
ANNClassifier ann11 = new ANNClassifier(playtennis, new Step(0.0f));
ann11.GenerateModel();
System.out.println("");
System.out.println("(E)");
System.out.println("Playtennis Biner Step Incremental");
Dataset playtennis_biner = _parser.loadDataset("data1_biner.arff");
ANNClassifier ann12 = new ANNClassifier(playtennis_biner, ANNClassifier.Mode.INCREMENTAL, new Step(0.5f));
ann12.GenerateModel();
System.out.println("(F)");
System.out.println("Playtennis Biner Step Batch");
ANNClassifier ann13 = new ANNClassifier(playtennis_biner, ANNClassifier.Mode.BATCH, new Step(0.0f));
ann13.GenerateModel();
System.out.println("(G)");
System.out.println("Playtennis Biner Step Batch Backpropagation");
ANNMultiLayer ann14 = new ANNMultiLayer(playtennis_biner, new int[]{5,1}, new Step(0.0f));
ann14.setMinMSE(0.001f);
ann14.setMaxIteration(3);
ann14.GenerateModel();
*/
//ann.GenerateModelBySplit(66);
/* ModelData 1 */
/*Dataset _dataset = _parser.loadDataset("data1.arff");
_dataset.PrintDataset();
ID3 id3 = new ID3(_dataset);
System.out.println("Model data 1");
System.out.println("==============");
System.out.println("Full Model");
System.out.println("==============");
id3.GenerateModel();
/* ModelData 2 */
//Dataset _dataset2 = _parser.loadDataset("data2.arff");
//_dataset2.PrintDataset();
/*ID3 id3_2 = new ID3(_dataset2);
System.out.println("Model Data ke 2");
System.out.println("==============");
System.out.println("Full Model");
System.out.println("==============");
id3_2.GenerateModel();
/* Hasil Klasifikasi */
/*Dataset _dataset3 = _parser.loadDataset("data3.arff");
System.out.println("Hasil Klasifikasi Data 3 ke Model 1");
System.out.println(id3.accuration(_dataset3.getData()) * 100 + "%");
_dataset3.PrintDataset();
System.out.println("Hasil Klasifikasi Data 3 ke Model 2");
System.out.println(id3_2.accuration(_dataset3.getData())* 100 + "%");
_dataset3.PrintDataset();
System.out.println("Monk Problem 1");
System.out.println("=================");
System.out.println("Model Tree");
System.out.println("");
Dataset _datatrain1 = _parser.loadDataset("monks-1.test");
ID3 monkModel1 = new ID3(_datatrain1);
monkModel1.classIdx = 0;
monkModel1.GenerateModel();
Dataset _datatest1 = _parser.loadDataset("monks-1.test");
System.out.println("");
System.out.println("Accuracy Test : " + monkModel1.accuration(_datatest1.getData())*100 + "%");
System.out.println("====================");
System.out.println("Monk Problem 2");
System.out.println("=================");
System.out.println("Model Tree");
System.out.println("");
Dataset _datatrain2 = _parser.loadDataset("monks-2.train");
ID3 monkModel2 = new ID3(_datatrain2);
monkModel2.classIdx = 0;
monkModel2.GenerateModel();
Dataset _datatest2 = _parser.loadDataset("monks-2.test");
System.out.println("");
System.out.println("Accuracy Test : " + monkModel2.accuration(_datatest2.getData())*100 + "%");
System.out.println("=================");
System.out.println("Monk Problem 3");
System.out.println("=================");
System.out.println("Model Tree");
System.out.println("");
Dataset _datatrain3 = _parser.loadDataset("monks-3.train");
ID3 monkModel3 = new ID3(_datatrain3);
monkModel3.classIdx = 0;
monkModel3.GenerateModel();
Dataset _datatest3 = _parser.loadDataset("monks-3.test");
System.out.println("");
System.out.println("Accuracy Test : " + monkModel3.accuration(_datatest3.getData())*100 + "%");
*/
}
}
| UTF-8 | Java | 9,967 | java | OnID3.java | Java | [
{
"context": "on;\nimport java.io.IOException;\n\n/**\n *\n * @author Nurul Fithria\n */\npublic class OnID3 {\n\n /**\n * @param a",
"end": 428,
"score": 0.999887228012085,
"start": 415,
"tag": "NAME",
"value": "Nurul Fithria"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package onid3;
import com.on.Alg.ANN.Sig;
import com.on.Alg.ANN.Sign;
import com.on.Alg.ANN.Step;
import com.on.Alg.ANNClassifier;
import com.on.Alg.ANNMultiLayer;
import com.on.Alg.ID3;
import com.on.clustering.BisectingKMeans;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
*
* @author <NAME>
*/
public class OnID3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
Parser _parser = new Parser();
Dataset trainset = _parser.loadDataset("pengawasan_1atr.arff");
//Dataset answerset = _parser.loadDataset("PlayTennis_Cluster_ans.arff");
BisectingKMeans bisectingKMeans = new BisectingKMeans(7, trainset);
bisectingKMeans.doCluster();
bisectingKMeans.printResult();
//System.out.println("Accuracy : " + bisectingKMeans.accuracy(answerset)*100 + "%" );
// Parser _parser = new Parser();
// Dataset trainset = _parser.loadDataset("trainingUTS.arff");
// Dataset testset = _parser.loadDataset("test.arff");
// ID3 id3 = new ID3(trainset);
// System.out.println("ID3");
// id3.GenerateModel();
// System.out.println("Accuracy Test set : " + id3.accuration(trainset.getData()));
//
// System.out.println("");
// System.out.println("ANN");
// ANNClassifier ann = new ANNClassifier(trainset, ANNClassifier.Mode.INCREMENTAL);
// ann.setLearningRate(0.25f);
// ann.setMaxIteration(100);
// ann.GenerateModel();
// System.out.println("Accuracy Test set : " + ann.accuration(trainset.getData()));
//
/*Dataset _dataset = _parser.loadDataset("and.arff");
System.out.println("(A)");
System.out.println("INCREMENTAL");
System.out.println("ANN for AND dataset with Linear Function : ");
ANNClassifier ann = new ANNClassifier(_dataset, ANNClassifier.Mode.INCREMENTAL);
ann.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Sigmoid Function : ");
ANNClassifier ann2 = new ANNClassifier(_dataset, ANNClassifier.Mode.INCREMENTAL, new Sig());
ann2.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann2.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Sign Function : ");
ANNClassifier ann3 = new ANNClassifier(_dataset, ANNClassifier.Mode.INCREMENTAL, new Sign());
ann3.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann3.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Step Function : ");
ANNClassifier ann4 = new ANNClassifier(_dataset, ANNClassifier.Mode.INCREMENTAL, new Step(0.0f));
ann4.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann4.GenerateModel();
System.out.println("");
System.out.println("BATCH");
System.out.println("ANN for AND dataset with Linear Function : ");
ANNClassifier ann5 = new ANNClassifier(_dataset, ANNClassifier.Mode.BATCH);
ann5.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann5.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Sigmoid Function : ");
ANNClassifier ann6 = new ANNClassifier(_dataset, ANNClassifier.Mode.BATCH, new Sig());
ann6.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann6.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Sign Function : ");
ANNClassifier ann7 = new ANNClassifier(_dataset, ANNClassifier.Mode.BATCH, new Sign());
ann7.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann7.GenerateModel();
System.out.println("");
System.out.println("ANN for AND dataset with Step Function : ");
ANNClassifier ann8 = new ANNClassifier(_dataset, ANNClassifier.Mode.BATCH, new Step(0.0f));
ann8.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f, 1.0f});
ann8.GenerateModel();
System.out.println("");
System.out.println("(B)");
Dataset xnor_dataset = _parser.loadDataset("xnor.arff");
System.out.println("ANN for XNOR Incremental, Sigmoid");
ANNClassifier ann9 = new ANNClassifier(xnor_dataset, ANNClassifier.Mode.INCREMENTAL, new Sig());
ann9.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f,1.0f});
ann9.setMinMSE(0.001f);
ann9.GenerateModel();
System.out.println("ANN for XNOR Batch, Sigmoid");
ANNClassifier ann10 = new ANNClassifier(xnor_dataset, ANNClassifier.Mode.BATCH, new Sig());
ann10.setReps(ANNClassifier.Rep.MODIF, new float[]{-1.0f,1.0f});
ann10.setMinMSE(0.001f);
ann10.GenerateModel();
System.out.println("");
System.out.println("(C)");
System.out.println("ANN Multilayer XNOR with Backpropagation Algorithm");
ANNMultiLayer annMultiLayer = new ANNMultiLayer(xnor_dataset, new int[]{2,1}, new Sig());
annMultiLayer.GenerateModel();
System.out.println("");
System.out.println("(D)");
System.out.println("Playtennis Step Incremental");
Dataset playtennis = _parser.loadDataset("data1.arff");
ANNClassifier ann11 = new ANNClassifier(playtennis, new Step(0.0f));
ann11.GenerateModel();
System.out.println("");
System.out.println("(E)");
System.out.println("Playtennis Biner Step Incremental");
Dataset playtennis_biner = _parser.loadDataset("data1_biner.arff");
ANNClassifier ann12 = new ANNClassifier(playtennis_biner, ANNClassifier.Mode.INCREMENTAL, new Step(0.5f));
ann12.GenerateModel();
System.out.println("(F)");
System.out.println("Playtennis Biner Step Batch");
ANNClassifier ann13 = new ANNClassifier(playtennis_biner, ANNClassifier.Mode.BATCH, new Step(0.0f));
ann13.GenerateModel();
System.out.println("(G)");
System.out.println("Playtennis Biner Step Batch Backpropagation");
ANNMultiLayer ann14 = new ANNMultiLayer(playtennis_biner, new int[]{5,1}, new Step(0.0f));
ann14.setMinMSE(0.001f);
ann14.setMaxIteration(3);
ann14.GenerateModel();
*/
//ann.GenerateModelBySplit(66);
/* ModelData 1 */
/*Dataset _dataset = _parser.loadDataset("data1.arff");
_dataset.PrintDataset();
ID3 id3 = new ID3(_dataset);
System.out.println("Model data 1");
System.out.println("==============");
System.out.println("Full Model");
System.out.println("==============");
id3.GenerateModel();
/* ModelData 2 */
//Dataset _dataset2 = _parser.loadDataset("data2.arff");
//_dataset2.PrintDataset();
/*ID3 id3_2 = new ID3(_dataset2);
System.out.println("Model Data ke 2");
System.out.println("==============");
System.out.println("Full Model");
System.out.println("==============");
id3_2.GenerateModel();
/* Hasil Klasifikasi */
/*Dataset _dataset3 = _parser.loadDataset("data3.arff");
System.out.println("Hasil Klasifikasi Data 3 ke Model 1");
System.out.println(id3.accuration(_dataset3.getData()) * 100 + "%");
_dataset3.PrintDataset();
System.out.println("Hasil Klasifikasi Data 3 ke Model 2");
System.out.println(id3_2.accuration(_dataset3.getData())* 100 + "%");
_dataset3.PrintDataset();
System.out.println("Monk Problem 1");
System.out.println("=================");
System.out.println("Model Tree");
System.out.println("");
Dataset _datatrain1 = _parser.loadDataset("monks-1.test");
ID3 monkModel1 = new ID3(_datatrain1);
monkModel1.classIdx = 0;
monkModel1.GenerateModel();
Dataset _datatest1 = _parser.loadDataset("monks-1.test");
System.out.println("");
System.out.println("Accuracy Test : " + monkModel1.accuration(_datatest1.getData())*100 + "%");
System.out.println("====================");
System.out.println("Monk Problem 2");
System.out.println("=================");
System.out.println("Model Tree");
System.out.println("");
Dataset _datatrain2 = _parser.loadDataset("monks-2.train");
ID3 monkModel2 = new ID3(_datatrain2);
monkModel2.classIdx = 0;
monkModel2.GenerateModel();
Dataset _datatest2 = _parser.loadDataset("monks-2.test");
System.out.println("");
System.out.println("Accuracy Test : " + monkModel2.accuration(_datatest2.getData())*100 + "%");
System.out.println("=================");
System.out.println("Monk Problem 3");
System.out.println("=================");
System.out.println("Model Tree");
System.out.println("");
Dataset _datatrain3 = _parser.loadDataset("monks-3.train");
ID3 monkModel3 = new ID3(_datatrain3);
monkModel3.classIdx = 0;
monkModel3.GenerateModel();
Dataset _datatest3 = _parser.loadDataset("monks-3.test");
System.out.println("");
System.out.println("Accuracy Test : " + monkModel3.accuration(_datatest3.getData())*100 + "%");
*/
}
}
| 9,960 | 0.603993 | 0.580415 | 231 | 42.147186 | 27.703049 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.991342 | false | false | 2 |
802662369757ea165a337ff5a7f024962bc92791 | 27,161,373,211,148 | 07e30d739e3f82e57cff0b88c60d2de93f0223cf | /src/1816. Truncate Sentence/Solution.java | ac5961df264ba35895985275595b56a6d4de6054 | [
"MIT"
] | permissive | hypocrite30/LeetCode | https://github.com/hypocrite30/LeetCode | 25c78c39e792a75b9e8ebc510ff2ade94e85c436 | b46daa9815a22511e85b184eff01bdd8efdf3777 | refs/heads/master | 2023-08-14T21:42:05.853000 | 2022-03-04T04:06:34 | 2022-03-04T04:06:34 | 349,713,924 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* 1816. Truncate Sentence */
public class Solution {
public String truncateSentence(String s, int k) {
int n = s.length(), idx = 0;
while (idx < n) {
if (s.charAt(idx) == ' ' && --k == 0) break;
idx++;
}
return s.substring(0, idx);
}
} | UTF-8 | Java | 301 | java | Solution.java | Java | [] | null | [] | /* 1816. Truncate Sentence */
public class Solution {
public String truncateSentence(String s, int k) {
int n = s.length(), idx = 0;
while (idx < n) {
if (s.charAt(idx) == ' ' && --k == 0) break;
idx++;
}
return s.substring(0, idx);
}
} | 301 | 0.478405 | 0.45515 | 12 | 24.166666 | 17.989965 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 2 |
f4f025f799904ff93769fb037cf3c0ce3cc3013f | 28,011,776,748,161 | 1d27d0b48b2e2dac86a18cab54e129786445c3ab | /src/test/java/org/m3/js/App.java | 0173885cca5a0fda7b8dde08340052469c4db634 | [] | no_license | jamiesweeney/order-manager | https://github.com/jamiesweeney/order-manager | 834eac2ba30cae5cee7853c86cbda3ecca77905a | ce021adf0d044dc3fb09dca4fd37b98dcd463b48 | refs/heads/master | 2020-03-23T19:35:41.613000 | 2018-12-12T20:18:49 | 2018-12-12T20:18:49 | 141,989,778 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.m3.js;
import org.m3.js.OrderManager.BasicOrderManager;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) {
// Start trader thread
RandomTrader randomTrader = new RandomTrader("localhost", 9093);
Thread traderThread = new Thread(randomTrader);
traderThread.start();
// Start OM thread
Thread omThread = new Thread(new BasicOrderManager("localhost", 9092,"localhost", 9093, "OM"));
omThread.start();
// Start Client threads
new Thread(new BetterClient("localhost", 9092)).start();
}
}
| UTF-8 | Java | 618 | java | App.java | Java | [] | null | [] | package org.m3.js;
import org.m3.js.OrderManager.BasicOrderManager;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) {
// Start trader thread
RandomTrader randomTrader = new RandomTrader("localhost", 9093);
Thread traderThread = new Thread(randomTrader);
traderThread.start();
// Start OM thread
Thread omThread = new Thread(new BasicOrderManager("localhost", 9092,"localhost", 9093, "OM"));
omThread.start();
// Start Client threads
new Thread(new BetterClient("localhost", 9092)).start();
}
}
| 618 | 0.634304 | 0.605178 | 25 | 23.719999 | 26.925854 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.56 | false | false | 2 |
42d1b43df394df550e8cc44f66d7ae67019ff5ac | 18,743,237,342,855 | 6f0b52a31fc75c1a89d8c205f741818632e97ced | /src/perpustakaan/controllers/AnggotaController.java | 7e220044492d8772b7e655f20372c007ac90ef9c | [] | no_license | sweetMethod/Program-Perpustakaan | https://github.com/sweetMethod/Program-Perpustakaan | 7fd8d2e19382966a18381efbf536b8e3a55c44e8 | cc6f9e2483cd1e1c9bdea6756cd70fb7f426d752 | refs/heads/master | 2020-05-09T12:09:07.996000 | 2019-04-13T01:11:31 | 2019-04-13T01:11:31 | 181,103,425 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package perpustakaan.controllers;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import perpustakaan.models.Anggota;
import static perpustakaan.models.Anggota.getAnggotaList;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.controls.JFXTreeTableView;
import com.jfoenix.controls.RecursiveTreeItem;
import com.jfoenix.controls.datamodels.treetable.RecursiveTreeObject;
import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.layout.AnchorPane;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.input.MouseEvent;
import perpustakaan.MemberCard;
public class AnggotaController implements Initializable{
@FXML
private AnchorPane anchor;
@FXML
private JFXButton back;
@FXML
private JFXButton buttonBatal;
@FXML
private JFXButton buttonPrint;
@FXML
void back(ActionEvent event) throws IOException {
anchor.getChildren().clear();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/home.fxml"));
Parent parent = loader.load();
anchor.getChildren().add(parent);
}
@FXML
private JFXTreeTableView<Anggota> table_anggota;
@FXML
private JFXTextField text_Namasiswa;
@FXML
private JFXTextField text_Kelas;
@FXML
private JFXButton buttonSimpan;
@FXML
private JFXButton buttonEdit;
@FXML
private JFXButton buttonHapus;
private final ObservableList<Anggota> anggotaList = FXCollections.observableArrayList();
@FXML
void editAnggota(ActionEvent event) {
if(validasi()){
int index = table_anggota.getSelectionModel().getSelectedIndex();
Anggota angg = anggotaList.get(index);
angg.setNama_anggota(text_Namasiswa.getText());
angg.setKelas(text_Kelas.getText());
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Edit Data Anggota");
alert.setHeaderText(null);
alert.setContentText("Apakah anda yakin untuk mengedit data anggota?");
Optional result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
if(angg.updateAnggota()>0){
table_anggota.refresh();
resetForm();
}
else {
alert.close();
}
}
}
else {
Alert alert2 = new Alert(AlertType.ERROR);
alert2.setTitle("Anggota");
alert2.setContentText("Nama Siswa atau Kelas kosong");
alert2.show();
}
}
@FXML
void hapusAnggota(ActionEvent event) {
int index = table_anggota.getSelectionModel().getSelectedIndex();
Anggota angg = anggotaList.get(index);
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Hapus Data Anggota");
alert.setHeaderText(null);
alert.setContentText("Apakah anda yakin untuk menghapus data anggota?");
Optional result = alert.showAndWait();
if (result.get() == ButtonType.OK){
if(angg.deleteAnggota()>0){
Alert keluar = new Alert(AlertType.INFORMATION);
keluar.setTitle("Data Anggota");
keluar.setHeaderText(null);
anggotaList.remove(angg);
keluar.setContentText("data berhasil di hapus");
keluar.showAndWait();
resetForm();
} else {
alert.close();
}
}
}
private boolean validasi(){
return !text_Namasiswa.getText().isEmpty() && !text_Kelas.getText().isEmpty();
}
@FXML
void simpanAnggota(ActionEvent event) {
if(validasi()){
Anggota angg = new Anggota(
text_Namasiswa.getText(),
text_Kelas.getText()
);
if(angg.createAnggota()>0){
anggotaList.setAll(getAnggotaList());
resetForm();
}
} else {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Anggota");
alert.setContentText("Nama Siswa atau Kelas kosong");
alert.show();
}
}
private void ambilData() {
int index = table_anggota.getSelectionModel().getSelectedIndex();
Anggota angg = anggotaList.get(index);
text_Namasiswa.setText(angg.getNama_anggota());
text_Kelas.setText(angg.getKelas());
}
private void resetForm() {
text_Namasiswa.setText("");
text_Kelas.setText("");
}
@FXML
void batalAnggota(ActionEvent event) {
resetForm();
buttonSimpan.setDisable(false);
buttonEdit.setDisable(true);
buttonHapus.setDisable(true);
}
@FXML
@SuppressWarnings("CallToPrintStackTrace")
void printAnggota(ActionEvent event) {
ObservableList<Integer> indexs = table_anggota.getSelectionModel().getSelectedIndices();
List<Anggota> list = new ArrayList();
indexs.stream().forEach((index) -> {
list.add(anggotaList.get(index));
});
Task <MemberCard> labeltask = new Task <MemberCard>() {
@Override
protected MemberCard call() throws Exception {
return new MemberCard(list);
}
};
labeltask.setOnSucceeded(evt->{
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream("out/membercard.pdf"));
} catch (FileNotFoundException | DocumentException ex) {
Logger.getLogger(AnggotaController.class.getName()).log(Level.SEVERE, null, ex);
}
document.setMargins(12f, 12f, 12f, 12f);
document.open();
try {
document.add(labeltask.get().getLayout());
} catch (InterruptedException | ExecutionException | DocumentException ex) {
Logger.getLogger(AnggotaController.class.getName()).log(Level.SEVERE, null, ex);
}
document.close();
File file = new File ("out/membercard.pdf");
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(AnggotaController.class.getName()).log(Level.SEVERE, null, ex);
}
});
labeltask.setOnFailed(evt -> labeltask.getException().printStackTrace());
Thread thread = new Thread(labeltask);
thread.setDaemon(true);
thread.start();
}
@FXML
void mousePressedHandle(MouseEvent event) {
if (event.getClickCount() == 1) {
ambilData();
buttonSimpan.setDisable(true);
buttonEdit.setDisable(false);
buttonHapus.setDisable(false);
buttonPrint.setDisable(false);
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
TreeTableColumn<Anggota, Integer> idCol = new TreeTableColumn<>("Id Anggota");
TreeTableColumn<Anggota, String> namaCol = new TreeTableColumn<>("Nama Anggota");
TreeTableColumn<Anggota, String> kelasCol = new TreeTableColumn<>("Kelas Anggota");
idCol.setCellValueFactory(param -> param.getValue().getValue().id_anggotaProperty());
namaCol.setCellValueFactory(param -> param.getValue().getValue().nama_anggotaProperty());
kelasCol.setCellValueFactory(param -> param.getValue().getValue().kelasProperty());
idCol.prefWidthProperty().bind(table_anggota.prefWidthProperty().multiply(0.2));
namaCol.prefWidthProperty().bind(table_anggota.prefWidthProperty().multiply(0.5));
kelasCol.prefWidthProperty().bind(table_anggota.prefWidthProperty().multiply(0.3));
table_anggota.getColumns().add(idCol);
table_anggota.getColumns().add(namaCol);
table_anggota.getColumns().add(kelasCol);
TreeItem<Anggota> anggotaRoot = new RecursiveTreeItem<>(anggotaList, RecursiveTreeObject::getChildren);
table_anggota.setRoot(anggotaRoot);
table_anggota.setShowRoot(false);
anggotaList.addAll(getAnggotaList());
table_anggota.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
}
} | UTF-8 | Java | 9,453 | java | AnggotaController.java | Java | [] | null | [] | package perpustakaan.controllers;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import perpustakaan.models.Anggota;
import static perpustakaan.models.Anggota.getAnggotaList;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.controls.JFXTreeTableView;
import com.jfoenix.controls.RecursiveTreeItem;
import com.jfoenix.controls.datamodels.treetable.RecursiveTreeObject;
import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.layout.AnchorPane;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.input.MouseEvent;
import perpustakaan.MemberCard;
public class AnggotaController implements Initializable{
@FXML
private AnchorPane anchor;
@FXML
private JFXButton back;
@FXML
private JFXButton buttonBatal;
@FXML
private JFXButton buttonPrint;
@FXML
void back(ActionEvent event) throws IOException {
anchor.getChildren().clear();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/home.fxml"));
Parent parent = loader.load();
anchor.getChildren().add(parent);
}
@FXML
private JFXTreeTableView<Anggota> table_anggota;
@FXML
private JFXTextField text_Namasiswa;
@FXML
private JFXTextField text_Kelas;
@FXML
private JFXButton buttonSimpan;
@FXML
private JFXButton buttonEdit;
@FXML
private JFXButton buttonHapus;
private final ObservableList<Anggota> anggotaList = FXCollections.observableArrayList();
@FXML
void editAnggota(ActionEvent event) {
if(validasi()){
int index = table_anggota.getSelectionModel().getSelectedIndex();
Anggota angg = anggotaList.get(index);
angg.setNama_anggota(text_Namasiswa.getText());
angg.setKelas(text_Kelas.getText());
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Edit Data Anggota");
alert.setHeaderText(null);
alert.setContentText("Apakah anda yakin untuk mengedit data anggota?");
Optional result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
if(angg.updateAnggota()>0){
table_anggota.refresh();
resetForm();
}
else {
alert.close();
}
}
}
else {
Alert alert2 = new Alert(AlertType.ERROR);
alert2.setTitle("Anggota");
alert2.setContentText("Nama Siswa atau Kelas kosong");
alert2.show();
}
}
@FXML
void hapusAnggota(ActionEvent event) {
int index = table_anggota.getSelectionModel().getSelectedIndex();
Anggota angg = anggotaList.get(index);
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Hapus Data Anggota");
alert.setHeaderText(null);
alert.setContentText("Apakah anda yakin untuk menghapus data anggota?");
Optional result = alert.showAndWait();
if (result.get() == ButtonType.OK){
if(angg.deleteAnggota()>0){
Alert keluar = new Alert(AlertType.INFORMATION);
keluar.setTitle("Data Anggota");
keluar.setHeaderText(null);
anggotaList.remove(angg);
keluar.setContentText("data berhasil di hapus");
keluar.showAndWait();
resetForm();
} else {
alert.close();
}
}
}
private boolean validasi(){
return !text_Namasiswa.getText().isEmpty() && !text_Kelas.getText().isEmpty();
}
@FXML
void simpanAnggota(ActionEvent event) {
if(validasi()){
Anggota angg = new Anggota(
text_Namasiswa.getText(),
text_Kelas.getText()
);
if(angg.createAnggota()>0){
anggotaList.setAll(getAnggotaList());
resetForm();
}
} else {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Anggota");
alert.setContentText("Nama Siswa atau Kelas kosong");
alert.show();
}
}
private void ambilData() {
int index = table_anggota.getSelectionModel().getSelectedIndex();
Anggota angg = anggotaList.get(index);
text_Namasiswa.setText(angg.getNama_anggota());
text_Kelas.setText(angg.getKelas());
}
private void resetForm() {
text_Namasiswa.setText("");
text_Kelas.setText("");
}
@FXML
void batalAnggota(ActionEvent event) {
resetForm();
buttonSimpan.setDisable(false);
buttonEdit.setDisable(true);
buttonHapus.setDisable(true);
}
@FXML
@SuppressWarnings("CallToPrintStackTrace")
void printAnggota(ActionEvent event) {
ObservableList<Integer> indexs = table_anggota.getSelectionModel().getSelectedIndices();
List<Anggota> list = new ArrayList();
indexs.stream().forEach((index) -> {
list.add(anggotaList.get(index));
});
Task <MemberCard> labeltask = new Task <MemberCard>() {
@Override
protected MemberCard call() throws Exception {
return new MemberCard(list);
}
};
labeltask.setOnSucceeded(evt->{
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream("out/membercard.pdf"));
} catch (FileNotFoundException | DocumentException ex) {
Logger.getLogger(AnggotaController.class.getName()).log(Level.SEVERE, null, ex);
}
document.setMargins(12f, 12f, 12f, 12f);
document.open();
try {
document.add(labeltask.get().getLayout());
} catch (InterruptedException | ExecutionException | DocumentException ex) {
Logger.getLogger(AnggotaController.class.getName()).log(Level.SEVERE, null, ex);
}
document.close();
File file = new File ("out/membercard.pdf");
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(AnggotaController.class.getName()).log(Level.SEVERE, null, ex);
}
});
labeltask.setOnFailed(evt -> labeltask.getException().printStackTrace());
Thread thread = new Thread(labeltask);
thread.setDaemon(true);
thread.start();
}
@FXML
void mousePressedHandle(MouseEvent event) {
if (event.getClickCount() == 1) {
ambilData();
buttonSimpan.setDisable(true);
buttonEdit.setDisable(false);
buttonHapus.setDisable(false);
buttonPrint.setDisable(false);
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
TreeTableColumn<Anggota, Integer> idCol = new TreeTableColumn<>("Id Anggota");
TreeTableColumn<Anggota, String> namaCol = new TreeTableColumn<>("Nama Anggota");
TreeTableColumn<Anggota, String> kelasCol = new TreeTableColumn<>("Kelas Anggota");
idCol.setCellValueFactory(param -> param.getValue().getValue().id_anggotaProperty());
namaCol.setCellValueFactory(param -> param.getValue().getValue().nama_anggotaProperty());
kelasCol.setCellValueFactory(param -> param.getValue().getValue().kelasProperty());
idCol.prefWidthProperty().bind(table_anggota.prefWidthProperty().multiply(0.2));
namaCol.prefWidthProperty().bind(table_anggota.prefWidthProperty().multiply(0.5));
kelasCol.prefWidthProperty().bind(table_anggota.prefWidthProperty().multiply(0.3));
table_anggota.getColumns().add(idCol);
table_anggota.getColumns().add(namaCol);
table_anggota.getColumns().add(kelasCol);
TreeItem<Anggota> anggotaRoot = new RecursiveTreeItem<>(anggotaList, RecursiveTreeObject::getChildren);
table_anggota.setRoot(anggotaRoot);
table_anggota.setShowRoot(false);
anggotaList.addAll(getAnggotaList());
table_anggota.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
}
} | 9,453 | 0.625516 | 0.623188 | 280 | 32.764286 | 25.097839 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.603571 | false | false | 2 |
af319720297561574cca6b60cd3d30fd0825c389 | 6,940,667,210,142 | 37735dd2cf203a9bb78d44fd06dfb26612cd586c | /nov_15_2019/Demo1.java | 6ed3c0b9496b3a67df178c2cfff12c4a6059bb6a | [] | no_license | vikrant911998/JavaBatchNew | https://github.com/vikrant911998/JavaBatchNew | b90860e509223345b1a56f8572c5aa940292cfb4 | 4967989fda5fa46f7d6e033e7641c618f8d26464 | refs/heads/master | 2020-08-05T17:21:52.567000 | 2019-11-21T08:21:03 | 2019-11-21T08:21:03 | 212,631,712 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nov_15_2019;
public class Demo1 {
public static void main(String[] args) {
int a = 10;
int b = 10;
String c = new String("Vikrant");
String d = new String("Vikrant");
System.out.println(c);
System.out.println(d);
// if(c == d)
// if(c.equals("Vikrant"))
// if(c.equals(d))
// System.out.println("Same");
// else
// System.out.println("Not Same");
//
}
}
| UTF-8 | Java | 400 | java | Demo1.java | Java | [
{
"context": "a = 10;\n\t\tint b = 10;\n\t\t\n\t\tString c = new String(\"Vikrant\");\n\t\tString d = new String(\"Vikrant\");\n\t\t\n\t\tSyste",
"end": 151,
"score": 0.999058723449707,
"start": 144,
"tag": "NAME",
"value": "Vikrant"
},
{
"context": "= new String(\"Vikrant\");\n\t\tString d = new String(\"Vikrant\");\n\t\t\n\t\tSystem.out.println(c);\n\t\tSystem.out.print",
"end": 187,
"score": 0.9988605976104736,
"start": 180,
"tag": "NAME",
"value": "Vikrant"
},
{
"context": "ut.println(d);\n\t\t\n//\t\tif(c == d)\n//\t\tif(c.equals(\"Vikrant\"))\n//\t\tif(c.equals(d))\n//\t\t\tSystem.out.println(\"S",
"end": 286,
"score": 0.9976444244384766,
"start": 279,
"tag": "NAME",
"value": "Vikrant"
}
] | null | [] | package nov_15_2019;
public class Demo1 {
public static void main(String[] args) {
int a = 10;
int b = 10;
String c = new String("Vikrant");
String d = new String("Vikrant");
System.out.println(c);
System.out.println(d);
// if(c == d)
// if(c.equals("Vikrant"))
// if(c.equals(d))
// System.out.println("Same");
// else
// System.out.println("Not Same");
//
}
}
| 400 | 0.5775 | 0.55 | 26 | 14.384615 | 13.508052 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.730769 | false | false | 2 |
7b611471726473dfe6feb66690154655b2ab1083 | 22,617,297,844,390 | f4214101b239236d6c33fc26d82a5534956d4f49 | /src/main/java/cl/adopciones/config/JpaConfig.java | fb5663286c5df6b700870a019ee24115a6989646 | [] | no_license | jorjazo/adopciones | https://github.com/jorjazo/adopciones | f652e26dfb967b7195b2d1f65cc8b6f3511b0df8 | 76c7ae67a5eb51d1854171b9de12cea3d7164f0f | refs/heads/master | 2021-08-31T00:05:08.237000 | 2017-12-19T22:37:43 | 2017-12-19T22:37:43 | 111,582,492 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cl.adopciones.config;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories(basePackages = { "io.rebelsouls.repositories", "cl.adopciones" })
@EntityScan(basePackages = { "io.rebelsouls.entities", "cl.adopciones" })
public class JpaConfig {
}
| UTF-8 | Java | 441 | java | JpaConfig.java | Java | [] | null | [] | package cl.adopciones.config;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories(basePackages = { "io.rebelsouls.repositories", "cl.adopciones" })
@EntityScan(basePackages = { "io.rebelsouls.entities", "cl.adopciones" })
public class JpaConfig {
}
| 441 | 0.816327 | 0.816327 | 12 | 35.75 | 32.688236 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
0595385c79cc39c06efbf72e901887a410f5f15c | 29,515,015,319,402 | 1496b8a8894a5e26df83af85ae849bcb495706fd | /src/main/java/com/genetech/service/impl/VoteRecordServiceImpl.java | 178dec911c4ffceeea86970f908e391b4ce243ec | [] | no_license | brucewsy1943/gene_tech_front | https://github.com/brucewsy1943/gene_tech_front | f75cb05cb9b4f1572e5ede61ec04b5f2c84a7e31 | eb39fa761f6a16b10cd066b4ebb0c0bbbe9f3305 | refs/heads/master | 2022-07-29T05:59:38.404000 | 2020-12-15T07:53:04 | 2020-12-15T07:53:04 | 252,746,881 | 0 | 0 | null | false | 2022-06-17T03:05:35 | 2020-04-03T13:52:45 | 2020-12-15T07:54:00 | 2022-06-17T03:05:33 | 28,017 | 0 | 0 | 3 | Java | false | false | package com.genetech.service.impl;
import com.genetech.bean.VoteRecord;
import com.genetech.dao.VoteRecordMapper;
import com.genetech.service.VoteRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("voteRecordService")
public class VoteRecordServiceImpl implements VoteRecordService {
@Autowired
private VoteRecordMapper voteRecordMapper;
/**
*
* @param voteRecord
* @return
*/
@Override
public Integer insertRecord(VoteRecord voteRecord) {
Integer record = voteRecordMapper.insert(voteRecord);
return record;
}
/**
* 判断是否投过票
* @param loginId
* @return
*/
@Override
public boolean isEmployeeVoted(Integer loginId) {
Integer voteRecord = voteRecordMapper.selectVoteRecord(loginId);
if(voteRecord == 0){
return false;
}
return true;
}
}
| UTF-8 | Java | 976 | java | VoteRecordServiceImpl.java | Java | [] | null | [] | package com.genetech.service.impl;
import com.genetech.bean.VoteRecord;
import com.genetech.dao.VoteRecordMapper;
import com.genetech.service.VoteRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("voteRecordService")
public class VoteRecordServiceImpl implements VoteRecordService {
@Autowired
private VoteRecordMapper voteRecordMapper;
/**
*
* @param voteRecord
* @return
*/
@Override
public Integer insertRecord(VoteRecord voteRecord) {
Integer record = voteRecordMapper.insert(voteRecord);
return record;
}
/**
* 判断是否投过票
* @param loginId
* @return
*/
@Override
public boolean isEmployeeVoted(Integer loginId) {
Integer voteRecord = voteRecordMapper.selectVoteRecord(loginId);
if(voteRecord == 0){
return false;
}
return true;
}
}
| 976 | 0.686071 | 0.685031 | 38 | 24.31579 | 20.913488 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false | 2 |
69390fbebedea2b3eb57917e31e8b2a16b6bd9fe | 9,637,906,614,916 | c8bb96453ed5356c1fbaede3e73f8b6b377f39a9 | /app/src/main/java/com/mtvindia/connect/ui/fragment/PrimaryQuestionFragment.java | 57b8301510eede62838057fcc94607101e55ff48 | [
"MIT"
] | permissive | iamdeowanshi/ChatApplication | https://github.com/iamdeowanshi/ChatApplication | a6cffaf2121e11adc70354aeff7037f0fae06c0c | 927cf7994b5af1dfbe2dd21bc03ea52136a7ad22 | refs/heads/master | 2021-07-06T21:45:32.142000 | 2017-09-28T00:11:33 | 2017-09-28T00:11:33 | 104,963,379 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mtvindia.connect.ui.fragment;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.mtvindia.connect.R;
import com.mtvindia.connect.app.base.BaseFragment;
import com.mtvindia.connect.data.model.Option;
import com.mtvindia.connect.data.model.Question;
import com.mtvindia.connect.data.model.ResultRequest;
import com.mtvindia.connect.data.model.ResultResponse;
import com.mtvindia.connect.data.model.User;
import com.mtvindia.connect.presenter.QuestionRequestPresenter;
import com.mtvindia.connect.presenter.QuestionViewInteractor;
import com.mtvindia.connect.presenter.ResultPresenter;
import com.mtvindia.connect.presenter.ResultViewInteractor;
import com.mtvindia.connect.ui.activity.NavigationActivity;
import com.mtvindia.connect.ui.custom.UbuntuTextView;
import com.mtvindia.connect.util.QuestionPreference;
import com.mtvindia.connect.util.UserPreference;
import com.squareup.picasso.Picasso;
import java.util.List;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;
/**
* @author Aaditya Deowanshi
*
* Primary question screen, which displays first high level question.
*/
public class PrimaryQuestionFragment extends BaseFragment implements QuestionViewInteractor, ResultViewInteractor{
@Inject UserPreference userPreference;
@Inject QuestionPreference questionPreference;
@Inject QuestionRequestPresenter questionRequestPresenter;
@Inject ResultPresenter resultPresenter;
@Bind(R.id.img_dp) ImageView userPic;
@Bind(R.id.img_dp_big_1) ImageView picOption1;
@Bind(R.id.img_dp_big_2) ImageView picOption2;
@Bind(R.id.progress) ProgressBar progress;
@Bind(R.id.txt_hello) UbuntuTextView txtHello;
@Bind(R.id.txt_option_1) UbuntuTextView txtOption1;
@Bind(R.id.txt_option_2) UbuntuTextView txtOption2;
@Bind(R.id.txt_prim_quest) UbuntuTextView txtPrimQuest;
@Bind(R.id.view) View view;
private User user;
private Question question;
private List<Option> option;
private ResultRequest resultRequest = new ResultRequest();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
injectDependencies();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_question_fragment, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
Window window = getActivity().getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getActivity().getResources().getColor(R.color.darkYellow));
}
questionRequestPresenter.setViewInteractor(this);
resultPresenter.setViewInteractor(this);
user = userPreference.readUser();
questionRequestPresenter.getPrimaryQuestion(user.getAuthHeader());
loadUserDetails(user);
}
@Override
public void onResume() {
super.onResume();
questionRequestPresenter.resume();
resultPresenter.resume();
}
@Override
public void onPause() {
super.onPause();
questionRequestPresenter.pause();
resultPresenter.pause();
}
@Override
public void showProgress() {
progress.setVisibility(View.VISIBLE);
}
@Override
public void hideProgress() {
progress.setVisibility(View.GONE);
}
@Override
public void showResult(ResultResponse response) {
questionPreference.saveResultResponse(response);
NavigationActivity navigationActivity = (NavigationActivity) getContext();
Fragment fragment = ResultFragment.getInstance(null);
navigationActivity.addFragment(fragment);
}
@Override
public void showQuestion(Question response) {
question = response;
questionPreference.saveQuestionResponse(question);
questionPreference.savePrimaryQuestionId(question.getQuestionId());
resultRequest.setQuestionId(question.getQuestionId());
option = question.getOptions();
txtPrimQuest.setText(question.getQuestion());
txtOption1.setText(option.get(0).getOption());
txtOption2.setText(option.get(1).getOption());
view.setVisibility(View.VISIBLE);
Picasso.with(getContext()).load(option.get(0).getOptionUrl()).fit().into(picOption1);
picOption1.setVisibility(View.VISIBLE);
Picasso.with(getContext()).load(option.get(1).getOptionUrl()).fit().into(picOption2);
picOption2.setVisibility(View.VISIBLE);
}
@Override
public void onError(Throwable throwable) {
hideProgress();
Timber.e(throwable, "Error");
toastShort("Error: " + throwable);
}
@OnClick(R.id.img_dp_big_1)
void option1() {
optionSelected(option.get(0).getOptionId());
questionPreference.saveOptionSelected(1);
}
@OnClick(R.id.img_dp_big_2)
void option2() {
optionSelected(option.get(1).getOptionId());
questionPreference.saveOptionSelected(2);
}
/**
* Method to make api call for secondary question on the basis of primary question selected.
* @param option
*/
private void optionSelected(int option) {
question.setIsAnswered(true);
questionPreference.saveQuestionResponse(question);
questionPreference.saveQuestionCount(1);
resultRequest.setPrimaryQuestionId(0);
resultRequest.setOptionId(option);
resultPresenter.requestResult(resultRequest, user.getAuthHeader());
}
/**
* Load user details.
* @param user
*/
private void loadUserDetails(User user) {
txtHello.setText("Hello " + user.getFirstName() + "!");
Picasso.with(getContext()).load(user.getProfilePic()).fit().into(userPic);
}
public static Fragment getInstance(Bundle bundle) {
PrimaryQuestionFragment primaryQuestionFragment = new PrimaryQuestionFragment();
primaryQuestionFragment.setArguments(bundle);
return primaryQuestionFragment;
}
}
| UTF-8 | Java | 6,985 | java | PrimaryQuestionFragment.java | Java | [
{
"context": "OnClick;\nimport timber.log.Timber;\n\n/**\n * @author Aaditya Deowanshi\n *\n * Primary question screen, which disp",
"end": 1481,
"score": 0.9998563528060913,
"start": 1464,
"tag": "NAME",
"value": "Aaditya Deowanshi"
}
] | null | [] | package com.mtvindia.connect.ui.fragment;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.mtvindia.connect.R;
import com.mtvindia.connect.app.base.BaseFragment;
import com.mtvindia.connect.data.model.Option;
import com.mtvindia.connect.data.model.Question;
import com.mtvindia.connect.data.model.ResultRequest;
import com.mtvindia.connect.data.model.ResultResponse;
import com.mtvindia.connect.data.model.User;
import com.mtvindia.connect.presenter.QuestionRequestPresenter;
import com.mtvindia.connect.presenter.QuestionViewInteractor;
import com.mtvindia.connect.presenter.ResultPresenter;
import com.mtvindia.connect.presenter.ResultViewInteractor;
import com.mtvindia.connect.ui.activity.NavigationActivity;
import com.mtvindia.connect.ui.custom.UbuntuTextView;
import com.mtvindia.connect.util.QuestionPreference;
import com.mtvindia.connect.util.UserPreference;
import com.squareup.picasso.Picasso;
import java.util.List;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;
/**
* @author <NAME>
*
* Primary question screen, which displays first high level question.
*/
public class PrimaryQuestionFragment extends BaseFragment implements QuestionViewInteractor, ResultViewInteractor{
@Inject UserPreference userPreference;
@Inject QuestionPreference questionPreference;
@Inject QuestionRequestPresenter questionRequestPresenter;
@Inject ResultPresenter resultPresenter;
@Bind(R.id.img_dp) ImageView userPic;
@Bind(R.id.img_dp_big_1) ImageView picOption1;
@Bind(R.id.img_dp_big_2) ImageView picOption2;
@Bind(R.id.progress) ProgressBar progress;
@Bind(R.id.txt_hello) UbuntuTextView txtHello;
@Bind(R.id.txt_option_1) UbuntuTextView txtOption1;
@Bind(R.id.txt_option_2) UbuntuTextView txtOption2;
@Bind(R.id.txt_prim_quest) UbuntuTextView txtPrimQuest;
@Bind(R.id.view) View view;
private User user;
private Question question;
private List<Option> option;
private ResultRequest resultRequest = new ResultRequest();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
injectDependencies();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_question_fragment, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
Window window = getActivity().getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getActivity().getResources().getColor(R.color.darkYellow));
}
questionRequestPresenter.setViewInteractor(this);
resultPresenter.setViewInteractor(this);
user = userPreference.readUser();
questionRequestPresenter.getPrimaryQuestion(user.getAuthHeader());
loadUserDetails(user);
}
@Override
public void onResume() {
super.onResume();
questionRequestPresenter.resume();
resultPresenter.resume();
}
@Override
public void onPause() {
super.onPause();
questionRequestPresenter.pause();
resultPresenter.pause();
}
@Override
public void showProgress() {
progress.setVisibility(View.VISIBLE);
}
@Override
public void hideProgress() {
progress.setVisibility(View.GONE);
}
@Override
public void showResult(ResultResponse response) {
questionPreference.saveResultResponse(response);
NavigationActivity navigationActivity = (NavigationActivity) getContext();
Fragment fragment = ResultFragment.getInstance(null);
navigationActivity.addFragment(fragment);
}
@Override
public void showQuestion(Question response) {
question = response;
questionPreference.saveQuestionResponse(question);
questionPreference.savePrimaryQuestionId(question.getQuestionId());
resultRequest.setQuestionId(question.getQuestionId());
option = question.getOptions();
txtPrimQuest.setText(question.getQuestion());
txtOption1.setText(option.get(0).getOption());
txtOption2.setText(option.get(1).getOption());
view.setVisibility(View.VISIBLE);
Picasso.with(getContext()).load(option.get(0).getOptionUrl()).fit().into(picOption1);
picOption1.setVisibility(View.VISIBLE);
Picasso.with(getContext()).load(option.get(1).getOptionUrl()).fit().into(picOption2);
picOption2.setVisibility(View.VISIBLE);
}
@Override
public void onError(Throwable throwable) {
hideProgress();
Timber.e(throwable, "Error");
toastShort("Error: " + throwable);
}
@OnClick(R.id.img_dp_big_1)
void option1() {
optionSelected(option.get(0).getOptionId());
questionPreference.saveOptionSelected(1);
}
@OnClick(R.id.img_dp_big_2)
void option2() {
optionSelected(option.get(1).getOptionId());
questionPreference.saveOptionSelected(2);
}
/**
* Method to make api call for secondary question on the basis of primary question selected.
* @param option
*/
private void optionSelected(int option) {
question.setIsAnswered(true);
questionPreference.saveQuestionResponse(question);
questionPreference.saveQuestionCount(1);
resultRequest.setPrimaryQuestionId(0);
resultRequest.setOptionId(option);
resultPresenter.requestResult(resultRequest, user.getAuthHeader());
}
/**
* Load user details.
* @param user
*/
private void loadUserDetails(User user) {
txtHello.setText("Hello " + user.getFirstName() + "!");
Picasso.with(getContext()).load(user.getProfilePic()).fit().into(userPic);
}
public static Fragment getInstance(Bundle bundle) {
PrimaryQuestionFragment primaryQuestionFragment = new PrimaryQuestionFragment();
primaryQuestionFragment.setArguments(bundle);
return primaryQuestionFragment;
}
}
| 6,974 | 0.723694 | 0.719399 | 207 | 32.743961 | 26.660093 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57971 | false | false | 2 |
df8e42c5a5566ebd45716140a9fd8171421aded1 | 36,627,481,129,460 | 05c9a8f61e1b351bf2f1d683836a9c0ce43ace4c | /src/main/java/com/lintcode/NullObject/Site.java | e4e7fa6adac54dd3b38024a0b7c0d3f54a5290e3 | [] | no_license | fanboqia/JavaAlgorithmCode | https://github.com/fanboqia/JavaAlgorithmCode | 41ea0464b8b95da11f9c20e3e449583aa0575192 | 23bd7ad8cf39da66930152fcf2a15cffa59214f3 | refs/heads/master | 2021-07-10T11:51:47.357000 | 2020-08-23T02:57:44 | 2020-08-23T02:57:44 | 200,864,866 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lintcode.NullObject;
public class Site {
private Customer _customer;
public Customer get_customer() {
return _customer;
}
public void set_customer(Customer _customer) {
this._customer = _customer;
}
public Customer getCustomer(){
return _customer == null ? Customer.newNull():_customer;
}
public static void main(String[] args){
Site site = new Site();
System.out.println(site.getCustomer().getName());
site.set_customer(new Customer("frank"));
System.out.println(site.getCustomer().getName());
}
}
| UTF-8 | Java | 609 | java | Site.java | Java | [
{
"context": "tName());\n site.set_customer(new Customer(\"frank\"));\n System.out.println(site.getCustomer()",
"end": 538,
"score": 0.9853780269622803,
"start": 533,
"tag": "NAME",
"value": "frank"
}
] | null | [] | package com.lintcode.NullObject;
public class Site {
private Customer _customer;
public Customer get_customer() {
return _customer;
}
public void set_customer(Customer _customer) {
this._customer = _customer;
}
public Customer getCustomer(){
return _customer == null ? Customer.newNull():_customer;
}
public static void main(String[] args){
Site site = new Site();
System.out.println(site.getCustomer().getName());
site.set_customer(new Customer("frank"));
System.out.println(site.getCustomer().getName());
}
}
| 609 | 0.623974 | 0.623974 | 25 | 23.360001 | 21.365168 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.36 | false | false | 2 |
a2016efefdf0f6c2c39bcf7a8c18a8e43ac11f58 | 34,815,004,938,579 | 70f0f15f2cff9a84cdaebf913e8b0bc6e60b1d01 | /src/main/java/com/wry/service/BerkeleyDBService.java | 092545b4e210bcae6bb65fd4a224d34567bd03a5 | [] | no_license | wenrongyao/video-crawler | https://github.com/wenrongyao/video-crawler | 54b15a6347b5b8317a90c3c488fc760dfa42549a | 58e796d0ca4b2a7c799aa19918d4b20c92b2458a | refs/heads/master | 2020-03-11T09:32:47.417000 | 2018-04-27T10:59:57 | 2018-04-27T10:59:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wry.service;
import java.util.List;
import java.util.Map;
import com.wry.constant.R;
import com.wry.dao.BerkeleyDBDao;
public class BerkeleyDBService {
private BerkeleyDBDao dbUtil;
public BerkeleyDBService(String dbName) {
dbUtil = new BerkeleyDBDao(R.CURRENTURL + R.BERKELEYDB_LOCATION, dbName);
}
/**
* 增加记录
*
* @param key
* @param value
* @param isOverwrite
*/
public void put(String key, String value, boolean isOverwrite) {
dbUtil.put(key, value, isOverwrite);
}
/**
* 删除信息
*
* @param key
*/
public void remove(String key) {
dbUtil.remove(key);
}
/**
* 查询单条记录
*
* @param key
* @return
*/
public String get(String key) {
return dbUtil.get(key);
}
/**
* 查询所有记录的key
*
* @return
*/
public List<String> getAll_list() {
return dbUtil.getAll_list();
}
/**
* 返回所有的记录
*
* @return
*/
public Map<String, String> getAll_map() {
return dbUtil.getAll_map();
}
/**
* 关闭资源
*/
public void close() {
dbUtil.close();
}
}
| GB18030 | Java | 1,085 | java | BerkeleyDBService.java | Java | [] | null | [] | package com.wry.service;
import java.util.List;
import java.util.Map;
import com.wry.constant.R;
import com.wry.dao.BerkeleyDBDao;
public class BerkeleyDBService {
private BerkeleyDBDao dbUtil;
public BerkeleyDBService(String dbName) {
dbUtil = new BerkeleyDBDao(R.CURRENTURL + R.BERKELEYDB_LOCATION, dbName);
}
/**
* 增加记录
*
* @param key
* @param value
* @param isOverwrite
*/
public void put(String key, String value, boolean isOverwrite) {
dbUtil.put(key, value, isOverwrite);
}
/**
* 删除信息
*
* @param key
*/
public void remove(String key) {
dbUtil.remove(key);
}
/**
* 查询单条记录
*
* @param key
* @return
*/
public String get(String key) {
return dbUtil.get(key);
}
/**
* 查询所有记录的key
*
* @return
*/
public List<String> getAll_list() {
return dbUtil.getAll_list();
}
/**
* 返回所有的记录
*
* @return
*/
public Map<String, String> getAll_map() {
return dbUtil.getAll_map();
}
/**
* 关闭资源
*/
public void close() {
dbUtil.close();
}
}
| 1,085 | 0.626836 | 0.626836 | 71 | 13.380281 | 15.423931 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.112676 | false | false | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.