blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 131 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 32 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 313 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
45a8b16ab682a972f33e5d24b369265816c3b40a | 26d30ed7154ca74e6da527c8879646060a615c45 | /zihan-blog-admin/src/main/java/com/zihan/blog/admin/controller/RestTagController.java | f385657931fa06744fbaab3e639c1377ceeee16b | [] | no_license | zh-Aispaly/zihan-blog | b4f57ed4d7c658687baddf76efd249055ee88306 | ac34ea0c02e3e5ce62936b00b7beb1d9ef34e66c | refs/heads/master | 2020-04-12T17:47:10.030498 | 2018-12-21T02:52:27 | 2018-12-21T02:52:27 | 162,108,797 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,029 | java | package com.zihan.blog.admin.controller;
import com.github.pagehelper.PageInfo;
import com.zihan.blog.core.business.annotation.BussinessLog;
import com.zihan.blog.core.business.entity.Tags;
import com.zihan.blog.core.business.enums.ResponseStatus;
import com.zihan.blog.core.business.service.BizTagsService;
import com.zihan.blog.core.business.vo.TagsConditionVO;
import com.zihan.blog.core.framework.object.PageResult;
import com.zihan.blog.core.framework.object.ResponseVO;
import com.zihan.blog.core.util.ResultUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 文章标签管理
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0
* @website https://www.zhyd.me
* @date 2018/4/24 14:37
* @since 1.0
*/
@RestController
@RequestMapping("/tag")
public class RestTagController {
@Autowired
private BizTagsService tagsService;
@RequiresPermissions("tags")
@PostMapping("/list")
public PageResult list(TagsConditionVO vo) {
PageInfo<Tags> pageInfo = tagsService.findPageBreakByCondition(vo);
return ResultUtil.tablePage(pageInfo);
}
@RequiresPermissions("tag:add")
@PostMapping(value = "/add")
@BussinessLog("添加标签")
public ResponseVO add(Tags tags) {
tagsService.insert(tags);
return ResultUtil.success("标签添加成功!新标签 - " + tags.getName());
}
@RequiresPermissions(value = {"tag:batchDelete", "tag:delete"}, logical = Logical.OR)
@PostMapping(value = "/remove")
@BussinessLog("删除标签")
public ResponseVO remove(Long[] ids) {
if (null == ids) {
return ResultUtil.error(500, "请至少选择一条记录");
}
for (Long id : ids) {
tagsService.removeByPrimaryKey(id);
}
return ResultUtil.success("成功删除 [" + ids.length + "] 个标签");
}
@RequiresPermissions("tag:get")
@PostMapping("/get/{id}")
@BussinessLog("获取标签详情")
public ResponseVO get(@PathVariable Long id) {
return ResultUtil.success(null, this.tagsService.getByPrimaryKey(id));
}
@RequiresPermissions("tag:edit")
@PostMapping("/edit")
@BussinessLog("编辑标签")
public ResponseVO edit(Tags tags) {
try {
tagsService.updateSelective(tags);
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.error("标签修改失败!");
}
return ResultUtil.success(ResponseStatus.SUCCESS);
}
@PostMapping("/listAll")
public ResponseVO listType() {
return ResultUtil.success(null, tagsService.listAll());
}
}
| [
"2351314567@qq.com"
] | 2351314567@qq.com |
37cd20a10f9f8d8b7829e34ddbcafdb02ff53b38 | 5b038080c6d7e84fdafec8a44c303d4986932f82 | /src/main/java/com/elementars/eclient/guirewrite/elements/Armor.java | 39cc6c280b7ac0488c95c0163712f162c16721ae | [] | no_license | Droid-D3V/XULU_Buildable_SRC | 9739a41a0daaef7a4d89f3b89379d0540849f856 | e5baa6f22730c79cbff969cb322d938d2168eb20 | refs/heads/master | 2023-08-28T09:10:14.384563 | 2021-11-05T16:43:39 | 2021-11-05T16:43:39 | 417,858,652 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,913 | java | package com.elementars.eclient.guirewrite.elements;
import com.elementars.eclient.Xulu;
import com.elementars.eclient.guirewrite.Element;
import com.elementars.eclient.module.Category;
import com.elementars.eclient.module.Module;
import com.elementars.eclient.util.ColorUtils;
import com.elementars.eclient.util.ColourHolder;
import dev.xulu.settings.Value;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.item.ItemStack;
import org.lwjgl.input.Keyboard;
/**
* @author Elementars
* @since 6/29/2020 - 2:50 PM
*/
public class Armor extends Element {
private final Value<String> aligned = register(new Value<>("Aligned", this, "X-axis", new String[]{
"X-axis", "Y-axis"
}))
.onChanged(onChangedValue -> {
switch (onChangedValue.getNew()) {
case "X-axis":
height = 16;
width = 79;
break;
case "Y-axis":
height = 72;
width = 16;
break;
}
});
private final Value<Boolean> progress = register(new Value<>("Durab. Bar", this, false));
private final Value<Integer> w = register(new Value<>("Width", this, 0, 0, 100));
private final Value<Integer> h = register(new Value<>("Height", this, 0, 0, 100));
private final Value<Boolean> cf = register(new Value<>("Custom Font", this, false));
private final Value<Boolean> damage = register(new Value<>("Damage", this, false));
private final Value<Boolean> fixed = register(new Value<>("Fixed", this, false));
public Armor() {
super("Armor");
}
@Override
public void onEnable() {
switch (aligned.getValue()) {
case "X-axis":
height = 16;
width = 79;
break;
case "Y-axis":
height = 72;
width = 16;
break;
}
}
private static RenderItem itemRender = Minecraft.getMinecraft()
.getRenderItem();
@Override
public void onRender() {
GlStateManager.enableTexture2D();
ScaledResolution resolution = new ScaledResolution(mc);
int i = resolution.getScaledWidth() / 2;
int iteration = 0;
int l = resolution.getScaledHeight() - 55 - (mc.player.isInWater() ? 10 : 0);
for (ItemStack is : mc.player.inventory.armorInventory) {
iteration++;
int x_2 = 0;
int y_2 = 0;
switch (aligned.getValue()) {
case "X-axis":
x_2 = (int) x - 90 + (9 - iteration) * 20 + 2 - 12;
y_2 = (int) y;
if (fixed.getValue()) {
x_2 = i - 90 + (9 - iteration) * 20 + 2;
y_2 = l;
}
break;
case "Y-axis":
x_2 = (int) x;
y_2 = (int) y - (iteration - 1) * 18 + 54;
if (fixed.getValue()) {
x_2 = i;
y_2 = l - (iteration - 1) * 18 + 54;
}
break;
}
if (progress.getValue()) {
switch (aligned.getValue()) {
case "X-axis":
Gui.drawRect(x_2 - 1, y_2 + 16, (x_2 + 19), (y_2 - 51) + 16, ColorUtils.changeAlpha(ColorUtils.Colors.BLACK, 60));
break;
case "Y-axis":
Gui.drawRect(x_2, y_2, (x_2 + 69), (y_2 + 18), ColorUtils.changeAlpha(ColorUtils.Colors.BLACK, 60));
break;
}
if (is.isEmpty()) continue;
float percentBar = ((float) is.getMaxDamage() - (float) is.getItemDamage()) / (float) is.getMaxDamage();
float red = 1 - percentBar;
switch (aligned.getValue()) {
case "X-axis":
Gui.drawRect(x_2 - 1, y_2 + 16, (x_2 + 19), (int) (y_2 - (percentBar * 51)) + 16, ColorUtils.changeAlpha(ColourHolder.toHex((int) (red * 255), (int) (percentBar * 255), 0), 150));
break;
case "Y-axis":
Gui.drawRect(x_2, y_2, (int) (x_2 + (percentBar * 69)), (y_2 + 18), ColorUtils.changeAlpha(ColourHolder.toHex((int) (red * 255), (int) (percentBar * 255), 0), 150));
break;
}
} else {
if (is.isEmpty()) continue;
}
GlStateManager.enableDepth();
itemRender.zLevel = 200F;
itemRender.renderItemAndEffectIntoGUI(is, x_2, y_2);
itemRender.renderItemOverlayIntoGUI(mc.fontRenderer, is, x_2, y_2, "");
itemRender.zLevel = 0F;
GlStateManager.enableTexture2D();
GlStateManager.disableLighting();
GlStateManager.disableDepth();
String s = is.getCount() > 1 ? is.getCount() + "" : "";
mc.fontRenderer.drawStringWithShadow(s, x_2 + 19 - 2 - mc.fontRenderer.getStringWidth(s), (int) y + 9, 0xffffff);
if (damage.getValue()) {
float green = ((float) is.getMaxDamage() - (float) is.getItemDamage()) / (float) is.getMaxDamage();
float red = 1 - green;
int dmg = 100 - (int) (red * 100);
switch (aligned.getValue()) {
case "X-axis":
if (cf.getValue()) {
Xulu.cFontRenderer.drawStringWithShadow(dmg + "", x_2 + 8 - Xulu.cFontRenderer.getStringWidth(dmg + "") / 2, y_2 - 11, ColourHolder.toHex((int) (red * 255), (int) (green * 255), 0));
} else {
fontRenderer.drawStringWithShadow(dmg + "", x_2 + 9 - fontRenderer.getStringWidth(dmg + "") / 2, y_2 - 11, ColourHolder.toHex((int) (red * 255), (int) (green * 255), 0));
}
break;
case "Y-axis":
if (cf.getValue()) {
Xulu.cFontRenderer.drawStringWithShadow(dmg + "", x_2 + 18, y_2 + 5, ColourHolder.toHex((int) (red * 255), (int) (green * 255), 0));
} else {
fontRenderer.drawStringWithShadow(dmg + "", x_2 + 18, y_2 + 5, ColourHolder.toHex((int) (red * 255), (int) (green * 255), 0));
}
break;
}
}
}
GlStateManager.enableDepth();
GlStateManager.disableLighting();
}
}
| [
"aronneyt@gmail.com"
] | aronneyt@gmail.com |
b4e48792438b97eb9936eaa87c86ada2ad39c7fa | 3c4425d520faeaa78a24ade0673da6cff431671e | /后台调试版/src/main/java/lottery/domains/content/payment/tgf/utils/XMLParserUtil.java | 58e4b884fc1b9982c38913604939df780c7fa7c4 | [] | no_license | yuruyigit/lotteryServer | de5cc848b9c7967817a33629efef4e77366b74c0 | 2cc97c54a51b9d76df145a98d72d3fe097bdd6af | refs/heads/master | 2020-06-17T03:39:24.838151 | 2019-05-25T11:32:00 | 2019-05-25T11:32:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 960 | java | package lottery.domains.content.payment.tgf.utils;
import java.util.List;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class XMLParserUtil
{
public static void parse(String xmlData, Map<String, String> resultMap)
throws Exception
{
Document doc = DocumentHelper.parseText(xmlData);
Element root = doc.getRootElement();
parseNode(root, resultMap);
}
private static void parseNode(Element node, Map<String, String> resultMap)
{
List attList = node.attributes();
List eleList = node.elements();
for (int i = 0; i < attList.size(); i++)
{
Attribute att = (Attribute)attList.get(i);
resultMap.put(att.getPath(), att.getText().trim());
}
resultMap.put(node.getPath(), node.getTextTrim());
for (int i = 0; i < eleList.size(); i++) {
parseNode((Element)eleList.get(i), resultMap);
}
}
}
| [
"nengbowan@163.com"
] | nengbowan@163.com |
24d716158507d7953a45a9a8a784e9a43222acf4 | 2b59aba9ddc603ef4597aeaf152249a500c4af2d | /My9_4-master/src/com/example/filter/Filter.java | cd82e0107f09985651bfe2cce64f017e02ee41d8 | [] | no_license | dukl/MagicMirror | 6657f375d3a7c2a75c7f37f6f7dd61ee3c57a6df | 35ca3ce58ee18ca204685246a5d3a7d83005f5cc | refs/heads/master | 2021-08-15T05:36:28.242091 | 2017-11-17T11:24:27 | 2017-11-17T11:24:27 | 111,095,328 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 148 | java | package com.example.filter;
import org.opencv.core.Mat;
public interface Filter {
public abstract void apply(final Mat src, final Mat dst);
}
| [
"du_keliang@163.com"
] | du_keliang@163.com |
c5b0ce6c12fb3511fe74c44da358c4435259ee83 | 552267b766af65fcc3413e35eb5d1d6b72b5a16d | /src/main/java/cn/jboa/util/PageSupport.java | ea852dc03e6c17bb338434c398f5eed9eaa2740e | [] | no_license | zycGitHubName/jboa | 1b50762336ede28529d2e3d0e85811e23aa3ab07 | 901340f34db8b138ceb111fde179cd520ed6e77c | refs/heads/master | 2020-04-14T10:15:15.202032 | 2019-01-05T09:34:56 | 2019-01-05T09:34:56 | 163,781,815 | 0 | 0 | null | 2019-01-05T09:34:57 | 2019-01-02T01:50:43 | Java | UTF-8 | Java | false | false | 1,419 | java | package cn.jboa.util;
import java.util.List;
/**
* 分页工具类,T:要分页的具体类
* @param <T>
*/
public class PageSupport<T> {
/**
* 当前页码
*/
private int currPageNo;
/**
* 每页显示条数
*/
private int pageSize;
/**
* 总页码
*/
private int totalPageCount;
/**
* 总条数
*/
private int totalCount;
/**
* 当前页面要展示的数据集合
*/
private List<T> items;
public int getCurrPageNo() {
return currPageNo;
}
public void setCurrPageNo(int currPageNo) {
this.currPageNo = currPageNo;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPageCount() {
totalPageCount = this.totalCount % this.pageSize != 0 ? this.totalCount / this.pageSize +1 : this.totalCount / this.pageSize;
return totalPageCount;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageCount;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public List<T> getItems() {
return items;
}
public void setItems(List<T> items) {
this.items = items;
}
}
| [
"1923889599@qq.com"
] | 1923889599@qq.com |
accaa46e50720152620b252507e7cc9bdd51501f | 5e10ada892b45db157e3efa89cadd27e6954cc1e | /Programs/Java/TestInheritance.java | 7297ca8329687e6be17625eacaa40135bea8c1df | [] | no_license | DheerajaManvi/Zeal | f3c01c96731e66a7aa3d26d2d216dd79cc977380 | 55da8eebee5b8476896ae67b477cfbdaa0ae14b8 | refs/heads/master | 2021-01-15T15:32:29.491289 | 2016-08-22T02:55:34 | 2016-08-22T02:55:34 | 57,143,575 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 459 | java | /*
*/
class TestInheritance extends Inheritance {
//public static int i = 10 ;
public TestInheritance() {
super() ;
}
public static void print () {
System.out.println ( "New i value: " + i ) ;
i += 5 ;
}
public static void main ( String[] args ) {
Inheritance in = new TestInheritance() ;
print() ;
Inheritance.print() ;
TestInheritance.print() ;
Inheritance.print() ;
}
}
| [
"dheeru.manvis@gmail.com"
] | dheeru.manvis@gmail.com |
f0710cbbecbd371ea107a80af7261b03b77e79ca | 37c6e7fbbd46e4fc06926e3719eae58bd2650136 | /test/com/roy/tiny/base/web/annotation/TestAuth.java | b07f4cc44a91edfd0da723f3efed3b470ee490d9 | [] | no_license | zhsyk34/tiny | 86229e4dc399ee20717e2560b554dfb767917ca6 | fcbcb68bd070ef3f65822a4af0a37644539e381f | refs/heads/master | 2021-01-21T10:33:31.857281 | 2014-03-07T09:26:26 | 2014-03-07T09:26:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,204 | java | package com.roy.tiny.base.web.annotation;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.Test;
import org.springframework.stereotype.Controller;
public class TestAuth {
@Test
public void testScanAuthMethod() {
String classpath = "com";
try {
Enumeration<URL> resourceUrls = Thread.currentThread().getContextClassLoader().getResources(classpath);
Set<Class> classes = new LinkedHashSet<Class>();
while (resourceUrls.hasMoreElements()) {
URL url = resourceUrls.nextElement();
if("file".equals(url.getProtocol())) {
findAllResourceByFilePath(url.getFile(),classes);
}
}
for(Class clazz : classes) {
if(clazz.isAnnotationPresent(Controller.class)) {
for(Method method : clazz.getDeclaredMethods()) {
if(method.isAnnotationPresent(Auth.class)) {
System.out.println(clazz.getName()+"."+method.getName()+"()");
}
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private void findAllResourceByFilePath(String filePath,Set<Class> classes) throws MalformedURLException, ClassNotFoundException {
File file = new File(filePath);
if(!file.exists()) {
return;
}
if(file.isDirectory()) {
File[] dirfiles = file.listFiles(new FileFilter() {
public boolean accept(File file) {
return (file.isDirectory() || file.getName().endsWith(".class"));
}
});
for(File f : dirfiles) {
findAllResourceByFilePath(f.getPath(),classes);
}
} else {
filePath = filePath.replace("\\", "/");
if(filePath.indexOf("/WEB-INF/classes/") > 0) {
String packagePath = filePath.substring(filePath.indexOf("/WEB-INF/classes/")+17, filePath.length());
String className = packagePath.substring(0, packagePath.indexOf(".")).replace("/", ".");
classes.add(Thread.currentThread().getContextClassLoader().loadClass(className));
}
}
}
}
| [
"wanghan0106@gmail.com"
] | wanghan0106@gmail.com |
84a9e450b54b7cce9f403c4cc38eb2cb8ca077b6 | f989ccd465c5ef5fac6b1e358165f0311297dd19 | /survey-system/SurveyTabletApp/src/com/example/surveyTabletApp/Assignment.java | 4aa52422f5d7fa2abdfed5ad2607c0c5358000cd | [] | no_license | dan-mckay/3rd-year-project | 3d28353d6566e7229592ace644eba3dff231c747 | 90cc071e7c4578e889d3a1094b0299344e3cddd5 | refs/heads/master | 2021-01-15T17:46:32.433193 | 2013-06-24T09:04:41 | 2013-06-24T09:04:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 222 | java | package com.example.surveyTabletApp;
/**
*
* @author Daniel McKay 2012
*
*/
public class Assignment {
public int id;
public String dateAssigned;
public String managerNotes;
public Survey survey;
}
| [
"r.reilly72@gmail.com"
] | r.reilly72@gmail.com |
aa99e5ced7eedc7c8aa2fa8a1dc2da4072b36221 | 45ba74907f0a3f18ee609c01186ce326e82bcb8e | /Android/YuLian/src/com/njkj/yulian/core/lib/gson/JsonParser.java | 255e6e3069f8c9c71e384919c678c749a0722ac6 | [] | no_license | qiu2421653/Yulian | b3e4f49b7fdbb8dd0643e25f7090921e908c8909 | 74ae61ecfe9977bd0d03f4476a2c0c54de6fdc6e | refs/heads/master | 2021-01-23T02:19:09.633795 | 2017-06-02T11:08:43 | 2017-06-02T11:08:43 | 92,915,856 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,140 | java | /*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.njkj.yulian.core.lib.gson;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import com.njkj.yulian.core.lib.gson.internal.Streams;
import com.njkj.yulian.core.lib.gson.stream.JsonReader;
import com.njkj.yulian.core.lib.gson.stream.JsonToken;
import com.njkj.yulian.core.lib.gson.stream.MalformedJsonException;
/**
* A parser to parse Json into a parse tree of {@link JsonElement}s
*
* @author Inderjeet Singh
* @author Joel Leitch
* @since 1.3
*/
public final class JsonParser {
/**
* Parses the specified JSON string into a parse tree
*
* @param json JSON text
* @return a parse tree of {@link JsonElement}s corresponding to the specified JSON
* @throws JsonParseException if the specified text is not valid JSON
* @since 1.3
*/
public JsonElement parse(String json) throws JsonSyntaxException {
return parse(new StringReader(json));
}
/**
* Parses the specified JSON string into a parse tree
*
* @param json JSON text
* @return a parse tree of {@link JsonElement}s corresponding to the specified JSON
* @throws JsonParseException if the specified text is not valid JSON
* @since 1.3
*/
public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException {
try {
JsonReader jsonReader = new JsonReader(json);
JsonElement element = parse(jsonReader);
if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) {
throw new JsonSyntaxException("Did not consume the entire document.");
}
return element;
} catch (MalformedJsonException e) {
throw new JsonSyntaxException(e);
} catch (IOException e) {
throw new JsonIOException(e);
} catch (NumberFormatException e) {
throw new JsonSyntaxException(e);
}
}
/**
* Returns the next value from the JSON stream as a parse tree.
*
* @throws JsonParseException if there is an IOException or if the specified
* text is not valid JSON
* @since 1.6
*/
public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException {
boolean lenient = json.isLenient();
json.setLenient(true);
try {
return Streams.parse(json);
} catch (StackOverflowError e) {
throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e);
} catch (OutOfMemoryError e) {
throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e);
} finally {
json.setLenient(lenient);
}
}
}
| [
"qiuyongzhi@aliyun.com"
] | qiuyongzhi@aliyun.com |
2b40a1a4809169ef2f5728fc6e04d630df349c2c | f9c94c23839e0451d3c6c09c407d71fb679a524c | /core-io/src/test/java/com/couchbase/client/core/CoreContextTest.java | ee74fe026ca2d8ec207685f25c178ba8bb080dce | [] | no_license | plokhotnyuk/couchbase-jvm-clients | 6127e97dbb77c9e46854c1f992afdbdee8c4dd8a | e12fe43f5d04f40e1aa3f5d9bd3c2095bccaafff | refs/heads/master | 2020-06-10T18:36:18.585785 | 2019-05-21T09:36:06 | 2019-06-24T13:44:15 | 193,707,958 | 1 | 0 | null | 2019-06-25T12:57:23 | 2019-06-25T12:57:23 | null | UTF-8 | Java | false | false | 1,407 | java | /*
* Copyright (c) 2018 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.couchbase.client.core;
import com.couchbase.client.core.cnc.Context;
import com.couchbase.client.core.env.CoreEnvironment;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
/**
* Verifies the functionality of the {@link CoreContext}.
*/
class CoreContextTest {
@Test
void getAndExportProperties() {
long id = 12345;
CoreEnvironment env = mock(CoreEnvironment.class);
Core core = mock(Core.class);
CoreContext ctx = new CoreContext(core, id, env);
assertEquals(core, ctx.core());
assertEquals(id, ctx.id());
assertEquals(env, ctx.environment());
String result = ctx.exportAsString(Context.ExportFormat.JSON);
assertEquals("{\"coreId\":12345}", result);
}
} | [
"michael@nitschinger.at"
] | michael@nitschinger.at |
5fba6b04f215b846701acf22a6471cad117a4747 | b3c2dfb283ee93e032f4c1b6d5cd24ea7807cce4 | /basics of java/src/MethodRunner.java | f048a505b02ddfa1c2da485a52b4371a9db5c449 | [] | no_license | Gopichand22/My-old-programs-2020 | 7c3b07c9e6db2f9fa9d1d5a604f80a01751c0117 | cda327e17572fccad931072fb4d5e171ba7a5103 | refs/heads/main | 2023-05-02T12:21:58.072878 | 2021-05-23T02:37:47 | 2021-05-23T02:37:47 | 369,944,808 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 140 | java |
public class MethodRunner {
public static void main(String[] args) {
Callmetwice();
}
private static void Callmetwice() {
}
}
| [
"62110262+Gopichand22@users.noreply.github.com"
] | 62110262+Gopichand22@users.noreply.github.com |
1aa68b7fd05678a8debd7962e887ac961c1e479d | 9a0da6d0dd7c20ea942479c8293194b19f6c8345 | /JavaPlugin/vro/o11nplugin-vro-core/src/main/java/com/vmware/avi/vro/VroPluginFactory.java | dec02a61459c1fad27238315e1575956ebbf8db7 | [
"Apache-2.0"
] | permissive | bhushanmopcito/avi-vrealize-orchestrator-plugin | dddabc7ef26a99d39bbfe39b0dd1ff84b9d3c378 | 35a9efabc097dee525437caccd58442e0c4ae9f5 | refs/heads/master | 2021-03-15T13:02:23.002388 | 2020-03-09T20:49:53 | 2020-03-09T20:49:53 | 246,852,467 | 0 | 0 | Apache-2.0 | 2020-03-12T14:17:14 | 2020-03-12T14:17:13 | null | UTF-8 | Java | false | false | 1,070 | java | package com.vmware.avi.vro;
import java.util.List;
import com.vmware.o11n.plugin.sdk.spring.AbstractSpringPluginFactory;
import com.vmware.o11n.plugin.sdk.spring.InventoryRef;
import ch.dunes.vso.sdk.api.QueryResult;
/**
*
* @author tushar
*
*/
public final class VroPluginFactory extends AbstractSpringPluginFactory {
@Override
public Object find(InventoryRef ref) {
if (ref.isOfType(Constants.FINDER_AVI_VRO_CLIENT)) {
return new AviVroClient();
} else if (ref.isOfType(Constants.FINDER_VRO_PLUGIN)) {
return new VroPlugin();
} else {
throw new UnsupportedOperationException("implement me");
}
}
@Override
public QueryResult findAll(String type, String query) {
throw new UnsupportedOperationException("implement me");
}
@Override
public List<?> findChildrenInRootRelation(String type, String relationName) {
throw new UnsupportedOperationException("implement me");
}
@Override
public List<?> findChildrenInRelation(InventoryRef parent, String relationName) {
throw new UnsupportedOperationException("implement me");
}
} | [
"noreply@github.com"
] | bhushanmopcito.noreply@github.com |
dc242ee2c5ead657262ec403c492c443a911a74a | c495142d4fc28ff7d18d66e570e84a462ebcacfc | /src/util/CommonUtil.java | 28823d9d0c42cc03c7cbef4cc03cddbea8b96168 | [] | no_license | yetianhua/MyBatisPractice | fd1b5648ee586b31f1be96417d3cda3dbfe23f33 | 1e99436e5b84c099f8bcaab45fe69a55bb7051c8 | refs/heads/master | 2021-01-09T20:19:13.803625 | 2016-07-26T14:18:28 | 2016-07-26T14:18:28 | 64,145,770 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 49 | java | package util;
public class CommonUtil {
}
| [
"qq1155609474476@sohu.com"
] | qq1155609474476@sohu.com |
98d543eb08ffc6055bb5802b8bc2dfd4c49b55b0 | 19e3302794a863949d3c5a403dd4ff7bde7e0255 | /app/src/main/java/com/example/peter/thekitchenmenu/data/databaseRemote/RemoteDbRefs.java | 68d33f7f382f95e3b53c66d8bb58ec47941a034b | [] | no_license | Peter-Wanden/TheKitchenMenu | 92b5a0ecb4089d80d0e0d4041d0bc7c1ee8e8701 | 08ac93595688a2f118db9a630da828cea1000599 | refs/heads/ArchitectureComponents | 2021-06-07T01:49:50.708879 | 2019-04-18T19:24:54 | 2019-04-18T19:24:54 | 142,435,549 | 0 | 0 | null | 2019-04-26T15:39:25 | 2018-07-26T12:05:57 | Java | UTF-8 | Java | false | false | 1,371 | java | package com.example.peter.thekitchenmenu.data.databaseRemote;
import static com.example.peter.thekitchenmenu.app.Constants.FB_COLLECTION_USED_PRODUCTS;
import static com.example.peter.thekitchenmenu.app.Constants.REMOTE_USER_LOCATION;
import static com.example.peter.thekitchenmenu.app.Constants.REMOTE_PRODUCT_LOCATION;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public abstract class RemoteDbRefs {
public static DatabaseReference getUserProductData(String remoteUserId) {
return FirebaseDatabase.getInstance().getReference(REMOTE_USER_LOCATION).
child(remoteUserId).child(REMOTE_PRODUCT_LOCATION);
}
public static DatabaseReference getUserProductData(String remoteUserId, String remoteProductId) {
return getUserProductData(remoteUserId).
child(remoteProductId);
}
public static DatabaseReference getRemoteProductData() {
return FirebaseDatabase.getInstance().getReference(REMOTE_PRODUCT_LOCATION);
}
public static DatabaseReference getRemoteUsers() {
return FirebaseDatabase.getInstance().getReference().child(REMOTE_USER_LOCATION);
}
public static DatabaseReference getUsersProducts() {
return FirebaseDatabase.getInstance().getReference().child(FB_COLLECTION_USED_PRODUCTS);
}
}
| [
"peter.wanden@gmail.com"
] | peter.wanden@gmail.com |
0b694ac80e74e53235326cb587756a3672039fce | d64ef92119b2b567add75d9763d4c167d223cf75 | /EcurieLoup/site/src/main/java/dao/page/PageDAO.java | 7f45c0e0fb2e0a818417d6d917501d90b6edea97 | [] | no_license | krack/Ecuries-du-loup | 194ca0e8283f3652467736300d9ac6f427906789 | ad0a51990f93fa634b291e9df14dd36e2bbb5ec5 | refs/heads/master | 2020-12-12T21:00:47.470504 | 2012-10-22T17:38:59 | 2012-10-22T17:38:59 | 884,119 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 237 | java | package dao.page;
import java.util.List;
import donnees.page.Page;
import fr.ecurie_du_loup.generique_util.dao.DaoIdLongUtil;
public interface PageDAO extends DaoIdLongUtil<Page> {
public List<Page> findVisiblePages();
}
| [
"krack_6@hotmail.com"
] | krack_6@hotmail.com |
31e379165f0469254178bdc45b70d2930e791f3c | 99a18aab8181fe821a3d5469ea08782e1e1112c8 | /src/com/peto/javarevisited/MissingNumberInArray.java | 67f07240335fd3ff64b8e9d076131ddf96c19935 | [] | no_license | roymithun/JavaWork_2015 | 7a1b19d53ae5ba922294a79eabb5b7f9a37e220b | 47c1aabc06309dd5604a271ff23c5fbdc0743b8c | refs/heads/master | 2021-07-09T21:42:58.694311 | 2016-10-01T21:02:40 | 2016-10-01T21:02:40 | 42,322,946 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,003 | java | package com.peto.javarevisited;
import java.util.Arrays;
import java.util.BitSet;
/**
*
* @author Mithun
*
*/
//http://javarevisited.blogspot.com/2014/11/how-to-find-missing-number-on-integer-array-java.html#ixzz3lSp3uCXP
public class MissingNumberInArray {
public static void main(String args[]) {
// one missing number
printMissingNumber(new int[] { 1, 2, 3, 4, 6 }, 6);
// two missing number
printMissingNumber(new int[] { 1, 2, 3, 4, 6, 7, 9, 8, 10 }, 10);
// three missing number
printMissingNumber(new int[] { 1, 2, 3, 4, 6, 9, 8 }, 10);
// four missing number
printMissingNumber(new int[] { 1, 2, 3, 4, 9, 8 }, 10);
// Only one missing number in array
int[] iArray = new int[] { 1, 2, 3, 5 };
int missing = getMissingNumber(iArray, 5);
System.out.printf("Missing number in array %s is %d %n", Arrays.toString(iArray), missing);
}
/**
* A general method to find missing values from an integer array in Java.
* This method will work even if array has more than one missing element.
*/
private static void printMissingNumber(int[] numbers, int count) {
int missingCount = count - numbers.length;
BitSet bitSet = new BitSet(count);
for (int number : numbers) {
bitSet.set(number - 1);
}
System.out.printf("Missing numbers in integer array %s, with total number %d is %n", Arrays.toString(numbers),
count);
int lastMissingIndex = 0;
for (int i = 0; i < missingCount; i++) {
lastMissingIndex = bitSet.nextClearBit(lastMissingIndex);
System.out.println(++lastMissingIndex);
}
}
/**
* Java method to find missing number in array of size n containing numbers
* from 1 to n only. can be used to find missing elements on integer array
* of numbers from 1 to 100 or 1 - 1000
*/
private static int getMissingNumber(int[] numbers, int totalCount) {
int expectedSum = totalCount * ((totalCount + 1) / 2);
int actualSum = 0;
for (int i : numbers) {
actualSum += i;
}
return expectedSum - actualSum;
}
}
| [
"mithunroy25@gmail.com"
] | mithunroy25@gmail.com |
1c8d6024cdea677e935f372dc3e1041e61f24929 | c16ea32a4cddb6b63ad3bacce3c6db0259d2bacd | /google/ads/googleads/v5/googleads-java/gapic-googleads-java/src/main/java/com/google/ads/googleads/v5/services/stub/GrpcThirdPartyAppAnalyticsLinkServiceCallableFactory.java | ac1f6e70b036eee8bacf9521c9aa5ea19752bd41 | [
"Apache-2.0"
] | permissive | dizcology/googleapis-gen | 74a72b655fba2565233e5a289cfaea6dc7b91e1a | 478f36572d7bcf1dc66038d0e76b9b3fa2abae63 | refs/heads/master | 2023-06-04T15:51:18.380826 | 2021-06-16T20:42:38 | 2021-06-16T20:42:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,815 | java | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ads.googleads.v5.services.stub;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcCallableFactory;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.BatchingCallSettings;
import com.google.api.gax.rpc.BidiStreamingCallable;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.ClientStreamingCallable;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallable;
import com.google.api.gax.rpc.StreamingCallSettings;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.longrunning.Operation;
import com.google.longrunning.stub.OperationsStub;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC callable factory implementation for the ThirdPartyAppAnalyticsLinkService service API.
*
* <p>This class is for advanced usage.
*/
@Generated("by gapic-generator-java")
public class GrpcThirdPartyAppAnalyticsLinkServiceCallableFactory
implements GrpcStubCallableFactory {
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createUnaryCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
UnaryCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createUnaryCallable(grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, PagedListResponseT>
UnaryCallable<RequestT, PagedListResponseT> createPagedCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
PagedCallSettings<RequestT, ResponseT, PagedListResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createPagedCallable(grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createBatchingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
BatchingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createBatchingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, MetadataT>
OperationCallable<RequestT, ResponseT, MetadataT> createOperationCallable(
GrpcCallSettings<RequestT, Operation> grpcCallSettings,
OperationCallSettings<RequestT, ResponseT, MetadataT> callSettings,
ClientContext clientContext,
OperationsStub operationsStub) {
return GrpcCallableFactory.createOperationCallable(
grpcCallSettings, callSettings, clientContext, operationsStub);
}
@Override
public <RequestT, ResponseT>
BidiStreamingCallable<RequestT, ResponseT> createBidiStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
StreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createBidiStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT>
ServerStreamingCallable<RequestT, ResponseT> createServerStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
ServerStreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createServerStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT>
ClientStreamingCallable<RequestT, ResponseT> createClientStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
StreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createClientStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
}
| [
"bazel-bot-development[bot]@users.noreply.github.com"
] | bazel-bot-development[bot]@users.noreply.github.com |
d540147ab365ef268e526a3092f3c17d1e4fd617 | b0b06d96662673a22286d3d96cb4dbf4e3a81bf8 | /demoSpringboot08/src/main/java/com/semillerojava/demospringboot/demoSpringboot/service/CuentaService.java | 3814029114408c6c360af6a8b03c769d0a2af6e1 | [] | no_license | estivenramirez/SemilleroJava | daf7764bb28bd0c898e6569b839453030843aeb2 | 430d2c253456a457a457e6ca812276b4244502fc | refs/heads/main | 2023-01-29T19:20:23.836695 | 2020-12-05T16:49:05 | 2020-12-05T16:49:05 | 312,613,990 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 250 | java | package com.semillerojava.demospringboot.demoSpringboot.service;
import java.util.List;
import com.semillerojava.demospringboot.demoSpringboot.model.Cuenta;
public interface CuentaService {
List<Cuenta> listar();
Cuenta crear(Cuenta cuena);
}
| [
"estiuv20@hotmail.com"
] | estiuv20@hotmail.com |
1fa2ea2287ad75f22f273e02a3f2f9469093c064 | 6986725b55bdf94729ba2f4ec2d9735ec16fe8d6 | /Your Doc/app/src/main/java/com/ahmed/yourdoc/view_holders/SubTitleViewHolder.java | 5c23f898ac615fdf20986ddf3ff56e1422f162fa | [
"Apache-2.0"
] | permissive | UchihaMadara/yourdoctor | 94f94e7478adeefa319f66d91aca1036731772f6 | 1ae222eeeef56440dab9d37ce6954ee7fc9945d6 | refs/heads/master | 2021-01-02T23:01:51.604682 | 2017-09-30T20:27:46 | 2017-09-30T20:27:46 | 99,446,028 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 598 | java | package com.ahmed.yourdoc.view_holders;
import android.view.View;
import android.widget.TextView;
import com.ahmed.yourdoc.R;
import com.thoughtbot.expandablerecyclerview.viewholders.ChildViewHolder;
/**
* Created by kuliza-195 on 12/23/16.
*/
public class SubTitleViewHolder extends ChildViewHolder {
private TextView subTitleTextView;
public SubTitleViewHolder(View itemView) {
super(itemView);
subTitleTextView = (TextView) itemView.findViewById(R.id.subtitle);
}
public void setSubTitletName(String sub) {
subTitleTextView.setText(sub);
}
}
| [
"Gemo@GeMoOo.local"
] | Gemo@GeMoOo.local |
6504b9bacbdbd9841715d6c22377770bc4b6a1a2 | 731b711d7b93aa33e1b25e59c76e048bc4c5a2b6 | /src/fuelefficiency/FuelEfficiency.java | ec73c0aa7473a3f0fabbe958592597f8f05e1a5c | [] | no_license | matthewludwig1/FuelEfficiency | 2415d787c3732daba1dbb69d4180b70d30eaf300 | 8d2fd5cf44f6348835b57b061258b3f0a66a3231 | refs/heads/master | 2020-05-23T05:44:15.624386 | 2019-05-16T15:33:31 | 2019-05-16T15:33:31 | 186,653,577 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,016 | java | /*
Matt Ludwig
2019-05-16
This program implements polymorphism
*/
package fuelefficiency;
/**
*
* @author malud0519
*/
import javax.swing.*;
public class FuelEfficiency {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
double fuel;
Vehicle vehicles[] = new Vehicle[4];
vehicles[0] = new Car();
vehicles[1] = new Truck();
vehicles[2] = new HybridCar();
vehicles[3] = new Motorcycle();
fuel = Double.parseDouble(JOptionPane.showInputDialog("Fuel Efficiencies for Vehicles: "
+ "Enter the amount of fuel: "));
System.out.println("On " + fuel + "L of gas, the vehicles can drive: " + "\n");
for (int i = 0; i < 4; i++) {
System.out.println(vehicles[i].getName() + vehicles[i].getDistance(fuel)); // inputs 50 litres into each vehicle's method getDistance()
}
}
}
| [
"malud0519@7L9N6Y1.Student.UGDSB.ED"
] | malud0519@7L9N6Y1.Student.UGDSB.ED |
1e950b02c11ab94796570f014876493a35cba2cc | aae731706bf2d9b5f23d9c37fbdca53a918e64e5 | /good-module/src/main/java/com/ooad/good/service/ShopService.java | f68ff5d30a0cbd649ce9a3a3754b807a12f43089 | [] | no_license | ESZAN/OOAD-Good-Module | 5648d7c890c2eb30df2a2eebbf1a1231808d6874 | e7856ec779bd9a730f64d99bb30d525618ecd78c | refs/heads/master | 2023-02-04T16:40:54.741337 | 2020-12-23T21:33:12 | 2020-12-23T21:33:12 | 320,555,880 | 0 | 0 | null | 2020-12-23T21:01:12 | 2020-12-11T11:33:06 | Java | UTF-8 | Java | false | false | 2,070 | java | package com.ooad.good.service;
import cn.edu.xmu.ooad.util.ReturnObject;
import com.ooad.good.dao.ShopDao;
import com.ooad.good.model.bo.Shop;
import com.ooad.good.model.vo.shop.ShopVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @Author: Chaoyang Deng
* @Date: 2020/12/9 上午8:46
*/
@Service
public class ShopService {
private Logger logger = LoggerFactory.getLogger(ShopService.class);
@Autowired
ShopDao shopDao;
/**
* 增加店铺
* @param shop
* @return
*/
@Transactional
public ReturnObject insertShop(Shop shop) {
ReturnObject<Shop> retObj = shopDao.insertShop(shop);
return retObj;
}
/**
* 查询
* @return
*/
/*
public ReturnObject<List> getAllShopStates() {
ReturnObject<List> retObj = shopDao.getAllShopStates();
return retObj;
}*/
/**
* 修改任意店铺信息
* @param id 店铺 id
* @param vo ShopEditVo 对象
* @return 返回对象 ReturnObject
*/
@Transactional
public ReturnObject<Object> modifyShopInfo(Long id, ShopVo vo) {
return shopDao.modifyShopByVo(id, vo);
}
/**
* 删除店铺
* @return
*/
@Transactional
public ReturnObject deleteShop(Long id) {
return shopDao.deleteShop(id);
}
/**
* 审核店铺信息
* @param id
* @return
*/
@Transactional
public ReturnObject auditShopInfo(Long id,boolean conJudge)
{
return shopDao.auditShopInfo(id,conJudge);
}
/**
* 上线店铺
* @return
*/
@Transactional
public ReturnObject onshelvesShop(Long id) {
return shopDao.onshelvesShop(id);
}
/**
* 下线店铺
* @return
*/
@Transactional
public ReturnObject offshelvesShop(Long id) {
return shopDao.offshelvesShop(id);
}
}
| [
"619589297@qq.com"
] | 619589297@qq.com |
5ec413d23d7d451431fcfe0883fb755aecec7a8c | 265399e93dd03aff21d852b5fef09975ecc8b408 | /app/src/main/java/com/diegovelez/petagram/fragment/iRecyclerViewFragmentView.java | c411693e8b01d0cd5a4f7ebe017f781510fbe99c | [] | no_license | diego8207/Petagram_ | 32057f53ccd2749cd437e0c29bbb7fed94380f67 | ba3c791fc9a10e4f50856bbdc01cd327285a96c4 | refs/heads/master | 2021-01-12T07:06:13.596321 | 2017-04-19T21:55:00 | 2017-04-19T21:55:00 | 76,911,776 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 462 | java | package com.diegovelez.petagram.fragment;
import com.diegovelez.petagram.adapter.MascotaAdaptador;
import com.diegovelez.petagram.pojo.Mascota;
import java.util.ArrayList;
/**
* Created by Diego Velez on 11/04/2017.
*/
public interface iRecyclerViewFragmentView {
public void generarLinearLayoutVertical();
public MascotaAdaptador crearAdaptador(ArrayList<Mascota> mascotas);
public void inicializarAdaptador(MascotaAdaptador adaptador);
}
| [
"si.macrosystem@gmail.com"
] | si.macrosystem@gmail.com |
80872a426f4670dfbb70caf9843e9a6e7f21e173 | 5305a38b72f2eab3712daa6d5a4dac076eb407d9 | /src/com/jh/multiplayergame/ui/ColorArea.java | d446393189de4d443557a418f48efc946a5bd4bc | [] | no_license | jholdstock/AndroidGame | ee0f8177147f688addbd05d55001558ee7a8d8ca | 0ca3b9502cf71a4a8b05a4744fc1db7ecbcfe0d2 | refs/heads/master | 2021-01-02T22:44:38.451720 | 2015-07-22T10:23:11 | 2015-07-22T10:23:11 | 39,499,503 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 526 | java | package com.jh.multiplayergame.ui;
import org.andengine.entity.sprite.Sprite;
import org.andengine.util.color.Color;
import com.jh.multiplayergame.C;
import com.jh.multiplayergame.Textures;
public class ColorArea
{
public Sprite area;
public static final int X = 690;
public static final int Y = 50;
public ColorArea()
{
area = new Sprite(X, Y, Textures.questionAreaTexture, C.VMANAGER);
C.SCENE.attachChild(area);
}
public void setColor(Color color)
{
area.setColor(color);
}
}
| [
"jam.jar69@gmail.com"
] | jam.jar69@gmail.com |
79236e65a8919993ab9286b386851ba911335180 | 3b8832a1c552c81a1854dff662b4bf48a0e842a2 | /java/datastructure/src/main/java/com/vicky/datastructure/sort/StraightSelectionSort.java | b4b60e2581cf3fff321484b7e2c2a57d61557652 | [] | no_license | cgcn/StudyBuddy | 4c52ea1a56a343557c07aab2f61ed12e28ba0c17 | 113a063f1c428b3fd9c05fa41d67b75bb0d40e4b | refs/heads/master | 2020-09-12T15:30:59.617438 | 2015-11-27T05:05:20 | 2015-11-27T05:05:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,583 | java | package com.vicky.datastructure.sort;
import java.util.Arrays;
import java.util.Random;
/**
* <p>
* 选择排序:直接选择排序
*
* 基本思想:
* 直接选择排序同直接插入排序,也是将整个序列分为有序区和无序区,所不同的是直接播放排序是将无序区的第一个元素直接插入到有序区以形成一个更大的有序区
* ,而直接选择排序是从无序区选一个最小的元素直接放到有序区的最后。
*
* 时间复杂度:O(n^2)
*
* 空间复杂度:θ(1)
*
* 稳定性:不稳定
* </p>
*
* @author Vicky
* @date 2015-8-13
*/
public class StraightSelectionSort {
/**
* 排序
*
* @param data
* 待排序的数组
*/
public static <T extends Comparable<T>> void sort(T[] data) {
if (null == data) {
throw new NullPointerException("data");
}
if (data.length == 1) {
return;
}
for (int st = 0; st < data.length - 1; st++) {
int j = st + 1;
int min = st;
// 找到最小元素的位置
for (; j < data.length; j++) {
if (data[j].compareTo(data[min]) < 0) {
min = j;
}
}
// 将最小元素放到有序区尾部
if (min != st) {// 避免跟自身交换
T temp = data[st];
data[st] = data[min];
data[min] = temp;
}
}
}
public static void main(String[] args) {
Random ran = new Random();
Integer[] data = new Integer[100000];
for (int i = 0; i < data.length; i++) {
data[i] = ran.nextInt(10000000);
}
StraightSelectionSort.sort(data);
System.out.println(Arrays.toString(data));
}
}
| [
"vickyqi012@gmail.com"
] | vickyqi012@gmail.com |
aeb8143fb2285e05c0ae7ddb1364b83e790b5633 | 70f3d9ba6621faf97ec3dee8f732474afea79e21 | /src/main/java/com/dh/s4/models/ClassEntity.java | 1a1d85ac139972c89f1224c4e3eb90a1efac2681 | [] | no_license | c-marv/test-s4 | 68ff523162678f782fdf60b2c015bd75f0b64893 | 1077f65dc7301feb65504a6aa39a56f744adf98b | refs/heads/master | 2023-03-17T11:27:36.882512 | 2021-03-18T20:57:13 | 2021-03-18T20:57:13 | 348,893,790 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 678 | java | package com.dh.s4.models;
public class ClassEntity {
private String code;
private String title;
private String description;
public ClassEntity(String code, String title, String description) {
this.code = code;
this.title = title;
this.description = description;
}
public String getCode() {
return code;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| [
"yerson.copa@gmail.com"
] | yerson.copa@gmail.com |
a78973fab1c6791f44a5fb58fc14d3287616eb1c | a1ef3d3c07a5d68c3a185b8043ba433f81f5026b | /src/main/java/com/aws/ec2/TerminateECS.java | 89c741d85b52ad5d73e9b9db32de4928e3f218bd | [] | no_license | ranjith494/backpack | d1776ebb0d01486de44383a1e60b6122a786ad3a | 9a9596943a36a7919ef8e4f8cf8e3c53ffe30d06 | refs/heads/master | 2021-01-10T05:39:07.221394 | 2015-10-24T23:22:40 | 2015-10-24T23:22:40 | 44,878,579 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,626 | java | package com.aws.ec2;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ecs.AmazonECSClient;
import com.aws.ec2.helper.AwsHelper;
public class TerminateECS {
private AmazonECSClient amazonECSClient;
private AmazonEC2Client amazonEC2Client;
private static AWSCredentials credentials;
private static final Logger logger = LogManager
.getLogger(TerminateECS.class.getName());
public static void main(String a[]) {
TerminateECS terminator = new TerminateECS(new AmazonECSClient(
credentials), new AmazonEC2Client(credentials));
terminator.terminate();
}
static {
AwsHelper helper = AwsHelper.getInstance();
credentials = helper.getAWSCredentials();
}
public TerminateECS() {
}
public TerminateECS(AmazonECSClient amazonECSClient,
AmazonEC2Client amazonEC2Client) {
super();
this.amazonECSClient = amazonECSClient;
this.amazonEC2Client = amazonEC2Client;
}
public void terminate() {
AwsHelper helper = AwsHelper.getInstance();
// Stop all Tasks running on ECS Instances
logger.debug("Stop all Tasks running on ECS Instances");
helper.stopTask(amazonECSClient);
// Deregister Task Definition
helper.deRegisterTaskDefinition("multi-browser-test-task:2",
amazonECSClient);
helper.deRegisterTaskDefinition("multi-browser-test-task:1",
amazonECSClient);
// Deregister all ECS Instances
helper.deRegisterContainerInstances(amazonECSClient);
// delete Services
// helper.deleteServiceRequest("selenium-vnc", amazonECSClient);
// Stop EC2 Instances
List<String> instanctIdList = new ArrayList<String>();
instanctIdList.add("i-663b62b2");
try {
helper.stopInstances(instanctIdList, amazonEC2Client);
} catch (RemoteException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Terminate Ec2 Instances
logger.debug("Terminate Ec2 Instances");
helper.terminateInstances(instanctIdList, amazonEC2Client);
// Delete Security group
try {
helper.deleteSecurityGroupRequestWithGroupName("ECSSecurityGroup",
null, amazonEC2Client);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
logger.warn("Unable to delete. Proceeding!!");
}
// Delete Key pair
helper.deleteKeyPairRequest("myecskeypair", amazonEC2Client);
}
}
| [
"ranjith494@gmail.com"
] | ranjith494@gmail.com |
f726475627a1e01b99dc115566f4bd6780ae5235 | fc69e286d5b787a59f2b04693aa884a0f961152d | /src/java/Controller/EstateStatusJpaController.java | f36755dd08622fe4396642cb09f75d2660250475 | [] | no_license | MustacheTuanVu/ProjectRealEstate | 9c1d82f3017f47075b00d001e7e9f3ef3fc18bd4 | 4ff39e3ae1425d6de632b3e4dc848e247dd597c0 | refs/heads/master | 2020-04-26T16:30:31.316206 | 2019-05-10T05:01:07 | 2019-05-10T05:01:07 | 173,681,385 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,874 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import Controller.exceptions.IllegalOrphanException;
import Controller.exceptions.NonexistentEntityException;
import Controller.exceptions.PreexistingEntityException;
import Controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entity.Estate;
import Entity.EstateStatus;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
/**
*
* @author kiems
*/
public class EstateStatusJpaController implements Serializable {
public EstateStatusJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(EstateStatus estateStatus) throws PreexistingEntityException, RollbackFailureException, Exception {
if (estateStatus.getEstateList() == null) {
estateStatus.setEstateList(new ArrayList<Estate>());
}
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
List<Estate> attachedEstateList = new ArrayList<Estate>();
for (Estate estateListEstateToAttach : estateStatus.getEstateList()) {
estateListEstateToAttach = em.getReference(estateListEstateToAttach.getClass(), estateListEstateToAttach.getId());
attachedEstateList.add(estateListEstateToAttach);
}
estateStatus.setEstateList(attachedEstateList);
em.persist(estateStatus);
for (Estate estateListEstate : estateStatus.getEstateList()) {
EstateStatus oldEstateStatusIdOfEstateListEstate = estateListEstate.getEstateStatusId();
estateListEstate.setEstateStatusId(estateStatus);
estateListEstate = em.merge(estateListEstate);
if (oldEstateStatusIdOfEstateListEstate != null) {
oldEstateStatusIdOfEstateListEstate.getEstateList().remove(estateListEstate);
oldEstateStatusIdOfEstateListEstate = em.merge(oldEstateStatusIdOfEstateListEstate);
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findEstateStatus(estateStatus.getId()) != null) {
throw new PreexistingEntityException("EstateStatus " + estateStatus + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(EstateStatus estateStatus) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
EstateStatus persistentEstateStatus = em.find(EstateStatus.class, estateStatus.getId());
List<Estate> estateListOld = persistentEstateStatus.getEstateList();
List<Estate> estateListNew = estateStatus.getEstateList();
List<String> illegalOrphanMessages = null;
for (Estate estateListOldEstate : estateListOld) {
if (!estateListNew.contains(estateListOldEstate)) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("You must retain Estate " + estateListOldEstate + " since its estateStatusId field is not nullable.");
}
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
List<Estate> attachedEstateListNew = new ArrayList<Estate>();
for (Estate estateListNewEstateToAttach : estateListNew) {
estateListNewEstateToAttach = em.getReference(estateListNewEstateToAttach.getClass(), estateListNewEstateToAttach.getId());
attachedEstateListNew.add(estateListNewEstateToAttach);
}
estateListNew = attachedEstateListNew;
estateStatus.setEstateList(estateListNew);
estateStatus = em.merge(estateStatus);
for (Estate estateListNewEstate : estateListNew) {
if (!estateListOld.contains(estateListNewEstate)) {
EstateStatus oldEstateStatusIdOfEstateListNewEstate = estateListNewEstate.getEstateStatusId();
estateListNewEstate.setEstateStatusId(estateStatus);
estateListNewEstate = em.merge(estateListNewEstate);
if (oldEstateStatusIdOfEstateListNewEstate != null && !oldEstateStatusIdOfEstateListNewEstate.equals(estateStatus)) {
oldEstateStatusIdOfEstateListNewEstate.getEstateList().remove(estateListNewEstate);
oldEstateStatusIdOfEstateListNewEstate = em.merge(oldEstateStatusIdOfEstateListNewEstate);
}
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = estateStatus.getId();
if (findEstateStatus(id) == null) {
throw new NonexistentEntityException("The estateStatus with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
EstateStatus estateStatus;
try {
estateStatus = em.getReference(EstateStatus.class, id);
estateStatus.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The estateStatus with id " + id + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
List<Estate> estateListOrphanCheck = estateStatus.getEstateList();
for (Estate estateListOrphanCheckEstate : estateListOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This EstateStatus (" + estateStatus + ") cannot be destroyed since the Estate " + estateListOrphanCheckEstate + " in its estateList field has a non-nullable estateStatusId field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
em.remove(estateStatus);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<EstateStatus> findEstateStatusEntities() {
return findEstateStatusEntities(true, -1, -1);
}
public List<EstateStatus> findEstateStatusEntities(int maxResults, int firstResult) {
return findEstateStatusEntities(false, maxResults, firstResult);
}
private List<EstateStatus> findEstateStatusEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(EstateStatus.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public EstateStatus findEstateStatus(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(EstateStatus.class, id);
} finally {
em.close();
}
}
public int getEstateStatusCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<EstateStatus> rt = cq.from(EstateStatus.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
| [
"41681048+MustacheTuanVu@users.noreply.github.com"
] | 41681048+MustacheTuanVu@users.noreply.github.com |
975a0a7f5e1937c76c0742b3e2878c8a2755ffda | 2693ef100f88d0d2fbbdc095a7526597cb683dc3 | /编译原理和设计/大作业/ex7/src/bit/minisys/minicc/icgen/ExampleICBuilder.java | 1f4d2d67db931510e713f5abeae17a29a872a110 | [] | no_license | RIU-13/BIT-Study-Materials | 4987623f1e073e2c34f2ddcf886b91c23441343e | 916047a832e806eb71642550f2029d6c0f39b583 | refs/heads/main | 2023-07-06T15:39:54.515875 | 2021-07-30T14:23:24 | 2021-07-30T14:23:24 | 405,106,611 | 4 | 2 | null | 2021-09-10T14:21:48 | 2021-09-10T14:21:47 | null | GB18030 | Java | false | false | 36,604 | java | package bit.minisys.minicc.icgen;
import java.util.*;
import bit.minisys.minicc.parser.ast.*;
// 一个简单样例,只实现了加法
class Symbol {
String name;//名字
String kind;//种类,包括变量、常量、函数定义、数组和标号等
String type;//int、double类型
int link; //上一个
List<Symbol> params;
int paraId;
int lbId;
int arrId;
public void print()
{
System.out.printf("{name:%s;kind:%s;type:%s;link:%d}\n",name,kind,type,link);
}
}
class BodySymbol {
int lastPar; //形参最后id
int last; //变量id最后
int pSize; //总参数变量大小
int vSize; //总变量大小
}//函数体body
class DisplaySymbol{
Stack<Integer> disTab; //层次关系
DisplaySymbol(){
disTab = new Stack<Integer>();
}
}
class LabelSymbol{
int id; //唯一标识
int ir_id;//中间代码的label值
boolean f;//定义性出现还是使用性出现
}
class ArrayTable{
int id; //唯一标识
String elType; //元素种类
int elRef; //若是多维数组
int size; //数组大小
}
public class ExampleICBuilder implements ASTVisitor{
private Map<ASTNode, ASTNode> map; // 使用map存储子节点的返回值,key对应子节点,value对应返回值,value目前类别包括ASTIdentifier,ASTIntegerConstant,TemportaryValue...
private List<Quat> quats; // 生成的四元式列表
private Integer tmpId; // 临时变量编号
Stack<Integer> false_num = new Stack<>();
Stack<Integer> label_num = new Stack<>();
Stack<Integer> step_num = new Stack<>();
public List<Symbol> SymbolTables = new ArrayList<>();
public DisplaySymbol displaySymbols = new DisplaySymbol();
public List<LabelSymbol> labelSymbols = new ArrayList<>();
//public List<ArrayTable> arrayTables = new ArrayList<>();
public List<BodySymbol> bodySymbols = new ArrayList<>();
Map<ASTNode, Symbol> mapSb = new HashMap<>();
Map<String,String> mapType = new HashMap<>();
Map<Symbol,Integer> mapGotolb = new HashMap<>();
//Map<ASTArrayDeclarator,Integer> mapArrRef = new HashMap<>();
boolean flag = false;
public int fIter = 0;//对循环语句标记,看是否在循环语句里面
public int freturn = 0;
public int bodyId = -1;
void printError(String errorstring,int errorid)
{
if(!flag)
{
System.out.println("errors:");
System.out.println("------------------------------------");
flag = true;
}
System.out.println("ES0"+errorid+" >> "+errorstring);
}
void printErrorEnd()
{
if(flag)
System.out.println("------------------------------------");
}
boolean checkAllLabel(BodySymbol bs){
//bs是函数定义的那部分
if(labelSymbols.size()!=0)
{
int j = 0;
int id = bs.last;
while(j<bs.vSize){
Symbol sb = SymbolTables.get(id);
//sb.print();
if(sb.kind == "GotoStatement")
{
LabelSymbol lsb = labelSymbols.get(sb.lbId);
if(!lsb.f){
printError("Label: "+sb.name+" is not defined.",7);
return false;
}
return true;
}
j++;
id = sb.link;
}
return true;
}
return true;
}
//有无重复定义变量
boolean checkRepeat(Symbol sb)
{
int btable_num = displaySymbols.disTab.peek();
//System.out.println("--"+btable_num);
int j =0;
int id = bodySymbols.get(btable_num).last;
// System.out.println(id);
// System.out.println(bodySymbols.get(btable_num).vSize);
while(j<bodySymbols.get(btable_num).vSize)
{
Symbol temp_sb = SymbolTables.get(id);
//temp_sb.print();
boolean cond1 = sb.name.equals(temp_sb.name)&&sb.kind.equals(temp_sb.kind);
boolean cond2 = sb.name.equals(temp_sb.name)&&sb.kind.equals("GotoStatement");
boolean cond3 = sb.name.equals(temp_sb.name)&&sb.kind.equals("LabeledStatement");
if(cond1||cond2||cond3){
if(sb.kind == "FunctionDefine")
//如果包含,则表示重复
printError(temp_sb.kind+" "+sb.name+" is defined.",2);
else if(temp_sb.kind == "LabeledStatement")
{
LabelSymbol ls = labelSymbols.get(temp_sb.lbId);
if(ls.f)
{
//定义性出现
printError("Label: "+temp_sb.name+" has been defined",1);
}
else //goto、未定义
{
mapGotolb.put(sb,ls.ir_id);
ls.f = true;
return false;
}
}
else if(temp_sb.kind == "GotoStatement"){
//之前已经出现过了
LabelSymbol ls = labelSymbols.get(temp_sb.lbId);
if(sb.kind == "LabeledStatement")
ls.f = true;
mapGotolb.put(sb,ls.ir_id);
return false;
}else
printError(temp_sb.kind+" "+ sb.name + " has been declarated.",2);
return false;
}
j++;
id = temp_sb.link;
}
return true;
}
//判断参数类型是否一致
boolean checkMatch(Symbol A, Symbol B)
{
if(!A.type.equals(B.type))
return false;
else
return true;
}
boolean checkIn(Symbol sb) {
// sb.print();
Symbol sb_res = new Symbol();
Stack<Integer> temp_s = new Stack<>();
BodySymbol btable_res = new BodySymbol();
boolean res = true;
boolean f = false;
int ksize = displaySymbols.disTab.size();
for (int i = 0; i < ksize; i++) {
int btable_num = displaySymbols.disTab.pop();
//System.out.println(btable_num);
temp_s.push(btable_num);
int j = 0;
int id = bodySymbols.get(btable_num).last;
while (j < bodySymbols.get(btable_num).vSize) {
Symbol sb_ed = SymbolTables.get(id);
//sb_ed.print();
//如果变量名相等
if (sb.name.equals(sb_ed.name)) {
f = true;
sb_res = sb_ed;
break;
}
id = sb_ed.link;
j++;
}
if (f) {
btable_res = bodySymbols.get(btable_num);
break;
}
}
if (f) {
//sb.print();
//找到了,看匹配
if (sb.kind == "FunctionCall") {
btable_res = bodySymbols.get(sb_res.paraId);
//先判断参数长度
//sb_res.print();
if (btable_res.pSize != sb.params.size()) {
printError(sb.kind + ":" + sb.name + "'s" + " param num is not matched.", 4);
res = false;
}
else{
//System.out.println(temp.param.size());
//再判断参数类型是否匹配
int j = 0;
int id = btable_res.lastPar;
while (j < btable_res.pSize) {
Symbol temp_sb = SymbolTables.get(id);
if (!checkMatch(temp_sb, sb.params.get(j))) {
printError(sb.kind + ":" + sb.name + "'s" + " param type is not matched.", 4);
res = false;
break;
}
j++;
id = temp_sb.link;
}
}
}else if(sb.kind == "GotoStatement"){
mapGotolb.put(sb,labelSymbols.get(sb_res.lbId).ir_id);
}
res = true;
}else if(sb.kind == "GotoStatement"){
//没有检查到
res = false;
}
else {
if (sb.kind == "FunctionCall")
printError(sb.kind + " " + sb.name + " is not declarated.", 1);
else
printError(sb.kind + " " + sb.name + " is not defined.", 1);
res = false;
}
//再恢复displaytable
ksize = temp_s.size();
for(int i=0;i<ksize;i++)
{
displaySymbols.disTab.push(temp_s.pop());
}
mapType.put(sb.name,sb_res.type);
return res;
}
public ExampleICBuilder() {
map = new HashMap<ASTNode, ASTNode>();
quats = new LinkedList<Quat>();
tmpId = 0;
}
public List<Quat> getQuats() {
return quats;
}
@Override
public void visit(ASTCompilationUnit program) throws Exception {
displaySymbols.disTab.push(0);
BodySymbol bodySymbol = new BodySymbol();
bodySymbol.last = bodySymbol.lastPar = -1;
bodySymbol.pSize = bodySymbol.vSize = 0;
bodySymbols.add(bodySymbol);
for (ASTNode node : program.items) {
if(node instanceof ASTFunctionDefine)
visit((ASTFunctionDefine)node);
else if(node instanceof ASTDeclaration)
visit((ASTDeclaration) node);
}
printErrorEnd();
}
@Override
public void visit(ASTDeclaration declaration) throws Exception {
// TODO Auto-generated method stub
BodySymbol bs = bodySymbols.get(displaySymbols.disTab.peek());
//System.out.println(displaySymbols.disTab.peek());
Symbol sb = new Symbol();
sb.type = "";
for(int i=0;i<declaration.specifiers.size();i++)
{
visit(declaration.specifiers.get(i));
sb.type += mapSb.get(declaration.specifiers.get(i)).type+" ";
}
for(int i=0;i<declaration.initLists.size();i++)
{
visit(declaration.initLists.get(i));
Symbol sb_res = mapSb.get(declaration.initLists.get(i));
sb_res.type = sb.type;
sb_res.link = bs.last;
//判断有无重复
if(checkRepeat(sb_res)){
//sb_res.print();
SymbolTables.add(sb_res);
bs.vSize++;
bs.last = SymbolTables.size()-1;
//System.out.println(bs.last);
}
}
}
@Override
public void visit(ASTArrayDeclarator arrayDeclarator) throws Exception {
// TODO Auto-generated method stub
visit(arrayDeclarator.declarator);
Symbol sb = mapSb.get(arrayDeclarator.declarator);
sb.kind = arrayDeclarator.getType();
mapSb.put(arrayDeclarator,sb);
}
@Override
public void visit(ASTVariableDeclarator variableDeclarator) throws Exception {
// TODO Auto-generated method stub
map.put(variableDeclarator,variableDeclarator.identifier);
//获得符号
visit(variableDeclarator.identifier);
Symbol symbol = mapSb.get(variableDeclarator.identifier);
mapSb.put(variableDeclarator,symbol);
}
@Override
public void visit(ASTFunctionDeclarator functionDeclarator) throws Exception {
// TODO Auto-generated method stub
//map.put(functionDeclarator,functionDeclarator.declarator);
visit(functionDeclarator.declarator);
Symbol sb = mapSb.get(functionDeclarator.declarator);
sb.kind = functionDeclarator.getType();
mapSb.put(functionDeclarator,sb);
if(functionDeclarator.params!=null)
{
for(int i=functionDeclarator.params.size()-1;i>=0;i--)
{
visit(functionDeclarator.params.get(i));
}
}
}
@Override
public void visit(ASTParamsDeclarator paramsDeclarator) throws Exception {
// TODO Auto-generated method stub
//fill the symbol ??
//形式参数
BodySymbol bs = bodySymbols.get(displaySymbols.disTab.peek());
Symbol sb = new Symbol();
sb.type = "";
for(int i=0;i<paramsDeclarator.specfiers.size();i++)
{
visit(paramsDeclarator.specfiers.get(i));
sb.type += mapSb.get(paramsDeclarator.specfiers.get(i)).type+" ";
}
visit(paramsDeclarator.declarator);
sb.name = mapSb.get(paramsDeclarator.declarator).name;
sb.kind = paramsDeclarator.declarator.getType();
sb.link = bs.lastPar;
if(checkRepeat(sb))
{
//sb.print();
SymbolTables.add(sb);
bs.lastPar = SymbolTables.size()-1;
bs.pSize++;
bs.last = SymbolTables.size()-1;
bs.vSize++;
}
//ir 生成
String op = "pop";
visit(paramsDeclarator.declarator);
ASTNode res = map.get(paramsDeclarator.declarator);
ASTNode opnd1 = null;
ASTNode opnd2 = null;
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
}
@Override
public void visit(ASTArrayAccess arrayAccess) throws Exception {
// TODO Auto-generated method stub
String op = "[]";
ASTNode res = null;
ASTNode opnd1 = null;
ASTNode opnd2 = null;
res = new TemporaryValue(++tmpId);
visit(arrayAccess.arrayName);
opnd1 = map.get(arrayAccess.arrayName);
for(int i=0;i<arrayAccess.elements.size();i++)
{
visit(arrayAccess.elements.get(i));
opnd2 = map.get(arrayAccess.elements.get(i));
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
}
map.put(arrayAccess,res);
}
public void visitSb(ASTExpression expression) throws Exception{
if(expression instanceof ASTIdentifier){
Symbol sb = new Symbol();
visit((ASTIdentifier) expression);
sb.name = mapSb.get(expression).name;
sb.kind = expression.getType();
checkIn(sb);
sb.type = mapType.get(sb.name);
mapSb.put(expression,sb);
//sb.print();
}
else if(expression instanceof ASTBinaryExpression) {
visitSb(((ASTBinaryExpression) expression).expr1);
visitSb(((ASTBinaryExpression) expression).expr2);
}
else if(expression instanceof ASTCastExpression){
visitSb(((ASTCastExpression) expression).expr);
}
else if(expression instanceof ASTUnaryExpression){
visitSb(((ASTUnaryExpression) expression).expr );
}
else if(expression instanceof ASTPostfixExpression){
visitSb(((ASTPostfixExpression) expression).expr);
}
}
@Override
public void visit(ASTBinaryExpression binaryExpression) throws Exception {
visitSb(binaryExpression);
Symbol sb = mapSb.get(binaryExpression);
//sb.print();
mapSb.put(binaryExpression,sb);
String op = binaryExpression.op.value;
String numType1="";
if(binaryExpression.expr1 instanceof ASTIdentifier)
{
//取出表达式左值类型
ASTIdentifier identifier = (ASTIdentifier) binaryExpression.expr1;
numType1 = mapType.get(identifier.value);
if(numType1=="")
return ;
}
else if(binaryExpression.expr1 instanceof ASTIntegerConstant)
{
numType1 = "int";
}
else if(binaryExpression.expr1 instanceof ASTFloatConstant)
{
numType1 = "float";
}
String numType2="" ;
if(binaryExpression.expr2 instanceof ASTIdentifier)
{
//取出表达式左值类型
ASTIdentifier identifier = (ASTIdentifier) binaryExpression.expr2;
numType2 = mapType.get(identifier.value);
if(numType2=="")
return ;
}
else if(binaryExpression.expr2 instanceof ASTIntegerConstant)
{
numType2 = "int";
}
else if(binaryExpression.expr2 instanceof ASTFloatConstant)
{
numType2 = "float";
}
switch (op)
{
case "|":
case "&":
case "^":
case "<<":
case ">>":
if(numType1.equals("float ")||numType2.equals("float ")||numType1.equals("double ")||numType2.equals("double "))
{
printError("BinaryExpression:(<< >> & | ^)expression's should be int.",5);
}
break;
default:
}
ASTNode res = null;
ASTNode opnd1 = null;
ASTNode opnd2 = null;
String[] bin_ops = {"+","-","*","/","%","<<",">>","<",">","<=",">=","&&","||","=="};
String[] un_ops = {"++","--","sizeof","~","!","-",};
String[] ass_ops = {"=","*=","/=","%=","+=","-=","<<=",">>=","&=","^=","|="};
if (Arrays.asList(ass_ops).contains(op)) {
// 赋值操作
// 获取被赋值的对象res
visit(binaryExpression.expr1);
res = map.get(binaryExpression.expr1);
// 判断源操作数类型, 为了避免出现a = b + c; 生成两个四元式:tmp1 = b + c; a = tmp1;的情况。也可以用别的方法解决
if (binaryExpression.expr2 instanceof ASTIdentifier) {
opnd1 = binaryExpression.expr2;
}else if(binaryExpression.expr2 instanceof ASTIntegerConstant) {
opnd1 = binaryExpression.expr2;
}else if(binaryExpression.expr2 instanceof ASTBinaryExpression) {
ASTBinaryExpression value = (ASTBinaryExpression)binaryExpression.expr2;
op = value.op.value;
visit(value.expr1);
opnd1 = map.get(value.expr1);
visit(value.expr2);
if(value.expr2 instanceof ASTIdentifier){
}
//sb.print();
opnd2 = map.get(value.expr2);
}else if(binaryExpression.expr2 instanceof ASTUnaryExpression){
ASTUnaryExpression value = (ASTUnaryExpression) binaryExpression.expr2;
opnd1 = null;
visit(value);
opnd2 = map.get(value.expr);
}else if(binaryExpression.expr2 instanceof ASTPostfixExpression){
ASTPostfixExpression value = (ASTPostfixExpression) binaryExpression.expr2;
visit(value);
opnd1 = map.get(value.expr);
opnd2 = null;
}else if(binaryExpression.expr2 instanceof ASTFunctionCall){
visit(binaryExpression.expr2);
opnd1 = map.get(binaryExpression.expr2);
}else if(binaryExpression.expr2 instanceof ASTArrayAccess){
visit(binaryExpression.expr2);
opnd1 = map.get(binaryExpression.expr2);
}
}else if (Arrays.asList(bin_ops).contains(op)) {
// 加法操作,结果存储到中间变量
res = new TemporaryValue(++tmpId);
visit(binaryExpression.expr1);
opnd1 = map.get(binaryExpression.expr1);
visit(binaryExpression.expr2);
opnd2 = map.get(binaryExpression.expr2);
}else if(Arrays.asList(un_ops).contains(op)) {
// 一元运算
res = new TemporaryValue(++tmpId);
visit(binaryExpression.expr1);
opnd1 = map.get(binaryExpression.expr1);
visit(binaryExpression.expr2);
opnd2 = map.get(binaryExpression.expr2);
}
// build quat
Quat quat = new Quat(op, res, opnd1, opnd2);
quats.add(quat);
map.put(binaryExpression, res);
}
@Override
public void visit(ASTBreakStatement breakStat) throws Exception {
// TODO Auto-generated method stub
if(fIter<=0)
{
//说明break没有在循环体里面
printError("BreakStatement:must be in a LoopStatement.",3);
}
if(!false_num.empty())
{
String op = "jmp";
int num = false_num.pop();
ASTNode res = new TemporaryValue(num);
false_num.push(num);
ASTNode opnd1 = null;
ASTNode opnd2 = null;
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
}
}
@Override
public void visit(ASTContinueStatement continueStatement) throws Exception {
// TODO Auto-generated method stub
if(fIter<=0)
{
//说明break没有在循环体里面
printError("BreakStatement:must be in a LoopStatement.",3);
}
else{
String op = "jmp";
ASTNode res = new TemporaryValue(++tmpId);
step_num.push(tmpId);
ASTNode opnd1 = null;
ASTNode opnd2 = null;
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
}
}
@Override
public void visit(ASTCastExpression castExpression) throws Exception {
// TODO Auto-generated method stub
visit(castExpression.typename);
}
@Override
public void visit(ASTCharConstant charConst) throws Exception {
// TODO Auto-generated method stub
map.put(charConst,charConst);
Symbol sb = new Symbol();
sb.type = "char ";
mapSb.put(charConst,sb);
}
@Override
public void visit(ASTCompoundStatement compoundStat) throws Exception {
for (ASTNode node : compoundStat.blockItems) {
if(node instanceof ASTDeclaration) {
visit((ASTDeclaration)node);
}else if (node instanceof ASTStatement) {
visit((ASTStatement)node);
}
}
}
public void visitCom(ASTCompoundStatement compoundStat) throws Exception {
displaySymbols.disTab.push(bodySymbols.size());
BodySymbol bs = new BodySymbol();
bs.lastPar = bs.last = -1;
bs.pSize = bs.vSize = 0;
bodySymbols.add(bs);
for (ASTNode node : compoundStat.blockItems) {
if(node instanceof ASTDeclaration) {
visit((ASTDeclaration)node);
}else if (node instanceof ASTStatement) {
visit((ASTStatement)node);
}
}
displaySymbols.disTab.pop();
}
@Override
public void visit(ASTConditionExpression conditionExpression) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void visit(ASTExpression expression) throws Exception {
if(expression instanceof ASTArrayAccess) {
//已完成
visit((ASTArrayAccess)expression);
}else if(expression instanceof ASTBinaryExpression) {
//已完成
visit((ASTBinaryExpression)expression);
}else if(expression instanceof ASTCastExpression) {
visit((ASTCastExpression)expression);
}else if(expression instanceof ASTCharConstant) {
//已完成
visit((ASTCharConstant)expression);
}else if(expression instanceof ASTConditionExpression) {
visit((ASTConditionExpression)expression);
}else if(expression instanceof ASTFloatConstant) {
//已完成
visit((ASTFloatConstant)expression);
}else if(expression instanceof ASTFunctionCall) {
//已完成
visit((ASTFunctionCall)expression);
}else if(expression instanceof ASTIdentifier) {
//已完成
visit((ASTIdentifier)expression);
}else if(expression instanceof ASTIntegerConstant) {
//已完成
visit((ASTIntegerConstant)expression);
}else if(expression instanceof ASTMemberAccess) {
visit((ASTMemberAccess)expression);
}else if(expression instanceof ASTPostfixExpression) {
//已完成
visit((ASTPostfixExpression)expression);
}else if(expression instanceof ASTStringConstant) {
//已完成
visit((ASTStringConstant)expression);
}else if(expression instanceof ASTUnaryExpression) {
//已完成
visit((ASTUnaryExpression)expression);
}else if(expression instanceof ASTUnaryTypename){
visit((ASTUnaryTypename)expression);
}
}
@Override
public void visit(ASTExpressionStatement expressionStat) throws Exception {
for (ASTExpression node : expressionStat.exprs) {
visit((ASTExpression)node);
}
}
@Override
public void visit(ASTFloatConstant floatConst) throws Exception {
// TODO Auto-generated method stub
map.put(floatConst,floatConst);
Symbol sb = new Symbol();
sb.type = "float ";
mapSb.put(floatConst,sb);
}
@Override
public void visit(ASTFunctionCall funcCall) throws Exception {
// TODO Auto-generated method stub
//函数调用先压栈
String op = "push";
ASTNode res = null;
ASTNode opnd1 = null;
ASTNode opnd2 = null;
Symbol sb = new Symbol();
sb.params = new ArrayList<>();
//System.out.println("functioncall");
for(int i=0;i<funcCall.argList.size();i++)
{
Symbol sb_type = new Symbol();
//System.out.println(funcCall.argList.get(i).getType());
visit(funcCall.argList.get(i));
if(mapSb.get(funcCall.argList.get(i))!=null)
{
sb_type.name = mapSb.get(funcCall.argList.get(i)).name;
sb_type.kind = mapSb.get(funcCall.argList.get(i)).kind;
sb_type.type = mapSb.get(funcCall.argList.get(i)).type;
if(sb_type.name != null)
checkIn(sb_type);
sb_type.type = mapType.get(sb_type.name);
sb.params.add(sb_type);
}
res = map.get(funcCall.argList.get(i));
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
}
op = "call";
visit(funcCall.funcname);
sb.name = mapSb.get(funcCall.funcname).name;
sb.kind = funcCall.getType();
//sb.params.get(0).print();
checkIn(sb);
opnd1 = map.get(funcCall.funcname);
res = new TemporaryValue(++tmpId);
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
map.put(funcCall,res);
}
@Override
public void visit(ASTGotoStatement gotoStat) throws Exception {
// TODO Auto-generated method stub
String op = "jmp";
ASTNode res = null;
ASTNode opnd1 = null;
ASTNode opnd2 = null;
BodySymbol bs = bodySymbols.get(displaySymbols.disTab.peek());
Symbol sb = new Symbol();
sb.name = gotoStat.label.value;
sb.kind = gotoStat.getType();
sb.link = bs.last;
if(checkIn(sb)){
//存在,则是定义性出现
res = new TemporaryValue(mapGotolb.get(sb));
}else{
res = new TemporaryValue(++tmpId);
sb.lbId = labelSymbols.size();
SymbolTables.add(sb);
bs.last = SymbolTables.size()-1;
bs.vSize++;
LabelSymbol ls = new LabelSymbol();
ls.id = bs.last;
ls.ir_id = tmpId;
ls.f = false;//使用性出现,没有定义
labelSymbols.add(ls);
}
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
}
@Override
public void visit(ASTIdentifier identifier) throws Exception {
map.put(identifier, identifier);
//放符号表
Symbol symbol = new Symbol();
symbol.name = identifier.value;
mapSb.put(identifier,symbol);
}
@Override
public void visit(ASTInitList initList) throws Exception {
// TODO Auto-generated method stub
String op = "=";
ASTNode res = null;
ASTNode opnd1 = null;
ASTNode opnd2 = null;
visit(initList.declarator);
res = map.get(initList.declarator);
if(initList.exprs.size()!=0)
{
for(int i=0;i<initList.exprs.size();i++)
{
visit(initList.exprs.get(i));
opnd1 = map.get(initList.exprs.get(i));
}
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
}
//获得符号名
Symbol sb = new Symbol();
visit(initList.declarator);
if(initList.declarator instanceof ASTArrayDeclarator){
ASTArrayDeclarator arrayDeclarator = (ASTArrayDeclarator) initList.declarator;
ASTVariableDeclarator variableDeclarator = (ASTVariableDeclarator) arrayDeclarator.declarator;
Quat quat = new Quat("arr[]",null,variableDeclarator.identifier,(ASTNode) arrayDeclarator.expr);
quats.add(quat);
}
sb.name = mapSb.get(initList.declarator).name;
sb.kind = initList.declarator.getType();
mapSb.put(initList,sb);
}
@Override
public void visit(ASTIntegerConstant intConst) throws Exception {
map.put(intConst, intConst);
Symbol sb = new Symbol();
sb.type = "int ";
mapSb.put(intConst,sb);
}
@Override
public void visit(ASTIterationDeclaredStatement iterationDeclaredStat) throws Exception {
// TODO Auto-generated method stub
//fill the table
displaySymbols.disTab.push(bodySymbols.size());
BodySymbol bs = new BodySymbol();
bs.lastPar = bs.last = -1;
bs.pSize = bs.vSize = 0;
bodySymbols.add(bs);
visit(iterationDeclaredStat.init);
String op = "label";
ASTNode res = new TemporaryValue(++tmpId);
ASTNode opnd1 = null;
ASTNode opnd2 = null;
label_num.push(tmpId);
//循环用的标号
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
false_num.push(++tmpId);
if(iterationDeclaredStat.cond!=null){
for(int i=0;i<iterationDeclaredStat.cond.size();i++)
{
visit(iterationDeclaredStat.cond.get(i));
//如果是否定,跳出循环
op = "jf";
int fnum = false_num.pop();
res = new TemporaryValue(fnum);
false_num.push(fnum);
opnd1 = map.get(iterationDeclaredStat.cond.get(i));
Quat quat2 = new Quat(op,res,opnd1,opnd2);
quats.add(quat2);
}
}
fIter ++;
//访问循环体内部
if(iterationDeclaredStat.stat instanceof ASTCompoundStatement){
visit((ASTCompoundStatement) iterationDeclaredStat.stat);
}else{
visit(iterationDeclaredStat.stat);
}
fIter--;
//step
if(iterationDeclaredStat.step!=null)
{
if(!step_num.empty())
{
op = "label";
int num = step_num.peek();
res = new TemporaryValue(num);
opnd1 = opnd2 = null;
Quat quat2 = new Quat(op,res,opnd1,opnd2);
quats.add(quat2);
}
for(int i=0;i<iterationDeclaredStat.step.size();i++)
{
visit(iterationDeclaredStat.step.get(i));
}
}
op = "jmp";
int lnum = label_num.pop();
res = new TemporaryValue(lnum);
opnd1 = opnd2 = null;
Quat quat1 = new Quat(op,res,opnd1,opnd2);
quats.add(quat1);
op = "label";
int fnum = false_num.pop();
res = new TemporaryValue(fnum);
opnd1 = opnd2 = null;
Quat quat3 = new Quat(op,res,opnd1,opnd2);
quats.add(quat3);
displaySymbols.disTab.pop();
}
@Override
public void visit(ASTIterationStatement iterationStat) throws Exception {
// TODO Auto-generated method stub
String op = "";
ASTNode res = null;
ASTNode opnd1 = null;
ASTNode opnd2 = null;
if(iterationStat.init!=null)
{
for(int i=0;i<iterationStat.init.size();i++)
{
visit(iterationStat.init.get(i));
}
}
op = "label";
res = new TemporaryValue(++tmpId);
opnd1 = null;
opnd2 = null;
label_num.push(tmpId);
//循环用的标号
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
false_num.push(++tmpId);
if(iterationStat.cond!=null)
{
for(int i=0;i<iterationStat.cond.size();i++)
{
visit(iterationStat.cond.get(i));
//如果是否定,跳出循环
op = "jf";
int fnum = false_num.pop();
res = new TemporaryValue(fnum);
false_num.push(fnum);
opnd1 = map.get(iterationStat.cond.get(i));
Quat quat2 = new Quat(op,res,opnd1,opnd2);
quats.add(quat2);
}
}
//访问循环体内部
fIter++;
//访问循环体内部
visit(iterationStat.stat);
fIter--;
if(iterationStat.step!=null)
{
//step
if(!step_num.empty())
{
op = "label";
int num = step_num.peek();
res = new TemporaryValue(num);
opnd1 = opnd2 = null;
Quat quat2 = new Quat(op,res,opnd1,opnd2);
quats.add(quat2);
}
for(int i=0;i<iterationStat.step.size();i++)
{
visit(iterationStat.step.get(i));
}
}
op = "jmp";
int lnum = label_num.pop();
res = new TemporaryValue(lnum);
opnd1 = opnd2 = null;
Quat quat1 = new Quat(op,res,opnd1,opnd2);
quats.add(quat1);
op = "label";
int fnum = false_num.pop();
res = new TemporaryValue(fnum);
opnd1 = opnd2 = null;
Quat quat3 = new Quat(op,res,opnd1,opnd2);
quats.add(quat3);
//displaySymbols.disTab.pop();
}
@Override
public void visit(ASTLabeledStatement labeledStat) throws Exception {
// TODO Auto-generated method stub
String op = "label";
ASTNode res = null;
ASTNode opnd1 = null;
ASTNode opnd2 = null;
BodySymbol bs = bodySymbols.get(displaySymbols.disTab.peek());
Symbol sb = new Symbol();
sb.name = labeledStat.label.value;
sb.kind = labeledStat.getType();
sb.link = bs.last;
if(checkRepeat(sb))
{
res = new TemporaryValue(++tmpId);
sb.lbId = labelSymbols.size();
SymbolTables.add(sb);
bs.last = SymbolTables.size()-1;
bs.vSize++;
LabelSymbol ls = new LabelSymbol();
ls.id = bs.last;
ls.ir_id = tmpId;
ls.f = true;//定义性出现
labelSymbols.add(ls);
}else {
res = new TemporaryValue(mapGotolb.get(sb));
// LabelSymbol ls = labelSymbols.get(sb.lbId);
// ls.f = true;
}
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
map.put(labeledStat,opnd1);
visit(labeledStat.stat);
}
@Override
public void visit(ASTMemberAccess memberAccess) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void visit(ASTPostfixExpression postfixExpression) throws Exception {
// TODO Auto-generated method stub
visitSb(postfixExpression);
String op = postfixExpression.op.value;
ASTNode res = null;
ASTNode opnd1 = null;
ASTNode opnd2 = null;
visit(postfixExpression.expr);
Symbol sb = new Symbol();
sb.name = mapSb.get(postfixExpression.expr).name;
sb.kind = postfixExpression.expr.getType();
res = new TemporaryValue(++tmpId);
if(postfixExpression.expr instanceof ASTIdentifier){
opnd1 = postfixExpression.expr;
}
else if(postfixExpression.expr instanceof ASTIntegerConstant){
opnd1 = postfixExpression.expr;
}
else if(postfixExpression.expr instanceof ASTFloatConstant){
opnd1 = postfixExpression.expr;
}
Quat quat = new Quat(op,opnd1,opnd1,opnd2);
quats.add(quat);
map.put(postfixExpression,opnd1);
}
@Override
public void visit(ASTReturnStatement returnStat) throws Exception {
// TODO Auto-generated method stub
freturn ++;
String op = "ret";
ASTNode res = null;
ASTNode opnd1 = null;
ASTNode opnd2 = null;
if(returnStat.expr!=null)
{
for(int i=0;i<returnStat.expr.size();i++){
visit(returnStat.expr.get(i));
opnd1 = map.get(returnStat.expr.get(i));
}
}
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
}
@Override
public void visit(ASTSelectionStatement selectionStat) throws Exception {
// TODO Auto-generated method stub
//选择语句
int num = 0;
Quat quat2 = new Quat(null,null,null,null);
for(int i=0;i<selectionStat.cond.size();i++)
{
visit(selectionStat.cond.get(i));
//增加条件语句
String op = "jf";
ASTNode opnd1 = map.get(selectionStat.cond.get(i));
ASTNode opnd2 = null;
ASTNode res = new TemporaryValue(++tmpId);
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
//否定的跳转label
op = "label";
res = new TemporaryValue(tmpId);
num = tmpId;
opnd1 = null;
opnd2 = null;
quat2 = new Quat(op,res,opnd1,opnd2);
}
visit(selectionStat.then);
if(selectionStat.otherwise!=null) {
String op = "jmp";
ASTNode opnd1 = null;
ASTNode opnd2 = null;
ASTNode res = new TemporaryValue(++tmpId);
num = tmpId;
Quat quat = new Quat(op, res, opnd1, opnd2);
quats.add(quat);
}
quats.add(quat2);
if(selectionStat.otherwise!=null) {
visit(selectionStat.otherwise);
String op = "label";
ASTNode res = new TemporaryValue(num);
ASTNode opnd1 = null;
ASTNode opnd2 = null;
Quat quat3 = new Quat(op, res, opnd1, opnd2);
quats.add(quat3);
}
}
@Override
public void visit(ASTStringConstant stringConst) throws Exception {
// TODO Auto-generated method stub
map.put(stringConst,stringConst);
// System.out.println(stringConst.value);
}
@Override
public void visit(ASTTypename typename) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void visit(ASTUnaryExpression unaryExpression) throws Exception {
// TODO Auto-generated method stub
visitSb(unaryExpression);
String op = unaryExpression.op.value;
ASTNode res = null;
ASTNode opnd1 = null;
ASTNode opnd2 = null;
visit(unaryExpression.expr);
Symbol sb = new Symbol();
sb.name = mapSb.get(unaryExpression.expr).name;
sb.kind = unaryExpression.expr.getType();
checkIn(sb);
res = new TemporaryValue(++tmpId);
if(unaryExpression.expr instanceof ASTIdentifier){
opnd2 = unaryExpression.expr;
}
else if(unaryExpression.expr instanceof ASTIntegerConstant){
opnd2 = unaryExpression.expr;
}
else if(unaryExpression.expr instanceof ASTFloatConstant){
opnd2 = unaryExpression.expr;
}
Quat quat = new Quat(op,opnd2,opnd1,opnd2);
quats.add(quat);
map.put(unaryExpression,opnd2);
}
@Override
public void visit(ASTUnaryTypename unaryTypename) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void visit(ASTFunctionDefine functionDefine) throws Exception {
//fill the symbol table?
BodySymbol bs = bodySymbols.get(displaySymbols.disTab.peek());
Symbol symbol = new Symbol();
symbol.link = bs.last;
symbol.kind = functionDefine.getType();
symbol.paraId = bodySymbols.size();
for(int i=0;i<functionDefine.specifiers.size();i++)
{
visit(functionDefine.specifiers.get(i));
symbol.type = mapSb.get(functionDefine.specifiers.get(i)).type+" ";
}
//函数定义
String op = "proc";
ASTNode res = null;
ASTFunctionDeclarator fundec = ((ASTFunctionDeclarator)functionDefine.declarator);
visit((ASTVariableDeclarator)fundec.declarator);
symbol.name = mapSb.get((ASTVariableDeclarator)fundec.declarator).name;
res = map.get((ASTVariableDeclarator)fundec.declarator);
ASTNode opnd1 = null;
ASTNode opnd2 = null;
Quat quat = new Quat(op,res,opnd1,opnd2);
quats.add(quat);
//check
if(checkRepeat(symbol))
{
SymbolTables.add(symbol);
//修改bodytable
bs.last = SymbolTables.size()-1;
bs.vSize++;
}
//symbol.print();
//主要是得到形式参数
//这里开始第二层
displaySymbols.disTab.push(bodySymbols.size());
BodySymbol bs2 = new BodySymbol();
bs2.lastPar = bs2.last = -1;
bs2.pSize = bs2.vSize = 0;
bodySymbols.add(bs2);
visit(functionDefine.declarator);
visit((ASTCompoundStatement) functionDefine.body);
checkAllLabel(bs2);
op = "endp";
opnd1 = null;
opnd2 = null;
Quat quat1 = new Quat(op,res,opnd1,opnd2);
quats.add(quat1);
displaySymbols.disTab.pop();
if(freturn<=0)
{
printError("Function: "+symbol.name+" must have a return in the end.",8);
}
}
@Override
public void visit(ASTDeclarator declarator) throws Exception {
// TODO Auto-generated method stub
if(declarator instanceof ASTVariableDeclarator){
//已完成
visit((ASTVariableDeclarator) declarator);
}else if(declarator instanceof ASTArrayDeclarator){
//已完成
visit((ASTArrayDeclarator) declarator);
}else if(declarator instanceof ASTFunctionDeclarator){
//已完成
visit((ASTFunctionDeclarator) declarator);
}
}
@Override
public void visit(ASTStatement statement) throws Exception {
if(statement instanceof ASTIterationDeclaredStatement) {
//已完成
visit((ASTIterationDeclaredStatement)statement);
}else if(statement instanceof ASTIterationStatement) {
//已完成
visit((ASTIterationStatement)statement);
}else if(statement instanceof ASTCompoundStatement) {
//已完成
visitCom((ASTCompoundStatement)statement);
}else if(statement instanceof ASTSelectionStatement) {
//已完成
visit((ASTSelectionStatement)statement);
}else if(statement instanceof ASTExpressionStatement) {
//已完成
visit((ASTExpressionStatement)statement);
}else if(statement instanceof ASTBreakStatement) {
//已完成
visit((ASTBreakStatement)statement);
}else if(statement instanceof ASTContinueStatement) {
//已完成
visit((ASTContinueStatement)statement);
}else if(statement instanceof ASTReturnStatement) {
//已完成
visit((ASTReturnStatement)statement);
}else if(statement instanceof ASTGotoStatement) {
visit((ASTGotoStatement)statement);
}else if(statement instanceof ASTLabeledStatement) {
visit((ASTLabeledStatement)statement);
}
}
@Override
public void visit(ASTToken token) throws Exception {
// TODO Auto-generated method stub
Symbol sb = new Symbol();
sb.type = token.value;
mapSb.put(token,sb);
}
}
| [
"1582713605@qq.com"
] | 1582713605@qq.com |
bc57247ddbdfea884482fff8e33552f9c50a41f6 | f2755ad4297fda786a60180cf84079bbaf5a3c05 | /src/test/java/CalculatorTest.java | 4040903e7a909751349c541be2580c0241d7b929 | [] | no_license | Dysio9/JUni5-intro | 16415a66e7a27810d2312b9ba976c00faf577dc9 | 7a565a88e29443e8079369dfe2e20597767ac678 | refs/heads/main | 2023-05-13T08:51:13.457725 | 2021-06-07T20:01:13 | 2021-06-07T20:01:13 | 373,846,978 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,947 | java | import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CalculatorTest {
static int counter = 0;
private Calculator calculator;
@BeforeAll
public static void beforeMethod() {
System.out.println("Testing begin...");
}
@BeforeEach
public void setUp() {
calculator = new Calculator();
System.out.println("Performing test no: " + ++counter);
}
@Test
@Order(1)
@DisplayName("First test")
public void testMultiply() {
assertEquals(20, calculator.multiply(4,5),
"Simple multiplication works");
}
@Test
@Order(2)
@DisplayName("Second test")
// @Disabled("disabling reason")
public void testMultiplyGWT() {
// Given
int first = 2;
int second = 3;
int expected = 6;
// When
int result = calculator.multiply(first, second);
// Then
assertEquals(expected, result, "Simple multiplication works");
}
@RepeatedTest(5)
@Order(3)
@DisplayName("Ensure correct handling of zero")
public void testMultiplyWithZero() {
assertEquals(0, calculator.multiply(0,5), "Multiple with zero should be zero");
assertEquals(0, calculator.multiply(5,0), "Multiple with zero should be zero");
}
@Test
@Order(4)
@DisplayName("Ensure correct handling of zero - Grouped assertion")
public void testMultiplyWithZeroGroupedAssertion() {
assertAll(
() -> assertEquals(0, calculator.multiply(0,5), "Multiple with zero should be zero"),
() -> assertEquals(0, calculator.multiply(5,0), "Multiple with zero should be zero")
);
}
@AfterAll
public static void afterMethod() {
System.out.println("Tests finished");
}
} | [
"michal.dys@britenet.com.pl"
] | michal.dys@britenet.com.pl |
69d52c32ac425d0f0652b2f2244d84067a7c69c5 | 4d37505edab103fd2271623b85041033d225ebcc | /spring-test/src/test/java/org/springframework/test/context/hierarchies/web/EarTests.java | 74d55394de3f34c8a582849aa965a88706e56fa1 | [
"Apache-2.0"
] | permissive | huifer/spring-framework-read | 1799f1f073b65fed78f06993e58879571cc4548f | 73528bd85adc306a620eedd82c218094daebe0ee | refs/heads/master | 2020-12-08T08:03:17.458500 | 2020-03-02T05:51:55 | 2020-03-02T05:51:55 | 232,931,630 | 6 | 2 | Apache-2.0 | 2020-03-02T05:51:57 | 2020-01-10T00:18:15 | Java | UTF-8 | Java | false | false | 1,842 | java | /*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.hierarchies.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.Assert.*;
/**
* @author Sam Brannen
* @since 3.2.2
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class EarTests {
@Autowired
private ApplicationContext context;
// -------------------------------------------------------------------------
@Autowired
private String ear;
@Test
public void verifyEarConfig() {
assertFalse(context instanceof WebApplicationContext);
assertNull(context.getParent());
assertEquals("ear", ear);
}
@Configuration
static class EarConfig {
@Bean
public String ear() {
return "ear";
}
}
}
| [
"huifer97@163.com"
] | huifer97@163.com |
ba452b93d80dccce23600af10aebec879b5dfb75 | 0bfb91f6ec12edf9740252843d8a85c358d94dcd | /core/src/main/java/com/adobe/core/hootsuite/integration/external/services/beans/MediaUploadItem.java | 86eca852fa4e93b9a1c7084f44a428cd02ac864f | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | isabella232/aem-hootsuite-integration | c0f86b8a9c3968a762995f7ab16504068b82b3b4 | c3b33f51b67418993c89bd55016e1edb408c3315 | refs/heads/master | 2023-03-09T15:53:15.870201 | 2020-09-11T10:03:02 | 2020-09-11T10:03:02 | 299,009,654 | 0 | 0 | Apache-2.0 | 2021-02-23T11:28:56 | 2020-09-27T10:43:42 | null | UTF-8 | Java | false | false | 3,170 | java | /*
* #%L
* Hootsuite Integration
* %%
* Copyright 2020 Adobe. All rights reserved.
* %%
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.core.hootsuite.integration.external.services.beans;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
// TODO: Auto-generated Javadoc
/**
* The Class MediaUploadItem.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MediaUploadItem {
/** The upload url. */
@JsonProperty("uploadUrl")
private String uploadUrl;
/** The upload url duration seconds. */
@JsonProperty("uploadUrlDurationSeconds")
private Integer uploadUrlDurationSeconds;
/** The id. */
@JsonProperty("id")
private String id;
/** The additional properties. */
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* Gets the upload url.
*
* @return the upload url
*/
@JsonProperty("uploadUrl")
public String getUploadUrl() {
return uploadUrl;
}
/**
* Sets the upload url.
*
* @param uploadUrl the new upload url
*/
@JsonProperty("uploadUrl")
public void setUploadUrl(String uploadUrl) {
this.uploadUrl = uploadUrl;
}
/**
* Gets the upload url duration seconds.
*
* @return the upload url duration seconds
*/
@JsonProperty("uploadUrlDurationSeconds")
public Integer getUploadUrlDurationSeconds() {
return uploadUrlDurationSeconds;
}
/**
* Sets the upload url duration seconds.
*
* @param uploadUrlDurationSeconds the new upload url duration seconds
*/
@JsonProperty("uploadUrlDurationSeconds")
public void setUploadUrlDurationSeconds(Integer uploadUrlDurationSeconds) {
this.uploadUrlDurationSeconds = uploadUrlDurationSeconds;
}
/**
* Gets the id.
*
* @return the id
*/
@JsonProperty("id")
public String getId() {
return id;
}
/**
* Sets the id.
*
* @param id the new id
*/
@JsonProperty("id")
public void setId(String id) {
this.id = id;
}
/**
* Gets the additional properties.
*
* @return the additional properties
*/
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
/**
* Sets the additional property.
*
* @param name the name
* @param value the value
*/
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
} | [
"namigupt@adobe.com"
] | namigupt@adobe.com |
79d156d80586016e1b5fa93a6f8d41625f10171a | 545641711a3b5ef6192b5a8c637df544c899e568 | /src/main/java/me/zero/cc/Zero_lite/utils/InfoLine.java | 34feab784adfea9bd3da04118252441a296c6d61 | [] | no_license | 1337Zero/Zombe | bbe7a3d5d302c16c6bce17fb95caaf433534f9d1 | 85a745d77c74ae967dae7805d7d23ea3f86d3c29 | refs/heads/master | 2021-01-23T09:51:51.363834 | 2017-10-16T15:31:11 | 2017-10-16T15:31:11 | 26,375,813 | 9 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,850 | java | package me.zero.cc.Zero_lite.utils;
import java.util.ArrayList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
public class InfoLine {
private ArrayList<String> infos = new ArrayList<String>();
private boolean visible = false;
private GuiPositions pos;
public InfoLine(GuiPositions pos){
this.pos = pos;
}
/**
* Return true if visible
* @return Boolean
*/
public boolean isVisible() {
return visible;
}
/**
* Set the Visible value
* @param Boolean
*/
public void setVisible(boolean visible) {
this.visible = visible;
}
/**
* Addes a Text to the Info Arraylist
* returns the position in the arraylist
* @param String
* @return Integer
*/
public int addInfo(String info){
infos.add(info);
return infos.size() -1;
}
/**
* Removes text from the Arraylist with the given id
* @param Integer
*/
public void removeInfo(int id){
infos.remove(id);
}
/**
* Resets the text with the given id
* @param Integer
*/
public void resetInfo(int id){
infos.set(id, "");
}
/**
* Sets the text with the given id
* @param Integer
* @param String
*/
public void setInfo(int id, String txt){
infos.set(id, txt);
}
/**
* Updates and draws the Infoline
* @param Minecraft
*/
public void UpdateLine(Minecraft minecraft){
ScaledResolution reso = new ScaledResolution(minecraft);
int posx = reso.getScaledWidth();
int posy = reso.getScaledHeight();
if(pos == GuiPositions.UP_LEFT){
posx = 5;
posy = 5;
}
if(pos == GuiPositions.UP_CENTER){
posx = posx/2;
posy = 5;
}
if(pos == GuiPositions.UP_RIGHT){
posy = 5;
}
if(pos == GuiPositions.MID_LEFT){
posx = 5;
posy = posy/2;
}
if(pos == GuiPositions.MID_CENTER){
posx = posx/2;
posy = posy/2;
}
if(pos == GuiPositions.MID_RIGHT){
posy = posy/2;
}
if(pos == GuiPositions.DOWN_LEFT){
posx = 5;
posy = posy-10;
}
if(pos == GuiPositions.DOWN_CENTER){
posx = posx/2;
posy = posy-10;
}
if(pos == GuiPositions.DOWN_RIGHT){
posy = posy-10;
}
if(pos != GuiPositions.UP_LEFT && pos != GuiPositions.MID_LEFT && pos != GuiPositions.DOWN_LEFT){
String info = createInfoLine();
minecraft.fontRenderer.drawString(info, (posx-minecraft.fontRenderer.getStringWidth(info)), posy, 0xffff0000);
}else{
minecraft.fontRenderer.drawString(createInfoLine(), posx, posy, 0xffff0000);
}
}
private String createInfoLine(){
ArrayList<String> newinfos = new ArrayList<String>();
for(int i = 0; i < infos.size();i++){
if(!infos.get(i).equalsIgnoreCase("")){
newinfos.add(infos.get(i));
}
}
return newinfos.toString().replace("[", "").replace("]", "");
}
}
| [
"julius.schoenhut@gmail.com"
] | julius.schoenhut@gmail.com |
1c58c2c6f71a0f6f233ba946cd9b588f49afca78 | ebc5bebdfef1096d9e4dc63106ba415d6c59b155 | /Week_09/src/com/algorithm/class20/FindAllAnagramsInAString.java | 50e78b9b47f8b0aaf9f02dd0f1d1541923251014 | [] | no_license | wujunshen/algorithm011-class02 | 06875a7791688ce91d2561a049f3af0bbf19335c | dc59ec5f99e595ba7d0600851ee2d41b26e7cade | refs/heads/master | 2022-12-08T07:18:02.048480 | 2020-08-30T09:39:43 | 2020-08-30T09:39:43 | 273,926,788 | 1 | 0 | null | 2020-06-21T15:01:57 | 2020-06-21T15:01:56 | null | UTF-8 | Java | false | false | 2,296 | java | package com.algorithm.class20;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 438. 找到字符串中所有字母异位词
*
* <p>给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。
*
* <p>字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。
*
* <p>说明:
*
* <p>字母异位词指字母相同,但排列不同的字符串。 不考虑答案输出的顺序。 示例 1:
*
* <p>输入: s: "cbaebabacd" p: "abc"
*
* <p>输出: [0, 6]
*
* <p>解释: 起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。 起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。 示例 2:
*
* <p>输入: s: "abab" p: "ab"
*
* <p>输出: [0, 1, 2]
*
* <p>解释: 起始索引等于 0 的子串是 "ab", 它是 "ab" 的字母异位词。 起始索引等于 1 的子串是 "ba", 它是 "ab" 的字母异位词。 起始索引等于 2 的子串是
* "ab", 它是 "ab" 的字母异位词。
*
* <p>来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-all-anagrams-in-a-string
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* @author frank woo(吴峻申) <br>
* email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
* @date 2020/8/16 23:14<br>
*/
public class FindAllAnagramsInAString {
/**
* https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/solution/chuang-kou-shu-zu-pai-xu-pan-duan-yi-wei-ci-by-bie/
*
* @param s
* @param p
* @return
*/
public List<Integer> findAnagrams(String s, String p) {
List<Integer> resultList = new ArrayList<>();
if (s == null || s.length() == 0 || s.length() < p.length()) {
return resultList;
}
char[] pChar = p.toCharArray();
Arrays.sort(pChar);
int pLen = p.length();
for (int i = 0; i < s.length() - pLen + 1; i++) {
String curr = s.substring(i, i + pLen);
char[] currChar = curr.toCharArray();
Arrays.sort(currChar);
if (Arrays.equals(pChar, currChar)) {
resultList.add(i);
}
}
return resultList;
}
}
| [
"frank_wjs@hotmail.com"
] | frank_wjs@hotmail.com |
c2dacb18db2b543f30459cd1ad5d6a5fc962c2a6 | 3713af137d31f95445b7ea581cbcbd9a06eafcb3 | /src/com/iesvirgendelcarmen/polimorfismo/ejercicios/TipoCombustible.java | 356958d62415fa3996775f23b7fd4deabc6ee027 | [] | no_license | programacionDAMVC/polimorfismo | 4646dbe2cf875e6f84690081da0feff1c64e07e0 | 2fb72bfc1a6a6460e76a5ebc772487eeda538266 | refs/heads/master | 2020-03-08T14:44:37.643918 | 2018-04-16T12:08:31 | 2018-04-16T12:08:31 | 128,193,860 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 137 | java | package com.iesvirgendelcarmen.polimorfismo.ejercicios;
public enum TipoCombustible {
GASOIL, GASOLINA, HIBRIDO, ELECTRICO, GAS;
}
| [
"programacionDAMVC@gmail.com"
] | programacionDAMVC@gmail.com |
626ac66abf006ffb58ced9c62f43ff62a8bd2e45 | 2a452a4fcd20941a61484d2a2aa103578809c97b | /skinlibrary/src/main/java/com/component/skinlibrary/SkinActivity.java | e0f7fd8b607e017960e468af1c171b810b4ae013 | [] | no_license | taxiao213/Component | f4e4a14bf3643fc8d353258c74dd8193048de2fc | f7351c191dc90c494f2e4466f5a0e4d42340857c | refs/heads/master | 2022-04-11T11:15:37.900674 | 2020-03-09T05:56:58 | 2020-03-09T05:56:58 | 205,277,532 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,146 | java | package com.component.skinlibrary;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.component.skinlibrary.base.SkinEngine;
/**
* 1.可以加载内部资源,切换为夜间和白天模式
* 2.可以加载外部皮肤
*/
public class SkinActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skin_main);
final TextView test1 = findViewById(R.id.tv_1);
test1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SkinEngine.getInstances().setNightMode(SkinActivity.this);
}
});
final Button test2 = findViewById(R.id.tv_2);
test2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SkinEngine.getInstances().setDayMode(SkinActivity.this);
}
});
}
}
| [
"han13593427958"
] | han13593427958 |
69c7ce0df69d4b827a100f8da707d149402fe706 | fe13c50aa0d5904c9d72b406516ec5587802daa3 | /Tripoto/app/src/androidTest/java/shelly/tripoto/ApplicationTest.java | 2fe2ccfe6343c55db92aa720c32240e71e3ef075 | [] | no_license | shealini/travel-blog-app | dc16d533700055795acb1b148e252b7839b1d310 | 38eba4a8fda06ecd10f699340a4c768ace6b071c | refs/heads/master | 2021-01-10T03:48:11.522667 | 2015-12-27T22:35:28 | 2015-12-27T22:35:28 | 48,662,980 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 345 | java | package shelly.tripoto;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"shealini@myswagapp.com"
] | shealini@myswagapp.com |
7f71bc790ec308be972c4cf92806859a86edef83 | c5ecb33f851ff512a476699b5b51b244108dd9fa | /app/src/main/java/com/allen_chou/instagramclone/Model/Comment.java | 78c047dafb9eadde03be9e15c1801394029cd6ca | [] | no_license | taeyeonst5/demo_ig_clone | 54b8679cec83a4894f7b1e3e5e3ffea106873dbe | 58fc31f3de52d36c41dfc445cb1b54ee2cd01b17 | refs/heads/master | 2020-04-09T01:59:19.564972 | 2019-07-14T04:50:29 | 2019-07-14T04:50:29 | 159,924,928 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 842 | java | package com.allen_chou.instagramclone.Model;
public class Comment {
private String comment;
private String publisher;
private String commentId;
public Comment(String comment, String publisher, String commentId) {
this.comment = comment;
this.publisher = publisher;
this.commentId = commentId;
}
public Comment() {
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getCommentId() {
return commentId;
}
public void setCommentId(String commentId) {
this.commentId = commentId;
}
}
| [
"taeyeonst5@gmail.com"
] | taeyeonst5@gmail.com |
b3511a95565cd1b8aee34ed970044012202af791 | 8dd943facb256c1cb248246cdb0b23ba3e285100 | /service-cbo/src/main/java/com/bit/module/cbo/vo/PmcStaffRelCommunityVO.java | f7566fc211a88f78dbc79c061956229dbbcf6d37 | [] | no_license | ouyangcode/WisdomTown | 6a121be9d23e565246b41c7c29716f3035d86992 | 5176a7cd0f92d47ffee6c5b4976aa8d185025bd9 | refs/heads/master | 2023-09-02T06:54:37.124507 | 2020-07-09T02:29:59 | 2020-07-09T02:29:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 530 | java | package com.bit.module.cbo.vo;
import lombok.Data;
/**
* @Description
* @Author liyang
* @Date 2019/7/22 17:02
**/
@Data
public class PmcStaffRelCommunityVO {
/**
* id
*/
private Long id;
/**
* 物业员工id
*/
private Long staffId;
/**
* 社区ID
*/
private Long orgId;
/**
* 社区名称
*/
private String orgName;
/**
* 小区ID
*/
private Long communityId;
/**
* 小区ID集合String
*/
private String communityIds;
/**
* 小区名称
*/
private String communityName;
}
| [
"liyang@126.com"
] | liyang@126.com |
445629f3408abf57500a56c0723d769f337de296 | e89f1c4e08a2b50a15d2dc4cc0fa047c0f68e5a3 | /FkThinkDesign-Assignment(Java Codes)/Java Codes/Chap-8/Part.java | 32accec98194b66e77c0a463c4acdd9bc9e2028c | [] | no_license | aditya-manit/FkApplyDesignRefactored | b3761d6dd7df27ecee1579b8ee70be38395395ce | b76c98c38ea9821193f63af465bb5c50c72ad40b | refs/heads/master | 2020-12-27T11:32:32.396906 | 2020-02-03T06:46:23 | 2020-02-03T06:46:23 | 237,887,607 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 279 | java | package chapter8;
public class Part {
String name, description;
boolean needs_spare=true;
public Part(String name,String description,boolean needs_spare) {
this.name=name;
this.description=description;
this.needs_spare=needs_spare;
}
} | [
"noreply@github.com"
] | aditya-manit.noreply@github.com |
0249983e23dd201f8d8e301ffcca534124a0cd09 | 1977757fa8a337e3346795cfb1ceca9ae95b97fb | /src/repl/Repl95.java | e024dc76d43edfad3c499fcd234787ce72f24e6c | [] | no_license | Tarana82/MyFirstProject | fcb3e81c3659e9f846a71c7856fcf4ba914e15ad | 6fe9bb5f1d90812f6c2e5ef68ba275435a7cabce | refs/heads/master | 2021-02-11T16:22:21.801471 | 2020-03-03T03:33:39 | 2020-03-03T03:33:39 | 244,509,280 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 365 | java | package repl;
import java.util.Scanner;
public class Repl95 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char start = scan.next().charAt(0);
char end = scan.next().charAt(0);
//code starts here
for (char i = start; i <= end; i++) {
System.out.print(i);
}
}
} | [
"tahmadova1982@gmail.com"
] | tahmadova1982@gmail.com |
de00c1514a9fb43eaf0b2d4bdc5728f03a091ff7 | c999564e11a0c56cd98cdf53ecf6e878bcf56bb9 | /src/main/java/io/github/dwin357/take4/Take4Application.java | 74c578b84c012025b18d6bae5232d1e57d2eb527 | [] | no_license | Dwin357/throwAwayTakeFour | 524000b747eac87f5353a586d1903efbbf238b2b | 8002c0fcef25712b07bb843d375009d3f0fbc04d | refs/heads/master | 2020-04-10T02:48:09.781197 | 2018-12-07T01:17:37 | 2018-12-07T01:17:37 | 160,752,938 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 405 | java | package io.github.dwin357.take4;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@SpringBootApplication
@EnableJpaAuditing
public class Take4Application {
public static void main(String[] args) {
SpringApplication.run(Take4Application.class, args);
}
}
| [
"dwin.e357@gmail.com"
] | dwin.e357@gmail.com |
5a7e6ffb77e23008a24d43f52db182afb5c37f81 | 97c854d9a05a84a781540f58feb1a2a25fcc43a6 | /src/main/java/com/qa/util/UtilPage.java | 5b36bfba11493667d72ca03852eb399eb48c1df4 | [] | no_license | padmajyothimortha/Maven_FirstGitDemo | 565219a325df0bf5b0c47883c6102bebe98326c0 | c1a26b0c24624a7165bf0cc4f516cc531510b865 | refs/heads/master | 2020-03-11T17:57:26.556995 | 2018-04-19T06:02:36 | 2018-04-19T06:02:36 | 130,162,500 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 49 | java | package com.qa.util;
public class UtilPage {
}
| [
"padmajyothi.mortha@gmail.com"
] | padmajyothi.mortha@gmail.com |
0941eedbc83709eec3808a2548cb6a3eb6683a95 | fe5cc29c3c488ef8da01dbf5c23f046b77a87034 | /src/FileBrowserFrame.java | 4419616f91d5a09f272c858be4e9e0e0b6f847f1 | [] | no_license | SamsadSajid/JFileExplorer | 19ab19f8e250c12f523635b374b0c895991ae71e | cb2bd51d185fa0303752694aed4d504529c1edb0 | refs/heads/master | 2021-01-19T18:35:46.562390 | 2017-04-15T18:26:59 | 2017-04-15T18:26:59 | 88,366,481 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,458 | java | import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* Created by shamsad on 4/15/17.
*/
public class FileBrowserFrame {
//private DesktopButtonPanel desktopButtonPanel;
private FileBrowserModel model;
//private FileDetailPanel fileDetailPanel;
private JFrame frame;
private JPanel mainPanel;
private TableScrollPane tableScrollPane;
private TreeScrollPane treeScrollPane;
public FileBrowserFrame(FileBrowserModel model) {
this.model = model;
setLookAndFeel();
createPartControl();
}
private void createPartControl() {
frame = new JFrame();
frame.setTitle("File Explorer");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event) {
exitProcedure();
}
});
createMainPanel();
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void createMainPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
treeScrollPane = new TreeScrollPane(this, model);
mainPanel.add(treeScrollPane.getScrollPane(), BorderLayout.WEST);
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BorderLayout());
tableScrollPane = new TableScrollPane(this, model);
rightPanel.add(tableScrollPane.getPanel(),
BorderLayout.CENTER);
mainPanel.add(rightPanel, BorderLayout.CENTER);
}
public void exitProcedure() {
frame.dispose();
System.exit(0);
}
public void setDefaultTableModel(DefaultMutableTreeNode node) {
tableScrollPane.setDefaultTableModel(node);
}
public void clearDefaultTableModel() {
tableScrollPane.clearDefaultTableModel();
}
private void setLookAndFeel() {
try {
// Significantly improves the look of the output in
// terms of the file names returned by FileSystemView!
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch(Exception weTried) {
weTried.printStackTrace();
}
}
}
| [
"1405118.ssr@ugrad.cse.buet.ac.bd"
] | 1405118.ssr@ugrad.cse.buet.ac.bd |
17e2d22db2735d037123dbc285dffc296c2fc14c | a81cda58e7e0163cbe7ffcea0aa3ff1d81867f65 | /qagui/src/test/java/pl/jsystems/qa/qagui/classic/page/MainUserPage.java | 54d0f1ff1e519ec91d11c0e218a12862dc2cf41b | [] | no_license | adamch28/qa | 6b6ddeb249f20dff4d788fc0b5316948d89fc786 | 9017ba7b010e1ce58302e428cadd82bdeba46c66 | refs/heads/master | 2023-01-22T13:15:59.040941 | 2020-11-17T19:08:09 | 2020-11-17T19:08:09 | 313,294,279 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 799 | java | package pl.jsystems.qa.qagui.classic.page;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class MainUserPage extends BasePage {
public MainUserPage(WebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
}
@FindBy(className = "empty-content__title")
public WebElement welcomeText;
// public WebElement welcomeText = driver.findElement(By.className("empty-content__title"));
@FindBy(css = ".masterbar__item.masterbar__item-me")
public WebElement userAvatar;
// public WebElement userAvatar = driver.findElement(By.cssSelector(".masterbar__item.masterbar__item-me"));
}
| [
"adamch28@gmail.com"
] | adamch28@gmail.com |
f66a808f323622ceced9889b28edd3a0f0e8a9b8 | e7e0065c0c1e6a7ab3801a571ca1386fd1c6a752 | /src/main/java/com/ryan/study/Alcatraz/jwt/JWT.java | e06e9e3611c843051cabccbf390a32bf5194b10a | [] | no_license | miguelkristian17/Alcatraz | 60b2c2ece8b4ef873a222d10fa12d142221ec4af | 2b5871efd60961694efe502d65ab0da49bf00eda | refs/heads/master | 2020-10-01T07:15:05.878675 | 2019-12-19T22:15:25 | 2019-12-19T22:15:25 | 227,487,047 | 0 | 3 | null | 2019-12-19T22:15:26 | 2019-12-12T00:31:55 | CSS | UTF-8 | Java | false | false | 415 | java | package com.ryan.study.Alcatraz.jwt;
import java.security.interfaces.RSAKey;
import java.util.UUID;
public class JWT {
//
// RSAKey jwk = new RSAKeyGenerator(2048)
// .keyUse(KeyUse.SIGNATURE) // indicate the intended use of the key
// .keyID(UUID.randomUUID().toString()) // give the key a unique ID
// .generate();
//
// System.out.println(jwk);
//
// System.out.println(jwk.toPublicJWK());
}
| [
"miguelkristian@Miguels-MacBook-Pro.local"
] | miguelkristian@Miguels-MacBook-Pro.local |
e528fa508df838b21321c525573e37a3e7327d82 | cce7f2a21410663e135d1e4998544f0e87b98481 | /src/main/java/org/mingtaoz/a9/string/ValidNumber.java | e9132c6b170bb40952c1c58b87a86fa98799c8e3 | [] | no_license | MagIciaNGTAO/a9-playground | 1de2ff3c25b76ae93963a3271fa30c51c62b0b76 | fd28d48cd93f36e8fa31eae5532330dcc6d8f058 | refs/heads/master | 2016-09-06T11:27:07.345061 | 2015-09-13T18:25:08 | 2015-09-13T18:25:08 | 20,468,849 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,437 | java | package org.mingtaoz.a9.string;
public class ValidNumber {
public boolean isNumber(String s) {
char[] characters = s.trim().toCharArray();
boolean eFlag = false, dotFlag = false, numberFlag = false;
if (characters.length == 0 || (characters.length == 1 && characters[0] == '.') || characters[0] == 'e') {
return false;
}
for (int i = characters.length - 1; i >= 0; i--) {
// reverse go through
if (characters[i] >= '0' && characters[i] <= '9') {
numberFlag = true;
} else if (characters[i] == 'e') {
if (eFlag || !numberFlag || dotFlag) {
return false;
}
numberFlag = false;
eFlag = true;
} else if (characters[i] == '.') {
if (dotFlag) {
// 000.000.000
return false;
}
dotFlag = true;
} else if (characters[i] == '-' || characters[i] == '+') {
if ((!numberFlag) || (i != 0 && characters[i - 1] != 'e')) {
// 000.000.000
return false;
}
} else {
// everything else
return false;
}
}
if (dotFlag && eFlag && !numberFlag) {
return false;
}
return true;
}
}
| [
"mail2mingtao@gmail.com"
] | mail2mingtao@gmail.com |
7273709ff99511dc01b428d73888951713abd8d1 | b014ddc779627e722e8b118692fc9c7a92248749 | /Day4App/app/src/androidTest/java/cloneapps/androidcourse/stepinleads/day4app/ExampleInstrumentedTest.java | 3111384e72cfbc4fd4cf7ffd70d40d8946c8ab0c | [] | no_license | suryathejareddy/AndroidBatch2 | 395462fd823589307aae1155c4185223538d03c2 | a47cf38cdd8469bfd65e8cbba770bfab473583eb | refs/heads/master | 2020-05-30T06:46:23.907429 | 2019-07-13T13:01:08 | 2019-07-13T13:01:08 | 189,414,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 770 | java | package cloneapps.androidcourse.stepinleads.day4app;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("cloneapps.androidcourse.stepinleads.day4app", appContext.getPackageName());
}
}
| [
"surya.seggari@gmail.com"
] | surya.seggari@gmail.com |
e79407d1caf0b0b3751e55fc2c643f5baa969853 | e3b4622a5f1e117c8c87eff7c4fb804d454ba299 | /src/main/java/com/example/quality/exceptions/InvalidFilterException.java | ab2cce721c2b8c46139eb1a1ae117d32875be7e8 | [] | no_license | ca-jimenez/desafioQuality | a145f5304d43c8835f4047f20f22c6e71d5a630b | 7682a7ea7571ac31f492d96610a417b93db78fe2 | refs/heads/main | 2023-04-08T04:02:15.837448 | 2021-04-23T19:30:13 | 2021-04-23T19:30:13 | 358,413,080 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 181 | java | package com.example.quality.exceptions;
public class InvalidFilterException extends Exception {
public InvalidFilterException(String message) {
super(message);
}
}
| [
"carolina.jimenez@mercadolibre.com"
] | carolina.jimenez@mercadolibre.com |
b06b5459f358f3538c9356e179b68f28967dae92 | 95ccc9bed31f10328bd51dc9462aa299daf8cb8b | /src/billingrecord/RecordData.java | dae9f83e69d5f5f24708927f16e9791af8631f53 | [] | no_license | akgarg0472/BillManagementSystem | 7b425422dfa7cf15215b89749506a0276a43bb92 | ee86220ec01a36dd126451403766c7107e2491fb | refs/heads/master | 2023-04-09T17:50:08.976379 | 2021-04-19T12:06:04 | 2021-04-19T12:06:04 | 359,441,241 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 16,101 | java | package billingrecord;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Alert;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
@SuppressWarnings("all")
public class RecordData {
public static final String TABLE_RECORDS = "records";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_ASSESSMENT_YEAR = "assessmentyear";
public static final String COLUMN_PAYMENT_DATE = "paymentdate";
public static final String COLUMN_PAYMENT_AMOUNT = "paymentamount";
public static final String COLUMN_IT_GST = "it_gst";
private static String OLD_NAME;
private static String OLD_ASSESSMENT_YEAR;
private static String OLD_TAX_TYPE;
private static String OLD_PAYMENT_DATE;
private static String OLD_PAYMENT_AMOUNT;
private static String NEW_NAME;
private static String NEW_ASSESSMENT_YEAR;
private static String NEW_TAX_TYPE;
private static String NEW_PAYMENT_DATE;
private static String NEW_PAYMENT_AMOUNT;
private final ObservableList<Record> records;
private final ObservableList<Record> searchRecords;
private PreparedStatement statement;
private Connection connection;
private ResultSet resultSet;
private Record record = null;
private final LogFile logFile = new LogFile();
//constructor to initialize the array list of all content and search content
public RecordData() {
records = FXCollections.observableArrayList();
searchRecords = FXCollections.observableArrayList();
}
public ObservableList<Record> getRecords() {
return records;
}
public boolean open() {
try {
connection = DriverManager.getConnection("jdbc:sqlite:records.db");
statement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS " + TABLE_RECORDS + "(" + COLUMN_NAME + ", " + COLUMN_ASSESSMENT_YEAR + ", " + COLUMN_IT_GST + "," + COLUMN_PAYMENT_DATE + ", " +
COLUMN_PAYMENT_AMOUNT + ")");
// statement.execute("CREATE TABLE IF NOT EXISTS " + TABLE_RECORDS + "(" + COLUMN_NAME + ", " + COLUMN_ASSESSMENT_YEAR + ", " + COLUMN_IT_GST + "," + COLUMN_PAYMENT_DATE + ", " +
// COLUMN_PAYMENT_AMOUNT + ")");
statement.execute();
return true;
} catch (SQLException e) {
logFile.modifyLogFile("Unable to load database/connection " + e.getMessage());
return false;
}
}
public boolean close() {
try {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
if (resultSet != null) {
resultSet.close();
}
return true;
} catch (SQLException e) {
logFile.modifyLogFile("Couldn't close connection/database " + e.getMessage());
e.printStackTrace();
return false;
}
}
public void loadAllRecords() {
try {
records.clear();
statement = connection.prepareStatement("Select * from records");
resultSet = statement.executeQuery();
if (!resultSet.next()) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Data Error");
alert.setHeaderText("Oops!");
alert.setContentText("No Data record Found in database");
alert.showAndWait();
} else {
do {
record = new Record();
record.setClientName(resultSet.getString(1));
record.setAssessmentYear(resultSet.getString(2));
record.setTaxType(resultSet.getString(3));
record.setPaymentDate(resultSet.getString(4));
record.setPaymentAmount(resultSet.getString(5));
records.add(record);
} while (resultSet.next());
}
} catch (SQLException e) {
logFile.modifyLogFile("Exception in populating all records, " + e.getMessage());
e.printStackTrace();
}
}
public void addRecord(Record record, String clientName, String assessmentYear, String taxType, String paymentDate, String paymentAmount) {
//insert into records values("name", "assessmentyear", "taxtype", "paymentdate", "paymentamount")
String add = "INSERT INTO " + TABLE_RECORDS + " VALUES" + "(\"" + clientName + "\",\"" + assessmentYear + "\"" + ",\"" + taxType + "\"" + ",\"" +
paymentDate + "\"" + ",\"" + paymentAmount + "\")";
records.add(record);
try {
statement = connection.prepareStatement(add);
statement.executeUpdate();
logFile.modifyLogFile("New record added successfully in database"); //writing insert statement into log file
} catch (SQLException e) {
logFile.modifyLogFile("Error adding new record in database : " + e.getMessage());
e.printStackTrace();
}
}
public void deleteRecord(Record record, String clientName, String assessmentYear, String taxType, String paymentDate, String paymentAmount) {
//delete from records where name="name 4" and it_gst="IT.GST" and assessmentyear="2021"
String delete = "DELETE FROM " + TABLE_RECORDS + " WHERE " + COLUMN_NAME + "=\"" + clientName + "\" AND " + COLUMN_ASSESSMENT_YEAR + "=\"" + assessmentYear + "\" AND " +
COLUMN_IT_GST + "=\"" + taxType + "\" AND " + COLUMN_PAYMENT_DATE + "=\"" + paymentDate + "\" AND " + COLUMN_PAYMENT_AMOUNT + "=\"" + paymentAmount + "\"";
records.remove(record);
try {
statement = connection.prepareStatement(delete);
statement.executeUpdate();
logFile.modifyLogFile("Data successfully deleted from database");
} catch (SQLException e) {
logFile.modifyLogFile("Error deleting record : " + e.getMessage());
e.printStackTrace();
}
}
public void setPreviousEntries(String OLD_NAME, String OLD_ASSESSMENT_YEAR, String OLD_TAX_TYPE, String OLD_PAYMENT_DATE, String OLD_PAYMENT_AMOUNT) {
this.OLD_NAME = OLD_NAME;
this.OLD_ASSESSMENT_YEAR = OLD_ASSESSMENT_YEAR;
this.OLD_TAX_TYPE = OLD_TAX_TYPE;
this.OLD_PAYMENT_DATE = OLD_PAYMENT_DATE;
this.OLD_PAYMENT_AMOUNT = OLD_PAYMENT_AMOUNT;
}
public void newEntries(String NEW_NAME, String NEW_ASSESSMENT_YEAR, String NEW_TAX_TYPE, String NEW_PAYMENT_DATE, String NEW_PAYMENT_AMOUNT) {
this.NEW_NAME = NEW_NAME;
this.NEW_ASSESSMENT_YEAR = NEW_ASSESSMENT_YEAR;
this.NEW_TAX_TYPE = NEW_TAX_TYPE;
this.NEW_PAYMENT_DATE = NEW_PAYMENT_DATE;
this.NEW_PAYMENT_AMOUNT = NEW_PAYMENT_AMOUNT;
}
public void updateRecord(Record selectedRecord) {
String updateRecord;
selectedRecord.setClientName(NEW_NAME);
selectedRecord.setAssessmentYear(NEW_ASSESSMENT_YEAR);
selectedRecord.setTaxType(NEW_TAX_TYPE);
selectedRecord.setPaymentDate(NEW_PAYMENT_DATE);
selectedRecord.setPaymentAmount(NEW_PAYMENT_AMOUNT);
// update records set name="newName",assessmentyear="newAY",it_gst="newTaxType",paymentdate="ni batara",paymentamount="2312.18" WHERE
// name="Sample name" AND assessmentyear="2025" AND it_gst="Income Tax" AND paymentdate="12-8-2020" AND paymentamount="100.00"
updateRecord = "UPDATE " + TABLE_RECORDS + " SET " + COLUMN_NAME + "=\"" + NEW_NAME + "\"," + COLUMN_ASSESSMENT_YEAR + "=\"" + NEW_ASSESSMENT_YEAR +
"\"," + COLUMN_IT_GST + "=\"" + NEW_TAX_TYPE + "\"," + COLUMN_PAYMENT_DATE + "=\"" + NEW_PAYMENT_DATE + "\"," + COLUMN_PAYMENT_AMOUNT +
"=\"" + NEW_PAYMENT_AMOUNT + "\" WHERE " +
COLUMN_NAME + "=\"" + OLD_NAME + "\" AND " + COLUMN_ASSESSMENT_YEAR + "=\"" + OLD_ASSESSMENT_YEAR +
"\" AND " + COLUMN_IT_GST + "=\"" + OLD_TAX_TYPE + "\" AND " + COLUMN_PAYMENT_DATE + "=\"" + OLD_PAYMENT_DATE + "\" AND " + COLUMN_PAYMENT_AMOUNT +
"=\"" + OLD_PAYMENT_AMOUNT + "\"";
try {
statement = connection.prepareStatement(updateRecord);
statement.executeUpdate();
logFile.modifyLogFile("Data record successfully updated in the database");
} catch (SQLException e) {
logFile.modifyLogFile("Data updated in database failed : " + e.getMessage());
e.printStackTrace();
}
}
public ObservableList<Record> searchRecord(String sqlStatement) {
try {
searchRecords.clear();
// ResultSet resultSet = statement.executeQuery("Select * from records WHERE assessmentyear=\"2021\"");
try {
statement = connection.prepareStatement(sqlStatement);
// System.out.println("Statement : " + sqlStatement);
resultSet = statement.executeQuery();
} catch (Exception e) {
logFile.modifyLogFile("Error in executing the search query : " + e.getMessage());
e.printStackTrace();
}
if (!resultSet.next()) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("No record found");
alert.setHeaderText(null);
alert.setContentText("No Record found in database");
alert.showAndWait();
} else {
do {
record = new Record();
record.setClientName(resultSet.getString(1));
record.setAssessmentYear(resultSet.getString(2));
record.setTaxType(resultSet.getString(3));
record.setPaymentDate(resultSet.getString(4));
record.setPaymentAmount(resultSet.getString(5));
searchRecords.add(record);
} while (resultSet.next());
return searchRecords;
}
} catch (SQLException e) {
System.out.println("Exception in searching record");
logFile.modifyLogFile("Exception in searching record : " + e.getMessage());
}
return null;
}
public void exportDataToExcel(Stage primaryStage) {
try {
statement = connection.prepareStatement("SELECT * FROM " + TABLE_RECORDS);
ResultSet excelSet = statement.executeQuery();
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Payment Details");
XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop((short) 1);
style.setBorderBottom((short) 1);
style.setBorderRight((short) 1);
style.setBorderLeft((short) 1);
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 15);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
style.setAlignment(CellStyle.ALIGN_CENTER);
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderTop((short) 1);
cellStyle.setBorderBottom((short) 1);
cellStyle.setBorderRight((short) 1);
cellStyle.setBorderLeft((short) 1);
cellStyle.setAlignment(HorizontalAlignment.CENTER);
XSSFRow header = sheet.createRow(0);
Cell cellZero = header.createCell(0);
cellZero.setCellValue("S.No");
cellZero.setCellStyle(style);
Cell cellOne = header.createCell(1);
cellOne.setCellValue("Client Name");
cellOne.setCellStyle(style);
Cell cellTwo = header.createCell(2);
cellTwo.setCellValue("Assessment Year");
cellTwo.setCellStyle(style);
Cell cellThree = header.createCell(3);
cellThree.setCellValue("Tax Type");
cellThree.setCellStyle(style);
Cell cellFour = header.createCell(4);
cellFour.setCellValue("Payment Date");
cellFour.setCellStyle(style);
Cell cellFive = header.createCell(5);
cellFive.setCellValue("Payment Amount");
cellFive.setCellStyle(style);
sheet.autoSizeColumn(0);
sheet.autoSizeColumn(1);
sheet.autoSizeColumn(2);
sheet.autoSizeColumn(3);
sheet.autoSizeColumn(4);
sheet.autoSizeColumn(5);
int index = 1; //to create rows for each record
int serial = 1; //to maintain serial number of all records
while (excelSet.next()) {
XSSFRow row = sheet.createRow(index++);
Cell serialNumber = row.createCell(0);
serialNumber.setCellValue(serial++);
serialNumber.setCellStyle(cellStyle);
Cell clientName = row.createCell(1);
clientName.setCellValue(excelSet.getString(1));
clientName.setCellStyle(cellStyle);
Cell assessmentYear = row.createCell(2);
assessmentYear.setCellValue(excelSet.getString(2));
assessmentYear.setCellStyle(cellStyle);
Cell taxType = row.createCell(3);
taxType.setCellValue(excelSet.getString(3));
taxType.setCellStyle(cellStyle);
Cell paymentDate = row.createCell(4);
paymentDate.setCellValue(excelSet.getString(4));
paymentDate.setCellStyle(cellStyle);
Cell paymentAmount = row.createCell(5);
paymentAmount.setCellValue(Double.parseDouble(excelSet.getString(5)));
paymentAmount.setCellStyle(cellStyle);
}
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Excel File", "*.xlsx"));
fileChooser.setInitialDirectory(new File(System.getProperty("user.home") + File.separator + "Desktop"));
fileChooser.setInitialFileName("MyExcelFile");
File excelFile = fileChooser.showSaveDialog(primaryStage);
if (excelFile != null) {
FileOutputStream fileOutputStream = new FileOutputStream(excelFile.getAbsolutePath());
workbook.write(fileOutputStream);
fileOutputStream.close();
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Export Success");
alert.setHeaderText(null);
alert.setContentText("\nData successfully exported to Excel Sheet\n");
alert.showAndWait();
logFile.modifyLogFile("Data successfully exported to Excel");
} else {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Export cancelled by user");
alert.setHeaderText(null);
alert.setContentText("\nExport to EXCEL cancelled\n");
alert.showAndWait();
logFile.modifyLogFile("Export cancelled");
}
} catch (SQLException | FileNotFoundException e) {
logFile.modifyLogFile("Export to EXCEL Failed : " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
logFile.modifyLogFile("Error during writing data to excel file");
e.printStackTrace();
}
}
}
| [
"Garg@2318"
] | Garg@2318 |
27a9f3406c484e282ec39e9e63a4e617b0e15606 | 151d9b68c40b8a06695478dde8bf8def25c8e453 | /app/src/main/java/com/zoho/mohammadrajabi/socialnetwork/data/model/CommentsResponse.java | ba35917192404b0522abae769ac321e23dd513a5 | [] | no_license | Pman-me/simple-social-network | 0486bcf02052886cfae39bd2de02f97e4bcdf615 | 8a4b1bd728212ed057da27deb8ecf636fbcbbd9a | refs/heads/master | 2023-03-07T21:17:21.618106 | 2020-11-11T19:03:04 | 2020-11-11T19:03:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 607 | java | package com.zoho.mohammadrajabi.socialnetwork.data.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class CommentsResponse {
@SerializedName("status")
private boolean status;
@SerializedName("comments")
private List<Comment> comments;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
}
| [
"C6@_hP39N}=!Bs8("
] | C6@_hP39N}=!Bs8( |
c94b967e2e76f3470c5b9755fdd61cb854164b35 | 1ca753ad031c4a1498caad4d0a739e7da159ff4d | /app/src/main/java/com/laurensius_dede_suhardiman/foodmarketplace/fragments/FragmentTransaksiPembelian.java | ce6ca554a075d92d022845b4c851c89d87c1ecf0 | [] | no_license | anggikozeal/KuninganFood | 3f77169dcd53053a7670b6405bd68902aee8ed56 | 31855586121e17bf325b66f831efd6ac29965d3e | refs/heads/master | 2020-04-09T04:50:11.658553 | 2018-12-21T11:57:35 | 2018-12-21T11:57:35 | 160,038,839 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,800 | java | package com.laurensius_dede_suhardiman.foodmarketplace.fragments;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.laurensius_dede_suhardiman.foodmarketplace.FoodMarketplace;
import com.laurensius_dede_suhardiman.foodmarketplace.R;
import com.laurensius_dede_suhardiman.foodmarketplace.adapter.KonfirmasiAdapter;
import com.laurensius_dede_suhardiman.foodmarketplace.adapter.FinishAdapter;
import com.laurensius_dede_suhardiman.foodmarketplace.adapter.ProsesAdapter;
import com.laurensius_dede_suhardiman.foodmarketplace.adapter.TagihanAdapter;
import com.laurensius_dede_suhardiman.foodmarketplace.appcontroller.AppController;
import com.laurensius_dede_suhardiman.foodmarketplace.model.Product;
import com.laurensius_dede_suhardiman.foodmarketplace.model.Shop;
import com.laurensius_dede_suhardiman.foodmarketplace.model.Transaction;
import com.laurensius_dede_suhardiman.foodmarketplace.model.TransactionDetail;
import com.laurensius_dede_suhardiman.foodmarketplace.model.User;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class FragmentTransaksiPembelian extends Fragment {
private LinearLayout llFailed,llSuccess,llNoData;
RecyclerView.LayoutManager mLayoutManager;
List<Transaction> listTransaction = new ArrayList<>();
private RecyclerView rvTransaksiPembelian;
private TagihanAdapter tagihanAdapter = null;
private KonfirmasiAdapter konfirmasiAdapter = null;
private ProsesAdapter prosesAdapter = null;
private FinishAdapter finishAdapter = null;
private int onTagihan = 1;
private int onKonfirmasi = 2;
private int onProses = 3;
private int onFinish = 4;
private int stage;
public FragmentTransaksiPembelian() { }
public static FragmentTransaksiPembelian newInstance(int sectionNumber) {
FragmentTransaksiPembelian fragment = new FragmentTransaksiPembelian();
Bundle args = new Bundle();
args.putInt("section_number", sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflaterTransaksiPembelian = inflater.inflate(R.layout.fragment_transaksi_pembelian, container, false);
llFailed = (LinearLayout)inflaterTransaksiPembelian.findViewById(R.id.ll_failed);
llNoData = (LinearLayout)inflaterTransaksiPembelian.findViewById(R.id.ll_no_data);
llSuccess = (LinearLayout)inflaterTransaksiPembelian.findViewById(R.id.ll_success);
rvTransaksiPembelian = (RecyclerView)inflaterTransaksiPembelian.findViewById(R.id.rv_transaksi);
return inflaterTransaksiPembelian;
}
@Override
public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
stage = getArguments().getInt("section_number");
llNoData.setVisibility(View.GONE);
llFailed.setVisibility(View.GONE);
llSuccess.setVisibility(View.GONE);
dataToView();
llFailed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dataToView();
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
public void dataToView(){
if(stage==onTagihan){
listTransaction.clear();
requestTransactionStage("ON_TAGIHAN");
rvTransaksiPembelian.setAdapter(null);
rvTransaksiPembelian.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
rvTransaksiPembelian.setLayoutManager(mLayoutManager);
tagihanAdapter = new TagihanAdapter(listTransaction,getActivity());
tagihanAdapter.notifyDataSetChanged();
rvTransaksiPembelian.setAdapter(tagihanAdapter);
}else
if(stage==onKonfirmasi){
listTransaction.clear();
requestTransactionStage("ON_KONFIRMASI");
rvTransaksiPembelian.setAdapter(null);
rvTransaksiPembelian.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
rvTransaksiPembelian.setLayoutManager(mLayoutManager);
konfirmasiAdapter = new KonfirmasiAdapter(listTransaction,getActivity());
konfirmasiAdapter.notifyDataSetChanged();
rvTransaksiPembelian.setAdapter(konfirmasiAdapter);
}else
if(stage==onProses){
listTransaction.clear();
requestTransactionStage("ON_PROSES");
requestTransactionStage("ON_KIRIM");
rvTransaksiPembelian.setAdapter(null);
rvTransaksiPembelian.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
rvTransaksiPembelian.setLayoutManager(mLayoutManager);
prosesAdapter = new ProsesAdapter(listTransaction,getActivity());
prosesAdapter.notifyDataSetChanged();
rvTransaksiPembelian.setAdapter(prosesAdapter);
}else
if(stage==onFinish){
listTransaction.clear();
requestTransactionStage("ON_FINISH");
rvTransaksiPembelian.setAdapter(null);
rvTransaksiPembelian.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
rvTransaksiPembelian.setLayoutManager(mLayoutManager);
finishAdapter = new FinishAdapter(listTransaction,getActivity());
finishAdapter.notifyDataSetChanged();
rvTransaksiPembelian.setAdapter(finishAdapter);
}
}
public void requestTransactionStage(String levelStage){
Random random = new Random();
int rnd = random.nextInt(999999 - 99) + 99;
String transac_by_status = getResources().getString(R.string.tag_request_transac_by_status);
String url = getResources().getString(R.string.api)
.concat(getResources().getString(R.string.endpoint_transac))
.concat("id_user") //key
.concat(getResources().getString(R.string.slash))
.concat(FoodMarketplace.currentUser.getId()) //val
.concat(getResources().getString(R.string.slash))
.concat(levelStage) //status
.concat(getResources().getString(R.string.slash))
.concat(String.valueOf(rnd))
.concat(getResources().getString(R.string.slash));
final ProgressDialog pDialog = new ProgressDialog(getContext());
pDialog.setMessage(getResources().getString(R.string.progress_loading));
pDialog.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.d(getResources().getString(R.string.debug),response.toString());
parseData(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
Toast.makeText(getContext(),"Response Error",Toast.LENGTH_LONG).show();
llNoData.setVisibility(View.GONE);
llFailed.setVisibility(View.VISIBLE);
llSuccess.setVisibility(View.GONE);
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, transac_by_status);
}
public void parseData(JSONObject responseJsonObj){
try{
String severity = responseJsonObj.getString(getResources().getString(R.string.json_key_severity));
JSONObject content = responseJsonObj.getJSONObject(getResources().getString(R.string.json_key_content));
if(severity.equals(getResources().getString(R.string.success))){
JSONArray jsonArrayTransaction = content.getJSONArray(getResources().getString(R.string.json_key_transaction));
List<TransactionDetail> transactionDetailList;
if(jsonArrayTransaction.length() > 0){
for(int x=0;x<jsonArrayTransaction.length();x++){
JSONObject objTransaction = jsonArrayTransaction.getJSONObject(x);
JSONObject objShop = objTransaction.getJSONObject(getResources().getString(R.string.json_key_shop));
JSONObject objUser = objShop.getJSONObject(getResources().getString(R.string.json_key_user));
JSONArray arrayTransactionDetail = objTransaction.getJSONArray(getResources().getString(R.string.json_key_product));
transactionDetailList = new ArrayList<>();
if(arrayTransactionDetail.length() > 0){
for(int y=0;y<arrayTransactionDetail.length();y++){
JSONObject objProduct = arrayTransactionDetail.getJSONObject(y);
transactionDetailList.add(new TransactionDetail(
objProduct.getString(getResources().getString(R.string.json_key_id)),
objProduct.getString(getResources().getString(R.string.json_key_id_transaction)),
objProduct.getString(getResources().getString(R.string.json_key_qty)),
objProduct.getString(getResources().getString(R.string.json_key_note)),
new Product(
objProduct.getString(getResources().getString(R.string.json_key_id)),
objProduct.getString(getResources().getString(R.string.json_key_id_shop)),
objProduct.getString(getResources().getString(R.string.json_key_name)),
objProduct.getString(getResources().getString(R.string.json_key_category)),
objProduct.getString(getResources().getString(R.string.json_key_status)),
objProduct.getString(getResources().getString(R.string.json_key_price)),
objProduct.getString(getResources().getString(R.string.json_key_discount)),
objProduct.getString(getResources().getString(R.string.json_key_description)),
objProduct.getString(getResources().getString(R.string.json_key_rating)),
objProduct.getString(getResources().getString(R.string.json_key_image)),
null
)
));
}
}
listTransaction.add(
new Transaction(
objTransaction.getString(getResources().getString(R.string.json_key_id)),
objTransaction.getString(getResources().getString(R.string.json_key_id_shop)),
objTransaction.getString(getResources().getString(R.string.json_key_id_user)),
objTransaction.getString(getResources().getString(R.string.json_key_status)),
objTransaction.getString(getResources().getString(R.string.json_key_image)),
objTransaction.getString(getResources().getString(R.string.json_key_datetime)),
new Shop(
objShop.getString(getResources().getString(R.string.json_key_id)),
objShop.getString(getResources().getString(R.string.json_key_id_user)),
objShop.getString(getResources().getString(R.string.json_key_shop_name)),
objShop.getString(getResources().getString(R.string.json_key_address)),
new User(
objUser.getString(getResources().getString(R.string.json_key_id)),
objUser.getString(getResources().getString(R.string.json_key_username)),
objUser.getString(getResources().getString(R.string.json_key_password)),
objUser.getString(getResources().getString(R.string.json_key_full_name)),
objUser.getString(getResources().getString(R.string.json_key_address)),
objUser.getString(getResources().getString(R.string.json_key_phone)),
objUser.getString(getResources().getString(R.string.json_key_last_login))
)
),
transactionDetailList
)
);
}
llNoData.setVisibility(View.GONE);
llFailed.setVisibility(View.GONE);
llSuccess.setVisibility(View.VISIBLE);
}else {
llNoData.setVisibility(View.VISIBLE);
llFailed.setVisibility(View.GONE);
llSuccess.setVisibility(View.GONE);
}
}else{
llNoData.setVisibility(View.GONE);
llFailed.setVisibility(View.VISIBLE);
llSuccess.setVisibility(View.GONE);
}
}catch (JSONException e){
llNoData.setVisibility(View.GONE);
llFailed.setVisibility(View.VISIBLE);
llSuccess.setVisibility(View.GONE);
}
if(stage==onTagihan){
tagihanAdapter.notifyDataSetChanged();
}else
if(stage==onKonfirmasi){
konfirmasiAdapter.notifyDataSetChanged();
}else
if(stage==onProses){
prosesAdapter.notifyDataSetChanged();
}else
if(stage==onFinish){
finishAdapter.notifyDataSetChanged();
}
}
}
| [
"burglar.tea@gmail.com"
] | burglar.tea@gmail.com |
a8b6879d2cdf460bfd45e9f487a8f861d17054d0 | bf76caaf56a4e4c99609deaf2be34607b8637cf9 | /src/com/example/menuactionbar/SecMainActivity.java | f4eee92e153f16e8e4cb3c04529529fccc2a5358 | [] | no_license | Sajnap/MenuActionBar | 27cb532b7fd4937e8bc5636e7a89bdb1787cd7db | 4c63688e81174ba2484effe42bcc403079b0efb5 | refs/heads/master | 2021-01-21T09:52:50.647180 | 2015-03-16T08:21:05 | 2015-03-16T08:21:05 | 32,312,493 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 632 | java | package com.example.menuactionbar;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class SecMainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sec_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
} | [
"sajnap81@gmail.com"
] | sajnap81@gmail.com |
ee4c05bc7c830a31e75afd81dd5c2050c4271a27 | 9fd2dc0e8e91bae56429d8100f03ea5b54170a16 | /jd-oct2014-igornagornov/src/Tanks/TanksOOP/BattleFieldObjects/Bullet.java | e8aecd7e772bb693a5f56726efc8cfe0060ad677 | [] | no_license | kademika/jd-oct14-igor.nagornov | 1d3ff53f449bdae7f996b561e42993a0476d9c6a | e9ac6cafd6372210620c79b11043c7d354289f71 | refs/heads/master | 2020-05-18T16:45:35.141608 | 2014-12-21T12:34:43 | 2014-12-21T12:34:43 | 26,880,835 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,841 | java | package Tanks.TanksOOP.BattleFieldObjects;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import Tanks.TanksOOP.Service.Destroyable;
import Tanks.TanksOOP.Service.Direction;
import Tanks.TanksOOP.Service.Drawable;
import Tanks.TanksOOP.Service.LoadImages;
public class Bullet implements Destroyable, Drawable{
private int x;
private int y;
private int speed = 3;
private Direction direction;
private boolean isDestroyed=false;
private Image image;
public Bullet(int x, int y, Direction direction) {
this.x = x;
this.y = y;
this.direction = direction;
image = LoadImages.getBullet();
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getSpeed() {
return speed;
}
public Direction getDirection() {
return this.direction;
}
public void updateX(int x) {
this.x += x;
}
public void updateY(int y) {
this.y += y;
}
@Override
public void destroy() {
// TODO Auto-generated method stub
x = -100;
y = -100;
direction = Direction.NONE;
isDestroyed = true;
}
@Override
public void draw(Graphics g) {
// TODO Auto-generated method stub
if(!isDestroyed){
if(image!=null){
g.drawImage(image, this.getX(), this.getY(),
new ImageObserver() {
@Override
public boolean imageUpdate(Image arg0, int arg1,
int arg2, int arg3, int arg4, int arg5) {
// TODO Auto-generated method stub
return false;
}
});
}else{
g.setColor(new Color(255, 255, 0));
g.fillRect(this.getX(), this.getY(), 14, 14);
}
}
}
@Override
public boolean isDestroyed() {
// TODO Auto-generated method stub
return isDestroyed;
}
}
| [
"shadow-in88@mail.ru"
] | shadow-in88@mail.ru |
110392bf4cde7fcec2275a6bb1f958286b8891c4 | 05f8a66e1ead66365bf2ae952a14be9d1aef72f8 | /admin-system/src/main/java/com/chanpion/admin/system/dao/RoleDao.java | 4165f66bee28473218f8ccee3abe0d53f5be1016 | [] | no_license | chanpion/universal-admin | 19a20a7b4236ceb48aff28223f31e68530f3b21d | df1f3e4bda57c6cb5c9b7672e2cf3d337689c836 | refs/heads/master | 2022-06-28T03:04:13.728345 | 2021-04-06T09:01:07 | 2021-04-06T09:01:07 | 165,257,919 | 0 | 0 | null | 2022-06-21T01:49:39 | 2019-01-11T14:36:49 | JavaScript | UTF-8 | Java | false | false | 503 | java | package com.chanpion.admin.system.dao;
import com.chanpion.admin.system.entity.Role;
import java.util.List;
/**
* @author April Chen
* @date 2019/9/25 13:53
*/
public interface RoleDao {
/**
* 新增用户
*
* @param role
* @return
*/
int save(Role role);
/**
* 获取全部
*
* @return
*/
List<Role> findAll();
/**
* 获取用户角色
*
* @param userId
* @return
*/
List<Role> find(Long userId);
}
| [
"forchpeng@163.com"
] | forchpeng@163.com |
8d49013619ccd522ce68c92e8047436723f5053a | 9974e5530b0cd7dd86c9e9cdf8004cabb03ea7d7 | /joyqueue-console/joyqueue-message-filter/joyqueue-message-filter-s3/src/main/java/org/joyqueue/msg/filter/s3/TopicMsgFilterS3Matcher.java | 7eab2b7efae42a4732b52ee78002d4dee32d073f | [
"Apache-2.0"
] | permissive | liyue2008/joyqueue | f41c2344b3f127fb5599549889fa66ec655f9459 | 554ac6f89213bbb8a91af798eb1f8210bf16a976 | refs/heads/master | 2020-06-23T12:52:50.062909 | 2020-05-25T01:52:28 | 2020-05-25T01:52:28 | 198,607,462 | 2 | 2 | Apache-2.0 | 2019-07-24T09:54:19 | 2019-07-24T09:54:18 | null | UTF-8 | Java | false | false | 1,015 | java | /**
* Copyright 2019 The JoyQueue Authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joyqueue.msg.filter.s3;
import org.apache.commons.lang3.StringUtils;
import org.joyqueue.msg.filter.TopicMsgFilterMatcher;
/**
* @author jiangnan53
* @date 2020/4/3
**/
public class TopicMsgFilterS3Matcher implements TopicMsgFilterMatcher {
@Override
public boolean match(String content, String filter) {
return StringUtils.containsIgnoreCase(content,filter);
}
}
| [
"1448588084@qq.com"
] | 1448588084@qq.com |
5f37e49f3c0e1b6660113229c14fa4ec9a580a63 | a1f2492a0c4941c8e18f5025555159112dc580c6 | /src/egr221a/types/ByteString.java | 628a5748ec4cf30798860d77d2da1d29166054bd | [] | no_license | isaOrdaz/hw7 | 6f6fdc795d473ba9e90ea13ad3a13b70b11b4f43 | 24e2457b6fcfa89386753376ddb0e22da510cec8 | refs/heads/master | 2020-05-02T17:31:17.837155 | 2019-04-20T01:02:46 | 2019-04-20T01:02:46 | 178,101,277 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 990 | java | package egr221a.types;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import egr221a.interfaces.trie.BString;
import egr221a.interfaces.worklists.FixedSizeFIFOWorkList;
public class ByteString extends BString<Byte> {
public ByteString(String s) {
super(BString.wrap(s.getBytes()));
}
public ByteString(byte[] s) {
super(BString.wrap(s));
}
public ByteString(FixedSizeFIFOWorkList<Byte> q) {
super(q);
}
public ByteString(Byte[] s) {
super(s);
}
public static Class<Byte> getLetterType() {
return Byte.class;
}
public String toString() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int i = 0; i < this.str.size(); i++) {
out.write(this.str.peek(i));
}
try {
return out.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
return out.toString();
}
}
}
| [
"isa.ordaz99@gmail.com"
] | isa.ordaz99@gmail.com |
03400146360ca24ed1e572f0ac075654a87e26f5 | 7c4873223436fa500c34b140f1d470dc0572a4de | /xf-scrumboard-api/src/main/java/model/Secured.java | a6c9f8776ebd0981308d48599c23163a4c8ab394 | [] | no_license | XFastGames/xf-scrumboard-api | b4b005600ad110d44a142f53326bdabc88da4573 | 65b72ea109779e8308b21255601f766a28a7c65e | refs/heads/master | 2021-01-11T14:06:27.888615 | 2017-06-23T08:07:44 | 2017-06-23T08:07:44 | 94,965,218 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 591 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
import javax.ws.rs.NameBinding;
/**
*
* @author Isuru
*/
@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
} | [
"isuru@xfastgames.com"
] | isuru@xfastgames.com |
194484e02811652b1de6be60ba5afd0403f857e1 | bf110f47bc1634009fed2a31cce037635672085e | /src/vistas/InscripcionVista.java | 9f4effd9103ed4886dacfcda820ed30bed2b763e | [] | no_license | arigiann99/transversal | 2e69438a4e9e4a2c29192bd0ee308768fca0ebb1 | 67cb4f14c5b4313d0f6fcdad0b1f93c07751f892 | refs/heads/master | 2023-01-12T02:57:35.084662 | 2020-11-17T02:45:41 | 2020-11-17T02:45:41 | 305,883,004 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,466 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vistas;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ButtonModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.*;
/**
*
* @author GIANELLI
*/
public class InscripcionVista extends javax.swing.JInternalFrame {
private DefaultTableModel modelo;
private CursadaData cursadaData;
private MateriaData materiaData;
private AlumnoData alumnoData;
//private ArrayList<Cursada> listaCursada;
//private ArrayList<Materia> listaMaterias;
private ArrayList<Alumno> listaAlumnos;
private Conexion con;
/**
* Creates new form InscripcionVista
*/
public InscripcionVista() {
initComponents();
con = new Conexion("jdbc:mysql://localhost:3306/universidadg2", "root", "");
modelo = new DefaultTableModel();
// cursadaData = new CursadaData(con);
// listaCursada = (ArrayList) cursadaData.obtenerCursadas();
//
// materiaData = new MateriaData(con);
// listaMaterias = (ArrayList)materiaData.obtenerMaterias();
alumnoData = new AlumnoData(con);
listaAlumnos = (ArrayList) alumnoData.obtenerAlumnos();
cargarAlumnos();
armarCabeceraTabla();
//cargarDatos();
}
/**
* 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() {
groupInscripciones = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
comboAlumno = new javax.swing.JComboBox<>();
jLabel3 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
tMaterias = new javax.swing.JTable();
jbInscribir = new javax.swing.JButton();
jbAnularI = new javax.swing.JButton();
jRinscriptas = new javax.swing.JRadioButton();
jRnoInscriptas = new javax.swing.JRadioButton();
jLabel4 = new javax.swing.JLabel();
jBsalir = new javax.swing.JButton();
setTitle("TP-Transversal");
jLabel1.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jLabel1.setText("FORMULARIO DE INSCRIPCION");
jLabel2.setText("ALUMNO");
comboAlumno.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboAlumnoActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel3.setText("LISTADO DE MATERIAS");
tMaterias.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(tMaterias);
jbInscribir.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
jbInscribir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/salvar.png"))); // NOI18N
jbInscribir.setText("INSCRIBIR");
jbInscribir.setEnabled(false);
jbInscribir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbInscribirActionPerformed(evt);
}
});
jbAnularI.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
jbAnularI.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/eliminar.png"))); // NOI18N
jbAnularI.setText("ANULAR INSCRIPCION");
jbAnularI.setEnabled(false);
jbAnularI.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbAnularIActionPerformed(evt);
}
});
groupInscripciones.add(jRinscriptas);
jRinscriptas.setText("INSCRIPTAS");
jRinscriptas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRinscriptasActionPerformed(evt);
}
});
groupInscripciones.add(jRnoInscriptas);
jRnoInscriptas.setText("NO INSCRIPTAS");
jRnoInscriptas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRnoInscriptasActionPerformed(evt);
}
});
jLabel4.setText("SELECCIONE QUE MATERIAS DESEA VER :");
jBsalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/salida.png"))); // NOI18N
jBsalir.setText("VOLVER");
jBsalir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBsalirActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(174, 174, 174)
.addComponent(jLabel3))
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jbInscribir, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jbAnularI)
.addGap(18, 18, 18)
.addComponent(jBsalir))
.addGroup(layout.createSequentialGroup()
.addGap(118, 118, 118)
.addComponent(jRinscriptas)
.addGap(70, 70, 70)
.addComponent(jRnoInscriptas)))
.addContainerGap(26, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 414, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(comboAlumno, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(107, 107, 107))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboAlumno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(34, 34, 34)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(17, 17, 17)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRnoInscriptas)
.addComponent(jRinscriptas))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jbAnularI)
.addComponent(jbInscribir)
.addComponent(jBsalir))
.addGap(44, 44, 44))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void comboAlumnoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboAlumnoActionPerformed
//cargarDatos();
}//GEN-LAST:event_comboAlumnoActionPerformed
private void jRnoInscriptasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRnoInscriptasActionPerformed
cargarDatosNoInscriptas();
jbInscribir.setEnabled(true);
jbAnularI.setEnabled(false);
}//GEN-LAST:event_jRnoInscriptasActionPerformed
private void jRinscriptasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRinscriptasActionPerformed
cargarDatosInscriptas();
jbInscribir.setEnabled(false);
jbAnularI.setEnabled(true);
}//GEN-LAST:event_jRinscriptasActionPerformed
private void jbInscribirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbInscribirActionPerformed
int filaSelect = tMaterias.getSelectedRow();
if(filaSelect != -1){
Alumno a = (Alumno)comboAlumno.getSelectedItem();
if(a!=null){
int idMateria = (Integer)modelo.getValueAt(filaSelect, 0);
String nombreMat = (String)modelo.getValueAt(filaSelect, 1);
Materia m = new Materia(nombreMat, idMateria);
Cursada c = new Cursada(a, m, 0);
cursadaData = new CursadaData(con);
cursadaData.guardarCursada(c);
borrarFilasTablas();
}
}
JOptionPane.showMessageDialog(this, "Inscripcion Completa");
}//GEN-LAST:event_jbInscribirActionPerformed
private void jbAnularIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAnularIActionPerformed
int filaSelect = tMaterias.getSelectedRow();
if(filaSelect != -1){
Alumno a = (Alumno)comboAlumno.getSelectedItem();
if(a!=null){
int idMateria = (Integer)modelo.getValueAt(filaSelect, 0);
cursadaData = new CursadaData(con);
cursadaData.borrarCursadaDeUnaMateriaDeunAlumno(a.getIdAlumno(), idMateria);
borrarFilasTablas();
}
}
JOptionPane.showMessageDialog(this, "Se Anulo Inscripcion Correctamente");
}//GEN-LAST:event_jbAnularIActionPerformed
private void jBsalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBsalirActionPerformed
dispose();
}//GEN-LAST:event_jBsalirActionPerformed
private void cargarAlumnos() {
for(Alumno item:listaAlumnos){
comboAlumno.addItem(item);
}
}
private void armarCabeceraTabla() {
ArrayList<Object> columns = new ArrayList<>();
columns.add("Id");
columns.add("Nombre");
columns.forEach((it) -> {
modelo.addColumn(it);
});
tMaterias.setModel(modelo);
}
public void borrarFilasTablas() {
int a = modelo.getRowCount() - 1; // -1 indice de ultima fila.
for (int i = a; i >= 0; i--) {
modelo.removeRow(i);
}
}
private void cargarDatosInscriptas() {
borrarFilasTablas();
cursadaData = new CursadaData(con);
Alumno select = (Alumno)comboAlumno.getSelectedItem();
List<Materia> lista = cursadaData.obtenerMateriasCursadas(select.getIdAlumno());
for(Materia m:lista){
modelo.addRow(new Object[]{m.getIdMateria(),m.getNombreMateria()});
}
}
private void cargarDatosNoInscriptas() {
borrarFilasTablas();
cursadaData = new CursadaData(con);
Alumno select = (Alumno)comboAlumno.getSelectedItem();
List<Materia> lista = cursadaData.obtenerMateriasNOCursadas(select.getIdAlumno());
for(Materia m:lista){
modelo.addRow(new Object[]{m.getIdMateria(),m.getNombreMateria()});
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<Alumno> comboAlumno;
private javax.swing.ButtonGroup groupInscripciones;
private javax.swing.JButton jBsalir;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JRadioButton jRinscriptas;
private javax.swing.JRadioButton jRnoInscriptas;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton jbAnularI;
private javax.swing.JButton jbInscribir;
private javax.swing.JTable tMaterias;
// End of variables declaration//GEN-END:variables
}
| [
"arielgiannelli@gmail.com"
] | arielgiannelli@gmail.com |
d232344803326a560d5940f829b6859ce54f7bc3 | faea8768dbafa15cfa7b400f68d74593633e4333 | /app/src/main/java/com/example/administrator/news/MainActivity.java | 8dc9a69e94b8937d7b5d01f51c67710e3b0ba8f0 | [] | no_license | Muz721/News | 282d74511550930f2ed23d65f395fb7218a4c108 | e51b14d235cb374e0d52bd8b36b32f223d94c695 | refs/heads/master | 2021-06-08T09:33:39.987999 | 2016-11-15T06:59:53 | 2016-11-15T06:59:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,007 | java | package com.example.administrator.news;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.administrator.adapter.NewsAdapter;
import com.example.administrator.entic.News;
import com.example.administrator.entic.OnLoadLister;
import com.example.administrator.fragment.CenterFragment;
import com.example.administrator.fragment.EnterFragment;
import com.example.administrator.fragment.FavoriteFragment;
/**
* Created by Administrator on 2016/10/27.
*/
public class MainActivity extends BaseActivity implements View.OnClickListener ,OnLoadLister,AdapterView.OnItemClickListener{
Button mBtn_menu;
Button mBtn_user;
DrawerLayout mDrawerLayout;
ImageView mImg_right_user;
LinearLayout mLilt_lift_news;
TextView mTxt_right_enter;
LinearLayout mLine_lift_favorite;
//Button mBtn_right_register;
//ListView mListView;
//public static final String PATH="http://118.244.212.82:9092/newsClient/path/news_list?ver=1&subid=1&dir=1&nid=1&stamp=20140321&cnt=20";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initview();
//DrawerLayout
initNetwork();
//initAdapter();
// initData();
//ArrayList<String> mList = null;
// TestAdapter testAdapter=new TestAdapter(this);
// testAdapter.setData(m);
}
@Override
public void onContentChanged() {
super.onContentChanged();
// CenterFragment fragment= (CenterFragment) getSupportFragmentManager().findFragmentById(R.id.frag_center);
CenterFragment fragment=new CenterFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragLayout,fragment);
fragmentTransaction.commit();
}
private void initData() {
News news=new News();
}
private void initAdapter() {
NewsAdapter adapter=new NewsAdapter(this);
//mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void initNetwork() {
// OkHttpClient client = new OkHttpClient();
// Request build = new Request.Builder().url(PATH).build();
// Call call = client.newCall(build);
// call.enqueue(new Callback() {
// @Override
// public void onFailure(Call call, IOException e) {
//
// }
//
// @Override
// public void onResponse(Call call, Response response) throws IOException {
// ResponseBody body = response.body();
// final String string=body.string();
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Gson gson=new Gson();
// Type type=new TypeToken<MainInfo>(){}.getType();
// MainInfo mainInfo = gson.fromJson(string, type);
// ArrayList<NewsInfo> data=mainInfo.getData();
// for (NewsInfo newsInfo : data) {
//
// }
// }
// });
// }
// });
}
private void initview() {
mBtn_menu= (Button) findViewById(R.id.btn_menu);
mBtn_user= (Button) findViewById(R.id.btn_main_user);
mDrawerLayout= (DrawerLayout) findViewById(R.id.drawerLayout);
//mListView= (ListView) findViewById(R.id.list_news);
mBtn_user.setOnClickListener(this);
mBtn_menu.setOnClickListener(this);
mImg_right_user= (ImageView) findViewById(R.id.img_right_user);
mImg_right_user.setOnClickListener(this);
SharedPreferences preferences=getSharedPreferences("user",MODE_PRIVATE);
String portration=preferences.getString("portration","");
int status=preferences.getInt("status",-1);
int result=preferences.getInt("result",-1);
Log.e("------","portration="+portration);
if(status==0&&result==0){
Glide.with(this).load(portration).into(mImg_right_user);
}
mTxt_right_enter= (TextView) findViewById(R.id.txt_right_enter);
mTxt_right_enter.setOnClickListener(this);
// mBtn_right_register= (Button) findViewById(R.id.btn_register);
// mBtn_right_register.setOnClickListener(this);
mLilt_lift_news= (LinearLayout) findViewById(R.id.line_lift_menu_news);
mLine_lift_favorite= (LinearLayout) findViewById(R.id.line_lift_menu_favorite);
mLilt_lift_news.setOnClickListener(this);
mLine_lift_favorite.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_main_user:
if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)==true) {
mDrawerLayout.closeDrawer(Gravity.RIGHT);
}else {
// startActivity(new Intent(MainActivity.this,NewsActivity.class));
mDrawerLayout.openDrawer(Gravity.RIGHT);}
break;
case R.id.btn_menu:
if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)==true) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
}else {
mDrawerLayout.openDrawer(Gravity.LEFT);}
break;
// case R.id.btn_register:
// FragmentTransaction fragmentRegister = getSupportFragmentManager().beginTransaction();
// fragmentRegister.replace(R.id.fragLayout,new RegisterFragment());
// fragmentRegister.commit();
// mDrawerLayout.closeDrawer(Gravity.RIGHT);
// break;
case R.id.img_right_user:
case R.id.txt_right_enter:
SharedPreferences preferences=this.getSharedPreferences("user",MODE_PRIVATE);
int status=preferences.getInt("status",-1);
int result=preferences.getInt("result",-1);
if(status==0&&result==0){
Intent intent=new Intent(MainActivity.this,UserActivity.class);
startActivity(intent);
}else{
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragLayout,new EnterFragment());
fragmentTransaction.commit();
mDrawerLayout.closeDrawer(Gravity.RIGHT);
}
break;
case R.id.line_lift_menu_news:
FragmentTransaction fragmentNews = getSupportFragmentManager().beginTransaction();
fragmentNews.replace(R.id.fragLayout,new CenterFragment());
fragmentNews.commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
case R.id.line_lift_menu_favorite:
FragmentTransaction fragmentFavorite=getSupportFragmentManager().beginTransaction();
fragmentFavorite.replace(R.id.fragLayout,new FavoriteFragment());
fragmentFavorite.commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
//case R.id.btn_register_register:
}
}
@Override
public void lister(String s) {
// Intent intent=new Intent
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
| [
"1248562370"
] | 1248562370 |
73e146bb43dc52215965a7f9ac5b496c45bdfc2b | 12b8ab33a40c568be2e036cbde23f041eb003b83 | /src/main/java/com/weychain/erp/domain/DO/Province.java | d03cd5d699ed9c179476031f5293d6d19cd61be6 | [
"Apache-2.0"
] | permissive | chenlingyx/erp_keeper | 3feb7f94424add3354bbc706d26cdaf819a95377 | f8f873955d71e17ccde864750ae2d866a9b6ba8d | refs/heads/master | 2022-06-24T08:08:19.862605 | 2019-10-01T14:24:45 | 2019-10-01T14:24:45 | 211,496,879 | 0 | 0 | Apache-2.0 | 2022-06-21T01:57:48 | 2019-09-28T12:27:12 | Java | UTF-8 | Java | false | false | 2,540 | java | package com.weychain.erp.domain.DO;
public class Province {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column erp_province.id
*
* @mbggenerated
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column erp_province.name
*
* @mbggenerated
*/
private String name;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column erp_province.province_code
*
* @mbggenerated
*/
private Integer provinceCode;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column erp_province.id
*
* @return the value of erp_province.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column erp_province.id
*
* @param id the value for erp_province.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column erp_province.name
*
* @return the value of erp_province.name
*
* @mbggenerated
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column erp_province.name
*
* @param name the value for erp_province.name
*
* @mbggenerated
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column erp_province.province_code
*
* @return the value of erp_province.province_code
*
* @mbggenerated
*/
public Integer getProvinceCode() {
return provinceCode;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column erp_province.province_code
*
* @param provinceCode the value for erp_province.province_code
*
* @mbggenerated
*/
public void setProvinceCode(Integer provinceCode) {
this.provinceCode = provinceCode;
}
} | [
"Tanghj@tom.com"
] | Tanghj@tom.com |
7b4e48e8a10d715f58d04775b7a423566aabf495 | 98dcc025b34d74d0c9534a4512078e16345ab567 | /Menu_ActionBar_Dialog/app/src/test/java/com/example/menu_actionbar_dialog/ExampleUnitTest.java | 6a7460c47dffd1c67105ab6eba94d816fc241958 | [] | no_license | HungNguyen501/Android | 4818bf0859105e62321067c66ec2f3aedbf9ccfd | 781ed55a1300a5141bd2b39d1f480f0139e3affb | refs/heads/main | 2023-04-19T08:09:30.520388 | 2021-04-27T15:25:17 | 2021-04-27T15:25:17 | 362,145,849 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 394 | java | package com.example.menu_actionbar_dialog;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"hungnguyendinh.501@gmail.com"
] | hungnguyendinh.501@gmail.com |
32b37adab2f5fb06d76e147e6c6cd28f55d4b535 | b7620aaff27066583bea755e251d437b4eeb834f | /android/app/src/main/java/com/example/weixindemo42d/MainApplication.java | a618cb1da107c2acf6b373f7114f9ea203fa8e58 | [] | no_license | y-chun/rn | 651be4071e6832329924a37f711bfef486515534 | b56317cb3bc0c81f639e57d0d5fef9c699327a2f | refs/heads/master | 2021-09-01T09:08:25.368499 | 2017-12-26T05:35:58 | 2017-12-26T05:35:58 | 115,377,848 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,588 | java | package com.example.weixindemo42d;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.RNFetchBlob.RNFetchBlobPackage;
import com.theweflex.react.WeChatPackage;
import com.imagepicker.ImagePickerPackage;
import org.devio.rn.splashscreen.SplashScreenReactPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.theweflex.react.WeChatPackage;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return com.example.weixindemo42d.BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNFetchBlobPackage(),
new WeChatPackage(),
new ImagePickerPackage(),
new SplashScreenReactPackage(),
new VectorIconsPackage(),
new WeChatPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
| [
"838087366@qq.com"
] | 838087366@qq.com |
e93d90e2e313ef997209ca6ce5f4bc7d9ff9c344 | 1501a479999fa07cf830dd59d9ad45041ea364f9 | /Ejercicios/02_OOP/Recital/src/app/Banda.java | 103ed20773a3d6ae7c5767d9d65eedf527de8bf8 | [] | no_license | andiizen/ADA-10ma-backend-maniana | 7bf4969dfb2244ee044a030cd5f98a22c1c86857 | d7b84cfee9103bb7f00230c9df3296536e488d08 | refs/heads/master | 2022-06-05T09:52:15.265831 | 2020-05-04T12:54:30 | 2020-05-04T12:54:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 531 | java | package app;
import java.util.ArrayList;
import java.util.List;
public class Banda extends Artista {
public int cantidadIntegrantes;
public List<Tema> temas = new ArrayList<>();
public void tocar(String nombreTema) {
Tema tema = buscarTema(nombreTema);
tema.comenzar();
}
public Tema buscarTema(String nombreTema) {
for (Tema tema : this.temas) {
if (tema.nombre.equals(nombreTema)) {
return tema;
}
}
return null;
}
} | [
"shadowdrone@hotmail.com"
] | shadowdrone@hotmail.com |
b3b70c0b358b18686b68b6ba2a9c64b3133320c5 | de1cd0baa2f29c168017adce27f33951f22f4c62 | /app/src/main/java/cs2340/donationtracker/model/ItemCategory.java | 1824d59a4eabe6f7833749ac06f95e5496afa6c8 | [] | no_license | The-6ix-of-us/donationtracker | 671e86f195b873eba166b0329d9e6422dea301f8 | 5dfeb5467e470075dafb7fcaa587cc4a0098fe80 | refs/heads/master | 2020-03-29T01:05:32.475855 | 2018-11-07T23:20:40 | 2018-11-07T23:20:40 | 149,370,858 | 0 | 0 | null | 2018-11-07T23:20:40 | 2018-09-19T00:53:07 | Java | UTF-8 | Java | false | false | 781 | java | package cs2340.donationtracker.model;
public enum ItemCategory {
CLOTHING ("Clothing"),
HAT ("Hat"),
KITCHEN("Kitchen"),
ELECTRONICS("Electronics"),
HOUSEHOLD("Household"),
OTHER("Other");
private final String itemCategory;
ItemCategory(String itemCategory) {
this.itemCategory = itemCategory;
}
public String toString() {
return itemCategory;
}
public static ItemCategory getCategory(String category) {
switch (category) {
case "Clothing": return CLOTHING;
case "Hat": return HAT;
case "Kitchen": return KITCHEN;
case "Electronics": return ELECTRONICS;
case "Household": return HOUSEHOLD;
default: return OTHER;
}
}
}
| [
"emilywilson6263@gmail.com"
] | emilywilson6263@gmail.com |
b577231de941773a0f105cddebe6f5a49743e18c | 9a87debe1c6f3bbbcdb8cf5b1c3f89576d89ff76 | /src/Q10.java | a5eda6695953a73cd3c24b81bf41e131aed6e03b | [] | no_license | a32871004/M2 | b7a054e302f872ed6e71560941055cd5b28788b1 | 85b64c5e2d4178b393a7f378ce642e199f17b3a1 | refs/heads/master | 2020-09-09T06:39:56.391053 | 2019-11-19T07:31:41 | 2019-11-19T07:31:41 | 221,377,830 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 343 | java | import java.util.Scanner;
public class Q10 {
public static void main(String[] args) {
Scanner sn=new Scanner(System.in);
int n=sn.nextInt();
for (int i=1;i<=n;i++){
for (int j=1;j<=n;j++){
System.out.printf("%d\t",i*j);
}
System.out.println();
}
}
}
| [
"a32871004@gmail.com"
] | a32871004@gmail.com |
a22d77f97e968890aed35658caff62cfe01bea7c | 52f1aac0daf1a4c415d1868b009687af8c3a4c52 | /src/main/java/com/movie/movie/dto/PagingDto.java | 272ea893dd7786971633db5a1e14aebc9d75657d | [] | no_license | qmqqqm/movie | a68d3c474c630d3fac68c80b62005000866042e6 | 254d26b3d20ff2ebb2a1c5bfa9f9e07284c296d3 | refs/heads/master | 2023-04-28T00:00:16.715793 | 2021-05-24T10:05:04 | 2021-05-24T10:05:04 | 370,303,673 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,900 | java | package com.movie.movie.dto;
public class PagingDto {
// 현재페이지, 시작페이지, 끝페이지, 게시글 총 갯수, 페이지당 글 갯수, 마지막페이지, SQL쿼리에 쓸 start, end
private int nowPage;
private int startPage;
private int endPage;
private int total;
private int cntPerPage;
private int lastPage;
private int start;
private int end;
private int movie_id;
private int cntPage = 5;
public PagingDto() {
}
public PagingDto(int total, int nowPage, int cntPerPage, int movie_id) {
setMovie_id(movie_id);
setNowPage(nowPage);
setCntPerPage(cntPerPage);
setTotal(total);
calcLastPage(getTotal(), getCntPerPage());
calcStartEndPage(getNowPage(), cntPage);
calcStartEnd(getNowPage(), getCntPerPage());
}
// 제일 마지막 페이지 계산
public void calcLastPage(int total, int cntPerPage) {
setLastPage((int) Math.ceil((double)total / (double)cntPerPage));
}
// 시작, 끝 페이지 계산
public void calcStartEndPage(int nowPage, int cntPage) {
setEndPage(((int)Math.ceil((double)nowPage / (double)cntPage)) * cntPage);
if (getLastPage() < getEndPage()) {
setEndPage(getLastPage());
}
setStartPage(getEndPage() - cntPage + 1);
if (getStartPage() < 1) {
setStartPage(1);
}
}
// DB 쿼리에서 사용할 start, end값 계산
public void calcStartEnd(int nowPage, int cntPerPage) {
setEnd(nowPage * cntPerPage);
setStart(getEnd() - cntPerPage + 1);
}
public int getMovie_id() {
return movie_id;
}
public void setMovie_id(int movie_id) {
this.movie_id = movie_id;
}
public int getNowPage() {
return nowPage;
}
public void setNowPage(int nowPage) {
this.nowPage = nowPage;
}
public int getStartPage() {
return startPage;
}
public void setStartPage(int startPage) {
this.startPage = startPage;
}
public int getEndPage() {
return endPage;
}
public void setEndPage(int endPage) {
this.endPage = endPage;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getCntPerPage() {
return cntPerPage;
}
public void setCntPerPage(int cntPerPage) {
this.cntPerPage = cntPerPage;
}
public int getLastPage() {
return lastPage;
}
public void setLastPage(int lastPage) {
this.lastPage = lastPage;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int setCntPage() {
return cntPage;
}
public void getCntPage(int cntPage) {
this.cntPage = cntPage;
}
@Override
public String toString() {
return "PagingDto [nowPage=" + nowPage + ", startPage=" + startPage + ", endPage=" + endPage + ", total=" + total
+ ", cntPerPage=" + cntPerPage + ", lastPage=" + lastPage + ", start=" + start + ", end=" + end
+ ", cntPage=" + cntPage + "]";
}
}
| [
"park jun gi@DESKTOP-J4U1CLA"
] | park jun gi@DESKTOP-J4U1CLA |
bdad0d6c7df81c04f606b633c5ba3fafbd1664d2 | 180e78725121de49801e34de358c32cf7148b0a2 | /dataset/protocol1/commons-lang/learning/6164/NumberUtils.java | 85f1cbc6de430887ad6b99b4d5af0da31e73d2a8 | [] | no_license | ASSERT-KTH/synthetic-checkstyle-error-dataset | 40e8d1e0a7ebe7f7711def96a390891a6922f7bd | 40c057e1669584bfc6fecf789b5b2854660222f3 | refs/heads/master | 2023-03-18T12:50:55.410343 | 2019-01-25T09:54:39 | 2019-01-25T09:54:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 65,790 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.math;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @since 2.0
*/
public class NumberUtils {
/** Reusable Long constant for zero. */
public static final Long LONG_ZERO = Long.valueOf(0L);
/** Reusable Long constant for one. */
public static final Long LONG_ONE = Long.valueOf(1L);
/** Reusable Long constant for minus one. */
public static final Long LONG_MINUS_ONE = Long.valueOf(-1L);
/** Reusable Integer constant for zero. */
public static final Integer INTEGER_ZERO = Integer.valueOf(0);
/** Reusable Integer constant for one. */
public static final Integer INTEGER_ONE = Integer.valueOf(1);
/** Reusable Integer constant for two */
public static final Integer INTEGER_TWO = Integer.valueOf(2);
/** Reusable Integer constant for minus one. */
public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1);
/** Reusable Short constant for zero. */
public static final Short SHORT_ZERO = Short.valueOf((short) 0);
/** Reusable Short constant for one. */
public static final Short SHORT_ONE = Short.valueOf((short) 1);
/** Reusable Short constant for minus one. */
public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1);
/** Reusable Byte constant for zero. */
public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0);
/** Reusable Byte constant for one. */
public static final Byte BYTE_ONE = Byte.valueOf((byte) 1);
/** Reusable Byte constant for minus one. */
public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1);
/** Reusable Double constant for zero. */
public static final Double DOUBLE_ZERO = Double.valueOf(0.0d);
/** Reusable Double constant for one. */
public static final Double DOUBLE_ONE = Double.valueOf(1.0d);
/** Reusable Double constant for minus one. */
public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d);
/** Reusable Float constant for zero. */
public static final Float FLOAT_ZERO = Float.valueOf(0.0f);
/** Reusable Float constant for one. */
public static final Float FLOAT_ONE = Float.valueOf(1.0f);
/** Reusable Float constant for minus one. */
public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f);
/**
* <p><code>NumberUtils</code> instances should NOT be constructed in standard programming.
* Instead, the class should be used as <code>NumberUtils.toInt("6");</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public NumberUtils() {
super();
}
//-----------------------------------------------------------------------
/**
* <p>Convert a <code>String</code> to an <code>int</code>, returning
* <code>zero</code> if the conversion fails.</p>
*
* <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>
*
* <pre>
* NumberUtils.toInt(null) = 0
* NumberUtils.toInt("") = 0
* NumberUtils.toInt("1") = 1
* </pre>
*
* @param str the string to convert, may be null
* @return the int represented by the string, or <code>zero</code> if
* conversion fails
* @since 2.1
*/
public static int toInt(final String str) {
return toInt(str, 0);
}
/**
* <p>Convert a <code>String</code> to an <code>int</code>, returning a
* default value if the conversion fails.</p>
*
* <p>If the string is <code>null</code>, the default value is returned.</p>
*
* <pre>
* NumberUtils.toInt(null, 1) = 1
* NumberUtils.toInt("", 1) = 1
* NumberUtils.toInt("1", 0) = 1
* </pre>
*
* @param str the string to convert, may be null
* @param defaultValue the default value
* @return the int represented by the string, or the default if conversion fails
* @since 2.1
*/
public static int toInt(final String str, final int defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Integer.parseInt(str);
} catch (final NumberFormatException nfe) {
return defaultValue;
}
}
/**
* <p>Convert a <code>String</code> to a <code>long</code>, returning
* <code>zero</code> if the conversion fails.</p>
*
* <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>
*
* <pre>
* NumberUtils.toLong(null) = 0L
* NumberUtils.toLong("") = 0L
* NumberUtils.toLong("1") = 1L
* </pre>
*
* @param str the string to convert, may be null
* @return the long represented by the string, or <code>0</code> if
* conversion fails
* @since 2.1
*/
public static long toLong(final String str) {
return toLong(str, 0L);
}
/**
* <p>Convert a <code>String</code> to a <code>long</code>, returning a
* default value if the conversion fails.</p>
*
* <p>If the string is <code>null</code>, the default value is returned.</p>
*
* <pre>
* NumberUtils.toLong(null, 1L) = 1L
* NumberUtils.toLong("", 1L) = 1L
* NumberUtils.toLong("1", 0L) = 1L
* </pre>
*
* @param str the string to convert, may be null
* @param defaultValue the default value
* @return the long represented by the string, or the default if conversion fails
* @since 2.1
*/
public static long toLong(final String str, final long defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Long.parseLong(str);
} catch (final NumberFormatException nfe) {
return defaultValue;
}
}
/**
* <p>Convert a <code>String</code> to a <code>float</code>, returning
* <code>0.0f</code> if the conversion fails.</p>
*
* <p>If the string <code>str</code> is <code>null</code>,
* <code>0.0f</code> is returned.</p>
*
* <pre>
* NumberUtils.toFloat(null) = 0.0f
* NumberUtils.toFloat("") = 0.0f
* NumberUtils.toFloat("1.5") = 1.5f
* </pre>
*
* @param str the string to convert, may be <code>null</code>
* @return the float represented by the string, or <code>0.0f</code>
* if conversion fails
* @since 2.1
*/
public static float toFloat(final String str) {
return toFloat(str, 0.0f);
}
/**
* <p>Convert a <code>String</code> to a <code>float</code>, returning a
* default value if the conversion fails.</p>
*
* <p>If the string <code>str</code> is <code>null</code>, the default
* value is returned.</p>
*
* <pre>
* NumberUtils.toFloat(null, 1.1f) = 1.0f
* NumberUtils.toFloat("", 1.1f) = 1.1f
* NumberUtils.toFloat("1.5", 0.0f) = 1.5f
* </pre>
*
* @param str the string to convert, may be <code>null</code>
* @param defaultValue the default value
* @return the float represented by the string, or defaultValue
* if conversion fails
* @since 2.1
*/
public static float toFloat(final String str, final float defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Float.parseFloat(str);
} catch (final NumberFormatException nfe) {
return defaultValue;
}
}
/**
* <p>Convert a <code>String</code> to a <code>double</code>, returning
* <code>0.0d</code> if the conversion fails.</p>
*
* <p>If the string <code>str</code> is <code>null</code>,
* <code>0.0d</code> is returned.</p>
*
* <pre>
* NumberUtils.toDouble(null) = 0.0d
* NumberUtils.toDouble("") = 0.0d
* NumberUtils.toDouble("1.5") = 1.5d
* </pre>
*
* @param str the string to convert, may be <code>null</code>
* @return the double represented by the string, or <code>0.0d</code>
* if conversion fails
* @since 2.1
*/
public static double toDouble(final String str) {
return toDouble(str, 0.0d);
}
/**
* <p>Convert a <code>String</code> to a <code>double</code>, returning a
* default value if the conversion fails.</p>
*
* <p>If the string <code>str</code> is <code>null</code>, the default
* value is returned.</p>
*
* <pre>
* NumberUtils.toDouble(null, 1.1d) = 1.1d
* NumberUtils.toDouble("", 1.1d) = 1.1d
* NumberUtils.toDouble("1.5", 0.0d) = 1.5d
* </pre>
*
* @param str the string to convert, may be <code>null</code>
* @param defaultValue the default value
* @return the double represented by the string, or defaultValue
* if conversion fails
* @since 2.1
*/
public static double toDouble(final String str, final double defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Double.parseDouble(str);
} catch (final NumberFormatException nfe) {
return defaultValue;
}
}
/**
* <p>Convert a <code>BigDecimal</code> to a <code>double</code>.</p>
*
* <p>If the <code>BigDecimal</code> <code>value</code> is
* <code>null</code>, then the specified default value is returned.</p>
*
* <pre>
* NumberUtils.toDouble(null) = 0.0d
* NumberUtils.toDouble(BigDecimal.valudOf(8.5d)) = 8.5d
* </pre>
*
* @param value the <code>BigDecimal</code> to convert, may be <code>null</code>.
* @return the double represented by the <code>BigDecimal</code> or
* <code>0.0d</code> if the <code>BigDecimal</code> is <code>null</code>.
* @since 3.8
*/
public static double toDouble(final BigDecimal value) {
return toDouble(value, 0.0d);
}
/**
* <p>Convert a <code>BigDecimal</code> to a <code>double</code>.</p>
*
* <p>If the <code>BigDecimal</code> <code>value</code> is
* <code>null</code>, then the specified default value is returned.</p>
*
* <pre>
* NumberUtils.toDouble(null, 1.1d) = 1.1d
* NumberUtils.toDouble(BigDecimal.valudOf(8.5d), 1.1d) = 8.5d
* </pre>
*
* @param value the <code>BigDecimal</code> to convert, may be <code>null</code>.
* @param defaultValue the default value
* @return the double represented by the <code>BigDecimal</code> or the
* defaultValue if the <code>BigDecimal</code> is <code>null</code>.
* @since 3.8
*/
public static double toDouble(final BigDecimal value, final double defaultValue) {
return value == null ? defaultValue : value.doubleValue();
}
//-----------------------------------------------------------------------
/**
* <p>Convert a <code>String</code> to a <code>byte</code>, returning
* <code>zero</code> if the conversion fails.</p>
*
* <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>
*
* <pre>
* NumberUtils.toByte(null) = 0
* NumberUtils.toByte("") = 0
* NumberUtils.toByte("1") = 1
* </pre>
*
* @param str the string to convert, may be null
* @return the byte represented by the string, or <code>zero</code> if
* conversion fails
* @since 2.5
*/
public static byte toByte(final String str) {
return toByte(str, (byte) 0);
}
/**
* <p>Convert a <code>String</code> to a <code>byte</code>, returning a
* default value if the conversion fails.</p>
*
* <p>If the string is <code>null</code>, the default value is returned.</p>
*
* <pre>
* NumberUtils.toByte(null, 1) = 1
* NumberUtils.toByte("", 1) = 1
* NumberUtils.toByte("1", 0) = 1
* </pre>
*
* @param str the string to convert, may be null
* @param defaultValue the default value
* @return the byte represented by the string, or the default if conversion fails
* @since 2.5
*/
public static byte toByte(final String str, final byte defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Byte.parseByte(str);
} catch (final NumberFormatException nfe) {
return defaultValue;
}
}
/**
* <p>Convert a <code>String</code> to a <code>short</code>, returning
* <code>zero</code> if the conversion fails.</p>
*
* <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>
*
* <pre>
* NumberUtils.toShort(null) = 0
* NumberUtils.toShort("") = 0
* NumberUtils.toShort("1") = 1
* </pre>
*
* @param str the string to convert, may be null
* @return the short represented by the string, or <code>zero</code> if
* conversion fails
* @since 2.5
*/
public static short toShort(final String str) {
return toShort(str, (short) 0);
}
/**
* <p>Convert a <code>String</code> to an <code>short</code>, returning a
* default value if the conversion fails.</p>
*
* <p>If the string is <code>null</code>, the default value is returned.</p>
*
* <pre>
* NumberUtils.toShort(null, 1) = 1
* NumberUtils.toShort("", 1) = 1
* NumberUtils.toShort("1", 0) = 1
* </pre>
*
* @param str the string to convert, may be null
* @param defaultValue the default value
* @return the short represented by the string, or the default if conversion fails
* @since 2.5
*/
public static short toShort(final String str, final short defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Short.parseShort(str);
} catch (final NumberFormatException nfe) {
return defaultValue;
}
}
/**
* Convert a <code>BigDecimal</code> to a <code>BigDecimal</code> with a scale of
* two that has been rounded using <code>RoundingMode.HALF_EVEN</code>. If the supplied
* <code>value</code> is null, then <code>BigDecimal.ZERO</code> is returned.
*
* <p>Note, the scale of a <code>BigDecimal</code> is the number of digits to the right of the
* decimal point.</p>
*
* @param value the <code>BigDecimal</code> to convert, may be null.
* @return the scaled, with appropriate rounding, <code>BigDecimal</code>.
* @since 3.8
*/
public static BigDecimal toScaledBigDecimal(final BigDecimal value) {
return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
}
/**
* Convert a <code>BigDecimal</code> to a <code>BigDecimal</code> whose scale is the
* specified value with a <code>RoundingMode</code> applied. If the input <code>value</code>
* is <code>null</code>, we simply return <code>BigDecimal.ZERO</code>.
*
* @param value the <code>BigDecimal</code> to convert, may be null.
* @param scale the number of digits to the right of the decimal point.
* @param roundingMode a rounding behavior for numerical operations capable of
* discarding precision.
* @return the scaled, with appropriate rounding, <code>BigDecimal</code>.
* @since 3.8
*/
public static BigDecimal toScaledBigDecimal(final BigDecimal value, final int scale, final RoundingMode roundingMode) {
if (value == null) {
return BigDecimal.ZERO;
}
return value.setScale(
scale,
(roundingMode == null) ? RoundingMode.HALF_EVEN : roundingMode
);
}
/**
* Convert a <code>Float</code> to a <code>BigDecimal</code> with a scale of
* two that has been rounded using <code>RoundingMode.HALF_EVEN</code>. If the supplied
* <code>value</code> is null, then <code>BigDecimal.ZERO</code> is returned.
*
* <p>Note, the scale of a <code>BigDecimal</code> is the number of digits to the right of the
* decimal point.</p>
*
* @param value the <code>Float</code> to convert, may be null.
* @return the scaled, with appropriate rounding, <code>BigDecimal</code>.
* @since 3.8
*/
public static BigDecimal toScaledBigDecimal(final Float value) {
return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
}
/**
* Convert a <code>Float</code> to a <code>BigDecimal</code> whose scale is the
* specified value with a <code>RoundingMode</code> applied. If the input <code>value</code>
* is <code>null</code>, we simply return <code>BigDecimal.ZERO</code>.
*
* @param value the <code>Float</code> to convert, may be null.
* @param scale the number of digits to the right of the decimal point.
* @param roundingMode a rounding behavior for numerical operations capable of
* discarding precision.
* @return the scaled, with appropriate rounding, <code>BigDecimal</code>.
* @since 3.8
*/
public static BigDecimal toScaledBigDecimal(final Float value, final int scale, final RoundingMode roundingMode) {
if (value == null) {
return BigDecimal.ZERO;
}
return toScaledBigDecimal(
BigDecimal.valueOf(value),
scale,
roundingMode
);
}
/**
* Convert a <code>Double</code> to a <code>BigDecimal</code> with a scale of
* two that has been rounded using <code>RoundingMode.HALF_EVEN</code>. If the supplied
* <code>value</code> is null, then <code>BigDecimal.ZERO</code> is returned.
*
* <p>Note, the scale of a <code>BigDecimal</code> is the number of digits to the right of the
* decimal point.</p>
*
* @param value the <code>Double</code> to convert, may be null.
* @return the scaled, with appropriate rounding, <code>BigDecimal</code>.
* @since 3.8
*/
public static BigDecimal toScaledBigDecimal(final Double value) {
return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
}
/**
* Convert a <code>Double</code> to a <code>BigDecimal</code> whose scale is the
* specified value with a <code>RoundingMode</code> applied. If the input <code>value</code>
* is <code>null</code>, we simply return <code>BigDecimal.ZERO</code>.
*
* @param value the <code>Double</code> to convert, may be null.
* @param scale the number of digits to the right of the decimal point.
* @param roundingMode a rounding behavior for numerical operations capable of
* discarding precision.
* @return the scaled, with appropriate rounding, <code>BigDecimal</code>.
* @since 3.8
*/
public static BigDecimal toScaledBigDecimal(final Double value, final int scale, final RoundingMode roundingMode) {
if (value == null) {
return BigDecimal.ZERO;
}
return toScaledBigDecimal(
BigDecimal.valueOf(value),
scale,
roundingMode
);
}
/**
* Convert a <code>String</code> to a <code>BigDecimal</code> with a scale of
* two that has been rounded using <code>RoundingMode.HALF_EVEN</code>. If the supplied
* <code>value</code> is null, then <code>BigDecimal.ZERO</code> is returned.
*
* <p>Note, the scale of a <code>BigDecimal</code> is the number of digits to the right of the
* decimal point.</p>
*
* @param value the <code>String</code> to convert, may be null.
* @return the scaled, with appropriate rounding, <code>BigDecimal</code>.
* @since 3.8
*/
public static BigDecimal toScaledBigDecimal(final String value) {
return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN);
}
/**
* Convert a <code>String</code> to a <code>BigDecimal</code> whose scale is the
* specified value with a <code>RoundingMode</code> applied. If the input <code>value</code>
* is <code>null</code>, we simply return <code>BigDecimal.ZERO</code>.
*
* @param value the <code>String</code> to convert, may be null.
* @param scale the number of digits to the right of the decimal point.
* @param roundingMode a rounding behavior for numerical operations capable of
* discarding precision.
* @return the scaled, with appropriate rounding, <code>BigDecimal</code>.
* @since 3.8
*/
public static BigDecimal toScaledBigDecimal(final String value, final int scale, final RoundingMode roundingMode) {
if (value == null) {
return BigDecimal.ZERO;
}
return toScaledBigDecimal(
createBigDecimal(value),
scale,
roundingMode
);
}
//-----------------------------------------------------------------------
// must handle Long, Float, Integer, Float, Short,
// BigDecimal, BigInteger and Byte
// useful methods:
// Byte.decode(String)
// Byte.valueOf(String, int radix)
// Byte.valueOf(String)
// Double.valueOf(String)
// Float.valueOf(String)
// Float.valueOf(String)
// Integer.valueOf(String, int radix)
// Integer.valueOf(String)
// Integer.decode(String)
// Integer.getInteger(String)
// Integer.getInteger(String, int val)
// Integer.getInteger(String, Integer val)
// Integer.valueOf(String)
// Double.valueOf(String)
// new Byte(String)
// Long.valueOf(String)
// Long.getLong(String)
// Long.getLong(String, int)
// Long.getLong(String, Integer)
// Long.valueOf(String, int)
// Long.valueOf(String)
// Short.valueOf(String)
// Short.decode(String)
// Short.valueOf(String, int)
// Short.valueOf(String)
// new BigDecimal(String)
// new BigInteger(String)
// new BigInteger(String, int radix)
// Possible inputs:
// 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd
// plus minus everything. Prolly more. A lot are not separable.
/**
* <p>Turns a string value into a java.lang.Number.</p>
*
* <p>If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it
* will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the
* prefix is more than 8 - or BigInteger if there are more than 16 digits.
* </p>
* <p>Then, the value is examined for a type qualifier on the end, i.e. one of
* <code>'f', 'F', 'd', 'D', 'l', 'L'</code>. If it is found, it starts
* trying to create successively larger types from the type specified
* until one is found that can represent the value.</p>
*
* <p>If a type specifier is not found, it will check for a decimal point
* and then try successively larger types from <code>Integer</code> to
* <code>BigInteger</code> and from <code>Float</code> to
* <code>BigDecimal</code>.</p>
*
* <p>
* Integral values with a leading {@code 0} will be interpreted as octal; the returned number will
* be Integer, Long or BigDecimal as appropriate.
* </p>
*
* <p>Returns <code>null</code> if the string is <code>null</code>.</p>
*
* <p>This method does not trim the input string, i.e., strings with leading
* or trailing spaces will generate NumberFormatExceptions.</p>
*
* @param str String containing a number, may be null
* @return Number created from the string (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static Number createNumber(final String str) {
if (str == null) {
return null;
}
if (StringUtils.isBlank(str)) {
throw new NumberFormatException("A blank string is not a valid number");
}
// Need to deal with all possible hex prefixes here
final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"};
int pfxLen = 0;
for (final String pfx : hex_prefixes) {
if (str.startsWith(pfx)) {
pfxLen += pfx.length();
break;
}
}
if (pfxLen > 0) { // we have a hex number
char firstSigDigit = 0; // strip leading zeroes
for (int i = pfxLen; i < str.length(); i++) {
firstSigDigit = str.charAt(i);
if (firstSigDigit == '0') { // count leading zeroes
pfxLen++;
} else {
break;
}
}
final int hexDigits = str.length() - pfxLen;
if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long
return createBigInteger(str);
}
if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int
return createLong(str);
}
return createInteger(str);
}
final char lastChar = str.charAt(str.length() - 1);
String mant;
String dec;
String exp;
final int decPos = str.indexOf('.');
final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present
// if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE)
// and the parsing which will detect if e or E appear in a number due to using the wrong offset
if (decPos > -1) { // there is a decimal point
if (expPos > -1) { // there is an exponent
if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE
throw new NumberFormatException(str + " is not a valid number.");
}
dec = str.substring(decPos + 1, expPos);
} else {
dec = str.substring(decPos + 1);
}
mant = getMantissa(str, decPos);
} else {
if (expPos > -1) {
if (expPos > str.length()) { // prevents double exponent causing IOOBE
throw new NumberFormatException(str + " is not a valid number.");
}
mant = getMantissa(str, expPos);
} else {
mant = getMantissa(str);
}
dec = null;
}
if (!Character.isDigit(lastChar) && lastChar != '.') {
if (expPos > -1 && expPos < str.length() - 1) {
exp = str.substring(expPos + 1, str.length() - 1);
} else {
exp = null;
}
//Requesting a specific type..
final String numeric = str.substring(0, str.length() - 1);
final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
switch (lastChar) {
case 'l' :
case 'L' :
if (dec == null
&& exp == null
&& (!numeric.isEmpty() && numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
try {
return createLong(numeric);
} catch (final NumberFormatException nfe) { // NOPMD
// Too big for a long
}
return createBigInteger(numeric);
}
throw new NumberFormatException(str + " is not a valid number.");
case 'f' :
case 'F' :
try {
final Float f = createFloat(str);
if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) {
//If it's too big for a float or the float value = 0 and the string
//has non-zeros in it, then float does not have the precision we want
return f;
}
} catch (final NumberFormatException nfe) { // NOPMD
// ignore the bad number
}
//$FALL-THROUGH$
case 'd' :
case 'D' :
try {
final Double d = createDouble(str);
if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) {
return d;
}
} catch (final NumberFormatException nfe) { // NOPMD
// ignore the bad number
}
try {
return createBigDecimal(numeric);
} catch (final NumberFormatException e) { // NOPMD
// ignore the bad number
}
//$FALL-THROUGH$
default :
throw new NumberFormatException(str + " is not a valid number.");
}
}
//User doesn't have a preference on the return type, so let's start
//small and go from there...
if (expPos > -1 && expPos < str.length() - 1) {
exp = str.substring(expPos + 1, str.length());
} else {
exp = null;
}
if (dec == null && exp == null) { // no decimal point and no exponent
//Must be an Integer, Long, Biginteger
try {
return createInteger(str);
} catch (final NumberFormatException nfe) { // NOPMD
// ignore the bad number
}
try {
return createLong(str);
} catch (final NumberFormatException nfe) { // NOPMD
// ignore the bad number
}
return createBigInteger(str);
}
//Must be a Float, Double, BigDecimal
final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
try {
final Float f = createFloat(str);
final Double d = createDouble(str);
if (!f.isInfinite()
&& !(f.floatValue() == 0.0F && !allZeros)
&& f.toString().equals(d.toString())) {
return f;
}
if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) {
final BigDecimal b = createBigDecimal(str);
if (b.compareTo(BigDecimal.valueOf(d.doubleValue())) == 0) {
return d;
}
return b;
}
} catch (final NumberFormatException nfe) { // NOPMD
// ignore the bad number
}
return createBigDecimal(str);
}
/**
* <p>Utility method for {@link #createNumber(java.lang.String)}.</p>
*
* <p>Returns mantissa of the given number.</p>
*
* @param str the string representation of the number
* @return mantissa of the given number
*/
private static String getMantissa(final String str) {
return getMantissa(str, str.length());
}
/**
* <p>Utility method for {@link #createNumber(java.lang.String)}.</p>
*
* <p>Returns mantissa of the given number.</p>
*
* @param str the string representation of the number
* @param stopPos the position of the exponent or decimal point
* @return mantissa of the given number
*/
private static String getMantissa(final String str, final int stopPos) {
final char firstChar = str.charAt(0);
final boolean hasSign = firstChar == '-' || firstChar == '+';
return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos);
}
/**
* <p>Utility method for {@link #createNumber(java.lang.String)}.</p>
*
* <p>Returns <code>true</code> if s is <code>null</code>.</p>
*
* @param str the String to check
* @return if it is all zeros or <code>null</code>
*/
private static boolean isAllZeros(final String str) {
if (str == null) {
return true;
}
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) != '0') {
return false;
}
}
return !str.isEmpty();
}
//-----------------------------------------------------------------------
/**
* <p>Convert a <code>String</code> to a <code>Float</code>.</p>
*
* <p>Returns <code>null</code> if the string is <code>null</code>.</p>
*
* @param str a <code>String</code> to convert, may be null
* @return converted <code>Float</code> (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static Float createFloat(final String str) {
if (str == null) {
return null;
}
return Float.valueOf(str);
}
/**
* <p>Convert a <code>String</code> to a <code>Double</code>.</p>
*
* <p>Returns <code>null</code> if the string is <code>null</code>.</p>
*
* @param str a <code>String</code> to convert, may be null
* @return converted <code>Double</code> (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static Double createDouble(final String str) {
if (str == null) {
return null;
}
return Double.valueOf(str);
}
/**
* <p>Convert a <code>String</code> to a <code>Integer</code>, handling
* hex (0xhhhh) and octal (0dddd) notations.
* N.B. a leading zero means octal; spaces are not trimmed.</p>
*
* <p>Returns <code>null</code> if the string is <code>null</code>.</p>
*
* @param str a <code>String</code> to convert, may be null
* @return converted <code>Integer</code> (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static Integer createInteger(final String str) {
if (str == null) {
return null;
}
// decode() handles 0xAABD and 0777 (hex and octal) as well.
return Integer.decode(str);
}
/**
* <p>Convert a <code>String</code> to a <code>Long</code>;
* since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations.
* N.B. a leading zero means octal; spaces are not trimmed.</p>
*
* <p>Returns <code>null</code> if the string is <code>null</code>.</p>
*
* @param str a <code>String</code> to convert, may be null
* @return converted <code>Long</code> (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static Long createLong(final String str) {
if (str == null) {
return null;
}
return Long.decode(str);
}
/**
* <p>Convert a <code>String</code> to a <code>BigInteger</code>;
* since 3.2 it handles hex (0x or #) and octal (0) notations.</p>
*
* <p>Returns <code>null</code> if the string is <code>null</code>.</p>
*
* @param str a <code>String</code> to convert, may be null
* @return converted <code>BigInteger</code> (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static BigInteger createBigInteger(final String str) {
if (str == null) {
return null;
}
int pos = 0; // offset within string
int radix = 10;
boolean negate = false; // need to negate later?
if (str.startsWith("-")) {
negate = true;
pos = 1;
}
if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex
radix = 16;
pos += 2;
} else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer)
radix = 16;
pos++;
} else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits
radix = 8;
pos++;
} // default is to treat as decimal
final BigInteger value = new BigInteger(str.substring(pos), radix);
return negate ? value.negate() : value;
}
/**
* <p>Convert a <code>String</code> to a <code>BigDecimal</code>.</p>
*
* <p>Returns <code>null</code> if the string is <code>null</code>.</p>
*
* @param str a <code>String</code> to convert, may be null
* @return converted <code>BigDecimal</code> (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static BigDecimal createBigDecimal(final String str) {
if (str == null) {
return null;
}
// handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException
if (StringUtils.isBlank(str)) {
throw new NumberFormatException("A blank string is not a valid number");
}
if (str.trim().startsWith("--")) {
// this is protection for poorness in java.lang.BigDecimal.
// it accepts this as a legal value, but it does not appear
// to be in specification of class. OS X Java parses it to
// a wrong value.
throw new NumberFormatException(str + " is not a valid number.");
}
return new BigDecimal(str);
}
// Min in array
//--------------------------------------------------------------------
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @since 3.4 Changed signature from min(long[]) to min(long...)
*/
public static long min(final long... array) {
// Validates input
validateArray(array);
// Finds and returns min
long min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @since 3.4 Changed signature from min(int[]) to min(int...)
*/
public static int min(final int... array) {
// Validates input
validateArray(array);
// Finds and returns min
int min = array[0];
for (int j = 1; j < array.length; j++) {
if (array[j] < min) {
min = array[j];
}
}
return min;
}
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @since 3.4 Changed signature from min(short[]) to min(short...)
*/
public static short min(final short... array) {
// Validates input
validateArray(array);
// Finds and returns min
short min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @since 3.4 Changed signature from min(byte[]) to min(byte...)
*/
public static byte min(final byte... array) {
// Validates input
validateArray(array);
// Finds and returns min
byte min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently
* @since 3.4 Changed signature from min(double[]) to min(double...)
*/
public static double min(final double... array) {
// Validates input
validateArray(array);
// Finds and returns min
double min = array[0];
for (int i = 1; i < array.length; i++) {
if (Double.isNaN(array[i])) {
return Double.NaN;
}
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* <p>Returns the minimum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the minimum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently
* @since 3.4 Changed signature from min(float[]) to min(float...)
*/
public static float min(final float... array) {
// Validates input
validateArray(array);
// Finds and returns min
float min = array[0];
for (int i = 1; i < array.length; i++) {
if (Float.isNaN(array[i])) {
return Float.NaN;
}
if (array[i] < min) {
min = array[i];
}
}
return min;
}
// Max in array
//--------------------------------------------------------------------
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the maximum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @since 3.4 Changed signature from max(long[]) to max(long...)
*/
public static long max(final long... array) {
// Validates input
validateArray(array);
// Finds and returns max
long max = array[0];
for (int j = 1; j < array.length; j++) {
if (array[j] > max) {
max = array[j];
}
}
return max;
}
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the maximum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @since 3.4 Changed signature from max(int[]) to max(int...)
*/
public static int max(final int... array) {
// Validates input
validateArray(array);
// Finds and returns max
int max = array[0];
for (int j = 1; j < array.length; j++) {
if (array[j] > max) {
max = array[j];
}
}
return max;
}
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the maximum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @since 3.4 Changed signature from max(short[]) to max(short...)
*/
public static short max(final short... array) {
// Validates input
validateArray(array);
// Finds and returns max
short max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the maximum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @since 3.4 Changed signature from max(byte[]) to max(byte...)
*/
public static byte max(final byte... array) {
// Validates input
validateArray(array);
// Finds and returns max
byte max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the maximum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently
* @since 3.4 Changed signature from max(double[]) to max(double...)
*/
public static double max(final double... array) {
// Validates input
validateArray(array);
// Finds and returns max
double max = array[0];
for (int j = 1; j < array.length; j++) {
if (Double.isNaN(array[j])) {
return Double.NaN;
}
if (array[j] > max) {
max = array[j];
}
}
return max;
}
/**
* <p>Returns the maximum value in an array.</p>
*
* @param array an array, must not be null or empty
* @return the maximum value in the array
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty
* @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently
* @since 3.4 Changed signature from max(float[]) to max(float...)
*/
public static float max(final float... array) {
// Validates input
validateArray(array);
// Finds and returns max
float max = array[0];
for (int j = 1; j < array.length; j++) {
if (Float.isNaN(array[j])) {
return Float.NaN;
}
if (array[j] > max) {
max = array[j];
}
}
return max;
}
/**
* Checks if the specified array is neither null nor empty.
*
* @param array the array to check
* @throws IllegalArgumentException if {@code array} is either {@code null} or empty
*/
private static void validateArray(final Object array) {
Validate.isTrue(array != null, "The Array must not be null");
Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty.");
}
// 3 param min
//-----------------------------------------------------------------------
/**
* <p>Gets the minimum of three <code>long</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the smallest of the values
*/
public static long min(long a, final long b, final long c) {
if (b < a) {
a = b;
}
if (c < a) {
a = c;
}
return a;
}
/**
* <p>Gets the minimum of three <code>int</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the smallest of the values
*/
public static int min(int a, final int b, final int c) {
if (b < a) {
a = b;
}
if (c < a) {
a = c;
}
return a;
}
/**
* <p>Gets the minimum of three <code>short</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the smallest of the values
*/
public static short min(short a, final short b, final short c) {
if (b < a) {
a = b;
}
if (c < a) {
a = c;
}
return a;
}
/**
* <p>Gets the minimum of three <code>byte</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the smallest of the values
*/
public static byte min(byte a, final byte b, final byte c) {
if (b < a) {
a = b;
}
if (c < a) {
a = c;
}
return a;
}
/**
* <p>Gets the minimum of three <code>double</code> values.</p>
*
* <p>If any value is <code>NaN</code>, <code>NaN</code> is
* returned. Infinity is handled.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the smallest of the values
* @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently
*/
public static double min(final double a, final double b, final double c) {
return Math.min(Math.min(a, b), c);
}
/**
* <p>Gets the minimum of three <code>float</code> values.</p>
*
* <p>If any value is <code>NaN</code>, <code>NaN</code> is
* returned. Infinity is handled.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the smallest of the values
* @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently
*/
public static float min(final float a, final float b, final float c) {
return Math.min(Math.min(a, b), c);
}
// 3 param max
//-----------------------------------------------------------------------
/**
* <p>Gets the maximum of three <code>long</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the largest of the values
*/
public static long max(long a, final long b, final long c) {
if (b > a) {
a = b;
}
if (c > a) {
a = c;
}
return a;
}
/**
* <p>Gets the maximum of three <code>int</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the largest of the values
*/
public static int max(int a, final int b, final int c) {
if (b > a) {
a = b;
}
if (c > a) {
a = c;
}
return a;
}
/**
* <p>Gets the maximum of three <code>short</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the largest of the values
*/
public static short max(short a, final short b, final short c) {
if (b > a) {
a = b;
}
if (c > a) {
a = c;
}
return a;
}
/**
* <p>Gets the maximum of three <code>byte</code> values.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the largest of the values
*/
public static byte max(byte a, final byte b, final byte c) {
if (b > a) {
a = b;
}
if (c > a) {
a = c;
}
return a;
}
/**
* <p>Gets the maximum of three <code>double</code> values.</p>
*
* <p>If any value is <code>NaN</code>, <code>NaN</code> is
* returned. Infinity is handled.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the largest of the values
* @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently
*/
public static double max(final double a, final double b, final double c) {
return Math.max(Math.max(a, b), c);
}
/**
* <p>Gets the maximum of three <code>float</code> values.</p>
*
* <p>If any value is <code>NaN</code>, <code>NaN</code> is
* returned. Infinity is handled.</p>
*
* @param a value 1
* @param b value 2
* @param c value 3
* @return the largest of the values
* @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently
*/
public static float max(final float a, final float b, final float c) {
return Math.max(Math.max(a, b), c);
}
//-----------------------------------------------------------------------
/**
* <p>Checks whether the <code>String</code> contains only
* digit characters.</p>
*
* <p><code>Null</code> and empty String will return
* <code>false</code>.</p>
*
* @param str the <code>String</code> to check
* @return <code>true</code> if str contains only Unicode numeric
*/
public static boolean isDigits(final String str) {
return StringUtils.isNumeric(str);
}
/**
* <p>Checks whether the String a valid Java number.</p>
*
* <p>Valid numbers include hexadecimal marked with the <code>0x</code> or
* <code>0X</code> qualifier, octal numbers, scientific notation and
* numbers marked with a type qualifier (e.g. 123L).</p>
*
* <p>Non-hexadecimal strings beginning with a leading zero are
* treated as octal values. Thus the string <code>09</code> will return
* <code>false</code>, since <code>9</code> is not a valid octal value.
* However, numbers beginning with {@code 0.} are treated as decimal.</p>
*
* <p><code>null</code> and empty/blank {@code String} will return
* <code>false</code>.</p>
*
* <p>Note, {@link #createNumber(String)} should return a number for every
* input resulting in <code>true</code>.</p>
*
* @param str the <code>String</code> to check
* @return <code>true</code> if the string is a correctly formatted number
* @since 3.3 the code supports hex {@code 0Xhhh} an
* octal {@code 0ddd} validation
* @deprecated This feature will be removed in Lang 4.0,
* use {@link NumberUtils#isCreatable(String)} instead
*/
@Deprecated
public static boolean isNumber(final String str) {
return isCreatable(str);
}
/**
* <p>Checks whether the String a valid Java number.</p>
*
* <p>Valid numbers include hexadecimal marked with the <code>0x</code> or
* <code>0X</code> qualifier, octal numbers, scientific notation and
* numbers marked with a type qualifier (e.g. 123L).</p>
*
* <p>Non-hexadecimal strings beginning with a leading zero are
* treated as octal values. Thus the string <code>09</code> will return
* <code>false</code>, since <code>9</code> is not a valid octal value.
* However, numbers beginning with {@code 0.} are treated as decimal.</p>
*
* <p><code>null</code> and empty/blank {@code String} will return
* <code>false</code>.</p>
*
* <p>Note, {@link #createNumber(String)} should return a number for every
* input resulting in <code>true</code>.</p>
*
* @param str the <code>String</code> to check
* @return <code>true</code> if the string is a correctly formatted number
* @since 3.5
*/
public static boolean isCreatable(final String str) {
if (StringUtils.isEmpty(str)) {
return false;
}
final char[] chars = str.toCharArray();
int sz = chars.length;
boolean hasExp = false;
boolean hasDecPoint = false;
boolean allowSigns = false;
boolean foundDigit = false;
// deal with any possible sign up front
final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0;
if (sz > start + 1 && chars[start] == '0' && !StringUtils.contains(str, '.')) { // leading 0, skip if is a decimal number
if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X
int i = start + 2;
if (i == sz) {
return false; // str == "0x"
}
// checking hex (it can't be anything else)
for (; i < chars.length; i++) {
if ((chars[i] < '0' || chars[i] > '9')
&& (chars[i] < 'a' || chars[i] > 'f')
&& (chars[i] < 'A' || chars[i] > 'F')) {
return false;
}
}
return true;
} else if (Character.isDigit(chars[start + 1])) {
// leading 0, but not hex, must be octal
int i = start + 1;
for (; i < chars.length; i++) {
if (chars[i] < '0' || chars[i] > '7') {
return false;
}
}
return true;
}
}
sz--; // don't want to loop to the last char, check it afterwords
// for type qualifiers
int i = start;
// loop to the next to last char or to the last char if we need another digit to
// make a valid number (e.g. chars[0..5] = "1234E")
while (i < sz || i < sz + 1 && allowSigns && !foundDigit) {
if (chars[i] >= '0' && chars[i] <= '9') {
foundDigit = true;
allowSigns = false;
} else if (chars[i] == '.') {
if (hasDecPoint || hasExp) {
// two decimal points or dec in exponent
return false;
}
hasDecPoint = true;
} else if (chars[i] == 'e' || chars[i] == 'E') {
// we've already taken care of hex.
if (hasExp) {
// two E's
return false;
}
if (!foundDigit) {
return false;
}
hasExp = true;
allowSigns = true;
} else if (chars[i] == '+' || chars[i] == '-') {
if (!allowSigns) {
return false;
}
allowSigns = false;
foundDigit = false; // we need a digit after the E
} else {
return false;
}
i++;
}
if (i < chars.length) {
if (chars[i] >= '0' && chars[i] <= '9') {
// no type qualifier, OK
return true;
}
if (chars[i] == 'e' || chars[i] == 'E') {
// can't have an E at the last byte
return false;
}
if (chars[i] == '.') {
if (hasDecPoint || hasExp) {
// two decimal points or dec in exponent
return false;
}
// single trailing decimal point after non-exponent is ok
return foundDigit;
}
if (!allowSigns
&& (chars[i] == 'd'
|| chars[i] == 'D'
|| chars[i] == 'f'
|| chars[i] == 'F')) {
return foundDigit;
}
if (chars[i] == 'l'
|| chars[i] == 'L') {
// not allowing L with an exponent or decimal point
return foundDigit && !hasExp && !hasDecPoint;
}
// last character is illegal
return false;
}
// allowSigns is true iff the val ends in 'E'
// found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
return !allowSigns && foundDigit;
}
/**
* <p>Checks whether the given String is a parsable number.</p>
*
* <p>Parsable numbers include those Strings understood by {@link Integer#parseInt(String)},
* {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or
* {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException}
* when calling one of those methods.</p>
*
* <p>Hexadecimal and scientific notations are <strong>not</strong> considered parsable.
* See {@link #isCreatable(String)} on those cases.</p>
*
* <p>{@code Null} and empty String will return <code>false</code>.</p>
*
* @param str the String to check.
* @return {@code true} if the string is a parsable number.
* @since 3.4
*/
public static boolean isParsable(final String str) {
if (StringUtils.isEmpty(str)) {
return false;
}
if (str.charAt(str.length() - 1) == '.') {
return false;
}
if (str.charAt(0) == '-') {
if (str.length() == 1) {
return false;
}
return withDecimalsParsing(str, 1);
}
return withDecimalsParsing(str, 0);
}
private static boolean withDecimalsParsing(final String str, final int beginIdx) {
int decimalPoints = 0;
for (int i = beginIdx; i < str.length(); i++) {
final boolean isDecimalPoint = str.charAt(i) == '.';
if (isDecimalPoint) {
decimalPoints++;
}
if (decimalPoints > 1) {
return false;
}
if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.</p>
*
* @param x the first {@code int} to compare
* @param y the second {@code int} to compare
* @return the value {@code 0} if {@code x == y};
* a value less than {@code 0} if {@code x < y}; and
* a value greater than {@code 0} if {@code x > y}
* @since 3.4
*/
public static int compare(final int x, final int y) {
if (x == y) {
return 0;
}
return x < y ? -1 : 1;
}
/**
* <p>Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.</p>
*
* @param x the first {@code long} to compare
* @param y the second {@code long} to compare
* @return the value {@code 0} if {@code x == y};
* a value less than {@code 0} if {@code x < y}; and
* a value greater than {@code 0} if {@code x > y}
* @since 3.4
*/
public static int compare(final long x, final long y) {
if (x == y) {
return 0;
}
return x < y ? -1 : 1;
}
/**
* <p>Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.</p>
*
* @param x the first {@code short} to compare
* @param y the second {@code short} to compare
* @return the value {@code 0} if {@code x == y};
* a value less than {@code 0} if {@code x < y}; and
* a value greater than {@code 0} if {@code x > y}
* @since 3.4
*/
public static int compare(final short x, final short y) {
if (x == y) {
return 0;
}
return x < y ? -1 : 1;
}
/**
* <p>Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.</p>
*
* @param x the first {@code byte} to compare
* @param y the second {@code byte} to compare
* @return the value {@code 0} if {@code x == y};
* a value less than {@code 0} if {@code x < y}; and
* a value greater than {@code 0} if {@code x > y}
* @since 3.4
*/
public static int compare(final byte x, final byte y) {
return x - y;
}
}
| [
"bloriot97@gmail.com"
] | bloriot97@gmail.com |
910c57e7b19e44f8527e39b322d6c99c78b767e0 | 5cb117a0f15b554e113d5f5dff0ef4cdb9dbb097 | /StudentMaintenance/src/main/java/com/onebill/Spring/controller/StudentMaintenanceController.java | d61d62228027136f0bc58ab802c1cbd58df8bff8 | [] | no_license | Ratheshprabakar/Student-Maintenance-Application | 7221b035aeb06fe39438dee230863c6075d6a401 | 111e0403fccef02ab95ad8d9f69d80c89a8dac99 | refs/heads/master | 2023-06-02T18:44:13.746626 | 2021-06-20T11:44:57 | 2021-06-20T11:44:57 | 377,746,353 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,289 | java | /*
* @Class : StudentMaintenanceController
* @Description : Rest Controller class to control all REST API's
* @API's
* 1. To Insert a Student Data(path variables = quaterlyMark/halfYearlyMark/AnnualMark) - /add/{quaterlyMark}/{halfYearlyMark}/{AnnualMark}
* 2. To Search a Student Data(path variable = id) - /search/{id}
* 3. To Remove a Student Data(path variable = id) - /remove/{id}
* 4. To Update student Email Address(request body = StudentInfoBean object contains id and email only) - /update
* 5. To return Aggregate Marks(path variable = id) - /getMark/{id}
* 6. To retrive Grade of the student(path variable = id) - /getGrade/{id}
* */
package com.onebill.Spring.controller;
/* @author : Rathesh Prabakar
* @version : 2.0 17/06/2021
* */
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.onebill.Spring.bean.StudentInfoBean;
import com.onebill.Spring.response.StudentMaintenanceResponse;
import com.onebill.Spring.service.StudentMaintenanceService;
@RestController
public class StudentMaintenanceController {
@Autowired
StudentMaintenanceService service;
@PostMapping(path = "/add/{quaterlyMark}/{halfYearlyMark}/{AnnualMark}", produces = { MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE }, consumes = { MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE })
public StudentMaintenanceResponse insertStudent(@PathVariable(name="quaterlyMark") double quaterlyMark,
@PathVariable(name="halfYearlyMark") double halfYearlyMark,
@PathVariable(name="AnnualMark") double AnnualMark,
@RequestBody StudentInfoBean studentInfoBean) {
StudentMaintenanceResponse response = new StudentMaintenanceResponse();
if (service.addStudent(studentInfoBean,quaterlyMark,halfYearlyMark,AnnualMark)) {
response.setStatusCode(200);
response.setStatusMessage("Success");
response.setDescription("Successfully Inserted");
} else {
response.setStatusCode(404);
response.setStatusMessage("Failure");
response.setDescription("Data not get added");
}
return response;
} // end of Insert Student data
@GetMapping(path = "/search/{id}", produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public StudentMaintenanceResponse searchStudent(@PathVariable(name = "id") int id) {
StudentMaintenanceResponse response = new StudentMaintenanceResponse();
StudentInfoBean studentInfoBean = service.searchStudent(id);
if (studentInfoBean != null) {
response.setStatusCode(200);
response.setStatusMessage("Success");
response.setDescription("Record Found for ID " + id);
response.setStudentInfoBean(studentInfoBean);
} else {
response.setStatusCode(404);
response.setStatusMessage("Failure");
response.setDescription("Record not found for ID " + id);
}
return response;
} // end of Search a Student data
@DeleteMapping(path = "/remove/{id}", produces = { MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE })
public StudentMaintenanceResponse removeStudent(@PathVariable(name = "id") int id) {
StudentMaintenanceResponse response = new StudentMaintenanceResponse();
if (service.deleteStudent(id)) {
response.setStatusCode(200);
response.setStatusMessage("Success");
response.setDescription("Successfully Deleted record with ID " + id);
} else {
response.setStatusCode(404);
response.setStatusMessage("Failure");
response.setDescription("Entry not found for ID " + id);
}
return response;
} // end of Remove a Student
@PutMapping(path = "/update", produces = { MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE }, consumes = { MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE })
public StudentMaintenanceResponse updateStudentEmail(@RequestBody StudentInfoBean studentInfoBean) {
StudentMaintenanceResponse response = new StudentMaintenanceResponse();
if (service.updateStudent(studentInfoBean)) {
response.setStatusCode(200);
response.setStatusMessage("Success");
response.setDescription("Successfully Updated the email for ID " + studentInfoBean.getUserid());
} else {
response.setStatusCode(404);
response.setStatusMessage("Failure");
response.setDescription("Data not found");
}
return response;
} // End of Update Email Address for a student
@GetMapping(path="/getMark/{id}", produces= {MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE})
public StudentMaintenanceResponse getAggregateMarks(@PathVariable(name="id") int id) {
StudentMaintenanceResponse response = new StudentMaintenanceResponse();
StudentInfoBean studentInfoBean = service.getMark(id);
if (studentInfoBean!=null) {
response.setStatusCode(200);
response.setStatusMessage("Success");
response.setDescription("Aggregate Mark for " + studentInfoBean.getName()+" is "+studentInfoBean.getMarks());
} else {
response.setStatusCode(404);
response.setStatusMessage("Failure");
response.setDescription("Data not found with ID "+id);
}
return response;
}
@GetMapping(path="/getGrade/{id}", produces= {MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE})
public StudentMaintenanceResponse getGrade(@PathVariable(name="id") int id) {
StudentMaintenanceResponse response = new StudentMaintenanceResponse();
StudentInfoBean studentInfoBean = service.getGrade(id);
if (studentInfoBean!=null) {
response.setStatusCode(200);
response.setStatusMessage("Success");
response.setDescription("Grade for " + studentInfoBean.getName()+" is "+studentInfoBean.getGrade());
} else {
response.setStatusCode(404);
response.setStatusMessage("Failure");
response.setDescription("Data not found with ID "+id);
}
return response;
} // end of Retrive Grade of the Student
}
| [
"ratheshprabakar@gmail.com"
] | ratheshprabakar@gmail.com |
eaf447ac032d34c988b47c274bdd3fa4cfe38800 | 16a1dcb767e8ddc443340158765b15e6ea10443a | /code/MohRptWeb/src/main/java/com/neev/moh/rpt/controller/DoctorReportController.java | 452fc69783ec1a5f8454925bfaacd3def5f86349 | [] | no_license | tgkprog/springHealthStarter | d38af1a83380ec328335b8fcb4eda6a9cce7defc | cb0958e697f33ddb2e423c2ff990b7edca7fa516 | refs/heads/master | 2022-12-25T09:23:29.298505 | 2021-06-07T20:36:01 | 2021-06-07T20:36:01 | 118,367,898 | 0 | 2 | null | 2022-12-16T15:51:41 | 2018-01-21T19:46:11 | Java | UTF-8 | Java | false | false | 1,269 | java | package com.neev.moh.rpt.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.neev.moh.logger.MohLogFactory;
import com.neev.moh.logger.MohLogger;
import com.neev.moh.rpt.facade.DoctorReportFacade;
import com.neev.moh.rpt.facade.dto.response.UserCountRes;
/**
* Handles requests for the application home page.
*/
@Controller
@RequestMapping(value = "/doctorReport")
public class DoctorReportController {
private static final MohLogger logger = MohLogFactory.getLoggerInstance(DoctorReportController.class.getName());
@Autowired(required = true)
private DoctorReportFacade reportFacade;
@RequestMapping(value = "getNumberAptsPerDoctor", method = RequestMethod.POST)
public @ResponseBody UserCountRes getNumberAptsPerDoctor(final HttpServletRequest req) {
UserCountRes userCountRes = null;
// logger.log(MohLogger.INFO, "Search text :: " + searchText);
userCountRes = reportFacade.getNumberAptsPerDoctor();
return userCountRes;
}
}
| [
"tgkprog@gmail.com"
] | tgkprog@gmail.com |
cbcdeb8aebfea715cd98fb15eebfca839d916ad5 | 7ff148a063be1721f3409e1166a9a0327effe182 | /LeagueTableCreator.java | 46535addecf3d41c18033e55d32aee09a83bdc3a | [] | no_license | siskakrislim/java-coursework-2 | 759c3a0c5f0233e684210c854bb43fb8dd274c20 | 15717ded0a61f3ee790f1cf6524d2cd7307510af | refs/heads/master | 2020-12-09T14:25:01.016078 | 2020-05-13T07:14:29 | 2020-05-13T07:14:29 | 233,333,055 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,782 | java | import java.time.LocalDate;
import java.util.*;
public class LeagueTableCreator {
private List<DatedMatchResult> results;
private Map<String, LeagueStanding> tabulatedResults;
private LocalDate onOrBeforeThisDate;
public LeagueTableCreator(List<DatedMatchResult> results) {
this.results = results;
}
public List<LeagueStanding> calculateLeagueTable(LocalDate onThisDate) {
initialiseData(onThisDate);
for (DatedMatchResult result : results) {
addIfInDateRange(result);
}
return getLeagueTable();
}
public List<LeagueStanding> calculateLeagueTable() {
return calculateLeagueTable(LocalDate.now());
}
private List<LeagueStanding> getLeagueTable() {
ArrayList<LeagueStanding> standings = new ArrayList<>(tabulatedResults.values());
standings.sort(new LeagueStandingComparator());
return standings;
}
private void addIfInDateRange(DatedMatchResult result) {
if (result.getDate().isAfter(onOrBeforeThisDate)) {
return;
}
updateLeagueStandings(result);
}
private void updateLeagueStandings(DatedMatchResult result) {
updatePlayedStats(result);
updateGoalStats(result);
if (isHomeWin(result)) {
recordHomeWin(result);
} else if (isAwayWin(result)) {
recordAwayWin(result);
} else { //it's a draw
recordDraw(result);
}
}
private void updatePlayedStats(DatedMatchResult result) {
LeagueStanding homeTeamStanding = getHomeTeam(result);
LeagueStanding awayTeamStanding = getAwayTeam(result);
int newHomePlayed = homeTeamStanding.getPlayed() + 1;
homeTeamStanding.setPlayed(newHomePlayed);
int newAwayPlayed = awayTeamStanding.getPlayed() + 1;
awayTeamStanding.setPlayed(newAwayPlayed);
}
private void updateGoalStats(DatedMatchResult result) {
LeagueStanding homeTeamStanding = getHomeTeam(result);
LeagueStanding awayTeamStanding = getAwayTeam(result);
int homeScore = result.getHomeScore();
int awayScore = result.getAwayScore();
int newHomeGoalsFor = homeTeamStanding.getGoalsFor() + homeScore;
homeTeamStanding.setGoalsFor(newHomeGoalsFor);
int newAwayGoalsFor = awayTeamStanding.getGoalsFor() + awayScore;
awayTeamStanding.setGoalsFor(newAwayGoalsFor);
int newHomeGoalsAgainst = homeTeamStanding.getGoalsAgainst() + awayScore;
homeTeamStanding.setGoalsAgainst(newHomeGoalsAgainst);
int newAwayGoalsAgainst = awayTeamStanding.getGoalsAgainst() + homeScore;
awayTeamStanding.setGoalsAgainst(newAwayGoalsAgainst);
int newHomeGoalDifference = homeTeamStanding.getGoalsFor() - homeTeamStanding.getGoalsAgainst();
homeTeamStanding.setGoalDifference(newHomeGoalDifference);
int newAwayGoalDifference = awayTeamStanding.getGoalsFor() - awayTeamStanding.getGoalsAgainst();
awayTeamStanding.setGoalDifference(newAwayGoalDifference);
}
private void recordHomeWin(DatedMatchResult result) {
LeagueStanding homeTeamStanding = getHomeTeam(result);
LeagueStanding awayTeamStanding = getAwayTeam(result);
int newHomeWon = homeTeamStanding.getWon() + 1;
homeTeamStanding.setWon(newHomeWon);
int newAwayLost = awayTeamStanding.getLost() + 1;
awayTeamStanding.setLost(newAwayLost);
int newHomePoints = homeTeamStanding.getPoints() + 3;
homeTeamStanding.setPoints(newHomePoints);
}
private void recordAwayWin(DatedMatchResult result) {
LeagueStanding homeTeamStanding = getHomeTeam(result);
LeagueStanding awayTeamStanding = getAwayTeam(result);
int newAwayWon = awayTeamStanding.getWon() + 1;
awayTeamStanding.setWon(newAwayWon);
int newHomeLost = homeTeamStanding.getLost() + 1;
homeTeamStanding.setLost(newHomeLost);
int newAwayPoints = awayTeamStanding.getPoints() + 3;
awayTeamStanding.setPoints(newAwayPoints);
}
private void recordDraw(DatedMatchResult result) {
LeagueStanding homeTeamStanding = getHomeTeam(result);
LeagueStanding awayTeamStanding = getAwayTeam(result);
int newHomeDrawn = homeTeamStanding.getDrawn() + 1;
homeTeamStanding.setDrawn(newHomeDrawn);
int newAwayDrawn = awayTeamStanding.getDrawn() + 1;
awayTeamStanding.setDrawn(newAwayDrawn);
int newHomePoints = homeTeamStanding.getPoints() + 1;
homeTeamStanding.setPoints(newHomePoints);
int newAwayPoints = awayTeamStanding.getPoints() + 1;
awayTeamStanding.setPoints(newAwayPoints);
}
private boolean isHomeWin(DatedMatchResult result) {
return result.getHomeScore() > result.getAwayScore();
}
private boolean isAwayWin(DatedMatchResult result) {
return result.getAwayScore() > result.getHomeScore();
}
private LeagueStanding getHomeTeam(DatedMatchResult result) {
return tabulatedResults.get(result.getHomeTeam());
}
private LeagueStanding getAwayTeam(DatedMatchResult result) {
System.out.println(result.getAwayTeam());
System.out.println(tabulatedResults.get(result.getAwayTeam()));
return tabulatedResults.get(result.getAwayTeam());
}
private void initialiseData(LocalDate date) {
tabulatedResults = new TreeMap<>();
onOrBeforeThisDate = date;
for (DatedMatchResult result : results) {
String team = result.getHomeTeam();
if (!tabulatedResults.keySet().contains(team)) {
tabulatedResults.put(team, new LeagueStanding(team));
}
}
}
}
| [
"noreply@github.com"
] | siskakrislim.noreply@github.com |
e31f42a458bedb52c11d0e69563dc71b6ca107bd | 23962421138cb2c9160c993a6817b252b1d031b1 | /src/main/java/com/test/springbootwebsocket/controller/Mycontroller.java | a4f1abff5e5de90dc231c30849d158127988fa35 | [] | no_license | CoderLG/SpringBoot-WebSocket | 8fa7a63fe75653c8d29b129ace713d86dee24830 | 876b79a1bf59ad9a8f1cea4e732222da1264532a | refs/heads/master | 2022-06-20T08:35:14.939010 | 2020-05-12T05:54:15 | 2020-05-12T05:54:15 | 263,509,576 | 2 | 0 | null | 2020-05-13T02:54:19 | 2020-05-13T02:54:18 | null | UTF-8 | Java | false | false | 961 | java | package com.test.springbootwebsocket.controller;
import com.test.springbootwebsocket.service.WebSocketServer;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.websocket.server.PathParam;
import java.io.IOException;
@RestController
@CrossOrigin
public class Mycontroller {
/**
* 页面请求
*/
@GetMapping("/socket/{uid}")
public ModelAndView socket(@PathVariable String uid) {
ModelAndView mav = new ModelAndView("/socket");
mav.addObject("uid", uid);
return mav;
}
/**
* 推送数据接口
*/
@RequestMapping("/socket/push/{uid}")
public String pushToWeb(@PathVariable String uid, String message) {
try {
WebSocketServer.sendInfo(message, uid);
} catch (IOException e) {
e.printStackTrace();
return "推送失败";
}
return "推送成功";
}
}
| [
"lixy@geovis.com.cn"
] | lixy@geovis.com.cn |
d3b49d4776295d491252b0b0bca4e4a447dd7849 | 6d2fe29219cbdd28b64a3cff54c3de3050d6c7be | /plc4j/drivers/bacnet/src/main/generated/org/apache/plc4x/java/bacnetip/readwrite/BACnetEventParameterChangeOfValueCivCriteria.java | 555594005428d2b767d523fb4ec3c0cb0e2203e6 | [
"Apache-2.0",
"Unlicense"
] | permissive | siyka-au/plc4x | ca5e7b02702c8e59844bf45ba595052fcda24ac8 | 44e4ede3b4f54370553549946639a3af2c956bd1 | refs/heads/develop | 2023-05-12T12:28:09.037476 | 2023-04-27T22:55:23 | 2023-04-27T22:55:23 | 179,656,431 | 4 | 3 | Apache-2.0 | 2023-03-02T21:19:18 | 2019-04-05T09:43:27 | Java | UTF-8 | Java | false | false | 8,929 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.plc4x.java.bacnetip.readwrite;
import static org.apache.plc4x.java.spi.codegen.fields.FieldReaderFactory.*;
import static org.apache.plc4x.java.spi.codegen.fields.FieldWriterFactory.*;
import static org.apache.plc4x.java.spi.codegen.io.DataReaderFactory.*;
import static org.apache.plc4x.java.spi.codegen.io.DataWriterFactory.*;
import static org.apache.plc4x.java.spi.generation.StaticHelper.*;
import java.time.*;
import java.util.*;
import org.apache.plc4x.java.api.exceptions.*;
import org.apache.plc4x.java.api.value.*;
import org.apache.plc4x.java.spi.codegen.*;
import org.apache.plc4x.java.spi.codegen.fields.*;
import org.apache.plc4x.java.spi.codegen.io.*;
import org.apache.plc4x.java.spi.generation.*;
// Code generated by code-generation. DO NOT EDIT.
public abstract class BACnetEventParameterChangeOfValueCivCriteria implements Message {
// Abstract accessors for discriminator values.
// Properties.
protected final BACnetOpeningTag openingTag;
protected final BACnetTagHeader peekedTagHeader;
protected final BACnetClosingTag closingTag;
// Arguments.
protected final Short tagNumber;
public BACnetEventParameterChangeOfValueCivCriteria(
BACnetOpeningTag openingTag,
BACnetTagHeader peekedTagHeader,
BACnetClosingTag closingTag,
Short tagNumber) {
super();
this.openingTag = openingTag;
this.peekedTagHeader = peekedTagHeader;
this.closingTag = closingTag;
this.tagNumber = tagNumber;
}
public BACnetOpeningTag getOpeningTag() {
return openingTag;
}
public BACnetTagHeader getPeekedTagHeader() {
return peekedTagHeader;
}
public BACnetClosingTag getClosingTag() {
return closingTag;
}
public short getPeekedTagNumber() {
return (short) (getPeekedTagHeader().getActualTagNumber());
}
protected abstract void serializeBACnetEventParameterChangeOfValueCivCriteriaChild(
WriteBuffer writeBuffer) throws SerializationException;
public void serialize(WriteBuffer writeBuffer) throws SerializationException {
PositionAware positionAware = writeBuffer;
boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();
int startPos = positionAware.getPos();
writeBuffer.pushContext("BACnetEventParameterChangeOfValueCivCriteria");
// Simple Field (openingTag)
writeSimpleField("openingTag", openingTag, new DataWriterComplexDefault<>(writeBuffer));
// Virtual field (doesn't actually serialize anything, just makes the value available)
short peekedTagNumber = getPeekedTagNumber();
writeBuffer.writeVirtual("peekedTagNumber", peekedTagNumber);
// Switch field (Serialize the sub-type)
serializeBACnetEventParameterChangeOfValueCivCriteriaChild(writeBuffer);
// Simple Field (closingTag)
writeSimpleField("closingTag", closingTag, new DataWriterComplexDefault<>(writeBuffer));
writeBuffer.popContext("BACnetEventParameterChangeOfValueCivCriteria");
}
@Override
public int getLengthInBytes() {
return (int) Math.ceil((float) getLengthInBits() / 8.0);
}
@Override
public int getLengthInBits() {
int lengthInBits = 0;
BACnetEventParameterChangeOfValueCivCriteria _value = this;
boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();
// Simple field (openingTag)
lengthInBits += openingTag.getLengthInBits();
// A virtual field doesn't have any in- or output.
// Length of sub-type elements will be added by sub-type...
// Simple field (closingTag)
lengthInBits += closingTag.getLengthInBits();
return lengthInBits;
}
public static BACnetEventParameterChangeOfValueCivCriteria staticParse(
ReadBuffer readBuffer, Object... args) throws ParseException {
PositionAware positionAware = readBuffer;
if ((args == null) || (args.length != 1)) {
throw new PlcRuntimeException(
"Wrong number of arguments, expected 1, but got " + args.length);
}
Short tagNumber;
if (args[0] instanceof Short) {
tagNumber = (Short) args[0];
} else if (args[0] instanceof String) {
tagNumber = Short.valueOf((String) args[0]);
} else {
throw new PlcRuntimeException(
"Argument 0 expected to be of type Short or a string which is parseable but was "
+ args[0].getClass().getName());
}
return staticParse(readBuffer, tagNumber);
}
public static BACnetEventParameterChangeOfValueCivCriteria staticParse(
ReadBuffer readBuffer, Short tagNumber) throws ParseException {
readBuffer.pullContext("BACnetEventParameterChangeOfValueCivCriteria");
PositionAware positionAware = readBuffer;
int startPos = positionAware.getPos();
int curPos;
boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();
BACnetOpeningTag openingTag =
readSimpleField(
"openingTag",
new DataReaderComplexDefault<>(
() -> BACnetOpeningTag.staticParse(readBuffer, (short) (tagNumber)), readBuffer));
BACnetTagHeader peekedTagHeader =
readPeekField(
"peekedTagHeader",
new DataReaderComplexDefault<>(
() -> BACnetTagHeader.staticParse(readBuffer), readBuffer));
short peekedTagNumber =
readVirtualField("peekedTagNumber", short.class, peekedTagHeader.getActualTagNumber());
// Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
BACnetEventParameterChangeOfValueCivCriteriaBuilder builder = null;
if (EvaluationHelper.equals(peekedTagNumber, (short) 0)) {
builder =
BACnetEventParameterChangeOfValueCivCriteriaBitmask
.staticParseBACnetEventParameterChangeOfValueCivCriteriaBuilder(
readBuffer, tagNumber);
} else if (EvaluationHelper.equals(peekedTagNumber, (short) 1)) {
builder =
BACnetEventParameterChangeOfValueCivCriteriaReferencedPropertyIncrement
.staticParseBACnetEventParameterChangeOfValueCivCriteriaBuilder(
readBuffer, tagNumber);
}
if (builder == null) {
throw new ParseException(
"Unsupported case for discriminated type"
+ " parameters ["
+ "peekedTagNumber="
+ peekedTagNumber
+ "]");
}
BACnetClosingTag closingTag =
readSimpleField(
"closingTag",
new DataReaderComplexDefault<>(
() -> BACnetClosingTag.staticParse(readBuffer, (short) (tagNumber)), readBuffer));
readBuffer.closeContext("BACnetEventParameterChangeOfValueCivCriteria");
// Create the instance
BACnetEventParameterChangeOfValueCivCriteria _bACnetEventParameterChangeOfValueCivCriteria =
builder.build(openingTag, peekedTagHeader, closingTag, tagNumber);
return _bACnetEventParameterChangeOfValueCivCriteria;
}
public interface BACnetEventParameterChangeOfValueCivCriteriaBuilder {
BACnetEventParameterChangeOfValueCivCriteria build(
BACnetOpeningTag openingTag,
BACnetTagHeader peekedTagHeader,
BACnetClosingTag closingTag,
Short tagNumber);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof BACnetEventParameterChangeOfValueCivCriteria)) {
return false;
}
BACnetEventParameterChangeOfValueCivCriteria that =
(BACnetEventParameterChangeOfValueCivCriteria) o;
return (getOpeningTag() == that.getOpeningTag())
&& (getPeekedTagHeader() == that.getPeekedTagHeader())
&& (getClosingTag() == that.getClosingTag())
&& true;
}
@Override
public int hashCode() {
return Objects.hash(getOpeningTag(), getPeekedTagHeader(), getClosingTag());
}
@Override
public String toString() {
WriteBufferBoxBased writeBufferBoxBased = new WriteBufferBoxBased(true, true);
try {
writeBufferBoxBased.writeSerializable(this);
} catch (SerializationException e) {
throw new RuntimeException(e);
}
return "\n" + writeBufferBoxBased.getBox().toString() + "\n";
}
}
| [
"christofer.dutz@c-ware.de"
] | christofer.dutz@c-ware.de |
6b7e0b248aaa987dfc16a1ff65a5b08143b7254d | 60ef2987f20558a03bfed3b5ba11ba8165f67f3e | /app/src/test/java/com/shresthakiran/calculatebmi/ExampleUnitTest.java | be40135510188091488e10f96901b4ded0cc2e5a | [] | no_license | ikiranshrestha/Calculate-BMI | db2db9da468aa5f32fab9b9d4380b24f7b0f35a4 | 11590a8d13897bf660036bb828b30805f3db2457 | refs/heads/master | 2022-04-18T11:01:10.205862 | 2020-04-20T05:18:32 | 2020-04-20T05:18:32 | 257,173,965 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 391 | java | package com.shresthakiran.calculatebmi;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"kiranshrestha903@gmail.com"
] | kiranshrestha903@gmail.com |
78f1c4b8ded3782f7165abb651213ac7dc2fba81 | 423481252ef2606ca855cc09a137dcd97cca2f0a | /app/src/main/java/com/chhay/taskreminder/AlarmCursorAdapter.java | 0cdadee404b51bc80dfd52cfd46b108a70c22b95 | [] | no_license | porchhayngov/TaskReminder | e89572dbfb48109bb7a878563c64ffa5e0a9855c | 857d05066855b0a6a5efc9d795c84ba9ea81e10c | refs/heads/master | 2022-11-14T10:56:35.046702 | 2020-07-13T06:25:36 | 2020-07-13T06:25:36 | 256,940,093 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,339 | java | package com.chhay.taskreminder;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import com.chhay.taskreminder.data.AlarmReminderContract;
public class AlarmCursorAdapter extends CursorAdapter {
private TextView mTitleText, mDateAndTimeText, mRepeatInfoText;
private ImageView mActiveImage , mThumbnailImage;
private ColorGenerator mColorGenerator = ColorGenerator.DEFAULT;
private TextDrawable mDrawableBuilder;
public AlarmCursorAdapter(Context context, Cursor c) {
super(context, c, 0 /* flags */);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.activity_add, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
mTitleText = (TextView) view.findViewById(R.id.recycle_title);
mDateAndTimeText = (TextView) view.findViewById(R.id.recycle_date_time);
mRepeatInfoText = (TextView) view.findViewById(R.id.recycle_repeat_info);
mActiveImage = (ImageView) view.findViewById(R.id.active_image);
mThumbnailImage = (ImageView) view.findViewById(R.id.thumbnail_image);
int titleColumnIndex = cursor.getColumnIndex(AlarmReminderContract.AlarmReminderEntry.KEY_TITLE);
int dateColumnIndex = cursor.getColumnIndex(AlarmReminderContract.AlarmReminderEntry.KEY_DATE);
int timeColumnIndex = cursor.getColumnIndex(AlarmReminderContract.AlarmReminderEntry.KEY_TIME);
int repeatColumnIndex = cursor.getColumnIndex(AlarmReminderContract.AlarmReminderEntry.KEY_REPEAT);
int repeatNoColumnIndex = cursor.getColumnIndex(AlarmReminderContract.AlarmReminderEntry.KEY_REPEAT_NO);
int repeatTypeColumnIndex = cursor.getColumnIndex(AlarmReminderContract.AlarmReminderEntry.KEY_REPEAT_TYPE);
int activeColumnIndex = cursor.getColumnIndex(AlarmReminderContract.AlarmReminderEntry.KEY_ACTIVE);
String title = cursor.getString(titleColumnIndex);
String date = cursor.getString(dateColumnIndex);
String time = cursor.getString(timeColumnIndex);
String repeat = cursor.getString(repeatColumnIndex);
String repeatNo = cursor.getString(repeatNoColumnIndex);
String repeatType = cursor.getString(repeatTypeColumnIndex);
String active = cursor.getString(activeColumnIndex);
String dateTime = date + " " + time;
setReminderTitle(title);
setReminderDateTime(dateTime);
setReminderRepeatInfo(repeat, repeatNo, repeatType);
setActiveImage(active);
}
// Set reminder title view
public void setReminderTitle(String title) {
mTitleText.setText(title);
String letter = "A";
if(title != null && !title.isEmpty()) {
letter = title.substring(0, 1);
}
int color = mColorGenerator.getRandomColor();
// Create a circular icon consisting of a random background colour and first letter of title
mDrawableBuilder = TextDrawable.builder()
.buildRound(letter, color);
mThumbnailImage.setImageDrawable(mDrawableBuilder);
}
// Set date and time views
public void setReminderDateTime(String datetime) {
mDateAndTimeText.setText(datetime);
}
// Set repeat views
public void setReminderRepeatInfo(String repeat, String repeatNo, String repeatType) {
if(repeat.equals("true")){
mRepeatInfoText.setText("Every " + repeatNo + " " + repeatType + "(s)");
}else if (repeat.equals("false")) {
mRepeatInfoText.setText("Repeat Off");
}
}
// Set active image as on or off
public void setActiveImage(String active){
if(active.equals("true")){
mActiveImage.setImageResource(R.drawable.ic_notifications_on_white_24dp);
}else if (active.equals("false")) {
mActiveImage.setImageResource(R.drawable.ic_notifications_off_grey600_24dp);
}
}
}
| [
"ngovporchhay@gmail.com"
] | ngovporchhay@gmail.com |
a369e1ec849dba1fac2f5a1054d4cbeafcbaa8b3 | bb8b3a208cccee3aea07d9cc94af36f25ba17548 | /DerivadorUniandes/coreModule/src/test/java/uniandes/fabricasw/ecotouring/IntegrationTest.java | c2c60030e7a0874b06089caa6ea5fc2d621f07ea | [] | no_license | MISO4204-201620/EcoTouring | ed7ade5fbb3fccba0e98641d375ee08d32efb7d5 | 43a70a3faa19916b1dd805a1cec6341da627cfef | refs/heads/master | 2021-01-17T04:40:36.327971 | 2016-05-28T17:23:07 | 2016-05-28T17:23:07 | 50,695,532 | 0 | 1 | null | 2016-02-01T01:00:56 | 2016-01-29T22:27:18 | null | UTF-8 | Java | false | false | 2,491 | java | package uniandes.fabricasw.ecotouring;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import com.google.common.base.Optional;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.ResourceHelpers;
import io.dropwizard.testing.junit.DropwizardAppRule;
import uniandes.fabricasw.ecotouring.api.Saying;
public class IntegrationTest {
private static final String TMP_FILE = createTempFile();
private static final String CONFIG_PATH = ResourceHelpers.resourceFilePath("test-example.yml");
@ClassRule
public static final DropwizardAppRule<EcoTouringConfiguration> RULE = new DropwizardAppRule<>(
EcoTouringApplication.class, CONFIG_PATH,
ConfigOverride.config("database.url", "jdbc:oracle:thin:admin/fabricasw@//54.174.139.165:1521/XE"));
private Client client;
@BeforeClass
public static void migrateDb() throws Exception {
RULE.getApplication().run("db", "migrate", CONFIG_PATH);
}
@Before
public void setUp() throws Exception {
client = ClientBuilder.newClient();
}
@After
public void tearDown() throws Exception {
client.close();
}
private static String createTempFile() {
try {
return File.createTempFile("test-example", null).getAbsolutePath();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Test
public void testHelloWorld() throws Exception {
final Optional<String> name = Optional.fromNullable("DrIntegrationTest");
final Saying saying = client.target("http://localhost:" + RULE.getLocalPort() + "/hello-world")
.queryParam("name", name.get()).request().get(Saying.class);
assertThat(saying.getContent()).isEqualTo(RULE.getConfiguration().buildTemplate().render(name));
}
/*
* @Test public void testPostPerson() throws Exception { final Person person
* = new Person("DrIntegrationTest", "ChiefWizard"); final Person newPerson
* = client.target("http://localhost:" + RULE.getLocalPort() +
* "/people").request() .post(Entity.entity(person,
* MediaType.APPLICATION_JSON_TYPE)).readEntity(Person.class);
* assertThat(newPerson.getId()).isNotNull();
* assertThat(newPerson.getFullName()).isEqualTo(person.getFullName());
* assertThat(newPerson.getJobTitle()).isEqualTo(person.getJobTitle()); }
*/
}
| [
"a.troncoso10@uniandes.edu.co"
] | a.troncoso10@uniandes.edu.co |
e3c2adf3d77b2e3830570e3e60a3084e3a4976cf | 1f8a0012e7a097e9131a2399410c3fa94e54c141 | /FindMedium.java | 62d5f2a175f9af66bf10f7c47ba9516032917893 | [] | no_license | rameshkum/algorithms | 71a66ea68a43baeef213fd23c41704b7157ebf9c | 6f3cb43f630060c65a2c414db56f55f1477205a7 | refs/heads/master | 2021-05-15T05:05:33.676150 | 2017-09-22T11:56:46 | 2017-09-22T11:56:46 | 103,667,541 | 0 | 0 | null | 2017-09-15T14:39:22 | 2017-09-15T14:39:22 | null | UTF-8 | Java | false | false | 556 | java | package hr.grubic.algorithms;
/**
* Given a linked list, find middle element with only one iteration
*
*/
public class FindMedium {
private static class ListNode {
int data;
ListNode next;
public ListNode(int data) {
this.data = data;
this.next = null;
}
}
public static ListNode findMiddle(ListNode head) {
if (head == null) return null;
ListNode mid = head;
int i = 0;
while (head.next != null) {
head = head.next;
i++;
if (i%2==0) {
mid = mid.next;
}
}
return mid;
}
}
| [
"maja"
] | maja |
842344169a20316ea08c6ab1fb51c6b3bc4fb6f5 | ba4fc05046398119ee2082ad1894b7f2223c2ca9 | /src/main/java/com/leetcode/math/_7.java | d7e32f55f8bb56a73e951179f3abbd1b7035db25 | [] | no_license | 1995hzczjut/leetcode | a35fbcdff1afef7c13bda0bb756616a3b5ce3a46 | afebe86760ec5e6c7cde017cd416b6f100cce58e | refs/heads/master | 2023-02-04T17:00:20.005825 | 2020-12-22T19:57:24 | 2020-12-22T19:57:24 | 323,720,057 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 476 | java | package com.leetcode.math;
/**
* @author Zhancong Huang
* @date 20:59 2019/1/7
*/
public class _7 {
/**
* 遍历一个int,只能/10 %10 从个位数迭代
*/
public int reverse(int x) {
long result = 0;
while (x != 0) {
result = result * 10 + x % 10;
x /= 10;
}
if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
return 0;
}
return (int)result;
}
}
| [
"zhancong@sf-smail.com"
] | zhancong@sf-smail.com |
29d272584d6283ac287929c11572fe19a3210a33 | 564dc3efb78c7f01f3548723a08de4a0ab14d513 | /LC315-01.java | cc0ae2db3c4da463700e8e6f81022fd19cafcdfd | [] | no_license | kellyli02111/leetcode | d9037f26d623c98a785886a1a1a5b1632d6d3b18 | 16bba905fcc1f35452b70bb65c37446edae86cc5 | refs/heads/master | 2020-04-01T00:34:05.702258 | 2019-03-28T06:53:14 | 2019-03-28T06:53:14 | 152,702,528 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 601 | java | // O(n^2)
class Solution {
public List<Integer> countSmaller(int[] nums) {
List<Integer> result = new ArrayList<Integer>();
if (nums == null || nums.length == 0) {
return result;
}
for (int index = 0; index < nums.length; index++) {
int compare = index + 1;
int count = 0;
while (compare < nums.length) {
if (nums[index] > nums[compare]) {
count++;
}
compare++;
}
result.add(count);
}
return result;
}
}
| [
"noreply@github.com"
] | kellyli02111.noreply@github.com |
6b106ab19e2382e7f705d14e3e2a8102e710b6fa | b825fe43a018a02e8885000bacbc2777ed44da92 | /src/main/java/edu/snu/tempest/operator/window/timescale/impl/PartialAggregatorOutputEmitter.java | e161dee4d05c35909d74492394dcd4166d361e92 | [] | no_license | taegeonum/tempest | a7881defac463c879f8a8284b94bbc9e36dab563 | a46aae46462a15eb144e5916ca3b1e9427dc639a | refs/heads/master | 2022-12-25T22:50:43.697778 | 2017-09-01T05:50:57 | 2017-09-01T05:50:57 | 303,347,063 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,271 | java | /*
* Copyright (C) 2015 Seoul National University
*
* 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 edu.snu.tempest.operator.window.timescale.impl;
import edu.snu.tempest.operator.OutputEmitter;
import javax.inject.Inject;
/**
* This class saves partial output into computation reuser
* and triggers overlapping window operators in order to do final aggregation.
* @param <V> partial output
*/
final class PartialAggregatorOutputEmitter<V> implements OutputEmitter<PartialTimeWindowOutput<V>> {
/**
* Computation reuser whichc saves partial/final results
* in order to do computation reuse between multiple timescales.
*/
private final SpanTracker<V> spanTracker;
/**
* Overlapping window stage executing overlapping window operators.
*/
private final FinalAggregatorManager<V> owoStage;
/**
* SlicedWindowOperatorOutputEmitter.
* @param spanTracker a computation reuser
* @param owoStage an overlapping window stage
*/
@Inject
private PartialAggregatorOutputEmitter(final SpanTracker<V> spanTracker,
final FinalAggregatorManager<V> owoStage) {
this.spanTracker = spanTracker;
this.owoStage = owoStage;
}
/**
* Save partial output into computation reuser
* and trigger overlapping window operators.
* @param output a partial output
*/
@Override
public void emit(final PartialTimeWindowOutput<V> output) {
// save partial result into computation reuser
spanTracker.savePartialOutput(output.windowStartTime, output.windowEndTime, output.output);
// trigger overlapping window operators for final aggregation
owoStage.onNext(output.windowEndTime);
}
@Override
public void close() throws Exception {
}
} | [
"taegeonum@gmail.com"
] | taegeonum@gmail.com |
458ae0f745ae928a887aeee1d2cda537dfbd6fcf | 8ad08374d57bd2b779b841078cfd50e4d82f3c0a | /core/src/main/java/be/cegeka/configurator/Main.java | c87824e84d505a42291638c17d8ef26204dc62f5 | [] | no_license | dwendelen/configurator | b38a871392ff44ec60109e22d5a83da01bbcf625 | 0f873c589bb33530a7d196dd6f43fb5fd50cc7da | refs/heads/master | 2020-05-19T14:15:40.669833 | 2015-04-20T19:59:46 | 2015-04-20T19:59:46 | 34,142,643 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,480 | java | package be.cegeka.configurator;
import be.cegeka.configurator.message.MessageSender;
import be.cegeka.configurator.message.MessageSenderFactory;
import be.cegeka.configurator.messageProcessor.MessageProcessor;
import be.cegeka.configurator.messageProcessor.MessageProcessorFactory;
import be.cegeka.configurator.serverRegistery.impl.ServerFactory;
import be.cegeka.configurator.serverRegistery.ServerRegistery;
import be.cegeka.configurator.serverRegistery.ServerRegisteryFactory;
import be.cegeka.configurator.socket.Socket;
import be.cegeka.configurator.socket.SocketFactory;
import org.codehaus.jackson.map.ObjectMapper;
public class Main {
public static void main(String [] args) throws Exception
{
SocketFactory socketFactory = new SocketFactory();
ObjectMapper objectMapper = new ObjectMapper();
MessageSenderFactory messageSenderFactory = new MessageSenderFactory(objectMapper);
MessageProcessorFactory messageProcessorFactory = new MessageProcessorFactory(socketFactory, objectMapper);
ServerRegisteryFactory serverRegisteryFactory = new ServerRegisteryFactory(messageSenderFactory, socketFactory, objectMapper);
MessageProcessor messageProcessor = messageProcessorFactory.create();
messageProcessor.start();
ServerRegistery serverRegistery = serverRegisteryFactory.create(messageProcessor);
serverRegistery.start();
System.in.read();
messageProcessor.stop();
}
}
| [
"daanwendelen@gmail.com"
] | daanwendelen@gmail.com |
01b64f8bca1d846073c77fa5b3bcea99f1b847a8 | 32e1ee5fe940293bbaa7cea09f537a943bc5f2a5 | /Lab_4/app/src/androidTest/java/com/saifniaz/lab_4/ExampleInstrumentedTest.java | 221da568ade81c27d779ee27440504cdc2922958 | [] | no_license | saifniaz/CSCI_4100U | dde7d526784efc073b59d1e3fa1fb1abf367271f | 754362f196ee36e365bcc5cb3192162887cceff8 | refs/heads/master | 2021-09-12T14:39:33.619673 | 2018-04-17T17:23:06 | 2018-04-17T17:23:06 | 103,992,688 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 740 | java | package com.saifniaz.lab_4;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.saifniaz.lab_4", appContext.getPackageName());
}
}
| [
"saifniaz.3@gmail.com"
] | saifniaz.3@gmail.com |
706d34eea81c78c807f144d0f2166ae719a6974e | 4cdcc67d8077901fa5c64d48968e0cf40620f891 | /src/main/java/au/com/nbtech/microservice/accountsapi/domain/dto/Account.java | 99043fba198c4b5af2d8c0f959ffd025afdeae8b | [] | no_license | nerryb/accountdetails | 1e89aa2d0b862f8e9492536a2e8cf6663e4b35a1 | fb77bdb4fde9c1b31f017528c3494121b70811c6 | refs/heads/master | 2020-04-14T16:41:15.840738 | 2019-01-03T10:34:40 | 2019-01-03T10:34:40 | 163,958,068 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 527 | java | package au.com.nbtech.microservice.accountsapi.domain.dto;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import java.math.BigDecimal;
import java.time.LocalDate;
@Builder
@Getter
@Setter
public class Account {
@NonNull
private Long accountNumber;
private String accountType;
private String accountName;
private LocalDate balanceDate;
private String currencyCode;
@NonNull
private BigDecimal availableBalance;
private String customerNumber;
}
| [
"niravbarot@gmail.com"
] | niravbarot@gmail.com |
e4a98d594ed2a343eb02369114af9037bee15dac | 2c5e6c066297c7d394ec036c4912eaac52d3b144 | /mvvmfx/src/test/java/de/saxsys/mvvmfx/scopes/example2/views/ScopedViewModelA.java | 9f1b52f7c614ac0c45d88314f16eba995ae0463f | [
"Apache-2.0"
] | permissive | sialcasa/mvvmFX | 49bacf5cb32657b09a0ccf4cacb0d1c4708c4407 | f195849ca98020ad74056991f147a05db9ce555a | refs/heads/develop | 2023-08-30T00:43:20.250600 | 2019-10-21T14:30:56 | 2019-10-21T14:30:56 | 12,903,179 | 512 | 160 | Apache-2.0 | 2022-06-24T02:09:43 | 2013-09-17T18:16:16 | Java | UTF-8 | Java | false | false | 140 | java | package de.saxsys.mvvmfx.scopes.example2.views;
import de.saxsys.mvvmfx.ViewModel;
public class ScopedViewModelA implements ViewModel {
}
| [
"manuel.mauky@saxsys.de"
] | manuel.mauky@saxsys.de |
7fa4293c002070291633ad78de2dbf352fa8570c | 68237b1bbcd08b1792a8d3137bd20fb3f3c808a1 | /app/src/main/java/com/example/motorshop/dialog/LuaChonThemPhuTungDialog.java | 594d39ad589687ade70b816924929feec1cd1cef | [] | no_license | conghau99/AndroidCarProductManager | a2ce50b81fbb60b23b1aba352ebb0c4b939c8090 | ce77ac594ff444e8f5ceea38422363b12e863fc0 | refs/heads/master | 2023-05-04T21:33:04.344869 | 2021-05-13T09:18:43 | 2021-05-13T09:18:43 | 364,229,519 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,355 | java | package com.example.motorshop.dialog;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.example.motorshop.QuanLyPhuTungActivity;
import com.example.motorshop.QuanLyXeActivity;
import com.example.motorshop.R;
public class LuaChonThemPhuTungDialog extends Dialog {
QuanLyPhuTungActivity quanLyPhuTungActivity;
public LuaChonThemPhuTungDialog(@NonNull Context context) {
super(context);
this.quanLyPhuTungActivity = (QuanLyPhuTungActivity) context;
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dg_nua_chon_them);
TextView tvThemPhuTung = findViewById(R.id.tvThemPhuTung);
TextView tvThemXe = findViewById(R.id.tvThemXe);
tvThemXe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
quanLyPhuTungActivity.chuyenDenManThemXe();
dismiss();
}
});
tvThemPhuTung.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
quanLyPhuTungActivity.chuyenDenManThemPhuTung();
dismiss();
}
});
}
}
| [
"cchvip.1999@gmail.com"
] | cchvip.1999@gmail.com |
f3a21ed4a0d85c48588d4f38dc294580414446e1 | eef5c9446fa6e8e7d6c1cb773786ea895d06db0c | /Wipro PRP Day2/src/Day2/Program8.java | 7d4c3e59298b45b16329e9d4fce26dd5ec26b582 | [] | no_license | 9873004/18P504 | d1277a6992dbe98d56b693bd71e0cd75c373d1f6 | 2db8511cf10f55eb00b2a4e263d4d03a94622e35 | refs/heads/master | 2022-11-16T00:05:13.301308 | 2020-07-04T16:30:51 | 2020-07-04T16:30:51 | 274,147,004 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 619 | java | package Day2;
import java.util.Scanner;
public class Program8 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
char ch=s.next().charAt(0);
s.close();
switch(ch)
{
case 'R':System.out.println("Red");break;
case 'B':System.out.println("Blue");break;
case 'G':System.out.println("Green");break;
case 'O':System.out.println("Orange");break;
case 'Y':System.out.println("Yellow");break;
case 'W':System.out.println("White");break;
default:System.out.println("Invalid Code");
}
}
} | [
"noreply@github.com"
] | 9873004.noreply@github.com |
309202d425daf1d72dc02be084915db83cca72fe | 0ea271177f5c42920ac53cd7f01f053dba5c14e4 | /5.3.5/sources/org/telegram/messenger/MediaController$21.java | dff3c2f36cd9c215f1a095dddc786eb29424b0c5 | [] | no_license | alireza-ebrahimi/telegram-talaeii | 367a81a77f9bc447e729b2ca339f9512a4c2860e | 68a67e6f104ab8a0888e63c605e8bbad12c4a20e | refs/heads/master | 2020-03-21T13:44:29.008002 | 2018-12-09T10:30:29 | 2018-12-09T10:30:29 | 138,622,926 | 12 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,120 | java | package org.telegram.messenger;
class MediaController$21 implements Runnable {
final /* synthetic */ MediaController this$0;
MediaController$21(MediaController this$0) {
this.this$0 = this$0;
}
public void run() {
try {
if (!(MediaController.access$6500(this.this$0) == null || MediaController.access$6500(this.this$0).audioProgress == 0.0f)) {
MediaController.access$3102(this.this$0, (long) (((float) MediaController.access$3200(this.this$0)) * MediaController.access$6500(this.this$0).audioProgress));
MediaController.access$5100(this.this$0, MediaController.access$6500(this.this$0).audioProgress);
}
} catch (Exception e) {
FileLog.e(e);
}
synchronized (MediaController.access$3800(this.this$0)) {
MediaController.access$3900(this.this$0).addAll(MediaController.access$4000(this.this$0));
MediaController.access$4000(this.this$0).clear();
}
MediaController.access$3602(this.this$0, false);
MediaController.access$3700(this.this$0);
}
}
| [
"alireza.ebrahimi2006@gmail.com"
] | alireza.ebrahimi2006@gmail.com |
25eaf921132138bbda5f9e864d1dd16f622b731f | 24b63edfbbc1d2832eca9f72079846c0b190ab95 | /src/main/java/cl/uchile/dcc/scrabble/dataTypes/scrabbleBinary.java | eda1448e74bf6bd800d58fd84999b631287e58c6 | [
"CC-BY-4.0"
] | permissive | VicenteVidela/scrabble | 56eadda9ceba8378329b12671e38e07b51948732 | 819a75f0cbb84d5ae2af925c5d2dc8f844b64f60 | refs/heads/main | 2023-06-27T18:17:26.604452 | 2021-08-01T05:00:24 | 2021-08-01T05:00:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,401 | java | package cl.uchile.dcc.scrabble.dataTypes;
import static java.lang.Math.max;
/**
* The Scrabble Binary class. It encapsulates a native Java String
* that has the value of the instance, composed of only 0s and 1s
*/
public class scrabbleBinary extends AbstractNumber implements SLogic{
private String value;
/**
* The constructor of the class
* @param str The value that will be assigned to the instance
*/
public scrabbleBinary(String str) {
this.value = str;
super.value = this.value;
}
/**
* @return the value of the instance
*/
public String getValue() {
return value;
}
/**
* @param value The new value that the instance will have
*/
protected void setValue(String value) {
this.value = value;
super.value = this.value;
}
/**
* {@inheritDoc}
* @param obj the object to be compared with
* @return wether the values are the same
*/
@Override
public boolean equals(Object obj){
if (obj.getClass() == this.getClass()){
var o = (scrabbleBinary) obj;
String s1 = o.value;
String s2 = this.value;
while (s1.length() > 1 && ((s1.charAt(0)=='0' && s1.charAt(1)=='0') || (s1.charAt(0)=='1' && s1.charAt(1)=='1'))){
s1 = s1.substring(1);
}
while (s2.length() > 1 && ((s2.charAt(0)=='0' && s2.charAt(1)=='0') || (s2.charAt(0)=='1' && s2.charAt(1)=='1'))){
s2 = s2.substring(1);
}
return s1.equals(s2);
}
return false;
}
/**
* {@inheritDoc}
* @return the transformed instance
*/
@Override
public scrabbleString toScrabString() {
return TypeFactory.createSString(value);
}
/**
* {@inheritDoc}
* @return the transformed instance
*/
@Override
public scrabbleInt toScrabInt(){
if (bitToInt(value.charAt(0)) == 0){
return TypeFactory.createSInt(positiveBinToInt(value));
} else {
return TypeFactory.createSInt(negativeBinaryToInt(value));
}
}
/**
* {@inheritDoc}
* @return the transformed instance
*/
@Override
public scrabbleFloat toScrabFloat(){
if (bitToInt(value.charAt(0)) == 0){
return TypeFactory.createSFloat(positiveBinToInt(value));
} else {
return TypeFactory.createSFloat(negativeBinaryToInt(value));
}
}
/**
* Transforms a negative binary to an int
* @param binary the binary to be transformed
* @return the int
*/
private int negativeBinaryToInt(String binary){
int n = binary.length() - 1;
int w = -bitToInt(binary.charAt(0)) * (int) Math.pow(2, n);
for (int i=n, j=0; i>0; i--, j++){
w += (int) Math.pow(2,j) * (binary.charAt(i) == '1' ? 1: 0);
}
return w;
}
/**
* Transforms a positive binary to an int
* @param binary the binary to be transformed
* @return the int
*/
private int positiveBinToInt(String binary){
int w = 0;
for (int i=binary.length()-1, j=0; i>0; i--, j++){
w += (int) Math.pow(2,j) * bitToInt(binary.charAt(i));
}
return w;
}
/**
* Transforms a char bit into an int
* @param bit the bit to be transformed
* @return the int
*/
private int bitToInt(char bit){
return bit == '0' ? 0 : 1;
}
/**
* Calculates the two's complement of a binary
* @return the complement
*/
public scrabbleBinary twosComplement(){
scrabbleBinary negated = this.negation();
int length = negated.getValue().length();
char newArr[] = new char[length];
int summed = 0;
for (int i=length-1; i>=0; i--){
char n = negated.getValue().charAt(i);
if (summed == 0) {
if (n == '1') newArr[i] = '0';
else {
newArr[i] = '1';
summed = 1;
}
}
else {
newArr[i] = n;
}
}
return TypeFactory.createSBinary(String.valueOf(newArr));
}
/**
* {@inheritDoc}
* @return the transformed instance
*/
@Override
public scrabbleBinary toScrabBinary() {
return this;
}
/**
* {@inheritDoc}
* @param l the value with which the conjunction will be made
* @return the result
*/
@Override
public SLogic conj(SLogic l) {
return l.conjBinary(this);
}
/**
* {@inheritDoc}
* @param l the value with which the disjunction will be made
* @return the result
*/
@Override
public SLogic disj(SLogic l) {
return l.disjBinary(this);
}
/**
* {@inheritDoc}
* @param bin the value with which the conjunction will be made
* @return the result
*/
@Override
public scrabbleBinary conjBinary(scrabbleBinary bin) {
String value1 = this.getValue();
String value2 = bin.getValue();
int largo1 = value1.length();
int largo2 = value2.length();
int largo = max(largo1, largo2);
while (value1.length() < largo){
value1 = '0' + value1;
}
while (value2.length() < largo){
value2 = '0' + value2;
}
char arr[] = new char[largo];
for (int i=0; i<largo; i++){
arr[i] = (value1.charAt(i) == '1' && value2.charAt(i) == '1') ? '1' : '0';
}
String s = String.valueOf(arr);
return TypeFactory.createSBinary(s);
}
/**
* {@inheritDoc}
* @param bin the value with which the disjunction will be made
* @return the result
*/
@Override
public scrabbleBinary disjBinary(scrabbleBinary bin) {
String value1 = this.getValue();
String value2 = bin.getValue();
int largo1 = value1.length();
int largo2 = value2.length();
int largo = max(largo1, largo2);
while (value1.length() < largo){
value1 = '0' + value1;
}
while (value2.length() < largo){
value2 = '0' + value2;
}
char arr[] = new char[largo];
for (int i=0; i<largo; i++){
arr[i] = (value1.charAt(i) == '1' || value2.charAt(i) == '1') ? '1' : '0';
}
String s = String.valueOf(arr);
return TypeFactory.createSBinary(s);
}
/**
* {@inheritDoc}
* @return the new value
*/
@Override
public scrabbleBinary negation(){
int length = this.value.length();
char newArr[] = new char[length];
for (int i=0; i<length; i++) {
char n = this.value.charAt(i);
if (n == '1') newArr[i] = '0';
else newArr[i] = '1';
}
return TypeFactory.createSBinary(String.valueOf(newArr));
}
/**
* {@inheritDoc}
* @param bool the value with which the conjunction will be made
* @return the result
*/
@Override
public scrabbleBinary conjBool(scrabbleBool bool){
if (bool.getValue()) {
return TypeFactory.createSBinary(this.value);
}
int length = this.value.length();
char newArr[] = new char[length];
for (int i=0; i<length; i++) {
newArr[i] = '0';
}
return TypeFactory.createSBinary(String.valueOf(newArr));
}
/**
* {@inheritDoc}
* @param bool the value with which the disjunction will be made
* @return the result
*/
@Override
public scrabbleBinary disjBool(scrabbleBool bool){
if (!bool.getValue()) {
return TypeFactory.createSBinary(this.value);
}
int length = this.value.length();
char newArr[] = new char[length];
for (int i=0; i<length; i++) {
newArr[i] = '1';
}
return TypeFactory.createSBinary(String.valueOf(newArr));
}
/**
* {@inheritDoc}
* @param n the number to be summed
* @return the result
*/
@Override
public SNumber sum(SNumber n) {
return n.sumByBinary(this);
}
/**
* {@inheritDoc}
* @param n the number to be subtracted
* @return the result
*/
@Override
public SNumber subs(SNumber n) {
return n.subsByBinary(this);
}
/**
* {@inheritDoc}
* @param n the number to be multiplied
* @return the result
*/
@Override
public SNumber mult(SNumber n) {
return n.multByBinary(this);
}
/**
* {@inheritDoc}
* @param n the number to be divided
* @return the result
*/
@Override
public SNumber div(SNumber n) {
return n.divByBinary(this);
}
/**
* {@inheritDoc}
* @param n the number that's summing this
* @return the result
*/
@Override
public scrabbleInt sumByInt(scrabbleInt n) {
return TypeFactory.createSInt(n.getValue() + this.toScrabInt().getValue());
}
/**
* {@inheritDoc}
* @param n the number that's subtracting this
* @return the result
*/
@Override
public scrabbleInt subsByInt(scrabbleInt n) {
return TypeFactory.createSInt(n.getValue() - this.toScrabInt().getValue());
}
/**
* {@inheritDoc}
* @param n the number that's multiplying this
* @return the result
*/
@Override
public scrabbleInt multByInt(scrabbleInt n) {
return TypeFactory.createSInt(n.getValue() * this.toScrabInt().getValue());
}
/**
* {@inheritDoc}
* @param n the number that's dividing this
* @return the result
*/
@Override
public scrabbleInt divByInt(scrabbleInt n) {
return TypeFactory.createSInt(n.getValue() / this.toScrabInt().getValue());
}
/**
* {@inheritDoc}
* @return the negated value
*/
@Override
public IdataTypes negate(){
return this.negation();
}
/**
* It calls the double dispatch function ddConj of eval, so that it doesn't have
* to know the type of the instance that will be evaluated with this.
* @param eval the value that will be evaluated with this
* @return the conjunction of the values, or null if instance is not operable
*/
@Override
public IdataTypes conjunction(IdataTypes eval) {
return eval.ddConj(this);
}
/**
* {@inheritDoc}
* @param logic the value that will be evaluated with this
* @return the conjunction
*/
@Override
public IdataTypes ddConj(SLogic logic) {
return logic.conj(this);
}
/**
* It calls the double dispatch function ddDisj of eval, so that it doesn't have
* to know the type of the instance that will be evaluated with this.
* @param eval the value that will be evaluated with this
* @return the disjunction of the values, or null if instance is not operable
*/
@Override
public IdataTypes disjunction(IdataTypes eval) {
return eval.ddDisj(this);
}
/**
* {@inheritDoc}
* @param logic the value that will be evaluated with this
* @return the disjunction
*/
@Override
public IdataTypes ddDisj(SLogic logic) {
return logic.disj(this);
}
}
| [
"vicente.videla@ug.uchile.cl"
] | vicente.videla@ug.uchile.cl |
3407e0d576c4f384f67933bdd424be5256e770e2 | d870a1f824ea47322d251d9814e9c1439cf5f5db | /randomchat/randomchat-server/src/main/java/org/randomchat/server/helper/redis/RedisImBindListener.java | a2d12af597d37cac269de8078c3938af8fcbde3d | [
"Apache-2.0"
] | permissive | leoyang0126/RandomChat | 59dde2545c450de87f1d74e99c0d0374d0dd36fb | c1149cce52872fea6dd2fa8248cc64af3964178c | refs/heads/master | 2020-03-21T12:44:04.672653 | 2018-07-31T02:53:49 | 2018-07-31T02:53:49 | 138,569,098 | 9 | 3 | null | null | null | null | UTF-8 | Java | false | false | 2,808 | java | package org.randomchat.server.helper.redis;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.randomchat.common.Const;
import org.randomchat.common.ImConfig;
import org.tio.core.ChannelContext;
import org.randomchat.common.cache.redis.RedisCache;
import org.randomchat.common.cache.redis.RedisCacheManager;
import org.randomchat.common.listener.ImBindListener;
/**
* @author Leo Yang
* @date 2018年4月8日 下午4:12:31
*/
public class RedisImBindListener implements ImBindListener,Const{
private RedisCache groupCache = null;
private RedisCache userCache = null;
private final String SUBFIX = ":";
public RedisImBindListener(){
groupCache = RedisCacheManager.getCache(GROUP);
userCache = RedisCacheManager.getCache(USER);
}
static{
RedisCacheManager.register(USER, Integer.MAX_VALUE, Integer.MAX_VALUE);
RedisCacheManager.register(GROUP, Integer.MAX_VALUE, Integer.MAX_VALUE);
RedisCacheManager.register(STORE, Integer.MAX_VALUE, Integer.MAX_VALUE);
RedisCacheManager.register(PUSH, Integer.MAX_VALUE, Integer.MAX_VALUE);
}
@Override
public void onAfterGroupBind(ChannelContext channelContext, String group) throws Exception {
if(!isStore())
return;
String userid = channelContext.getUserid();
initGroupUsers(group,userid);
}
@Override
public void onAfterGroupUnbind(ChannelContext channelContext, String group) throws Exception {
if(!isStore())
return;
String userid = channelContext.getUserid();
groupCache.listRemove(group, userid);//移除群组成员;
RedisCacheManager.getCache(PUSH).remove(GROUP+SUBFIX+group+SUBFIX+userid);
}
@Override
public void onAfterUserBind(ChannelContext channelContext, String userid) throws Exception {
if(!isStore())
return;
}
@Override
public void onAfterUserUnbind(ChannelContext channelContext, String userid) throws Exception {
if(!isStore())
return;
}
/**
* 初始化群组用户;
* @param group
* @param userid
*/
public void initGroupUsers(String group ,String userid){
if(!isStore())
return;
if(StringUtils.isEmpty(group) || StringUtils.isEmpty(userid))
return;
List<String> users = groupCache.listGetAll(group);
if(!users.contains(userid)){
groupCache.listPushTail(group, userid);
}
initUserGroups(userid, group);
}
/**
* 初始化用户拥有哪些群组;
* @param userid
* @param group
*/
public void initUserGroups(String userid, String group){
if(!isStore())
return;
if(StringUtils.isEmpty(group) || StringUtils.isEmpty(userid))
return;
List<String> groups = userCache.listGetAll(userid+SUBFIX+GROUP);
if(!groups.contains(group)){
userCache.listPushTail(userid+SUBFIX+GROUP, group);
}
}
//是否开启持久化;
public boolean isStore(){
return ON.equals(ImConfig.isStore);
}
}
| [
"yang.liu@xiaoyi.com"
] | yang.liu@xiaoyi.com |
a6301ece083124b7badb3c0145ae6139cd14f659 | 85d3b0efcd20d162fe4bb6f46472205388d81e7d | /src/test/java/dev/sunrise/application/event_time/sunrise_api/SunriseApiResultDTOFixture.java | 444faa892fdcd8472188aeb494c6e9a30ff3f92d | [] | no_license | BoykovOleg/sunrise | b8a005025840ee665ce6072de993b6763443dd33 | fdc03339671f05c5a84f5ab2f4c5503d53220b84 | refs/heads/master | 2020-04-29T02:36:26.232930 | 2019-03-15T08:28:17 | 2019-03-15T08:28:17 | 175,776,316 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 498 | java | package dev.sunrise.application.event_time.sunrise_api;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
public class SunriseApiResultDTOFixture {
public static List<ResultDTO> getFixtures() {
List<ResultDTO> list = new ArrayList<>();
list.add(ResultDTO.createWithResponseResult(new ResponseResult(ZonedDateTime.now(), ZonedDateTime.now())));
list.add(ResultDTO.createWithError("Something went wrong"));
return list;
}
}
| [
"boykovoleg.bov@gmail.com"
] | boykovoleg.bov@gmail.com |
fa889f95d21060bb72fb7c3e6d946caf76266280 | 69fb90420e7b36ac63adc7f4e1e2cb77068cfc47 | /apecmdb/src/main/java/com/apecmdb/apecmdb/controller/GenreController.java | 015888e6953cd725d2556b4ec79a2d35ba7690b6 | [] | no_license | arkmalcom/apecmdb | cc985820c2fc482ef0fe6c0c85fdf39a78434478 | 9cf1f8a958cc37a9d5cd2e2c87e8098716caafd9 | refs/heads/main | 2023-07-05T10:01:54.873318 | 2021-08-11T21:21:33 | 2021-08-11T21:21:33 | 395,119,380 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,560 | java | package com.apecmdb.apecmdb.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import com.apecmdb.apecmdb.model.Genre;
import com.apecmdb.apecmdb.model.GenreRepository;
@Controller
public class GenreController {
@Autowired
private final GenreRepository genreRepository;
@Autowired
public GenreController(GenreRepository genreRepository) {
this.genreRepository = genreRepository;
}
@GetMapping("/admin/genre")
public String showGenre(Genre genre, BindingResult result, Model model) {
model.addAttribute("genres", genreRepository.findAll());
return "/admin/genre/read";
}
@GetMapping("/admin/genre/add")
public String showGenreForm(Genre genre) {
return "admin/genre/add";
}
@PostMapping("admin/genre/save")
public String addGenre(@Valid Genre genre, BindingResult result, Model model) {
if(result.hasErrors()) {
return "/admin/genre/add";
}
genreRepository.save(genre);
model.addAttribute("genres", genreRepository.findAll());
return "redirect:/admin/genre";
}
@GetMapping("admin/genre/update/{id}")
public String showUpdateForm(@PathVariable("id") long id, Model model) {
Genre genre = genreRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid genre Id:" + id));
model.addAttribute("genre", genre);
return "/admin/genre/update";
}
@PostMapping("admin/genre/update/{id}")
public String updateGenre(@PathVariable("id") long id, @Valid Genre genre, BindingResult result, Model model) {
if (result.hasErrors()) {
genre.setId(id);
return "/admin/genre/update";
}
genreRepository.save(genre);
model.addAttribute("genres", genreRepository.findAll());
return "redirect:/admin/genre";
}
@GetMapping("admin/genre/delete/{id}")
public String deleteGenre(@PathVariable("id") long id, Model model) {
Genre genre = genreRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid genre Id:" + id));
genreRepository.delete(genre);
model.addAttribute("genres", genreRepository.findAll());
return "redirect:/admin/genre";
}
}
| [
"arkmalcom@gmail.com"
] | arkmalcom@gmail.com |
5081c46efbda2859d2e1a220ffa9823837190a39 | fc3d1954fc20dc2458bdc00a7aedf37f13a0e736 | /contacts-react/contacts-react-shared/src/main/java/com/contacts/app/AppRestServiceFactory.java | c28781d7861c7b63572d51ebc312d290094b4ebb | [] | no_license | jesse-gallagher/contactstemp | 4fe2352919bf5f5e37fae332edcb2c91827e2c65 | 4dd3724a87830924135c89923829f8786e569783 | refs/heads/master | 2021-04-03T07:00:50.362611 | 2018-03-14T15:28:26 | 2018-03-14T15:28:26 | 125,063,978 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,281 | java | /*!COPYRIGHT HEADER!
*
* (c) Copyright Darwino Inc. 2014-2016.
*
* Licensed under The MIT License (https://opensource.org/licenses/MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.contacts.app;
import java.util.List;
import com.darwino.commons.services.HttpService;
import com.darwino.commons.services.HttpServiceContext;
import com.darwino.commons.services.rest.RestServiceBinder;
import com.darwino.commons.services.rest.RestServiceFactory;
import com.darwino.platform.DarwinoHttpConstants;
import com.contacts.app.services.AppInformationRest;
/**
* Application REST Services Factory.
*
* This is the place where to define custom application services.
*
* @author Philippe Riand
*/
public class AppRestServiceFactory extends RestServiceFactory {
public AppRestServiceFactory() {
super(DarwinoHttpConstants.APPSERVICES_PATH);
}
@Override
protected void createServicesBinders(List<RestServiceBinder> binders) {
/////////////////////////////////////////////////////////////////////////////////
// APP INFORMATION
binders.add(new RestServiceBinder() {
@Override
public HttpService createService(HttpServiceContext context, String[] parts) {
return new AppInformationRest();
}
});
}
}
| [
"jesse@secondfoundation.org"
] | jesse@secondfoundation.org |
7a5c29159a58a5e73abe12f85244d467837fac9b | d2cad5d7b4b3d085eacfa3c927baf4ba2f55f491 | /app/src/main/java/cs321/classcamapp/CustomGrid.java | 517e947448e2c5bccb701b3466b2b83bc7848246 | [] | no_license | FlavioAmurrioCS/ClassCam | 2acb99a594b94d09db55bf05bd0bdff710787ea3 | e114cf7f24c44b8af00be8a4bf989a4598a231cc | refs/heads/master | 2021-01-21T06:25:12.634474 | 2017-05-01T00:20:48 | 2017-05-01T00:20:48 | 88,545,950 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,629 | java | package cs321.classcamapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by Jonathan on 4/22/2017.
*/
public class CustomGrid extends BaseAdapter{
private Context mContext;
private final String[] className;
private final Integer[] imageID;
public CustomGrid(Context c, String[] className, Integer[] imageID){
mContext = c;
this.imageID = imageID;
this.className = className;
}
@Override
public int getCount() {
return imageID.length;
}
@Override
public Object getItem(int i) {
//TODO this method..
return null;
}
@Override
public long getItemId(int i) {
//TODO this method
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(view == null){
grid = new View(mContext);
grid = inflater.inflate(R.layout.custom_grid, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
textView.setTextSize(12);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(className[i]);
imageView.setImageResource(imageID[i]);
} else {
grid = (View)view;
}
return grid;
}
}
| [
"jperry16@masonlive.gmu.edu"
] | jperry16@masonlive.gmu.edu |
5f5b8a95175f2a954cd507fe58f076f5a4c9708e | 5008d87e6321ea89b40a8c21c58715664bb99356 | /24 handson/helloworld.java | a550ba46b4fd3833fe08b70771d655a85ed35dfa | [] | no_license | chandhinikonagalla/exercise-2 | 8a993f0e689a9e5879c277c4ed0fc3404168dd41 | fc1033fd1fd60dde756044cf3d9a304ce34ec97e | refs/heads/master | 2022-12-30T09:20:46.430952 | 2020-10-08T14:07:02 | 2020-10-08T14:07:02 | 290,385,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 190 | java | public class HelloWorldge {
public static void main(String[] args) {
// TODO Auto-generated method stub
String name ="chandhini";
System.out.println("Hello "+name);
}
}
| [
"noreply@github.com"
] | chandhinikonagalla.noreply@github.com |
b39ee963dd9c6a79204ca6a5b7ed12d68a8a9be7 | 2122d24de66635b64ec2b46a7c3f6f664297edc4 | /dp/src/main/java/com/lee/dp/proxy/example6/Order.java | 4bc274601481ac0ce3b255ce2bda4277efd339cd | [] | no_license | yiminyangguang520/Java-Learning | 8cfecc1b226ca905c4ee791300e9b025db40cc6a | 87ec6c09228f8ad3d154c96bd2a9e65c80fc4b25 | refs/heads/master | 2023-01-10T09:56:29.568765 | 2022-08-29T05:56:27 | 2022-08-29T05:56:27 | 92,575,777 | 5 | 1 | null | 2023-01-05T05:21:02 | 2017-05-27T06:16:40 | Java | UTF-8 | Java | false | false | 1,141 | java | package com.lee.dp.proxy.example6;
/**
* 订单对象
*/
public class Order {
/**
* 订单订购的产品名称
*/
private String productName;
/**
* 订单订购的数量
*/
private int orderNum;
/**
* 创建订单的人员
*/
private String orderUser;
/**
* 构造方法,传入构建需要的数据
*
* @param productName 订单订购的产品名称
* @param orderNum 订单订购的数量
* @param orderUser 创建订单的人员
*/
public Order(String productName, int orderNum, String orderUser) {
this.productName = productName;
this.orderNum = orderNum;
this.orderUser = orderUser;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName, String user) {
this.productName = productName;
}
public int getOrderNum() {
return orderNum;
}
public void setOrderNum(int orderNum, String user) {
this.orderNum = orderNum;
}
public String getOrderUser() {
return orderUser;
}
public void setOrderUser(String orderUser, String user) {
this.orderUser = orderUser;
}
}
| [
"litz-a@glodon.com"
] | litz-a@glodon.com |
caabb82637ef19282309235c66fb558fcdd7a793 | 64a57283d422fd17b9cdac0c4528059008002d5c | /Project-new-spring/boost-server-master/boost-server-api/src/main/java/com/qooco/boost/data/mongo/embedded/ConversationEmbedded.java | 036f3f2a6ef33d788cc6deda89ccdfbe32e6ac6d | [
"BSL-1.0"
] | permissive | dolynhan15/Java-spring-boot | b2ff6785b45577a5e16b016d8eeab00cf0dec56b | 3541b6ba1b0e6a2c254f29bf29cf90d7efd1479a | refs/heads/main | 2023-08-13T11:53:57.369574 | 2021-10-19T07:36:42 | 2021-10-19T07:36:42 | 397,813,627 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 378 | java | package com.qooco.boost.data.mongo.embedded;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.bson.types.ObjectId;
import java.util.List;
@Setter
@Getter
@NoArgsConstructor
public class ConversationEmbedded {
private ObjectId id;
private List<UserProfileCvEmbedded> participants;
private UserProfileCvEmbedded createdBy;
}
| [
"dolynhan15@gmail.com"
] | dolynhan15@gmail.com |
fcdb4697138834418985da99b8d0fc7a28cc0062 | 30109d412a9f693af409fef2046692a891a7faa5 | /src/main/java/io/motolola/inMemoryactiveMQ/InMemoryActiveMqApplication.java | 04ccb98257747cc892d955c3ebbe2e2b7f373f0a | [] | no_license | motolola/SpringBoot-InMemory-activeMQ | a021d300589fea1175fb10ca7074ad6973d5dcd5 | f2bc2d67137eaac91274f2afb112129db6153372 | refs/heads/master | 2020-03-27T11:43:26.881310 | 2018-08-28T23:28:20 | 2018-08-28T23:28:20 | 146,504,117 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 340 | java | package io.motolola.inMemoryactiveMQ;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class InMemoryActiveMqApplication {
public static void main(String[] args) {
SpringApplication.run(InMemoryActiveMqApplication.class, args);
}
}
| [
"motolola@icloud.com"
] | motolola@icloud.com |
10a90723545ab9f6ad7b2cf8a5cfe0f11a05b898 | 597b6fac07d6fa7785bd705916e5751b5ee45096 | /game/Start.java | 4a0dbb34a1ca72d18a5ad7d3d5b2e998f90f1603 | [
"MIT"
] | permissive | humaeed/Tic-Tac-Toe | 432d853dc2962a8ce88027e35df04f1f53195577 | 28f0854d2ca355f063a51c45f318de629c685040 | refs/heads/master | 2021-09-13T08:08:47.291364 | 2018-04-27T02:18:44 | 2018-04-27T02:18:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 173 | java | import java.lang.*;
public class Start {
public static void main(String args[]) throws Exception {
TicTacFrame xo = new TicTacFrame();
xo.setVisible(true);
}
} | [
"noreply@github.com"
] | humaeed.noreply@github.com |
deafcd0061a019e9b8f927224c861efa3065ff1f | 40665051fadf3fb75e5a8f655362126c1a2a3af6 | /intuit-Tank/74bf78f210de41af1732ba65eade14540e88d98c/1258/ScriptConverter.java | 8ced32ef5d671c9b6f024a2e66f460be19371f53 | [] | no_license | fermadeiral/StyleErrors | 6f44379207e8490ba618365c54bdfef554fc4fde | d1a6149d9526eb757cf053bc971dbd92b2bfcdf1 | refs/heads/master | 2020-07-15T12:55:10.564494 | 2019-10-24T02:30:45 | 2019-10-24T02:30:45 | 205,546,543 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,043 | java | /**
* Copyright 2011 Intuit Inc. All Rights Reserved
*/
package com.intuit.tank.converter;
/*
* #%L
* JSF Support Beans
* %%
* Copyright (C) 2011 - 2015 Intuit Inc.
* %%
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* #L%
*/
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.intuit.tank.dao.ScriptDao;
import com.intuit.tank.project.Script;
import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;
/**
* ListConverter
*
* @author dangleton
*
*/
@FacesConverter(value = "tsScriptConverter")
public class ScriptConverter implements Converter {
private static final Logger LOG = LogManager.getLogger(ScriptConverter.class);
/**
* @inheritDoc
*/
@Override
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {
try {
DualListModel<Script> model = (DualListModel<Script>) ((PickList) uiComponent).getValue();
for (Script script : model.getSource()) {
if (Integer.toString(script.getId()).equals(value)) {
return script;
}
}
} catch (Exception e) {
// throw new IllegalArgumentException("Passed in value was not a valid date format in the pattern of " +
// PATTERN);
LOG.error("Cannot parse script id value of" + value + ".");
}
return null;
}
/**
* @inheritDoc
*/
@Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object obj) {
return Integer.toString(((Script) obj).getId());
}
}
| [
"fer.madeiral@gmail.com"
] | fer.madeiral@gmail.com |
4e53069928dfb524deb8ce8cf7bb5ba2ec218072 | 8b4495b50af47ef576eb2573a512055a11e7412f | /dnd-supplier-ms/src/main/java/com/capg/dnd/supplier/ms/model/RawMaterialStock.java | 5fe05e221e30eb27bc4dbcf1b986eae4fc229247 | [] | no_license | Praveena21/capg-bvrit-b1-Drink-And-Delight-Inventory-Management_System | a47c0c1c6bba749a09c0464749afaabfa263b1f6 | 5d9e0a5b921016e6c7803ab9ced9d791395b381d | refs/heads/master | 2022-12-11T00:47:07.730034 | 2020-09-07T15:47:00 | 2020-09-07T15:47:00 | 286,462,208 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,405 | java | package com.capg.dnd.supplier.ms.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class RawMaterialStock {
@Id
private String orderId;
private String name;
private double pricePerUnit;
private double quantityValue;
private String quantityUnit;
private double price;
private String warehouseId;
private Date deliveryDate;
private Date manufactuingDate;
private Date expiryDate;
private String qualityCheck;
private Date processDate;
public RawMaterialStock(String orderId, String name, double pricePerUnit, double quantityValue, String quantityUnit,
double price, String warehouseId, Date deliveryDate, Date manufactuingDate, Date expiryDate,
String qualityCheck, Date processDate) {
super();
this.orderId = orderId;
this.name = name;
this.pricePerUnit = pricePerUnit;
this.quantityValue = quantityValue;
this.quantityUnit = quantityUnit;
this.price = price;
this.warehouseId = warehouseId;
this.deliveryDate = deliveryDate;
this.manufactuingDate = manufactuingDate;
this.expiryDate = expiryDate;
this.qualityCheck = qualityCheck;
this.processDate = processDate;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPricePerUnit() {
return pricePerUnit;
}
public void setPricePerUnit(double pricePerUnit) {
this.pricePerUnit = pricePerUnit;
}
public double getQuantityValue() {
return quantityValue;
}
public void setQuantityValue(double quantityValue) {
this.quantityValue = quantityValue;
}
public String getQuantityUnit() {
return quantityUnit;
}
public void setQuantityUnit(String quantityUnit) {
this.quantityUnit = quantityUnit;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getWarehouseId() {
return warehouseId;
}
public void setWarehouseId(String warehouseId) {
this.warehouseId = warehouseId;
}
public Date getDeliveryDate() {
return deliveryDate;
}
public void setDeliveryDate(Date deliveryDate) {
this.deliveryDate = deliveryDate;
}
public Date getManufactuingDate() {
return manufactuingDate;
}
public void setManufactuingDate(Date manufactuingDate) {
this.manufactuingDate = manufactuingDate;
}
public Date getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
public String getQualityCheck() {
return qualityCheck;
}
public void setQualityCheck(String qualityCheck) {
this.qualityCheck = qualityCheck;
}
public Date getProcessDate() {
return processDate;
}
public void setProcessDate(Date processDate) {
this.processDate = processDate;
}
@Override
public String toString() {
return "RawMaterialStock [orderId=" + orderId + ", name=" + name + ", pricePerUnit=" + pricePerUnit
+ ", quantityValue=" + quantityValue + ", quantityUnit=" + quantityUnit + ", price=" + price
+ ", warehouseId=" + warehouseId + ", deliveryDate=" + deliveryDate + ", manufactuingDate="
+ manufactuingDate + ", expiryDate=" + expiryDate + ", qualityCheck=" + qualityCheck + ", processDate="
+ processDate + "]";
}
} | [
"Praveena@DESKTOP-DHU41K7"
] | Praveena@DESKTOP-DHU41K7 |
00299bea4bf5995260cc775eafb2b5e8fcf8628b | e788e12551e83bc5ccea0fb80e7c2ba1eeb4285a | /app/src/main/java/com/example/firearms/PatrolRifleActivity.java | 7f690e277005d98db219eb89393ee0212b89a5cd | [] | no_license | dwester24/Firearms | 5ffb9130052adf008f9f0005507d18f22ecd4cfd | 972d17590bb0d580f51c8e5bb140812754bfe769 | refs/heads/master | 2022-11-23T17:22:27.829409 | 2020-07-15T23:51:44 | 2020-07-15T23:51:44 | 280,007,576 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,297 | java | package com.example.firearms;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import RifleDay.RifleDay10;
import RifleNight.RifleNight10;
public class PatrolRifleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patrol_rifle);
//Initialize Text Views
TextView day = findViewById(R.id.day_text_view);
TextView night = findViewById(R.id.night_text_view);
//Set Day click listener
day.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent patrol_day = new Intent(PatrolRifleActivity.this, RifleDay10.class);
startActivity(patrol_day);
}
});
//Set Night click listener
night.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent patrol_night = new Intent(PatrolRifleActivity.this, RifleNight10.class);
startActivity(patrol_night);
}
});
}
} | [
"dwester@fcsoserver.local"
] | dwester@fcsoserver.local |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.