hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
00130be8b7fba4eaa2982b9070d85c2ae948b361
558
package io.nybbles.progclac.compiler.ast; import io.nybbles.progclac.compiler.lexer.Token; public class BooleanLiteralAstNode implements AstNode { private Boolean _value; private Token _token; public BooleanLiteralAstNode(Boolean value, Token token) { _value = value; _token = token; } @Override public Token getToken() { return _token; } public Boolean getValue() { return _value; } @Override public AstNodeType getType() { return AstNodeType.BooleanLiteral; } }
19.928571
62
0.66129
b5a1aaedc7a13899c7750cb3c1da0b2e50634ca5
3,057
package com.tonybeltramelli.lab.display; import com.tonybeltramelli.lab.Controller; import com.tonybeltramelli.lab.brain.Brain; import com.tonybeltramelli.lab.config.Config; import com.tonybeltramelli.lib.graphics.ImageSprite; import com.tonybeltramelli.lib.graphics.ViewPort; import javafx.scene.image.Image; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; /** * @author Tony Beltramelli www.tonybeltramelli.com - created 01/04/2014 */ public class Display extends ViewPort implements Environment { private Maze _maze; private Organism _organism; private ImageSprite _leftView; private ImageSprite _rightView; private Controller _controller; private Text _progress; public Display(Controller controller, Stage stage) { super(stage, Config.WINDOW_TITLE, Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT + 20); stage.getScene().setFill(Color.DARKGREY); _maze = new Maze(); _spriteContainer.addChild(_maze); _leftView = new ImageSprite(); _rightView = new ImageSprite(); _displaySensorView(_leftView, Config.LEFT_SENSOR, 10, Config.SCREEN_HEIGHT + 12); _displaySensorView(_rightView, Config.RIGHT_SENSOR, 100, Config.SCREEN_HEIGHT + 12); _controller = controller; _progress = new Text(); _setTextStyle(_progress); _progress.setTranslateX(Config.SCREEN_WIDTH / 2); _progress.setTranslateY(Config.SCREEN_HEIGHT + 12); _spriteContainer.addGraphics(_progress); } public void build(Brain brain) { _organism = null; _organism = new Organism(this, brain); _organism.setPosition(Config.START_POSITION_X, Config.START_POSITION_Y); _spriteContainer.addChild(_organism); _engine.add(_organism); } private void _displaySensorView(ImageSprite view, String text, double x, double y) { Text label = new Text(); _setTextStyle(label); label.setText(text); label.setTranslateX(x); label.setTranslateY(y); _spriteContainer.addGraphics(label); view.setPosition(x + label.getLayoutBounds().getWidth() + 10, y - 6); _spriteContainer.addChild(view); } @Override public Image getSurroundingEnvironment(int x, int y, int width, int height) { return _maze.getSquare(x, y, width, height); } @Override public void displayOrganismVision(Image left, Image right) { _leftView.replaceContent(left); _rightView.replaceContent(right); } @Override public void organismHasCollided() { _engine.remove(_organism); _spriteContainer.removeChild(_organism); _controller.saveFitnessScore(_organism.getFitnessScore()); } private void _setTextStyle(Text text) { text.setFont(new Font(10)); text.setFill(Color.BLACK); } public void setProgress(String progress) { _progress.setText(progress); } }
28.839623
92
0.688584
a10ff198be1a6d6c1304e7a9cae730416b5f7719
1,894
package com.ae2dms; import com.ae2dms.model.GameEngines.GameEngine; import javafx.application.Application; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.WindowEvent; /** * This class the start of the program, and extends the {@code Application}. * @program: sokobanFX * @author: Yuting He * @create: 2020-10-31 20:14 */ public class Main extends Application { /** * Primary stage to handle */ public static Stage primaryStage; /** * Root of stages */ public static Parent root; /** * Theme name global */ public static String themeName = "theme-crayon"; /** * Difficulty global */ public static String difficulty = "simple"; /** * launch the game * @param args */ public static void main(String[] args) { launch(args); } /** * This method starts the application, and handle the * contains "new game" "continue" * @param primaryStage * @throws Exception */ @Override public void start(Stage primaryStage) throws Exception{ FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/view/StartPage-layout.fxml")); root = loader.load(); Scene scene = new Scene(root); primaryStage.resizableProperty().set(false); primaryStage.setScene(scene); primaryStage.setTitle("SokobanFX"); primaryStage.show(); Main.primaryStage = primaryStage; primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { System.exit(0); } }); } }
25.253333
83
0.604013
e41b984ed23b492c2702a7dd9cec8958494e7d09
4,689
package org.telegram.ui.Components; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Parcel; import android.text.Layout; import android.text.Spanned; import android.text.style.LeadingMarginSpan; public class BulletSpan implements LeadingMarginSpan { private static final int STANDARD_BULLET_RADIUS = 4; public static final int STANDARD_GAP_WIDTH = 2; private static final int STANDARD_COLOR = 0; private final int mGapWidth; private final int mBulletRadius; private final int mColor; private final boolean mWantColor; /** * Creates a {@link BulletSpan} with the default values. */ public BulletSpan() { this(STANDARD_GAP_WIDTH, STANDARD_COLOR, false, STANDARD_BULLET_RADIUS); } /** * Creates a {@link BulletSpan} based on a gap width * * @param gapWidth the distance, in pixels, between the bullet point and the paragraph. */ public BulletSpan(int gapWidth) { this(gapWidth, STANDARD_COLOR, false, STANDARD_BULLET_RADIUS); } /** * Creates a {@link BulletSpan} based on a gap width and a color integer. * * @param gapWidth the distance, in pixels, between the bullet point and the paragraph. * @param color the bullet point color, as a color integer * @see android.content.res.Resources#getColor(int, Resources.Theme) */ public BulletSpan(int gapWidth, int color) { this(gapWidth, color, true, STANDARD_BULLET_RADIUS); } /** * Creates a {@link BulletSpan} based on a gap width and a color integer. * * @param gapWidth the distance, in pixels, between the bullet point and the paragraph. * @param color the bullet point color, as a color integer. * @param bulletRadius the radius of the bullet point, in pixels. * @see android.content.res.Resources#getColor(int, Resources.Theme) */ public BulletSpan(int gapWidth, int color, int bulletRadius) { this(gapWidth, color, true, bulletRadius); } private BulletSpan(int gapWidth, int color, boolean wantColor, int bulletRadius) { mGapWidth = gapWidth; mBulletRadius = bulletRadius; mColor = color; mWantColor = wantColor; } /** * Creates a {@link BulletSpan} from a parcel. */ public BulletSpan(Parcel src) { mGapWidth = src.readInt(); mWantColor = src.readInt() != 0; mColor = src.readInt(); mBulletRadius = src.readInt(); } @Override public int getLeadingMargin(boolean first) { return 2 * mBulletRadius + mGapWidth; } /** * Get the distance, in pixels, between the bullet point and the paragraph. * * @return the distance, in pixels, between the bullet point and the paragraph. */ public int getGapWidth() { return mGapWidth; } /** * Get the radius, in pixels, of the bullet point. * * @return the radius, in pixels, of the bullet point. */ public int getBulletRadius() { return mBulletRadius; } /** * Get the bullet point color. * * @return the bullet point color */ public int getColor() { return mColor; } @Override public void drawLeadingMargin(Canvas canvas, Paint paint, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) { if (((Spanned) text).getSpanStart(this) == start) { Paint.Style style = paint.getStyle(); int oldcolor = 0; if (mWantColor) { oldcolor = paint.getColor(); paint.setColor(mColor); } paint.setStyle(Paint.Style.FILL); if (layout != null) { // "bottom" position might include extra space as a result of line spacing // configuration. Subtract extra space in order to show bullet in the vertical // center of characters. final int line = layout.getLineForOffset(start); int spacing = line != layout.getLineCount() - 1 ? (int) layout.getSpacingAdd() : 0; bottom = bottom - spacing; } final float yPosition = (top + bottom) / 2f; final float xPosition = x + dir * mBulletRadius; canvas.drawCircle(xPosition, yPosition, mBulletRadius, paint); if (mWantColor) { paint.setColor(oldcolor); } paint.setStyle(style); } } }
31.897959
99
0.607592
c34b7b83b5dfc863cf9b48d49a425dae83eb866f
1,870
package org.gds; import org.gds.command.Command; import java.util.Queue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class BackgroundCommandProcessor { private Queue<Command> commandQueue; private ExecutorService threadExecutor; public BackgroundCommandProcessor(Queue<Command> commandQueue) { this.commandQueue = commandQueue; } public void startCommandProcessor() { System.out.println("Starting the command processor ..."); //Instantiate an anonymous implementation of a Runnable using a lambda Runnable runnable = () -> { // loop forever, there is control logic in the loop to break out while (true) { // if there is no command in the queue, sleep if (commandQueue.peek() == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { // The thread will be interrupted when this Runnable is asked to shutdown System.out.println("This Runnable has been interrupted, breaking out of the loop."); break; } } // there is a command in the queue, execute it! else { Command command = commandQueue.poll(); command.execute(); } } }; // We just need a single background thread here, but using an ExecutorService is a good practice. threadExecutor = Executors.newSingleThreadExecutor(); threadExecutor.submit(runnable); } public void stopCommandProcessor(){ System.out.println("Stopping the command processor ..."); // Shutdown the ExecutorService threadExecutor.shutdownNow(); } }
36.666667
108
0.594118
3f6e5cb881ea25d8876458b72777982605f47f5e
5,913
package cn.abelib.biz.controller.admin; import cn.abelib.st.core.data.redis.RedisStringService; import cn.abelib.st.core.utils.CookieUtil; import cn.abelib.st.core.utils.JsonUtil; import cn.abelib.biz.pojo.Product; import cn.abelib.biz.pojo.User; import cn.abelib.biz.service.UserService; import cn.abelib.biz.service.ProductService; import cn.abelib.st.core.result.Response; import cn.abelib.biz.constant.StatusConstant; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; /** * * @author abel * @date 2017/9/9 */ @RestController @RequestMapping("/admin/product") public class AdminProductController { @Autowired private ProductService productService; @Autowired private UserService userService; @Autowired private RedisStringService redisStringService; /** * 列表 * @param request * @param pageNum * @param pageSize * @return */ @GetMapping("/list.do") public Response listProduct(HttpServletRequest request, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){ String token = CookieUtil.readToken(request); if (StringUtils.isEmpty(token)){ return Response.failed(StatusConstant.USER_NOT_LOGIN); } String userJson = redisStringService.get(token); User user = JsonUtil.str2Obj(userJson, User.class); if (user == null){ return Response.failed(StatusConstant.USER_NOT_LOGIN); } if (userService.checkAdminRole(user).isSuccess()){ return productService.listProduct(pageNum, pageSize); }else { return Response.failed(StatusConstant.NOT_ADMIN_ERROR); } } /** * 查找 * @param request * @param productName * @param productId * @param pageNum * @param pageSize * @return */ @GetMapping("/cn.abelib.st.core.data.search.do") public Response productSearch(HttpServletRequest request, String productName, Integer productId, @RequestParam(value = "pageNum", defaultValue = "10") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "1") Integer pageSize) { String token = CookieUtil.readToken(request); if (StringUtils.isEmpty(token)){ return Response.failed(StatusConstant.USER_NOT_LOGIN); } String userJson = redisStringService.get(token); User user = JsonUtil.str2Obj(userJson, User.class); if (user == null){ return Response.failed(StatusConstant.USER_NOT_LOGIN); } if (userService.checkAdminRole(user).isSuccess()) { return productService.productSearch(productName, productId, pageNum, pageSize); } else { return Response.failed(StatusConstant.NOT_ADMIN_ERROR); } } /** * 保存商品, 需要检查是否是管理员权限 * @param request * @param product * @return */ @PostMapping("/save.do") public Response saveProduct(HttpServletRequest request, Product product){ String token = CookieUtil.readToken(request); if (StringUtils.isEmpty(token)){ return Response.failed(StatusConstant.USER_NOT_LOGIN); } String userJson = redisStringService.get(token); User user = JsonUtil.str2Obj(userJson, User.class); if (user == null){ return Response.failed(StatusConstant.USER_NOT_LOGIN); } if (userService.checkAdminRole(user).isSuccess()){ return productService.saveOrUpdateProduct(product); }else { return Response.failed(StatusConstant.NOT_ADMIN_ERROR); } } /** * 修改商品的销售状态 * @param request * @param productId * @param status * @return */ @PostMapping("/set_status.do") public Response setSaleStatus(HttpServletRequest request, Integer productId, Integer status){ String token = CookieUtil.readToken(request); if (StringUtils.isEmpty(token)){ return Response.failed(StatusConstant.USER_NOT_LOGIN); } String userJson = redisStringService.get(token); User user = JsonUtil.str2Obj(userJson, User.class); if (user == null){ return Response.failed(StatusConstant.USER_NOT_LOGIN); } if (userService.checkAdminRole(user).isSuccess()){ return productService.setSalesStatus(productId, status); }else { return Response.failed(StatusConstant.NOT_ADMIN_ERROR); } } /** * 获取商品详情 * @param request * @param productId * @return */ @PostMapping("/detail.do") public Response getDetail(HttpServletRequest request, Integer productId){ String token = CookieUtil.readToken(request); if (StringUtils.isEmpty(token)){ return Response.failed(StatusConstant.USER_NOT_LOGIN); } String userJson = redisStringService.get(token); User user = JsonUtil.str2Obj(userJson, User.class); if (user == null){ return Response.failed(StatusConstant.USER_NOT_LOGIN); } if (userService.checkAdminRole(user).isSuccess()){ }else { return productService.getProductDetail(productId); } return Response.failed(StatusConstant.NOT_ADMIN_ERROR); } @GetMapping("/delete.do") public Response deleteProduct(Integer id){ return Response.failed(StatusConstant.GENERAL_SUCCESS); } @PostMapping public Response upload(){ return Response.failed(StatusConstant.GENERAL_SUCCESS); } }
33.982759
105
0.644512
5ed48fd1f333d5499768fe07222f2023832d6436
5,287
package com.dtstack.flinkx.es.writer.test; import org.apache.http.HttpHost; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EsDemo { public static void test1() throws Exception { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("study", 9200, "http"), new HttpHost("study", 9201, "http"))); IndexRequest request = new IndexRequest( "nani", "doc"); String jsonString = "{" + "\"user\":\"xxxx\"," + "\"postDate\":\"2013-01-30\"," + "\"message\":\"trying out Elasticsearch\"" + "}"; request.source(jsonString, XContentType.JSON); IndexResponse response = client.index(request); System.out.println(response.getResult()); client.close(); } public static void test3() throws Exception { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("study", 9200, "http"), new HttpHost("study", 9201, "http"))); IndexRequest request = new IndexRequest( "nani", "doc"); // String jsonString = "{" + // "\"user\":\"xxxx\"," + // "\"postDate\":\"2013-01-30\"," + // "\"message\":\"trying out Elasticsearch\"" + // "}"; Map<String,Object> jsonMap = new HashMap<>(); jsonMap.put("xxx", "asfdasdf"); jsonMap.put("zzz", "asdfsadf"); request.source(jsonMap); IndexResponse response = client.index(request); System.out.println(response.getResult()); client.close(); } public static void test2() throws Exception { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http"))); UpdateRequest request = new UpdateRequest( "nani1", "doc", "2"); String jsonString = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2013-01-30\"," + "\"message\":\"trying out Elasticsearch\"" + "}"; request.doc(jsonString, XContentType.JSON); UpdateResponse response = client.update(request); System.out.println(response.getResult()); client.close(); } public static void test4() throws IOException { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("study", 9200, "http"), new HttpHost("study", 9201, "http"))); SearchRequest searchRequest = new SearchRequest(); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchAllQuery()); SearchResponse searchResponse = client.search(searchRequest); System.out.println(searchResponse.getTotalShards()); } public static void test5() throws Exception { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("study", 9200, "http"), new HttpHost("study", 9201, "http"))); BulkRequest bulkRequest = new BulkRequest(); IndexRequest request = new IndexRequest("nani", "doc1"); Map<String,Object> jsonMap = new HashMap<>(); jsonMap.put("xxx", "8888"); jsonMap.put("yyy", "9999"); bulkRequest.add(request.source(jsonMap)); // bulkRequest.setRefreshPolicy(null); // WriteRequest.RefreshPolicy; BulkResponse bulkResponse = client.bulk(bulkRequest); System.out.println(bulkResponse); } public static void test6() throws IOException { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("study", 9200, "http"), new HttpHost("study", 9201, "http"))); SearchRequest searchRequest = new SearchRequest(); SearchResponse resp = client.search(searchRequest); resp.getAggregations(); } public static void main(String[] args) throws Exception { test4(); } }
35.722973
76
0.596368
35b05d2369ce7e95198b4e8addc2f28dc239abaa
1,373
/* * Copyright 2019 Arcus Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.iris.driver.groovy.zigbee; public class MessageDescriptor { private final int id; private final boolean clusterSpecific; private final byte group; public MessageDescriptor(int id, boolean clusterSpecific, String groupName) { this.id = id; this.clusterSpecific = clusterSpecific; this.group = "server".equals(groupName) ? ZigbeeContext.GROUP_SERVER : "client".equals(groupName) ? ZigbeeContext.GROUP_CLIENT : ZigbeeContext.GROUP_GENERAL; } public byte getIdAsByte() { return (byte)id; } public short getIdAsShort() { return (short)id; } public boolean isClusterSpecific() { return clusterSpecific; } public byte getGroup() { return group; } }
28.020408
100
0.696286
1551643f95fcadf0d8088e1e3706ebe5db7d76cd
7,548
package com.werb.pickphotoview; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.animation.DecelerateInterpolator; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.RequestManager; import com.shizhefei.view.largeimage.LargeImageView; import com.shizhefei.view.largeimage.factory.FileBitmapDecoderFactory; import com.werb.pickphotoview.model.PickData; import com.werb.pickphotoview.util.PickConfig; import com.werb.pickphotoview.widget.MyToolbar; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created by wanbo on 2017/1/4. */ public class PickPhotoPreviewActivity extends AppCompatActivity { private List<String> allImagePath; private List<String> selectImagePath; private String path; private ViewPager viewPager; private List<LargeImageView> imageViews; private MyToolbar myToolbar; private boolean mIsHidden,misSelect; private PickData pickData; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pick_activty_preview_photo); pickData = (PickData) getIntent().getSerializableExtra(PickConfig.INTENT_PICK_DATA); path = getIntent().getStringExtra(PickConfig.INTENT_IMG_PATH); allImagePath = (List<String>) getIntent().getSerializableExtra(PickConfig.INTENT_IMG_LIST); selectImagePath = (List<String>) getIntent().getSerializableExtra(PickConfig.INTENT_IMG_LIST_SELECT); imageViews = new ArrayList<>(); if(selectImagePath == null){ selectImagePath = new ArrayList<>(); } for (int i = 0; i < 4; i++) { LargeImageView imageView = new LargeImageView(this); imageView.setEnabled(true); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hideOrShowToolbar(); } }); imageViews.add(imageView); } initView(); Log.d("image size", allImagePath.size() + ""); } private void initView() { Window window = getWindow(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.setStatusBarColor(pickData.getStatusBarColor()); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if(pickData.isLightStatusBar()) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); } } myToolbar = (MyToolbar) findViewById(R.id.toolbar); myToolbar.setBackgroundColor(pickData.getToolbarColor()); myToolbar.setIconColor(pickData.getToolbarIconColor()); myToolbar.setLeftIcon(R.mipmap.pick_ic_back); myToolbar.setLeftLayoutOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finishForResult(); } }); viewPager = (ViewPager) findViewById(R.id.image_vp); int indexOf = allImagePath.indexOf(path); judgeSelect(allImagePath.get(indexOf)); viewPager.setAdapter(new listPageAdapter()); viewPager.setCurrentItem(indexOf); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { String path = allImagePath.get(position); judgeSelect(path); } @Override public void onPageScrollStateChanged(int state) { } }); } //通过ViewPager实现滑动的图片 private class listPageAdapter extends PagerAdapter { @Override public int getCount() { return allImagePath.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, final int position) { int i = position % 4; final LargeImageView pic = imageViews.get(i); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); container.addView(pic,params); String path = allImagePath.get(position); pic.setImage(new FileBitmapDecoderFactory(new File(path))); return pic; } @Override public void destroyItem(ViewGroup container, int position, Object object) { int i = position % 4; final LargeImageView imageView = imageViews.get(i); container.removeView(imageView); } } @Override public void finish() { super.finish(); viewPager = null; overridePendingTransition(0, R.anim.pick_finish_slide_out_left); } //固定 toolbar private void hideOrShowToolbar() { myToolbar.animate() .translationY(mIsHidden ? 0 : -myToolbar.getHeight()) .setInterpolator(new DecelerateInterpolator(2)) .start(); mIsHidden = !mIsHidden; } private void judgeSelect(final String path){ int indexOf = selectImagePath.indexOf(path); if(indexOf != -1){ myToolbar.setRightIconDefault(R.mipmap.pick_ic_select); misSelect = true; }else { myToolbar.setRightIcon(R.mipmap.pick_ic_un_select_black); misSelect = false; } myToolbar.setRightLayoutOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(misSelect){ myToolbar.setRightIcon(R.mipmap.pick_ic_un_select_black); selectImagePath.remove(path); misSelect = false; }else { if(selectImagePath.size() < pickData.getPickPhotoSize()) { myToolbar.setRightIconDefault(R.mipmap.pick_ic_select); selectImagePath.add(path); misSelect = true; }else { Toast.makeText(PickPhotoPreviewActivity.this, String.format(v.getContext().getString(R.string.pick_photo_size_limit), String.valueOf(pickData.getPickPhotoSize())), Toast.LENGTH_SHORT).show(); } } } }); } @Override public void onBackPressed() { finishForResult(); } private void finishForResult(){ Intent intent = new Intent(); intent.setClass(PickPhotoPreviewActivity.this, PickPhotoActivity.class); intent.putExtra(PickConfig.INTENT_IMG_LIST_SELECT, (Serializable) selectImagePath); setResult(PickConfig.PREVIEW_PHOTO_DATA,intent); finish(); } }
35.772512
215
0.640037
0cfb837bc6b799b18f224fb3f7fed55444ed1233
2,315
package org.jboss.summit2015.beacon.bluez; import java.nio.ByteBuffer; /** * Simple wrapper around the ByteBuffer of the beacon event that provides getters similar to the beacon_info struct * in C */ public class BeaconInfo { public String uuid; public boolean isHeartbeat; public int count; public int code; public int manufacturer; public int major; public int minor; public int power; public int calibrated_power; public int rssi; public long time; public int scannerSequenceNo; public BeaconInfo(byte[] rawBuffer) { freeze(ByteBuffer.wrap(rawBuffer)); } public BeaconInfo(ByteBuffer buffer) { freeze(buffer); } /** * Read the underlying buffer into the public fields */ public void freeze(ByteBuffer buffer) { HCIDump.freezeBeaconInfo(this, buffer); } public String getUuid() { return uuid; } public boolean isHeartbeat() { return isHeartbeat; } public int getCount() { return count; } public int getCode() { return code; } public int getManufacturer() { return manufacturer; } public int getMajor() { return major; } public int getMinor() { return minor; } public int getPower() { return power; } public int getCalibrated_power() { return calibrated_power; } public int getRssi() { return rssi; } public long getTime() { return time; } public void setScannerSequenceNo(int scannerSequenceNo) { this.scannerSequenceNo = scannerSequenceNo; } public int getScannerSequenceNo() { return scannerSequenceNo; } @Override public String toString() { return "BeaconInfo{" + "uuid='" + uuid + '\'' + ", isHeartbeat=" + isHeartbeat + ", count=" + count + ", code=" + code + ", manufacturer=" + manufacturer + ", major=" + major + ", minor=" + minor + ", power=" + power + ", calibrated_power=" + calibrated_power + ", rssi=" + rssi + ", time=" + time + ", scannerSequenceNo=" + scannerSequenceNo + '}'; } }
21.635514
115
0.568898
9da455418d7591d2152e9c9b13ac57f6eca6ae38
221
package com.realcomp.mvr; public enum Color{ BEIGE, BLACK, BLUE, BROWN, GOLD, GRAY, GREEN, MAROON, ORANGE, PINK, PURPLE, RED, SILVER, TAN, WHITE, YELLOW }
10.045455
25
0.511312
7e6674ba41d53d9994157179bbc7d5412c7919e6
410
package com.javarush.task.task34.task3410.controller; import com.javarush.task.task34.task3410.model.Direction; /** * @author Sergey Ponomarev on 09.01.2021 * @project JavaRushTasks/com.javarush.task.task34.task3410.controller */ public interface EventListener { public void move(Direction direction); public void restart(); public void startNextLevel(); public void levelCompleted(int level); }
25.625
70
0.77561
b01f20c67feebdf6b15dcbc0879c4545c89bc63c
4,890
package eu.ldob.lpm.be.service; import eu.ldob.lpm.be.converter.MemberConverter; import eu.ldob.lpm.be.converter.ProjectConverter; import eu.ldob.lpm.be.exception.LpmNoResultException; import eu.ldob.lpm.be.model.AssignedProjectModel; import eu.ldob.lpm.be.model.ProjectModel; import eu.ldob.lpm.be.model.UserModel; import eu.ldob.lpm.be.model.type.EProjectRole; import eu.ldob.lpm.be.repository.AssignedProjectRepository; import eu.ldob.lpm.be.repository.ProjectRepository; import eu.ldob.lpm.be.repository.UserRepository; import eu.ldob.lpm.be.request.ProjectRequest; import eu.ldob.lpm.be.response.MemberResponse; import eu.ldob.lpm.be.response.ProjectListResponse; import eu.ldob.lpm.be.response.ProjectResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service @Transactional public class ProjectService { @Autowired ProjectConverter converter; @Autowired MemberConverter memberConverter; @Autowired ProjectRepository projectRepository; @Autowired AssignedProjectRepository assignedProjectRepository; @Autowired UserRepository userRepository; @Autowired ServiceUtil util; public ProjectResponse save(ProjectRequest request, UserModel user) { ProjectModel model = converter.requestToModel(request); if(request.getId() != null) { Optional<ProjectModel> p = projectRepository.findById(request.getId()); if (p.isPresent()) { model.setAssignedUsers(p.get().getAssignedUsers()); model.setTodos(p.get().getTodos()); } } model = projectRepository.save(model); if(model.getAssignedUsers().size() < 1) { model.addAssignedUser(new AssignedProjectModel(model, user, EProjectRole.MANAGE)); } return converter.modelToResponse(model); } public ProjectListResponse findAll(UserModel user) { List<AssignedProjectModel> assignedProjects = assignedProjectRepository.findByUser(user); ProjectListResponse responseList = new ProjectListResponse(); for (AssignedProjectModel model : assignedProjects) { responseList.addProject(model.getRole(), converter.modelToResponse(model.getProject())); } return responseList; } public ProjectResponse findById(Long id, UserModel user) throws LpmNoResultException { ProjectModel model = util.getAllowedProject(id, user); if(model != null) { return converter.modelToResponse(model); } throw new LpmNoResultException("Project " + id + " not found"); } public ProjectResponse findByIdInternal(Long id) throws LpmNoResultException { Optional<ProjectModel> model = projectRepository.findById(id); if(model.isPresent()) { return converter.modelToResponse(model.get()); } throw new LpmNoResultException("Project " + id + " not found"); } public List<MemberResponse> findAllAssignedMembers(Long projectId, List<EProjectRole> roles, UserModel user) { ProjectModel model = util.getAllowedProject(projectId, user); if(model != null) { List<MemberResponse> assignedMembers = new ArrayList<>(); for(AssignedProjectModel m : model.getAssignedUsers()) { if(roles.contains(m.getRole())) { assignedMembers.add(memberConverter.modelToResponse(m.getUser())); } } return assignedMembers; } throw new LpmNoResultException("Project " + projectId + " not found"); } public void addMember(Long projectId, String memberUsername, EProjectRole role, UserModel user) { ProjectModel project = util.getAllowedProject(projectId, user); if(project != null) { Optional<UserModel> member = userRepository.findByUsername(memberUsername); if(member.isEmpty()) { throw new LpmNoResultException("Member " + memberUsername + " not found"); } project.addAssignedUser(new AssignedProjectModel(project, member.get(), role)); } } public void removeMember(Long projectId, String memberUsername, EProjectRole role, UserModel user) { ProjectModel project = util.getAllowedProject(projectId, user); if(project != null) { Optional<UserModel> member = userRepository.findByUsername(memberUsername); if(member.isEmpty()) { throw new LpmNoResultException("Member " + memberUsername + " not found"); } project.removeAssignedUser(new AssignedProjectModel(project, member.get(), role)); } } }
35.693431
114
0.686912
55d91a1ad22d0f859fca23839365b324ff1679a3
2,723
package mb.nabl2.terms.build; import static org.metaborg.util.unit.Unit.unit; import java.util.Objects; import org.immutables.serial.Serial; import org.immutables.value.Value; import com.google.common.collect.ImmutableMultiset; import mb.nabl2.terms.IConsTerm; import mb.nabl2.terms.IListTerm; import mb.nabl2.terms.ITerm; import mb.nabl2.terms.ITermVar; import mb.nabl2.terms.ListTerms; @Value.Immutable @Serial.Version(value = 42L) abstract class ConsTerm extends AbstractTerm implements IConsTerm { @Value.Parameter @Override public abstract ITerm getHead(); @Value.Parameter @Override public abstract IListTerm getTail(); @Value.Lazy @Override public boolean isGround() { return getHead().isGround() && getTail().isGround(); } @Value.Lazy @Override public ImmutableMultiset<ITermVar> getVars() { final ImmutableMultiset.Builder<ITermVar> vars = ImmutableMultiset.builder(); vars.addAll(getHead().getVars()); vars.addAll(getTail().getVars()); return vars.build(); } @Override public <T> T match(ITerm.Cases<T> cases) { return cases.caseList(this); } @Override public <T, E extends Throwable> T matchOrThrow(ITerm.CheckedCases<T, E> cases) throws E { return cases.caseList(this); } @Override public <T> T match(IListTerm.Cases<T> cases) { return cases.caseCons(this); } @Override public <T, E extends Throwable> T matchOrThrow(IListTerm.CheckedCases<T, E> cases) throws E { return cases.caseCons(this); } @Override public int hashCode() { return Objects.hash(getHead(), getTail()); } @Override public boolean equals(Object other) { if(other == null) { return false; } if(!(other instanceof IConsTerm)) { return false; } IConsTerm that = (IConsTerm) other; if(!getHead().equals(that.getHead())) { return false; } if(!getTail().equals(that.getTail())) { return false; } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(getHead()); getTail().match(ListTerms.casesFix( // @formatter:off (f,cons) -> { sb.append(","); sb.append(cons.getHead()); return cons.getTail().match(f); }, (f,nil) -> unit, (f,var) -> { sb.append("|"); sb.append(var); return unit; } // @formatter:on )); sb.append("]"); return sb.toString(); } }
28.072165
107
0.592729
656f2b143654c2df839d53d2708cf60148ef7fe4
3,723
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.test.hwui; import android.app.Activity; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.View; import android.widget.FrameLayout; @SuppressWarnings({"UnusedDeclaration"}) public class ThinPatchesActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FrameLayout layout = new FrameLayout(this); PatchView b = new PatchView(this); b.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); layout.addView(b); layout.setBackgroundColor(0xffffffff); setContentView(layout); } private class PatchView extends View { private Drawable mPatch1, mPatch2, mPatch3; private Bitmap mTexture; public PatchView(Activity activity) { super(activity); final Resources resources = activity.getResources(); mPatch1 = resources.getDrawable(R.drawable.patch); mPatch2 = resources.getDrawable(R.drawable.btn_toggle_on); mPatch3 = resources.getDrawable(R.drawable.patch2); mTexture = Bitmap.createBitmap(4, 3, Bitmap.Config.ARGB_8888); mTexture.setPixel(0, 0, 0xffff0000); mTexture.setPixel(1, 0, 0xffffffff); mTexture.setPixel(2, 0, 0xff000000); mTexture.setPixel(3, 0, 0xffff0000); mTexture.setPixel(0, 1, 0xffff0000); mTexture.setPixel(1, 1, 0xff000000); mTexture.setPixel(2, 1, 0xffffffff); mTexture.setPixel(3, 1, 0xffff0000); mTexture.setPixel(0, 2, 0xffff0000); mTexture.setPixel(1, 2, 0xffff0000); mTexture.setPixel(2, 2, 0xffff0000); mTexture.setPixel(3, 2, 0xffff0000); } @Override protected void onDraw(Canvas canvas) { final int width = 100; final int height = 60; final int left = (getWidth() - width) / 2; final int top = (getHeight() - height) / 2; canvas.save(); canvas.translate(0.0f, -height * 2 - 20.0f); mPatch3.setBounds(left, top, left + height, top + width); mPatch3.draw(canvas); canvas.restore(); mPatch1.setBounds(left, top, left + width, top + height); mPatch1.draw(canvas); canvas.save(); canvas.translate(0.0f, height + 20.0f); mPatch2.setBounds(left, top, left + width, top + height); mPatch2.draw(canvas); canvas.restore(); // Rect src = new Rect(1, 0, 3, 2); // RectF dst = new RectF(0, 0, getWidth(), getHeight()); // canvas.drawBitmap(mTexture, src, dst, null); } } }
35.122642
93
0.627451
42716c9f805e676f508ea6a48edea467f8b1baea
2,627
/* * Copyright 2017-2021 Tim Segall * * 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.cobber.fta; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Locale; import java.util.Map; import com.cobber.fta.core.FTAPluginException; import com.cobber.fta.core.FTAType; import com.cobber.fta.dates.DateTimeParser; import com.cobber.fta.dates.DateTimeParser.DateResolutionMode; import com.cobber.fta.token.TokenStreams; public class PluginBirthDate extends LogicalTypeInfinite { public final static String REGEXP = "\\d{4}/\\d{2}/\\d{2}"; private static DateTimeParser dtp = new DateTimeParser(); private static LocalDate plausibleBirth = LocalDate.of(1910, 1, 1); public PluginBirthDate(final PluginDefinition plugin) { super(plugin); } @Override public boolean isCandidate(final String trimmed, final StringBuilder compressed, final int[] charCounts, final int[] lastIndex) { final String format = dtp.determineFormatString(trimmed, DateResolutionMode.MonthFirst); final DateTimeFormatter formatter = DateTimeParser.ofPattern(format, locale); final LocalDate localDate = LocalDate.parse(trimmed, formatter); return localDate.isAfter(plausibleBirth); } @Override public boolean initialize(final Locale locale) throws FTAPluginException { super.initialize(locale); return true; } @Override public String nextRandom() { return null; } @Override public String getQualifier() { return "BIRTHDATE"; } @Override public String getRegExp() { return REGEXP; } @Override public FTAType getBaseType() { return FTAType.LOCALDATE; } @Override public boolean isValid(final String input) { return isCandidate(input.trim(), null, null, null); } @Override public String isValidSet(final AnalyzerContext context, final long matchCount, final long realSamples, String currentRegExp, final FactsTypeBased facts, final Map<String, Long> cardinality, final Map<String, Long> outliers, TokenStreams tokenStreams, AnalysisConfig analysisConfig) { return (double)matchCount/realSamples >= getThreshold()/100.0 ? null : ".+"; } }
30.546512
183
0.765131
bf29949e8e1962cd88d6cc697ce55035fc1cd3ce
647
/** * @(#)BindSingleQuestionRequest.java, 4月 14, 2021. * <p> * Copyright 2021 fenbi.com. All rights reserved. * FENBI.COM PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.imcuttle.bar.web.data; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.util.List; /** * @author chenyibo */ @Data public class BindSingleQuestionRequest { @ApiModelProperty("录题任务id") private long taskId; @ApiModelProperty("题目id") private int questionId; @ApiModelProperty("题目原图地址") private List<String> snapshotImgIds; @ApiModelProperty("套卷id") private long examPaperId; }
20.21875
71
0.718702
e88ebf35b46bb09ba085e586875d83e344c62027
19,590
/* * Copyright 2018-2019 Lukas Krejci * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.revapi.classif.progress; import static java.util.Collections.emptyMap; import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toCollection; import static java.util.stream.Collectors.toList; import static org.revapi.classif.TestResult.DEFERRED; import static org.revapi.classif.TestResult.NOT_PASSED; import static org.revapi.classif.TestResult.PASSED; import static org.revapi.classif.util.LogUtil.traceParams; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.stream.Collectors; import javax.lang.model.element.Element; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.EntryMessage; import org.revapi.classif.StructuralMatcher; import org.revapi.classif.TestResult; import org.revapi.classif.progress.context.MatchContext; import org.revapi.classif.util.Nullable; import org.revapi.classif.util.execution.Node; /** * Graph of statements: * * <pre>{@code * type ^%y=* extends %x { <1> * <init>(); <2> * } * * class %x=* directly extends java.lang.Object {} <3> * * class * extends %y {} <4> * }</pre> * <p> * Can be visually represented as: * * <pre>{@code * +---+ +---+ * | 1 |---->| 3 | * +---+ +---+ * | ^ * v | * +---+ +---+ * | 2 | | 4 | * +---+ +---+ * }</pre> * <p> * Matching algorithm at a high level: * <ol> * <li> Elements enter the graph in a tree like manner. The matching algorithm instructs the caller how to proceed with * the hierarchical traversal of the elements. * <li> An element matches the statement graph if at least 1 returning statement (number 1 in the example) matches it. * <li> A statement matches an element if the element satisfies the following conditions: * <ol> * <li> all children of the statement match at least 1 child of the element each * <li> each referenced statement matches the type that is referenced by the element on the appropriate position * <li> all statements that reference the current statement match at least 1 element * <li> the statement matches the element disregarding the references, referents and children * </ol> * </ol> * <p> * Example: * * <pre>{@code * class A {} * * class B extends A {} * * class C extends B {} * }</pre> * <p> * {@code class A} doesn't match the example graph, because the returning statement ({@code <1>}) doesn't match it * ({@code class A} doesn't extends another class that would extend {@code Object}, but rather extends * {@code Object} directly itself). * <p> * {@code class B} matches the example graph because of these reasons: * <ol> * <li> It extends {@code class A} which directly extends {@code Object} - e.g. {@code class A} satisfies the {@code %x} * variable in {@code <1>}. * <li> It has a no-arg constructor and therefore the no-arg constructor method satisfies statement {@code <2>}. * <li> {@code class C} satisfies statement {@code <4>} which references {@code <1>}, because it extends {@code class B} * which is evaluated by {@code <1>}. * </ol> * Importantly, if we didn't pass {@code class C} to the matcher, {@code class B} WOULDN'T match, because {@code <4>} * would not be satisfied by any element seen by the matcher. */ final class MultiMatchingProgress<M> extends MatchingProgress<M> { private static final Logger LOG = LogManager.getLogger(MultiMatchingProgress.class); private final List<Node<StatementMatch<M>>> roots; private final Deque<WalkContext<M>> statementStack = new ArrayDeque<>(); private final StructuralMatcher.Configuration config; private final Set<WalkContext<M>> undecided; private final List<Node<StatementMatch<M>>> returningStatements; private final Map<String, Node<StatementMatch<M>>> definingStatements; MultiMatchingProgress(StructuralMatcher.Configuration configuration, List<Node<StatementMatch<M>>> statements) { config = configuration; roots = new ArrayList<>(); returningStatements = new ArrayList<>(); definingStatements = new HashMap<>(); statements.forEach(s -> { if (s.getParent() == null) { roots.add(s); } if (s.getObject().getContext().isReturn()) { returningStatements.add(s); } String var = s.getObject().getContext().getDefinedVariable(); if (var != null) { definingStatements.put(var, s); } }); undecided = Collections.newSetFromMap(new IdentityHashMap<>()); } @Override public WalkInstruction start(M model) { EntryMessage methodTrace = LOG.traceEntry(traceParams(LOG, "this", this, "model", model)); WalkContext<M> parentCtx = statementStack.isEmpty() ? null : requireNonNull(statementStack.peek()); Collection<Node<StatementMatch<M>>> currentStatements = parentCtx == null ? roots : parentCtx.nextStatements; Collection<Node<StatementMatch<M>>> nextStatements = new ArrayList<>(); boolean mustHaveChildren = true; TestResult res = NOT_PASSED; for (Node<StatementMatch<M>> sm : currentStatements) { TestResult sr = sm.getObject().independentTest(model); if (sm.getObject().getContext().isReturn()) { res = res.or(sr); } if (!(sm.out().isEmpty() && sm.in().isEmpty())) { // even though we're basically re-setting the result here to DEFERRED, we need to let all the tests // go through so that we're collecting the match candidates at the individual statements res = DEFERRED; } nextStatements.addAll(sm.getChildren()); mustHaveChildren = mustHaveChildren && !sm.getChildren().isEmpty(); } if (!config.isStrictHierarchy()) { nextStatements.addAll(roots); } boolean descend = !config.isStrictHierarchy() || !nextStatements.isEmpty(); statementStack.push(new WalkContext<>(parentCtx, model, res, mustHaveChildren, nextStatements)); return LOG.traceExit(methodTrace, WalkInstruction.of(descend, res)); } @Override public TestResult finish(M model) { EntryMessage methodTrace = LOG.traceEntry(traceParams(LOG, "this", this, "model", model)); if (statementStack.isEmpty()) { throw LOG.traceExit(methodTrace, new IllegalStateException("Unbalanced start/finish calls.")); } WalkContext<M> ctx = statementStack.pop(); if (ctx.model != model) { throw LOG.traceExit(methodTrace, new IllegalStateException("Unbalanced start/finish calls.")); } if (ctx.mustHaveChildren && !ctx.childrenEncountered) { ctx.finishResult = NOT_PASSED; } if (ctx.finishResult == NOT_PASSED) { LOG.trace("start of model {} didn't pass, so bailing out quickly.", model); return LOG.traceExit(methodTrace, NOT_PASSED); } if (ctx.parent != null) { ctx.parent.finishResult = ctx.parent.finishResult.and(ctx.finishResult); ctx.parent.childrenEncountered = true; } if (ctx.finishResult == DEFERRED) { undecided.add(ctx); } return ctx.finishResult; } @Override public Map<M, TestResult> finish() { EntryMessage methodTrace = LOG.traceEntry(traceParams(LOG, "this", this)); // 1. Find all the statements defining variables // 2. Build a context for each permutation of candidate models for those statements // 3. for each undecided model, for each returning statement, for each context, compute the union of the results // for the statement with the model and the context if (undecided.isEmpty()) { return LOG.traceExit(methodTrace, emptyMap()); } List<String> vars = new ArrayList<>(definingStatements.keySet()); List<Collection<M>> candidates = definingStatements.values().stream().map(n -> n.getObject().getCandidates()) .map(c -> c.isEmpty() ? Collections.<M>singleton(null) : c) .collect(toList()); Map<M, TestResult> ret = undecided.stream().map(wc -> wc.model).collect(Collectors.toMap(identity(), model -> { for (Node<StatementMatch<M>> st : returningStatements) { Iterator<List<M>> combinations = combinations(candidates); while (combinations.hasNext()) { List<M> combination = combinations.next(); Map<String, M> binding = new HashMap<>(vars.size()); for (int i = 0; i < vars.size(); ++i) { binding.put(vars.get(i), combination.get(i)); } StatementMatch<M> match = st.getObject(); TestResult combinationResult = testBinding(st, model, binding, new IdentityHashMap<>()); if (combinationResult == PASSED) { return PASSED; } } } return NOT_PASSED; })); return LOG.traceExit(methodTrace, ret); } private TestResult testBinding(Node<StatementMatch<M>> statementNode, M model, Map<String, M> binding, Map<Node<StatementMatch<M>>, Map<M, TestResult>> cache) { EntryMessage methodTrace = LOG.traceEntry(traceParams(LOG, "this", this, "statementNode", statementNode, "model", model, "binding", binding)); TestResult cached = cache.computeIfAbsent(statementNode, __ -> new HashMap<>()).get(model); if (cached != null) { LOG.trace("Found cached result {} for {}", cached, statementNode); return LOG.traceExit(methodTrace, cached); } else { if (cache.get(statementNode).containsKey(model)) { // the evaluation is in progress, yet we arrived here again... pretending a passing result basically // cancels out the effect of this statement on the result LOG.trace("Evaluation loop detected on {}", statementNode); return LOG.traceExit(methodTrace, PASSED); } } cache.get(statementNode).put(model, null); StatementMatch<M> match = statementNode.getObject(); TestResult ret = match.test(model, match.getContext().require(binding).getMatchContext()) .and(() -> { // match children EntryMessage trace = LOG.traceEntry("Matching children"); if (statementNode.getChildren().isEmpty()) { LOG.trace("No children on statement {}", statementNode); return LOG.traceExit(trace, PASSED); } for (Node<StatementMatch<M>> child : statementNode.getChildren()) { StatementMatch<M> childSt = child.getObject(); boolean somePassed = false; for (M candidate : childSt.getCandidates()) { MatchContext<M> ctx = childSt.getContext().require(binding).getMatchContext(); Element parent = ctx.getModelInspector().toElement(candidate).getEnclosingElement(); if (parent == null || !model.equals(ctx.getModelInspector().fromElement(parent))) { continue; } if (testBinding(child, candidate, binding, cache) == PASSED) { somePassed = true; break; } } if (!somePassed) { LOG.trace("No candidate on child {} passes with binding {}", child, binding); return LOG.traceExit(trace, NOT_PASSED); } } return LOG.traceExit(trace, PASSED); }) .and(() -> { // match dependencies EntryMessage trace = LOG.traceEntry("Matching dependencies"); if (statementNode.in().isEmpty()) { LOG.trace("No dependencies found on {}", statementNode); return LOG.traceExit(trace, PASSED); } TestResult result = requireDependencies(model, statementNode, binding, cache); return LOG.traceExit(trace, result); }) .and(() -> { // match dependents EntryMessage trace = LOG.traceEntry("Matching dependents"); if (statementNode.out().isEmpty()) { LOG.trace("No dependents on statement {}", statementNode); return LOG.traceExit(trace, PASSED); } String var = match.getContext().getDefinedVariable(); if (model != binding.get(var)) { LOG.trace("Current model {} is not bound as {} on the current statement {}." + " Dependents cannot pass.", model, var, statementNode); return LOG.traceExit(trace, NOT_PASSED); } TestResult result = PASSED; for (Node<StatementMatch<M>> dep : statementNode.out()) { StatementMatch<M> depSt = dep.getObject(); boolean someCandidatePasses = false; for (M depCandidate : depSt.getCandidates()) { if (testBinding(dep, depCandidate, binding, cache) == PASSED) { someCandidatePasses = true; break; } } if (!someCandidatePasses) { LOG.trace("No candidate match of {} matches with binding {}.", dep, binding); result = NOT_PASSED; break; } } return LOG.traceExit(trace, result); }); cache.get(statementNode).put(model, ret); return LOG.traceExit(methodTrace, ret); } private TestResult requireDependencies(M model, Node<StatementMatch<M>> statementNode, Map<String, M> binding, Map<Node<StatementMatch<M>>, Map<M, TestResult>> cache) { // potential optimization here is to as the statement whether it needs to process all the dependencies or // if we can somehow short-circuit here - either if the statement requires all deps to pass and we find // a non-matching or if the statement requires at least one dep to pass and we find such. // This requires some complex logic in the matches though because we need to basically reconstruct the Map<String, TestResult> results = new HashMap<>(); for (Node<StatementMatch<M>> dep : statementNode.in()) { String var = dep.getObject().getContext().getDefinedVariable(); if (dep.getObject().getCandidates().contains(binding.get(var))) { results.put(var, testBinding(dep, binding.get(var), binding, cache)); } else { results.put(var, NOT_PASSED); } } return statementNode.getObject() .test(model, statementNode.getObject().getContext().withResults(results).getMatchContext()); } @Override public void reset() { statementStack.clear(); undecided.clear(); roots.forEach(this::resetStatement); } private void resetStatement(Node<StatementMatch<M>> st) { st.getObject().reset(); for (Node<StatementMatch<M>> child : st.getChildren()) { resetStatement(child); } } private static class WalkContext<M> { final @Nullable WalkContext<M> parent; final M model; final TestResult startResult; TestResult finishResult; final boolean mustHaveChildren; boolean childrenEncountered; final Collection<Node<StatementMatch<M>>> nextStatements; private WalkContext(WalkContext<M> parent, M model, TestResult startResult, boolean shouldHaveChildren, Collection<Node<StatementMatch<M>>> nextStatements) { this.parent = parent; this.model = model; this.startResult = startResult; this.nextStatements = nextStatements; this.mustHaveChildren = shouldHaveChildren; this.finishResult = startResult; } } private <T> Iterator<List<T>> combinations(Collection<? extends Collection<T>> source) { return new Iterator<List<T>>() { final List<Collection<T>> sources = new ArrayList<>(source); final List<Iterator<T>> current = source.stream().map(Collection::iterator).collect(toList()); List<T> last = null; @Override public boolean hasNext() { for (Iterator<?> it : current) { if (it.hasNext()) { return true; } } return false; } @Override public List<T> next() { if (last == null) { return first(); } for (int i = 0; i < last.size(); ++i) { Iterator<T> it = current.get(i); if (it.hasNext()) { last.set(i, it.next()); return last; } else { it = sources.get(i).iterator(); current.set(i, it); last.set(i, it.next()); } } throw new NoSuchElementException(); } private List<T> first() { if (last == null) { last = current.stream().map(Iterator::next).collect(toCollection(ArrayList::new)); } return last; } }; } }
40.8125
150
0.575753
7ac03d140c32482450368fb60dffa88bc1810cbf
5,133
/* * Creation : 11 févr. 2015 * Project Computer Science L2 Semester 4 - BattleShip */ package com.battleship.views.app; import com.battleship.asset.CheatCode; import com.battleship.asset.Session; import com.battleship.network.Capsule; import com.battleship.network.Request; import com.battleship.observers.ObservableLan; import com.battleship.observers.ObserverLan; import com.battleship.views.tools.ContentPanel; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Insets; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; /** * * * @since Feb 11. 2015 * @author Constantin MASSON * @author Anthony CHAFFOT * @author Jessica FAVIN */ public class ChatPanel extends ContentPanel implements ObserverLan{ private JPanel p_sentence; private JPanel p_north; private JTextField tf_sentence; private JTextArea ta_chat; private JScrollPane sp_scroll; //************************************************************************** // CONSTRUCTOR //************************************************************************** /** * Constructor of the ChatPanel * @param pParent parent panel */ public ChatPanel(JPanel pParent) { super(pParent); this.initComponents(); this.setSizes(); this.addEachComponents(); this.setActions(); if(Session.isConnected()){ Session.getNetwork().addLanObserver(this); } } //************************************************************************** // METHODS //************************************************************************** /** * Set the size of the chat */ private void setSizes(){ tf_sentence.setPreferredSize(new Dimension(180, 25)); } /** * Init all components */ private void initComponents() { p_sentence = new JPanel(); p_north = new JPanel(); p_north.setLayout(new BorderLayout()); //this.setLayout(new GridLayout(2,1)); this.setLayout(new BorderLayout()); tf_sentence = new JTextField(); ta_chat = new JTextArea(); setupChat(); this.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); this.ta_chat .setMargin(new Insets(10, 10, 10, 10)); this.tf_sentence .setMargin(new Insets(0,10,0,10)); this.setOpaque(false); } /** * Set the chat with the the scroll pane */ private void setupChat() { ta_chat = new JTextArea(); sp_scroll = new JScrollPane(ta_chat); ta_chat.setLineWrap(true); ta_chat.setEditable(false); sp_scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); } /** * add each components to the panel */ private void addEachComponents() { p_north.add(sp_scroll, BorderLayout.CENTER); p_sentence.add(tf_sentence); this.add(p_north, BorderLayout.CENTER); this.add(p_sentence, BorderLayout.SOUTH); } public void printChatMessage(String string) { if(string != null){ string = string.trim(); if(!string.isEmpty() && !string.equals("\n")){ ta_chat.append(string+"\n"); ta_chat.setCaretPosition(ta_chat.getText().length()); } } } //Peut être à changer un peu pour eviter d'appuyer sur enter par erreur public void setActions() { tf_sentence.addKeyListener( new KeyListener() { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ENTER) { String sentence = tf_sentence.getText(); CheatCode.processStrCode(sentence); if(Session.isConnected()){ Session.getNetwork().sendCapsule(new Capsule(Request.MSG_CHAT, sentence)); } printChatMessage(sentence); tf_sentence.setText(""); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } } ); } //************************************************************************** // UI Functions //************************************************************************** @Override public void loadUI(){ } @Override public void reloadUI(){ } @Override public void updateLan(ObservableLan o, Object arg){ if(arg instanceof String){ String msg = (String)arg; this.printChatMessage(msg); } } }
28.203297
102
0.519969
b38c0cc3b3ce45c91feff9b7f95948fadde7cbdb
9,779
/* * Copyright 2016-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.isis.io.isispacket.pdu; import org.easymock.EasyMock; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.onosproject.isis.controller.IsisPduType; import org.onosproject.isis.io.isispacket.IsisHeader; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; /** * Unit test class for P2PHelloPdu. */ public class P2PHelloPduTest { private final byte[] p2p = { 2, 51, 51, 51, 51, 51, 51, 0, 100, 5, -39, -126, 1, 4, 3, 73, 0, 0, -127, 1, -52, -124, 4, -64, -88, 56, 102, 8, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, -81, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private P2PHelloPdu p2PHelloPdu; private IsisHeader isisHeader; private byte resultByte; private ChannelBuffer channelBuffer; private byte[] result; private int resultInt; @Before public void setUp() throws Exception { isisHeader = new IsisHeader(); isisHeader.setIsisPduType(IsisPduType.P2PHELLOPDU.value()); p2PHelloPdu = new P2PHelloPdu(isisHeader); channelBuffer = EasyMock.createMock(ChannelBuffer.class); } @After public void tearDown() throws Exception { isisHeader = null; p2PHelloPdu = null; channelBuffer = null; } /** * Tests localCircuitId() getter method. */ @Test public void testLocalCircuitId() throws Exception { p2PHelloPdu.setLocalCircuitId((byte) 1); resultByte = p2PHelloPdu.localCircuitId(); assertThat(resultByte, is((byte) 1)); } /** * Tests localCircuitId() setter method. */ @Test public void testSetLocalCircuitId() throws Exception { p2PHelloPdu.setLocalCircuitId((byte) 1); resultByte = p2PHelloPdu.localCircuitId(); assertThat(resultByte, is((byte) 1)); } /** * Tests setVariableLengths() method. */ @Test public void testSetVariableLengths() throws Exception { } /** * Tests readFrom() method. */ @Test public void testReadFrom() throws Exception { channelBuffer = ChannelBuffers.copiedBuffer(p2p); p2PHelloPdu.readFrom(channelBuffer); assertThat(p2PHelloPdu, is(notNullValue())); } /** * Tests asBytes() method. */ @Test public void testAsBytes() throws Exception { channelBuffer = ChannelBuffers.copiedBuffer(p2p); p2PHelloPdu.readFrom(channelBuffer); result = p2PHelloPdu.asBytes(); assertThat(result, is(notNullValue())); } /** * Tests p2PHeader() method. */ @Test public void testP2PHeader() throws Exception { result = p2PHelloPdu.p2PHeader(); assertThat(result, is(notNullValue())); } /** * Tests p2P2HelloPduBody() method. */ @Test public void testP2P2HelloPduBody() throws Exception { channelBuffer = ChannelBuffers.copiedBuffer(p2p); p2PHelloPdu.readFrom(channelBuffer); result = p2PHelloPdu.p2P2HelloPduBody(); assertThat(result, is(notNullValue())); } /** * Tests toString() method. */ @Test public void testToString() throws Exception { assertThat(p2PHelloPdu.toString(), is(notNullValue())); } /** * Tests equals() method. */ @Test public void testEquals() throws Exception { assertThat(p2PHelloPdu.equals(new P2PHelloPdu(new IsisHeader())), is(true)); } /** * Tests hashCode() method. */ @Test public void testHashCode() throws Exception { resultInt = p2PHelloPdu.hashCode(); assertThat(resultInt, is(notNullValue())); } }
40.409091
84
0.444115
31031cb92cce991a5048d2fc8147d713d934a657
2,036
package com.offsetnull.bt.responder.script; import com.offsetnull.bt.R; import com.offsetnull.bt.responder.TriggerResponderEditorDoneListener; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; public class ScriptResponderEditor extends Dialog { private ScriptResponder the_responder; private ScriptResponder original; private TriggerResponderEditorDoneListener finish_with; private boolean isEditor = false; public ScriptResponderEditor(Context context,ScriptResponder input,TriggerResponderEditorDoneListener listener) { super(context); finish_with = listener; if(input == null) { the_responder = new ScriptResponder(); } else { the_responder = input.copy(); original = input.copy(); isEditor = true; } } public void onCreate(Bundle b) { this.getWindow().requestFeature(Window.FEATURE_NO_TITLE); this.getWindow().setBackgroundDrawableResource(R.drawable.dialog_window_crawler1); setContentView(R.layout.responder_script_dialog); EditText function = (EditText)findViewById(R.id.function); function.setText(the_responder.getFunction()); Button done = (Button)findViewById(R.id.done); done.setOnClickListener(new DoneListener()); Button cancel = (Button)findViewById(R.id.cancel); cancel.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { ScriptResponderEditor.this.dismiss(); } }); } private class DoneListener implements View.OnClickListener { public void onClick(View arg0) { EditText function = (EditText)findViewById(R.id.function); //ackwith.setText(the_responder.getAckWith()); the_responder.setFunction(function.getText().toString()); if(isEditor) { finish_with.editTriggerResponder(the_responder, original); } else { finish_with.newTriggerResponder(the_responder); } ScriptResponderEditor.this.dismiss(); } }; }
27.146667
114
0.761297
070d1306f90490895c9d0d62e0ede38d0df4671f
509
package org.codehaus.waffle.taglib.form; import javax.servlet.jsp.JspException; import java.io.IOException; import java.io.Writer; /** * A form row. * * @author Guilherme Silveira */ public class RowTag extends FormElement { @Override protected String getDefaultLabel() { return ""; } public RowTag() { // does nothing } @Override protected IterationResult start(Writer out) throws JspException, IOException { return IterationResult.BODY; } }
17.551724
82
0.669941
62a38a7999b308d5aa988faa270464005cb111da
85
package singletonPattern; public enum Subsystem { PRIMARY, AUXILIARY, FALLBACK }
10.625
25
0.776471
e97277c22bbae003884af72108259820fa8f2397
1,148
package jplee.worldmanager.util; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.JsonToNBT; import net.minecraft.nbt.NBTException; public class ItemUtils { public static ItemStack parsItem(String item) throws NBTException { String[] parts = item.trim().split(" +", 3); int amount = 1; if(parts.length >= 2) { amount = Integer.parseInt(parts[1]); } String id = parts[0]; String[] idParts = id.split(":"); int meta = 0; Item i = null; if(idParts.length == 3) { meta = Integer.parseInt(idParts[2]); i = Item.getByNameOrId(idParts[0] + ":" + idParts[1]); } else if(idParts.length == 2) { try { meta = Integer.parseInt(idParts[1]); i = Item.getByNameOrId(idParts[0]); } catch(NumberFormatException e) { i = Item.getByNameOrId(idParts[0] + ":" + idParts[1]); } } else { i = Item.getByNameOrId(idParts[0]); } ItemStack stack = new ItemStack(i, amount, meta); if(parts.length == 3) { try { stack.setTagCompound(JsonToNBT.getTagFromJson(parts[2])); } catch(NBTException e) { throw e; } } return stack; } }
22.96
68
0.638502
00cb15fbf3441606288c406964215fa6dae05e67
1,223
package com.lendico.coding.codingtask.service; import com.lendico.coding.codingtask.model.Repayment; import com.lendico.coding.codingtask.model.RepaymentPlan; import org.javamoney.moneta.FastMoney; import javax.money.CurrencyUnit; import java.time.LocalDateTime; /** * @author Anil Kurmi */ public interface RepaymentService { /** * @param loanAmount * @param nominalRate * @param duration * @param startDate * @return The repayments plan for the given input values */ RepaymentPlan generatePlan(FastMoney loanAmount, double nominalRate, int duration, LocalDateTime startDate, CurrencyUnit currencyUnit); /** * Calculates the repayments for a given month after the start date. * * @param loanAmount * @param nominalRate * @param duration * @param startDate * @param initialOutstandingPrincipal * @param monthsAfterStart * @return The resulting repayment for the given input values */ Repayment generateRepayment(FastMoney loanAmount, double nominalRate, int duration, LocalDateTime startDate, FastMoney initialOutstandingPrincipal, int monthsAfterStart, CurrencyUnit currencyUnit); }
33.054054
139
0.718724
d6bd578dd66a7ab21465595e06157cbdf8b2c5a9
5,292
/* * Copyright © "Open Digital Education", 2014 * * This program is published by "Open Digital Education". * You must indicate the name of the software and the company in any production /contribution * using the software and indicate on the home page of the software industry in question, * "powered by Open Digital Education" with a reference to the website: https://opendigitaleducation.com/. * * This program is free software, licensed under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, version 3 of the License. * * You can redistribute this application and/or modify it since you respect the terms of the GNU Affero General Public License. * If you modify the source code and then use this modified source code in your creation, you must make available the source code of your modifications. * * You should have received a copy of the GNU Affero General Public License along with the software. * If not, please see : <http://www.gnu.org/licenses/>. Full compliance requires reading the terms of this license and following its directives. */ package org.entcore.common.sql; import fr.wseduc.webutils.Utils; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class DB { private static final Logger log = LoggerFactory.getLogger(DB.class); public static void loadScripts(final String schema, final Vertx vertx, final String path) { final String s = (schema != null && !schema.trim().isEmpty()) ? schema + "." : ""; final Sql sql = Sql.getInstance(); String query = "SELECT count(*) FROM information_schema.tables WHERE table_name = 'scripts'" + " AND table_schema = '" + ((!s.isEmpty()) ? schema : "public") + "'"; sql.raw(query, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> message) { Long nb = SqlResult.countResult(message); if (nb == null) { log.error("Error loading sql scripts."); } else if (nb == 1) { sql.raw("SELECT filename FROM " + s + "scripts", new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> message) { if ("ok".equals(message.body().getString("status"))) { JsonArray fileNames = Utils.flatten(message.body().getJsonArray("results")); loadAndExecute(s, vertx, path, fileNames); } } }); } else if (nb == 0) { loadAndExecute(s, vertx, path, new fr.wseduc.webutils.collections.JsonArray()); } } }); } private static void loadAndExecute(final String schema, final Vertx vertx, final String path, final JsonArray excludeFileNames) { vertx.fileSystem().readDir(path, ".*?\\.sql$", new Handler<AsyncResult<List<String>>>() { @Override public void handle(AsyncResult<List<String>> asyncResult) { if (asyncResult.succeeded()) { final List<String> files = asyncResult.result(); Collections.sort(files); final SqlStatementsBuilder s = new SqlStatementsBuilder(); final JsonArray newFiles = new fr.wseduc.webutils.collections.JsonArray(); final AtomicInteger count = new AtomicInteger(files.size()); for (final String f : files) { final String filename = f.substring(f.lastIndexOf(File.separatorChar) + 1); if (!excludeFileNames.contains(filename)) { vertx.fileSystem().readFile(f, new Handler<AsyncResult<Buffer>>() { @Override public void handle(AsyncResult<Buffer> bufferAsyncResult) { if (bufferAsyncResult.succeeded()) { String script = bufferAsyncResult.result().toString(); script = script.replaceAll("\\-\\-\\s.*(\r|\n|$)", "").replaceAll("(\r|\n|\t)", " "); s.raw(script); newFiles.add(new fr.wseduc.webutils.collections.JsonArray().add(filename)); } else { log.error("Error reading file : " + f, bufferAsyncResult.cause()); } if (count.decrementAndGet() == 0) { commit(schema, s, newFiles); } } }); } else { count.decrementAndGet(); } } if (count.get() == 0 && newFiles.size() > 0) { commit(schema, s, newFiles); } } else { log.error("Error reading sql directory : " + path, asyncResult.cause()); } } private void commit(final String schema, SqlStatementsBuilder s, final JsonArray newFiles) { s.insert(schema + "scripts", new fr.wseduc.webutils.collections.JsonArray().add("filename"), newFiles); Sql.getInstance().transaction(s.build(), new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> message) { if ("ok".equals(message.body().getString("status"))) { log.info("Scripts added : " + newFiles.encode()); } else { log.error("Error when commit transaction : " + message.body().getString("message")); } } }); } }); } }
40.707692
152
0.674414
eda6113aa1e33d659534b3ab771a7f5eaef6c4ed
5,435
/* * Copyright 2020 jrosclient project * * Website: https://github.com/lambdaprime/jrosclient * * 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. */ /* * Authors: * - lambdaprime <[email protected]> */ package id.jrosclient.ros.transport; import java.util.Optional; import id.xfunction.XJson; import id.xfunction.logging.XLogger; /** * <a href="http://wiki.ros.org/ROS/Connection%20Header">http://wiki.ros.org/ROS/Connection%20Header</a> */ public class ConnectionHeader { private static final XLogger LOGGER = XLogger.getLogger(ConnectionHeader.class); public static final String CALLER_ID = "callerid"; public static final String TOPIC = "topic"; public static final String TYPE = "type"; public static final String MESSAGE_DEFINITION = "message_definition"; public static final String MD5_SUM = "md5sum"; public static final String LATCHING = "latching"; /** * Name of node sending data. * * Required to be set by the subscriber. * It is recommended to set it by publisher as well for debugging purposes. */ public Optional<String> callerId = Optional.empty(); /** * Name of the topic the subscriber is connecting to * * Required to be set by the subscriber. */ public Optional<String> topic = Optional.empty(); /** * Message type. * * Required to be set by the subscriber. * Required to be set by the publisher. */ public Optional<String> type = Optional.empty(); /** * Md5sum of the message type * * Required to be set by the subscriber. * Required to be set by the publisher. */ public Optional<String> md5sum = Optional.empty(); /** * Enables "latching" on a connection. When a connection is * latched, the last message published is saved and automatically * sent to any future subscribers that connect. This is useful for * slow-changing to static data like a map. * * Optional by the publisher/subscriber. */ public Optional<String> latching = Optional.empty(); /** * Required to be set by the subscriber. */ public Optional<String> messageDefinition = Optional.empty(); public ConnectionHeader withCallerId(String callerId) { this.callerId = Optional.of(callerId); return this; } public ConnectionHeader withTopic(String topic) { this.topic = Optional.of(topic); return this; } public ConnectionHeader withType(String type) { this.type = Optional.of(type); return this; } public ConnectionHeader withMessageDefinition(String messageDefinition) { this.messageDefinition = Optional.of(messageDefinition); return this; } public ConnectionHeader withMd5Sum(String md5sum) { this.md5sum = Optional.of(md5sum); return this; } public ConnectionHeader withLatching(boolean value) { this.latching = Optional.of(value? "1": "0"); return this; } public void add(String key, String value) { switch (key) { case CALLER_ID: withCallerId(value); break; case TOPIC: withTopic(value); break; case TYPE: withType(value); break; case MESSAGE_DEFINITION: withMessageDefinition(value); break; case MD5_SUM: withMd5Sum(value); break; case LATCHING: withLatching(Integer.parseInt(value) == 1); break; default: LOGGER.warning("Received unknown Connection Header field: {0} = {1} ", key, value); } } public Optional<String> getMd5sum() { return md5sum; } public Optional<String> getType() { return type; } public Optional<String> getCallerId() { return callerId; } public Optional<String> getTopic() { return topic; } public Optional<String> getLatching() { return latching; } @Override public String toString() { return XJson.asString( CALLER_ID, callerId.orElse("empty"), TOPIC, topic.orElse("empty"), TYPE, type.orElse("empty"), MESSAGE_DEFINITION, messageDefinition.orElse("empty"), MD5_SUM, md5sum.orElse("empty"), LATCHING, latching.orElse("empty")); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (this.getClass() != obj.getClass()) return false; ConnectionHeader ch = (ConnectionHeader) obj; return callerId.equals(ch.callerId) && topic.equals(ch.topic) && type.equals(ch.type) && messageDefinition.equals(ch.messageDefinition) && md5sum.equals(ch.md5sum) && latching.equals(ch.latching); } }
30.194444
104
0.631831
e530320891d510ffd95c0189782194379e67fefd
1,491
package uk.dioxic.mgenerate.core.operator.geo; import org.junit.jupiter.api.Test; import uk.dioxic.mgenerate.core.transformer.ReflectiveTransformerRegistry; import java.util.List; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; class LineStringTest { @Test void resolve() { List<Number> longBounds = asList(0d, 10d); List<Number> latBounds = asList(-20, 0); LineString lineString = new LineStringBuilder(ReflectiveTransformerRegistry.getInstance()).longBounds(longBounds).latBounds(latBounds).build(); assertThat(lineString.resolveInternal()).isNotNull(); assertThat(lineString.resolveInternal().get("type")).as("geo type").isEqualTo("LineString"); assertThat(lineString.resolveInternal().get("coordinates")).as("coordinates class type").isInstanceOf(List.class); List<?> coordinates = (List<?>)lineString.resolveInternal().get("coordinates"); coordinates.forEach(c -> { assertThat(c).isInstanceOf(uk.dioxic.mgenerate.core.operator.type.Coordinates.class); uk.dioxic.mgenerate.core.operator.type.Coordinates p = (uk.dioxic.mgenerate.core.operator.type.Coordinates) c; assertThat(p.getX()).as("longitude").isBetween(longBounds.get(0).doubleValue(), longBounds.get(1).doubleValue()); assertThat(p.getY()).as("latitude").isBetween(latBounds.get(0).doubleValue(), latBounds.get(1).doubleValue()); }); } }
43.852941
151
0.711603
ad112394f2bcd7a9197b3aa0823466e33a241677
1,019
//Copyright (C) 2021, Grzegorz Stefański package edu.ib.project.crazyeights.backend; import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; public class BotsAlgorithmTest { public BotsAlgorithmTest() { System.out.println("\n" + " ".repeat(15) + "--- BotsAlgorithm class tests ---"); } @Test public void makeBotMove() throws Exception { System.out.printf("%-50s", "\t* makeBotMove method... "); Game game = new Game("2 players"); Player player1 = game.getPlayer(); Player player2 = game.getBotsList().get(0); BotsAlgorithm botsAlgorithm = new BotsAlgorithm(game); botsAlgorithm.makeBotMove(player1); botsAlgorithm.makeBotMove(player2); List<Card> cards = new ArrayList<>(); cards.add(new Card((byte) 0, (byte) 6)); Player player3 = new Player("test_8", cards); botsAlgorithm.makeBotMove(player3); botsAlgorithm.makeBotMove(player3); System.out.println("OK"); } }
26.815789
84
0.690873
ef901adf42c6ded50df8505571dcfe2954db5c9d
401
public class OopTheRealWay { public static void main(String[] args) { Constants constants = new Constants(); System.out.println(constants.three); } } class Constants { final static double MAX_LENGTH = 9.0; final static int ONE = 1; final static String NAME = "John Doe"; public static char A = 'a'; static String location = "Jakarta"; public Number ninety = 90; }
15.423077
42
0.668329
74d82de40d68e7e9f1239568915389f343d2e581
2,816
package com.rasto.accommodationbookingsystem; import com.rasto.accommodationbookingsystem.backend.data.Role; import com.rasto.accommodationbookingsystem.backend.data.entity.User; import com.rasto.accommodationbookingsystem.backend.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Lazy; import org.springframework.security.crypto.password.PasswordEncoder; @SpringBootApplication public class AccommodationBookingSystemApplication extends SpringBootServletInitializer implements CommandLineRunner, HasLogger { public static void main(String[] args) { SpringApplication.run(AccommodationBookingSystemApplication.class, args); } private UserService userService; private PasswordEncoder passwordEncoder; @Autowired public void setUserService(UserService userService) { this.userService = userService; } @Autowired public void setPasswordEncoder(@Lazy PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; } private static final String TEST_USER_EMAIL = "[email protected]"; private static final String TEST_ADMIN_EMAIL = "[email protected]"; private static final String TEST_USER_PASSWORD = "test.user"; private static final String TEST_ADMIN_PASSWORD = "test.admin"; @Override public void run(String... args) throws Exception { getLogger().info("Creating test user..."); if (userService.exists(TEST_USER_EMAIL)) { getLogger().info("Test user already exists: \nLogin email: " + TEST_USER_EMAIL + "\nPassword: " + TEST_USER_PASSWORD); } else { User user = userService.createNew(); user.setEmail(TEST_USER_EMAIL); user.setPassword(passwordEncoder.encode(TEST_USER_PASSWORD)); user.setName("Test"); user.setSurname("User"); userService.saveOrUpdate(user); getLogger().info("Test user created: \nLogin email: " + TEST_USER_EMAIL + "\nPassword: " + TEST_USER_PASSWORD); } getLogger().info("Creating test user admin..."); if (userService.exists(TEST_ADMIN_EMAIL)) { getLogger().info("Test user admin already exists: \nLogin email: " + TEST_ADMIN_EMAIL + "\nPassword: " + TEST_ADMIN_PASSWORD); } else { User user = userService.createNew(); user.setEmail(TEST_ADMIN_EMAIL); user.setPassword(passwordEncoder.encode(TEST_ADMIN_PASSWORD)); user.setName("Admin"); user.setSurname("Test"); user.setRole(Role.ADMIN); userService.saveOrUpdate(user); getLogger().info("Test user admin created: \nLogin email: " + TEST_ADMIN_EMAIL + "\nPassword: " + TEST_ADMIN_PASSWORD); } } }
39.111111
129
0.783026
b399cc0929adde18f2fe3cca6ce0e41d033e4ca1
1,461
package peacefulotter.engine.rendering.graphics; // A basic material used when loading a texture from a .mtl file public class SimpleMaterial { private final Texture texture; private final float specularIntensity, specularPower; public SimpleMaterial( Texture texture, float specularIntensity, float specularPower ) { this.texture = texture; this.specularIntensity = specularIntensity; this.specularPower = specularPower; } public Texture getTexture() { return texture; } public float getSpecularIntensity() { return specularIntensity; } public float getSpecularPower() { return specularPower; } public static class MaterialBuilder { private Texture texture; private float specularIntensity = 1; private float specularPower = 0; public MaterialBuilder setTexture( Texture texture ) { this.texture = texture; return this; } public MaterialBuilder setSpecularIntensity( float specularIntensity ) { this.specularIntensity = specularIntensity; return this; } public MaterialBuilder setSpecularPower( float specularPower ) { this.specularPower = specularPower; return this; } public SimpleMaterial build() { return new SimpleMaterial( texture, specularIntensity, specularPower ); } } }
29.22
90
0.6564
d96c4f71438bb03524a021439168ed8d671f4602
1,113
package org.iron.ultimate.jpa.dao.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "AR_USER_NAME") public class ArUserName implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "USER_NAME_ID") private Long userNameId; @Column(name = "CLAN_MEMBER_ID") private Long clanMemberId; @Column(name = "USER_NAME") private String userName; public ArUserName() { super(); } public ArUserName(String userName) { super(); this.userName = userName; } public Long getUserNameId() { return userNameId; } public void setUserNameId(Long userNameId) { this.userNameId = userNameId; } public Long getClanMemberId() { return clanMemberId; } public void setClanMemberId(Long clanMemberId) { this.clanMemberId = clanMemberId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
20.611111
50
0.706199
7ec5f742248254eb87947090701866095578b3c2
1,685
package com.vk.demo.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.vk.demo.entities.Employee; import com.vk.demo.repositories.EmployeeRepository; @Component public class EmployeeDaoImpl implements EmployeeDao { @Autowired private EmployeeRepository employeeRepository; public List<Employee> getAllEmployee(){ return (List<Employee>) employeeRepository.findAll(); } @Override public Employee getEmployee(Integer tId) { // Employee emp = new Employee(); // if(employeeRepository.findOne(tId).equals(emp)){ // throw new IdNotFoundException(tId); // }else { // return employeeRepository.findOne(tId); // } return employeeRepository.getOne(tId); } @Override public List<Employee> findEmployeesByBankId(Integer bId) { return employeeRepository.findEmployeesByBankId(bId); } @Override public Employee updateEmployee(Employee emp) { Employee newEntity = employeeRepository.getOne(emp.getEmployeeId()); newEntity.setAddress(emp.getAddress()); newEntity.setEmail(emp.getEmail()); newEntity.setFirstName(emp.getFirstName()); newEntity.setLastName(emp.getLastName()); employeeRepository.save(newEntity); return newEntity; } @Override public List<Employee> findByEmployeeId(Integer employeeid) { return employeeRepository.findByEmployeeId(employeeid); } @Override public void addEmployee(Employee empUp) { employeeRepository.saveAndFlush(empUp); } }
24.779412
81
0.694362
609f069499eaeb360c2637d223d97fa86a975402
11,181
package deepthinking.fgi.dao.mapper; import deepthinking.fgi.domain.TableFunc; import deepthinking.fgi.domain.TableFuncCriteria.Criteria; import deepthinking.fgi.domain.TableFuncCriteria.Criterion; import deepthinking.fgi.domain.TableFuncCriteria; import java.util.List; import java.util.Map; import org.apache.ibatis.jdbc.SQL; public class TableFuncSqlProvider { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table table_func * * @mbg.generated */ public String countByExample(TableFuncCriteria example) { SQL sql = new SQL(); sql.SELECT("count(*)").FROM("table_func"); applyWhere(sql, example, false); return sql.toString(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table table_func * * @mbg.generated */ public String deleteByExample(TableFuncCriteria example) { SQL sql = new SQL(); sql.DELETE_FROM("table_func"); applyWhere(sql, example, false); return sql.toString(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table table_func * * @mbg.generated */ public String insertSelective(TableFunc record) { SQL sql = new SQL(); sql.INSERT_INTO("table_func"); if (record.getId() != null) { sql.VALUES("ID", "#{id,jdbcType=INTEGER}"); } if (record.getModuleid() != null) { sql.VALUES("ModuleID", "#{moduleid,jdbcType=INTEGER}"); } if (record.getVarname() != null) { sql.VALUES("VarName", "#{varname,jdbcType=VARCHAR}"); } if (record.getVartype() != null) { sql.VALUES("VarType", "#{vartype,jdbcType=VARCHAR}"); } if (record.getValvalue() != null) { sql.VALUES("ValValue", "#{valvalue,jdbcType=VARCHAR}"); } if (record.getRemark() != null) { sql.VALUES("Remark", "#{remark,jdbcType=VARCHAR}"); } return sql.toString(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table table_func * * @mbg.generated */ public String selectByExample(TableFuncCriteria example) { SQL sql = new SQL(); if (example != null && example.isDistinct()) { sql.SELECT_DISTINCT("ID"); } else { sql.SELECT("ID"); } sql.SELECT("ModuleID"); sql.SELECT("VarName"); sql.SELECT("VarType"); sql.SELECT("ValValue"); sql.SELECT("Remark"); sql.FROM("table_func"); applyWhere(sql, example, false); if (example != null && example.getOrderByClause() != null) { sql.ORDER_BY(example.getOrderByClause()); } return sql.toString(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table table_func * * @mbg.generated */ public String updateByExampleSelective(Map<String, Object> parameter) { TableFunc record = (TableFunc) parameter.get("record"); TableFuncCriteria example = (TableFuncCriteria) parameter.get("example"); SQL sql = new SQL(); sql.UPDATE("table_func"); if (record.getId() != null) { sql.SET("ID = #{record.id,jdbcType=INTEGER}"); } if (record.getModuleid() != null) { sql.SET("ModuleID = #{record.moduleid,jdbcType=INTEGER}"); } if (record.getVarname() != null) { sql.SET("VarName = #{record.varname,jdbcType=VARCHAR}"); } if (record.getVartype() != null) { sql.SET("VarType = #{record.vartype,jdbcType=VARCHAR}"); } if (record.getValvalue() != null) { sql.SET("ValValue = #{record.valvalue,jdbcType=VARCHAR}"); } if (record.getRemark() != null) { sql.SET("Remark = #{record.remark,jdbcType=VARCHAR}"); } applyWhere(sql, example, true); return sql.toString(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table table_func * * @mbg.generated */ public String updateByExample(Map<String, Object> parameter) { SQL sql = new SQL(); sql.UPDATE("table_func"); sql.SET("ID = #{record.id,jdbcType=INTEGER}"); sql.SET("ModuleID = #{record.moduleid,jdbcType=INTEGER}"); sql.SET("VarName = #{record.varname,jdbcType=VARCHAR}"); sql.SET("VarType = #{record.vartype,jdbcType=VARCHAR}"); sql.SET("ValValue = #{record.valvalue,jdbcType=VARCHAR}"); sql.SET("Remark = #{record.remark,jdbcType=VARCHAR}"); TableFuncCriteria example = (TableFuncCriteria) parameter.get("example"); applyWhere(sql, example, true); return sql.toString(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table table_func * * @mbg.generated */ public String updateByPrimaryKeySelective(TableFunc record) { SQL sql = new SQL(); sql.UPDATE("table_func"); if (record.getModuleid() != null) { sql.SET("ModuleID = #{moduleid,jdbcType=INTEGER}"); } if (record.getVarname() != null) { sql.SET("VarName = #{varname,jdbcType=VARCHAR}"); } if (record.getVartype() != null) { sql.SET("VarType = #{vartype,jdbcType=VARCHAR}"); } if (record.getValvalue() != null) { sql.SET("ValValue = #{valvalue,jdbcType=VARCHAR}"); } if (record.getRemark() != null) { sql.SET("Remark = #{remark,jdbcType=VARCHAR}"); } sql.WHERE("ID = #{id,jdbcType=INTEGER}"); return sql.toString(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table table_func * * @mbg.generated */ protected void applyWhere(SQL sql, TableFuncCriteria example, boolean includeExamplePhrase) { if (example == null) { return; } String parmPhrase1; String parmPhrase1_th; String parmPhrase2; String parmPhrase2_th; String parmPhrase3; String parmPhrase3_th; if (includeExamplePhrase) { parmPhrase1 = "%s #{example.oredCriteria[%d].allCriteria[%d].value}"; parmPhrase1_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}"; parmPhrase2 = "%s #{example.oredCriteria[%d].allCriteria[%d].value} and #{example.oredCriteria[%d].criteria[%d].secondValue}"; parmPhrase2_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{example.oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}"; parmPhrase3 = "#{example.oredCriteria[%d].allCriteria[%d].value[%d]}"; parmPhrase3_th = "#{example.oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}"; } else { parmPhrase1 = "%s #{oredCriteria[%d].allCriteria[%d].value}"; parmPhrase1_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}"; parmPhrase2 = "%s #{oredCriteria[%d].allCriteria[%d].value} and #{oredCriteria[%d].criteria[%d].secondValue}"; parmPhrase2_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}"; parmPhrase3 = "#{oredCriteria[%d].allCriteria[%d].value[%d]}"; parmPhrase3_th = "#{oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}"; } StringBuilder sb = new StringBuilder(); List<Criteria> oredCriteria = example.getOredCriteria(); boolean firstCriteria = true; for (int i = 0; i < oredCriteria.size(); i++) { Criteria criteria = oredCriteria.get(i); if (criteria.isValid()) { if (firstCriteria) { firstCriteria = false; } else { sb.append(" or "); } sb.append('('); List<Criterion> criterions = criteria.getAllCriteria(); boolean firstCriterion = true; for (int j = 0; j < criterions.size(); j++) { Criterion criterion = criterions.get(j); if (firstCriterion) { firstCriterion = false; } else { sb.append(" and "); } if (criterion.isNoValue()) { sb.append(criterion.getCondition()); } else if (criterion.isSingleValue()) { if (criterion.getTypeHandler() == null) { sb.append(String.format(parmPhrase1, criterion.getCondition(), i, j)); } else { sb.append(String.format(parmPhrase1_th, criterion.getCondition(), i, j,criterion.getTypeHandler())); } } else if (criterion.isBetweenValue()) { if (criterion.getTypeHandler() == null) { sb.append(String.format(parmPhrase2, criterion.getCondition(), i, j, i, j)); } else { sb.append(String.format(parmPhrase2_th, criterion.getCondition(), i, j, criterion.getTypeHandler(), i, j, criterion.getTypeHandler())); } } else if (criterion.isListValue()) { sb.append(criterion.getCondition()); sb.append(" ("); List<?> listItems = (List<?>) criterion.getValue(); boolean comma = false; for (int k = 0; k < listItems.size(); k++) { if (comma) { sb.append(", "); } else { comma = true; } if (criterion.getTypeHandler() == null) { sb.append(String.format(parmPhrase3, i, j, k)); } else { sb.append(String.format(parmPhrase3_th, i, j, k, criterion.getTypeHandler())); } } sb.append(')'); } } sb.append(')'); } } if (sb.length() > 0) { sql.WHERE(sb.toString()); } } }
37.27
171
0.524729
7ddb845c5a58f3bfa5b3fad3f368f598aba81ae5
348
package ru.job4j.loop; public class Mortgage { public int year(int amount, int monthly, double percent) { int year = 0; double total = ((amount * percent) / 100) + amount; int yearly = monthly * 12; while (total > 0) { total -= yearly; year++; } return year; } }
18.315789
62
0.508621
9dd848842ff6db48de17a4ba31f6880029629c23
2,010
private Tuple execute(final HttpMethodBase method, int numTries) throws IOException { final Timer timer = Metric.newTimer("RestClientImpl.execute"); try { final int sc = httpClient.executeMethod(method); if (sc < OK_MIN || sc > OK_MAX) { throw new RestException("Unexpected status code: " + sc + ": " + method.getStatusText() + " -- " + method, sc); } final InputStream in = method.getResponseBodyAsStream(); try { final StringWriter writer = new StringWriter(2048); IOUtils.copy(in, writer, method.getResponseCharSet()); return new Tuple(sc, writer.toString()); } finally { in.close(); } } catch (NullPointerException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (SocketException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (IOException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw e; } finally { method.releaseConnection(); timer.stop(); } }
39.411765
127
0.462687
90d527e09eadcc20e00e8470f3abd06052a09c04
77
/** * エナジードリンクを生産する工場に関するクラスが含まれています。 */ package factory.drink.energydrink;
19.25
34
0.779221
71d188d53b569d0a972c1955071c3c3fe6d425eb
4,872
package org.apache.fop.afp; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.fop.afp.modca.ResourceGroup; import org.apache.fop.afp.modca.StreamedResourceGroup; public class AFPStreamer implements Streamable { private static final Log log; private static final String AFPDATASTREAM_TEMP_FILE_PREFIX = "AFPDataStream_"; private static final int BUFFER_SIZE = 4096; private static final String DEFAULT_EXTERNAL_RESOURCE_FILENAME = "resources.afp"; private final Factory factory; private final Map pathResourceGroupMap = new HashMap(); private StreamedResourceGroup printFileResourceGroup; private String defaultResourceGroupFilePath = "resources.afp"; private File tempFile; private OutputStream documentOutputStream; private OutputStream outputStream; private RandomAccessFile documentFile; private DataStream dataStream; public AFPStreamer(Factory factory) { this.factory = factory; } public DataStream createDataStream(AFPPaintingState paintingState) throws IOException { this.tempFile = File.createTempFile("AFPDataStream_", (String)null); this.documentFile = new RandomAccessFile(this.tempFile, "rw"); this.documentOutputStream = new BufferedOutputStream(new FileOutputStream(this.documentFile.getFD())); this.dataStream = this.factory.createDataStream(paintingState, this.documentOutputStream); return this.dataStream; } public void setDefaultResourceGroupFilePath(String filePath) { this.defaultResourceGroupFilePath = filePath; } public ResourceGroup getResourceGroup(AFPResourceLevel level) { ResourceGroup resourceGroup = null; if (level.isInline()) { return null; } else { if (level.isExternal()) { String filePath = level.getExternalFilePath(); if (filePath == null) { log.warn("No file path provided for external resource, using default."); filePath = this.defaultResourceGroupFilePath; } resourceGroup = (ResourceGroup)this.pathResourceGroupMap.get(filePath); if (resourceGroup == null) { BufferedOutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(filePath)); } catch (FileNotFoundException var10) { log.error("Failed to create/open external resource group file '" + filePath + "'"); } finally { if (os != null) { resourceGroup = this.factory.createStreamedResourceGroup(os); this.pathResourceGroupMap.put(filePath, resourceGroup); } } } } else if (level.isPrintFile()) { if (this.printFileResourceGroup == null) { this.printFileResourceGroup = this.factory.createStreamedResourceGroup(this.outputStream); } resourceGroup = this.printFileResourceGroup; } else { resourceGroup = this.dataStream.getResourceGroup(level); } return (ResourceGroup)resourceGroup; } } public void close() throws IOException { Iterator it = this.pathResourceGroupMap.entrySet().iterator(); while(it.hasNext()) { StreamedResourceGroup resourceGroup = (StreamedResourceGroup)it.next(); resourceGroup.close(); } if (this.printFileResourceGroup != null) { this.printFileResourceGroup.close(); } this.writeToStream(this.outputStream); this.outputStream.close(); this.tempFile.delete(); } public void setOutputStream(OutputStream outputStream) { this.outputStream = outputStream; } public void writeToStream(OutputStream os) throws IOException { int len = (int)this.documentFile.length(); int numChunks = len / 4096; int remainingChunkSize = len % 4096; this.documentFile.seek(0L); byte[] buffer; if (numChunks > 0) { buffer = new byte[4096]; for(int i = 0; i < numChunks; ++i) { this.documentFile.read(buffer, 0, 4096); os.write(buffer, 0, 4096); } } else { buffer = new byte[remainingChunkSize]; } if (remainingChunkSize > 0) { this.documentFile.read(buffer, 0, remainingChunkSize); os.write(buffer, 0, remainingChunkSize); } os.flush(); } static { log = LogFactory.getLog(AFPStreamer.class); } }
34.553191
108
0.663177
d5696b991be9fc65d2b5a457fcd5fd36839bcbbb
1,797
package bu.edu.ec500.sshealthapp; import android.hardware.SensorManager; public class SensorData { public float[] accelerate, gyroscope, magnetic, gameRotation; public long timestamp; public float[] worldAcc; public SensorData() { accelerate = new float[3]; gyroscope = new float[3]; magnetic = new float[3]; worldAcc = new float[3]; gameRotation = new float[3]; timestamp = System.currentTimeMillis(); } public void clone(SensorData sd) { System.arraycopy(sd.accelerate, 0, this.accelerate, 0, 3); System.arraycopy(sd.gyroscope, 0, this.gyroscope, 0, 3); System.arraycopy(sd.magnetic, 0, this.magnetic, 0, 3); System.arraycopy(sd.worldAcc, 0, this.worldAcc, 0, 3); System.arraycopy(sd.gameRotation, 0, this.gameRotation, 0, 3); this.timestamp = sd.timestamp; } public void calculateWorldAcc() { float[] Rotate = new float[16]; float[] I = new float[16]; float[] currOrientation = new float[3]; if ((int)gameRotation[0] == 0 && (int)gameRotation[1] == 0 && (int)gameRotation[2] == 0) { SensorManager.getRotationMatrix(Rotate, I, accelerate, magnetic); } else { SensorManager.getRotationMatrixFromVector(Rotate, gameRotation); } float[] relativeAcc = new float[4]; float[] earthAcc = new float[4]; float[] inv = new float[16]; System.arraycopy(accelerate, 0, relativeAcc, 0, 3); relativeAcc[3] = 0; android.opengl.Matrix.invertM(inv, 0, Rotate, 0); android.opengl.Matrix.multiplyMV(earthAcc, 0, inv, 0, relativeAcc, 0); System.arraycopy(earthAcc, 0, worldAcc, 0, 3); } }
35.235294
99
0.601558
372ac4d74818c44b01e2cf6e97b1b7ea7b9102ff
633
package java_basic; /** * Project:Exercise * Package:main.java.java_basic * Author:Alan Ruan * Date:2018-11-09 15:17 * Description://TODO */ public class ThreadExtends { public static void main(String[] args) { new MyThread("Thread测试").start(); new MyThread("Thread测试").start(); } } class MyThread extends Thread{ private String acceptStr; public MyThread(String acceptStr) { this.acceptStr = acceptStr; } @Override public void run() { for (int i = 0; i < 5; i ++) { System.out.println("这个传给我的值:"+acceptStr+",加上一个变量,看看是什么效果:"+i); } } }
18.617647
74
0.601896
60be77ecc4718975b65eb8611ba3373573538f29
3,294
package org.apache.lucene.index; /** * Copyright 2006 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import junit.framework.TestCase; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.Token; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import java.io.Reader; import java.io.IOException; import java.util.Random; /** * @author yonik * @version $Id$ */ class RepeatingTokenStream extends TokenStream { public int num; Token t; public RepeatingTokenStream(String val) { t = new Token(val,0,val.length()); } public Token next() throws IOException { return --num<0 ? null : t; } } public class TestTermdocPerf extends TestCase { void addDocs(Directory dir, final int ndocs, String field, final String val, final int maxTF, final float percentDocs) throws IOException { final Random random = new Random(0); final RepeatingTokenStream ts = new RepeatingTokenStream(val); Analyzer analyzer = new Analyzer() { public TokenStream tokenStream(String fieldName, Reader reader) { if (random.nextFloat() < percentDocs) ts.num = random.nextInt(maxTF)+1; else ts.num=0; return ts; } }; Document doc = new Document(); doc.add(new Field(field,val, Field.Store.NO, Field.Index.NO_NORMS)); IndexWriter writer = new IndexWriter(dir, analyzer, true); writer.setMaxBufferedDocs(100); writer.setMergeFactor(100); for (int i=0; i<ndocs; i++) { writer.addDocument(doc); } writer.optimize(); writer.close(); } public int doTest(int iter, int ndocs, int maxTF, float percentDocs) throws IOException { Directory dir = new RAMDirectory(); long start = System.currentTimeMillis(); addDocs(dir, ndocs, "foo", "val", maxTF, percentDocs); long end = System.currentTimeMillis(); System.out.println("milliseconds for creation of " + ndocs + " docs = " + (end-start)); IndexReader reader = IndexReader.open(dir); TermEnum tenum = reader.terms(new Term("foo","val")); TermDocs tdocs = reader.termDocs(); start = System.currentTimeMillis(); int ret=0; for (int i=0; i<iter; i++) { tdocs.seek(tenum); while (tdocs.next()) { ret += tdocs.doc(); } } end = System.currentTimeMillis(); System.out.println("milliseconds for " + iter + " TermDocs iteration: " + (end-start)); return ret; } public void testTermDocPerf() throws IOException { // performance test for 10% of documents containing a term // doTest(100000, 10000,3,.1f); } }
28.396552
141
0.689739
08f10967b5baa6679f3da6fd0fc99a8d38efff3e
618
package org.batfish.question.boolean_expr; import org.batfish.question.Environment; import org.batfish.question.ipsec_vpn_expr.IpsecVpnExpr; import org.batfish.representation.IpsecVpn; public class HasRemoteIpsecVpnIpsecVpnBooleanExpr extends BaseBooleanExpr { private IpsecVpnExpr _caller; public HasRemoteIpsecVpnIpsecVpnBooleanExpr(IpsecVpnExpr caller) { _caller = caller; } @Override public Boolean evaluate(Environment environment) { environment.initRemoteIpsecVpns(); IpsecVpn caller = _caller.evaluate(environment); return caller.getRemoteIpsecVpn() != null; } }
26.869565
75
0.779935
d7de62bd31077ea8ebc1dfb92bffb46a897f5f6d
7,545
package com.morethanheroic.taskforce.job.builder; import com.morethanheroic.taskforce.generator.Generator; import com.morethanheroic.taskforce.job.Job; import com.morethanheroic.taskforce.sink.Sink; import com.morethanheroic.taskforce.task.Task; import com.morethanheroic.taskforce.task.decorator.StatisticsDecoratorTask; import com.morethanheroic.taskforce.task.domain.TaskContext; import org.junit.Test; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; /* * We are testing the whole builder in one go. Otherwise we would need to do some heavy reflection hacking. */ public class JobBuilderTest { private static final String TEST_TASK_NAME = "TASK_NAME"; private static final int DEFAULT_UUID_LENGTH = 36; private static final int DEFAULT_STATISTICS_REPORTING_RATE = 100; @Test public void testBuilderWithNoNameNoContextTask() { final Generator<Integer> mockGenerator = mock(Generator.class); final Task<Integer, Integer> mockTask = mock(Task.class); final Sink<Integer> mockSink = mock(Sink.class); final Job job = JobBuilder.newBuilder() .generator(mockGenerator) .task(mockTask) .sink(mockSink) .build(); assertThat(job.getGenerator(), is(mockGenerator)); assertThat(job.getTaskDescriptors().size(), is(1)); assertThat(job.getTaskDescriptors().get(0).getTask(), is(mockTask)); assertThat(job.getTaskDescriptors().get(0).getTaskName().length(), is(DEFAULT_UUID_LENGTH)); assertThat(job.getSink(), is(mockSink)); } @Test public void testBuilderWithNamedNoContextTask() { final Generator<Integer> mockGenerator = mock(Generator.class); final Task<Integer, Integer> mockTask = mock(Task.class); final Sink<Integer> mockSink = mock(Sink.class); final Job job = JobBuilder.newBuilder() .generator(mockGenerator) .task(TEST_TASK_NAME, mockTask) .sink(mockSink) .build(); assertThat(job.getGenerator(), is(mockGenerator)); assertThat(job.getTaskDescriptors().size(), is(1)); assertThat(job.getTaskDescriptors().get(0).getTask(), is(mockTask)); assertThat(job.getTaskDescriptors().get(0).getTaskName(), is(TEST_TASK_NAME)); assertThat(job.getSink(), is(mockSink)); } @Test public void testBuilderWithNoNameAndStatisticsCollectionEnabled() { final Generator<Integer> mockGenerator = mock(Generator.class); final Task<Integer, Integer> mockTask = mock(Task.class); final Sink<Integer> mockSink = mock(Sink.class); final TaskContext taskContext = TaskContext.builder() .statisticsCollectionEnabled(true) .build(); final Job job = JobBuilder.newBuilder() .generator(mockGenerator) .task(mockTask, taskContext) .sink(mockSink) .build(); assertThat(job.getGenerator(), is(mockGenerator)); assertThat(job.getTaskDescriptors().size(), is(1)); assertThat(job.getTaskDescriptors().get(0).getTask(), is(instanceOf(StatisticsDecoratorTask.class))); final StatisticsDecoratorTask statisticsDecoratorTask = (StatisticsDecoratorTask) job.getTaskDescriptors() .get(0).getTask(); assertThat(statisticsDecoratorTask.getDelegate(), is(mockTask)); assertThat(statisticsDecoratorTask.getReportingRate(), is(DEFAULT_STATISTICS_REPORTING_RATE)); assertThat(statisticsDecoratorTask.getDelegateName().length(), is(DEFAULT_UUID_LENGTH)); assertThat(statisticsDecoratorTask.isReportingEnabled(), is(false)); assertThat(job.getTaskDescriptors().get(0).getTaskName().length(), is(DEFAULT_UUID_LENGTH)); assertThat(job.getSink(), is(mockSink)); } @Test public void testBuilderWithNoNameAndStatisticsCollectionAndReportingEnabled() { final Generator<Integer> mockGenerator = mock(Generator.class); final Task<Integer, Integer> mockTask = mock(Task.class); final Sink<Integer> mockSink = mock(Sink.class); final TaskContext taskContext = TaskContext.builder() .statisticsCollectionEnabled(true) .statisticsReportingEnabled(true) .build(); final Job job = JobBuilder.newBuilder() .generator(mockGenerator) .task(mockTask, taskContext) .sink(mockSink) .build(); assertThat(job.getGenerator(), is(mockGenerator)); assertThat(job.getTaskDescriptors().size(), is(1)); assertThat(job.getTaskDescriptors().get(0).getTask(), is(instanceOf(StatisticsDecoratorTask.class))); final StatisticsDecoratorTask statisticsDecoratorTask = (StatisticsDecoratorTask) job.getTaskDescriptors() .get(0).getTask(); assertThat(statisticsDecoratorTask.getDelegate(), is(mockTask)); assertThat(statisticsDecoratorTask.getReportingRate(), is(DEFAULT_STATISTICS_REPORTING_RATE)); assertThat(statisticsDecoratorTask.getDelegateName().length(), is(DEFAULT_UUID_LENGTH)); assertThat(statisticsDecoratorTask.isReportingEnabled(), is(true)); assertThat(job.getTaskDescriptors().get(0).getTaskName().length(), is(DEFAULT_UUID_LENGTH)); assertThat(job.getSink(), is(mockSink)); } @Test public void testBuilderWithNoNameAndOnlyReportingEnabled() { final Generator<Integer> mockGenerator = mock(Generator.class); final Task<Integer, Integer> mockTask = mock(Task.class); final Sink<Integer> mockSink = mock(Sink.class); final TaskContext taskContext = TaskContext.builder() .statisticsReportingEnabled(true) .build(); final Job job = JobBuilder.newBuilder() .generator(mockGenerator) .task(mockTask, taskContext) .sink(mockSink) .build(); assertThat(job.getGenerator(), is(mockGenerator)); assertThat(job.getTaskDescriptors().size(), is(1)); assertThat(job.getTaskDescriptors().get(0).getTask(), is(instanceOf(StatisticsDecoratorTask.class))); final StatisticsDecoratorTask statisticsDecoratorTask = (StatisticsDecoratorTask) job.getTaskDescriptors() .get(0).getTask(); assertThat(statisticsDecoratorTask.getDelegate(), is(mockTask)); assertThat(statisticsDecoratorTask.getReportingRate(), is(DEFAULT_STATISTICS_REPORTING_RATE)); assertThat(statisticsDecoratorTask.getDelegateName().length(), is(DEFAULT_UUID_LENGTH)); assertThat(statisticsDecoratorTask.isReportingEnabled(), is(true)); assertThat(job.getTaskDescriptors().get(0).getTaskName().length(), is(DEFAULT_UUID_LENGTH)); assertThat(job.getSink(), is(mockSink)); } @Test public void testBuilderWithCustomThreadCount() { final Generator<Integer> mockGenerator = mock(Generator.class); final Task<Integer, Integer> mockTask = mock(Task.class); final Sink<Integer> mockSink = mock(Sink.class); final Job job = JobBuilder.newBuilder() .generator(mockGenerator) .task(mockTask) .sink(mockSink) .withThreadCount(120) .build(); assertThat(job.getTaskExecutor().getThreadCount(), is(120)); } }
46.288344
114
0.673691
6f79276014c5c0dec1d7b937aa4c7482696d5c60
450
package com.cy.core.mobileLocal.dao; import com.cy.core.mobileLocal.entity.MobileScratch; public interface MobileScratchMapper { /** * 新增 * * @param mobileLocal */ void insert(MobileScratch mobileScratch); /** * 找不到归属地的手机号前7位暂存在MobileScratch里面 * * @param mobileNumber * @return */ MobileScratch selectByMobileNumber(String mobileNumber); /** * 删除 * * @param mobileNumber */ void delete(String mobileNumber); }
16.071429
57
0.7
559d9f2a2f4dad07417aae7cea20c5590e216e1d
246
package com.capitalone.dashboard.utils; import com.capitalone.dashboard.model.CodeQuality; import com.capitalone.dashboard.model.quality.QualityVisitor; public interface CodeQualityConverter { QualityVisitor<CodeQuality> produceVisitor(); }
24.6
61
0.837398
dc1fe19cda44536a04dba93f0f04bcdcb5e6bddd
1,523
package org.jspare.jpa.injector; import lombok.AllArgsConstructor; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.jspare.core.InjectorAdapter; import org.jspare.core.MySupport; import org.jspare.jpa.PersistenceUnitProvider; import org.jspare.jpa.annotation.RepositoryInject; import org.springframework.data.repository.Repository; import javax.inject.Inject; import javax.persistence.EntityManagerFactory; import java.lang.reflect.Field; import java.lang.reflect.Proxy; @Slf4j public class RepositoryInjectStrategy extends MySupport implements InjectorAdapter { @Inject private PersistenceUnitProvider provider; @Override public boolean isInjectable(Field field) { return field.isAnnotationPresent(RepositoryInject.class); } @Override public void inject(Object result, Field field) { try { String datasourceName = field.getAnnotation(RepositoryInject.class).datasource(); EntityManagerFactory emf = provider.getProvider(datasourceName); if (emf == null) return; Object repository = Proxy.newProxyInstance(RepositoryInjectStrategy.class.getClassLoader(), new Class[]{field.getType(), Repository.class}, new RepositoryInvocationHandler(field.getType(), emf)); field.setAccessible(true); field.set(result, repository); } catch (Exception e) { log.error("Failed to create repository {}", field.getType(), e); } } @Data @AllArgsConstructor class RepositoryHolder { private String datasource; } }
27.196429
111
0.757058
60d0626fd73177324019410a6afc18431ac0e5b3
2,921
/* * 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.directory.fortress.core.ant; import org.apache.directory.fortress.core.model.Role; import java.util.ArrayList; import java.util.List; /** * The class is used by {@link FortressAntTask} to load {@link org.apache.directory.fortress.core.model.Role}s used to * drive {@link org.apache.directory.fortress.core.AdminMgr#addRole(org.apache.directory.fortress.core.model.Role)}}. * It is not intended to be callable by programs outside of the Ant load utility. The class name itself maps to the xml * tag used by load utility. * <p> * This class name, 'Addrole', is used for the xml tag in the load script. * <pre> * {@code * <target name="all"> * <FortressAdmin> * <addrole> * ... * </addrole> * </FortressAdmin> * </target> * } * </pre> * * @author <a href="mailto:[email protected]">Apache Directory Project</a> */ public class Addrole { final private List<Role> roles = new ArrayList<>(); /** * All Ant data entities must have a default constructor. */ public Addrole() { } /** * This method name, 'addRole', is used for derived xml tag 'role' in the load script. * <pre> * {@code * <addrole> * <role name="role1" description="Tomcat Role for Calendar App" beginTime="0800" endTime="1700" beginDate="20110101" * endDate="20111231" beginLockDate="20110601" endLockDate="20110615" dayMask="23456" timeout="60"/> * <role name="role2" description="Tomcat Role 2 for Calendar App"/> * </addrole> * } * </pre> * * @param role contains reference to data element targeted for insertion.. */ public void addRole(Role role) { this.roles.add(role); } /** * Used by {@link FortressAntTask#addRoles()} to retrieve list of Roles as defined in input xml file. * * @return collection containing {@link org.apache.directory.fortress.core.model.Role}s targeted for insertion. */ public List<Role> getRoles() { return this.roles; } }
32.820225
126
0.661417
6c3c0aadda9ae8ac0e119dca687dfe09c3fc015b
511
package io.github.growingunderthetree.events; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; public class fall implements Listener { @EventHandler public void onRiding(PlayerMoveEvent e) { Player player = e.getPlayer(); float distance = player.getFallDistance(); player.sendMessage("You are falling!\n amounts of blocks you falled:" + distance); } }
30.058824
91
0.716243
f2fc41040f6429c7e6446f13855240c72d93eaa7
2,346
package io.confluent.cp.factflow; import org.apache.kafka.clients.producer.*; import java.util.Properties; import java.util.concurrent.ExecutionException; public class FactQueryProducer extends GenericProducerWrapper { public static long startTime = 0; public static int nrOfStatements = 0; static Properties props; static String TOPIC = "_kst_knowledgegraph"; public static void init( String appId, Properties properties ) { props = properties; producer = createProducer( props, appId ); startTime = System.currentTimeMillis(); } public static boolean showNote = true; public static int sentCounter = 0; public static void sendFact( String query ) throws ExecutionException, InterruptedException { try { RecordMetadata metadata = null; nrOfStatements = nrOfStatements + 1; final ProducerRecord<String, String> record = new ProducerRecord<String,String>(TOPIC, startTime+"_"+nrOfStatements, query ); if ( producer != null ) { producer.send(record).get(); sentCounter++; } else { if ( showNote ) { showNote = false; System.out.println(">>> NOTE <<< \n\t No Kafka Producer configured! Data will be collected in Neo4J Graph.\n\n"); } } } catch (Exception ex) { ex.printStackTrace(); props.list( System.out ); System.out.println( " " ); throw ex; } } public static Producer<String,String> createProducer(Properties props, String appID) { if( props.get( ProducerConfig.CLIENT_ID_CONFIG ) == null ) props.put(ProducerConfig.CLIENT_ID_CONFIG, appID); // props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "io.confluent.kafka.serializers.KafkaJsonSerializer"); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); return new KafkaProducer<>(props); } public static boolean isReady() { return producer != null; } }
28.26506
134
0.629156
3619d3a0e88a49f898fd36b7f816ec528fb2d3cc
4,665
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.quickstep.util; import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR; import static com.android.systemui.shared.system.RemoteAnimationTargetCompat.MODE_CLOSING; import android.graphics.Rect; import com.android.systemui.shared.recents.model.ThumbnailData; import com.android.systemui.shared.system.RecentsAnimationControllerCompat; import com.android.systemui.shared.system.RemoteAnimationTargetCompat; import java.util.function.Consumer; /** * Extension of {@link RemoteAnimationTargetSet} with additional information about swipe * up animation */ public class SwipeAnimationTargetSet extends RemoteAnimationTargetSet { private final boolean mShouldMinimizeSplitScreen; private final Consumer<SwipeAnimationTargetSet> mOnFinishListener; public final RecentsAnimationControllerCompat controller; public final Rect homeContentInsets; public final Rect minimizedHomeBounds; public SwipeAnimationTargetSet(RecentsAnimationControllerCompat controller, RemoteAnimationTargetCompat[] targets, Rect homeContentInsets, Rect minimizedHomeBounds, boolean shouldMinimizeSplitScreen, Consumer<SwipeAnimationTargetSet> onFinishListener) { super(targets, MODE_CLOSING); this.controller = controller; this.homeContentInsets = homeContentInsets; this.minimizedHomeBounds = minimizedHomeBounds; this.mShouldMinimizeSplitScreen = shouldMinimizeSplitScreen; this.mOnFinishListener = onFinishListener; } public boolean hasTargets() { return unfilteredApps.length != 0; } /** * Clones the target set without any actual targets. Used only when continuing a gesture after * the actual recents animation has finished. */ public SwipeAnimationTargetSet cloneWithoutTargets() { return new SwipeAnimationTargetSet(controller, new RemoteAnimationTargetCompat[0], homeContentInsets, minimizedHomeBounds, mShouldMinimizeSplitScreen, mOnFinishListener); } public void finishController(boolean toRecents, Runnable callback, boolean sendUserLeaveHint) { mOnFinishListener.accept(this); UI_HELPER_EXECUTOR.execute(() -> { controller.setInputConsumerEnabled(false); controller.finish(toRecents, sendUserLeaveHint); if (callback != null) { MAIN_EXECUTOR.execute(callback); } }); } public void enableInputConsumer() { UI_HELPER_EXECUTOR.submit(() -> { controller.hideCurrentInputMethod(); controller.setInputConsumerEnabled(true); }); } public void setWindowThresholdCrossed(boolean thresholdCrossed) { UI_HELPER_EXECUTOR.execute(() -> { controller.setAnimationTargetsBehindSystemBars(!thresholdCrossed); if (mShouldMinimizeSplitScreen && thresholdCrossed) { // NOTE: As a workaround for conflicting animations (Launcher animating the task // leash, and SystemUI resizing the docked stack, which resizes the task), we // currently only set the minimized mode, and not the inverse. // TODO: Synchronize the minimize animation with the launcher animation controller.setSplitScreenMinimized(thresholdCrossed); } }); } public ThumbnailData screenshotTask(int taskId) { return controller != null ? controller.screenshotTask(taskId) : null; } public void cancelAnimation() { finishController(false /* toRecents */, null, false /* sendUserLeaveHint */); } public void finishAnimation() { finishController(true /* toRecents */, null, false /* sendUserLeaveHint */); } public interface SwipeAnimationListener { void onRecentsAnimationStart(SwipeAnimationTargetSet targetSet); void onRecentsAnimationCanceled(); } }
38.875
99
0.716184
85a29b2cd31729a48b9e8c0480b39a923e937432
536
package com.turbomandelbrot.draw; public class TextObject { public String text; public float x; public float y; public float[] color; public TextObject() { text = "default"; x = 0f; y = 0f; color = new float[] {1f, 1f, 1f, 1.0f}; } public TextObject(String txt, float xcoord, float ycoord) { text = txt; x = xcoord; y = ycoord; color = new float[] {1f, 1f, 1f, 1.0f}; } /*public boolean validate() { if(text.compareTo("")==0) return false; return true; }*/ }
16.242424
59
0.576493
c69cf81af0b1424621b3b0ca6a08846f16d440b1
610
package com.example.BookTradingClub.service.exception; public class BookHasOtherOwnerException extends RuntimeException{ public BookHasOtherOwnerException(String message) { super(message); } public BookHasOtherOwnerException(String message, Throwable cause) { super(message, cause); } public BookHasOtherOwnerException(String bookTitle, String validOwner, String invalidOwner) { super( " '"+ bookTitle +"' belongs to another user. "+ "Expected: "+ validOwner+" "+ "Found: "+ invalidOwner ); } }
30.5
97
0.640984
4d47bff074b3004b8e3cb8354632f14cf606fbbc
267
package com.github.liuyuyu.dictator.service.redis; import lombok.Data; /* * zk内缓存的值 * @author liuyuyu */ @Data public class CachedConfigInfo { /** * 配置值 */ private String value; /** * 上次更新时间 */ private Long lastUpdatedTime; }
13.35
50
0.610487
5200af3c9ffafffc80b9316b0a3616284aa2e0e9
5,794
/* * Copyright 2019 Arcus Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package arcus.app.common.utils; import android.content.SharedPreferences; import android.text.TextUtils; import arcus.app.ArcusApplication; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class PreferenceCache { private final static PreferenceCache instance = new PreferenceCache(); private final static String ATTRS_SUFFIX = "-attributes"; private final static String VALUES_SUFFIX = "-values"; private final static String STRING_DELIMINATOR = "%%%%"; private final HashMap<String, Object> cache = new HashMap<>(); private PreferenceCache () {} public static PreferenceCache getInstance () {return instance;} public void clear() { cache.clear(); } public void putStringMap(String key, Map<String,String> map) { List<String> keys = new ArrayList<>(); List<String> values = new ArrayList<>(); for (String thisKey : map.keySet()) { keys.add(thisKey); values.add(String.valueOf(map.get(thisKey))); } putStringList(key + ATTRS_SUFFIX, keys); putStringList(key + VALUES_SUFFIX, values); } public Map<String,String> getStringMap(String key) { String[] attributes = getStringList(key + ATTRS_SUFFIX); String[] values = getStringList(key + VALUES_SUFFIX); Map<String,String> map = new HashMap<>(); if (attributes == null || values == null || attributes.length != values.length) { return map; } for (int index = 0; index < attributes.length; index++) { map.put(attributes[index], values[index]); } return map; } public void putString(String key, String value) { SharedPreferences.Editor editor = ArcusApplication.getSharedPreferences().edit(); editor.putString(key, value); editor.apply(); cache.put(key, value); } public String getString(String key, String dflt) { if (cache.containsKey(key)) { return (String) cache.get(key); } else { String value = ArcusApplication.getSharedPreferences().getString(key, dflt); cache.put(key, value); return value; } } public void putStringSet(String key, Set<String> value) { SharedPreferences.Editor editor = ArcusApplication.getSharedPreferences().edit(); editor.putStringSet(key, value); editor.apply(); cache.put(key, value); } public Set<String> getStringSet(String key, Set<String> dflt) { if (cache.containsKey(key)) { return (Set<String>) cache.get(key); } else { Set<String> value = ArcusApplication.getSharedPreferences().getStringSet(key, dflt); cache.put(key, value); return value; } } public void putBoolean(String key, boolean value) { SharedPreferences.Editor editor = ArcusApplication.getSharedPreferences().edit(); editor.putBoolean(key, value); editor.apply(); cache.put(key, value); } public boolean getBoolean(String key, boolean dflt) { if (cache.containsKey(key)) { return (boolean) cache.get(key); } else { boolean value = ArcusApplication.getSharedPreferences().getBoolean(key, dflt); cache.put(key, value); return value; } } public void putInteger(String key, Integer integer) { SharedPreferences.Editor editor = ArcusApplication.getSharedPreferences().edit(); editor.putInt(key, integer); editor.apply(); cache.put(key, integer); } public Integer getInteger (String key, Integer dflt) { if (cache.containsKey(key)) { return (Integer) cache.get(key); } else { Integer value = ArcusApplication.getSharedPreferences().getInt(key, dflt); cache.put(key, value); return value; } } public void putStringList(String key, List values) { putString(key, TextUtils.join(STRING_DELIMINATOR, values)); } public String[] getStringList(String key) { String value = getString(key, ""); if (!value.equals("")) { return TextUtils.split(value, STRING_DELIMINATOR); } return new String[]{}; } public void putLong(String key, long value) { SharedPreferences.Editor editor = ArcusApplication.getSharedPreferences().edit(); editor.putLong(key, value).apply(); cache.put(key, value); } public long getLong(String key, long defaultValue) { Object value = cache.get(key); if (value != null) { return (Long) value; } Long prefValue = ArcusApplication.getSharedPreferences().getLong(key, defaultValue); cache.put(key, prefValue); return prefValue; } public void removeKey(String key) { if (TextUtils.isEmpty(key)) { return; } cache.remove(key); ArcusApplication.getSharedPreferences().edit().remove(key).apply(); } }
30.020725
96
0.626338
36696f1fc09aee09546a697b773194c31fba7362
733
package io.vividcode.happytakeaway.restaurant.api.v1.web; import io.vividcode.happytakeaway.restaurant.api.v1.Address; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import org.eclipse.microprofile.openapi.annotations.media.Schema; @Data @Builder @NoArgsConstructor @AllArgsConstructor @Schema(name = "CreateRestaurantRequest", description = "Request to create a restaurant") public class CreateRestaurantWebRequest { @NonNull @Schema(required = true) private String name; private String description; @NonNull @Schema(required = true) private String phoneNumber; @NonNull @Schema(required = true) private Address address; }
25.275862
89
0.79809
f5b3c7a36d17dc2d84a8f3bb4af7a79dbef16853
13,702
/* * MIT LICENSE * Copyright 2000-2020 Simplified Logic, Inc * 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.simplifiedlogic.nitro.jshell.json.handler; import java.util.Hashtable; import com.simplifiedlogic.nitro.jlink.data.ExportResults; import com.simplifiedlogic.nitro.jlink.intf.IJLTransfer; import com.simplifiedlogic.nitro.jshell.json.request.JLInterfaceRequestParams; import com.simplifiedlogic.nitro.jshell.json.response.JLInterfaceResponseParams; import com.simplifiedlogic.nitro.rpc.JLIException; /** * Handle JSON requests for "interface" functions * * @author Adam Andrews * */ public class JLJsonInterfaceHandler extends JLJsonCommandHandler implements JLInterfaceRequestParams, JLInterfaceResponseParams { private IJLTransfer intfHandler = null; /** * @param intfHandler */ public JLJsonInterfaceHandler(IJLTransfer intfHandler) { this.intfHandler = intfHandler; } /* (non-Javadoc) * @see com.simplifiedlogic.nitro.jshell.json.handler.JLJsonCommandHandler#handleFunction(java.lang.String, java.lang.String, java.util.Hashtable) */ public Hashtable<String, Object> handleFunction(String sessionId, String function, Hashtable<String, Object> input) throws JLIException { if (function==null) return null; if (function.equals(FUNC_EXPORT_IMAGE)) return actionExportImage(sessionId, input); else if (function.equals(FUNC_EXPORT_FILE)) return actionExportFile(sessionId, input); else if (function.equals(FUNC_EXPORT_PDF)) return actionExportPDF(sessionId, input); else if (function.equals(FUNC_EXPORT_3DPDF)) return actionExport3DPDF(sessionId, input); else if (function.equals(FUNC_PLOT)) return actionPlot(sessionId, input); else if (function.equals(FUNC_MAPKEY)) return actionMapkey(sessionId, input); else if (function.equals(FUNC_EXPORT_PROGRAM)) return actionExportProgram(sessionId, input); else if (function.equals(FUNC_IMPORT_PROGRAM)) return actionImportProgram(sessionId, input); // else if (function.equals(FUNC_IMPORT_PV)) // return actionImportPV(sessionId, input); else if (function.equals(FUNC_IMPORT_FILE)) return actionImportFile(sessionId, input); // else if (function.equals(FUNC_IMPORT_STEP)) // return actionImportSTEP(sessionId, input); // else if (function.equals(FUNC_IMPORT_IGES)) // return actionImportIGES(sessionId, input); // else if (function.equals(FUNC_IMPORT_NEUTRAL)) // return actionImportNeutral(sessionId, input); else { throw new JLIException("Unknown function name: " + function); } } private Hashtable<String, Object> actionExportImage(String sessionId, Hashtable<String, Object> input) throws JLIException { String type = checkStringParameter(input, PARAM_TYPE, true); String model = checkStringParameter(input, PARAM_MODEL, false); String filename = checkStringParameter(input, PARAM_FILENAME, false); Double height = checkDoubleParameter(input, PARAM_HEIGHT, false); Double width = checkDoubleParameter(input, PARAM_WIDTH, false); Integer dpi = checkIntParameter(input, PARAM_DPI, false, null); Integer depth = checkIntParameter(input, PARAM_DEPTH, false, null); ExportResults results = null; if (TYPE_BMP.equalsIgnoreCase(type)) results = intfHandler.exportBMP(model, filename, height, width, dpi, depth, sessionId); else if (TYPE_EPS.equalsIgnoreCase(type)) results = intfHandler.exportEPS(model, filename, height, width, dpi, depth, sessionId); else if (TYPE_JPEG.equalsIgnoreCase(type)) results = intfHandler.exportJPEG(model, filename, height, width, dpi, depth, sessionId); else if (TYPE_TIFF.equalsIgnoreCase(type)) results = intfHandler.exportTIFF(model, filename, height, width, dpi, depth, sessionId); if (results!=null) { Hashtable<String, Object> out = new Hashtable<String, Object>(); out.put(OUTPUT_DIRNAME, results.getDirname()); out.put(OUTPUT_FILENAME, results.getFilename()); return out; } return null; } private Hashtable<String, Object> actionExportFile(String sessionId, Hashtable<String, Object> input) throws JLIException { String type = checkStringParameter(input, PARAM_TYPE, true); String model = checkStringParameter(input, PARAM_MODEL, false); String filename = checkStringParameter(input, PARAM_FILENAME, false); String dirname = checkStringParameter(input, PARAM_DIRNAME, false); String geomType = checkStringParameter(input, PARAM_GEOM_FLAGS, false); boolean advanced = checkFlagParameter(input, PARAM_ADVANCED, false, false); ExportResults results = null; if (TYPE_DXF.equalsIgnoreCase(type)) results = intfHandler.exportDXF(model, filename, dirname, advanced, sessionId); // else if (TYPE_CATIA.equalsIgnoreCase(type)) // results = intfHandler.exportCATIA(model, filename, dirname, geomType, sessionId); else if (TYPE_IGES.equalsIgnoreCase(type)) results = intfHandler.exportIGES(model, filename, dirname, geomType, advanced, sessionId); else if (TYPE_PV.equalsIgnoreCase(type)) results = intfHandler.exportPV(model, filename, dirname, sessionId); else if (TYPE_STEP.equalsIgnoreCase(type)) results = intfHandler.exportSTEP(model, filename, dirname, geomType, advanced, sessionId); else if (TYPE_VRML.equalsIgnoreCase(type)) results = intfHandler.exportVRML(model, filename, dirname, sessionId); else if (TYPE_NEUTRAL.equalsIgnoreCase(type)) results = intfHandler.exportNeutral(model, filename, dirname, advanced, sessionId); if (results!=null) { Hashtable<String, Object> out = new Hashtable<String, Object>(); out.put(OUTPUT_DIRNAME, results.getDirname()); out.put(OUTPUT_FILENAME, results.getFilename()); return out; } return null; } private Hashtable<String, Object> actionExportPDF(String sessionId, Hashtable<String, Object> input) throws JLIException { String model = checkStringParameter(input, PARAM_MODEL, false); String filename = checkStringParameter(input, PARAM_FILENAME, false); String dirname = checkStringParameter(input, PARAM_DIRNAME, false); boolean useDrawingSettings = checkFlagParameter(input, PARAM_USE_DRW_SETTINGS, false, false); Double height = checkDoubleParameter(input, PARAM_HEIGHT, false); Double width = checkDoubleParameter(input, PARAM_WIDTH, false); Integer dpi = checkIntParameter(input, PARAM_DPI, false, null); ExportResults results = intfHandler.exportPDF(model, filename, dirname, false, height, width, dpi, useDrawingSettings, sessionId); if (results!=null) { Hashtable<String, Object> out = new Hashtable<String, Object>(); out.put(OUTPUT_DIRNAME, results.getDirname()); out.put(OUTPUT_FILENAME, results.getFilename()); return out; } return null; } private Hashtable<String, Object> actionExport3DPDF(String sessionId, Hashtable<String, Object> input) throws JLIException { String model = checkStringParameter(input, PARAM_MODEL, false); String filename = checkStringParameter(input, PARAM_FILENAME, false); String dirname = checkStringParameter(input, PARAM_DIRNAME, false); boolean useDrawingSettings = checkFlagParameter(input, PARAM_USE_DRW_SETTINGS, false, false); Double height = checkDoubleParameter(input, PARAM_HEIGHT, false); Double width = checkDoubleParameter(input, PARAM_WIDTH, false); Integer dpi = checkIntParameter(input, PARAM_DPI, false, null); ExportResults results = intfHandler.exportPDF(model, filename, dirname, true, height, width, dpi, useDrawingSettings, sessionId); if (results!=null) { Hashtable<String, Object> out = new Hashtable<String, Object>(); out.put(OUTPUT_DIRNAME, results.getDirname()); out.put(OUTPUT_FILENAME, results.getFilename()); return out; } return null; } private Hashtable<String, Object> actionPlot(String sessionId, Hashtable<String, Object> input) throws JLIException { String model = checkStringParameter(input, PARAM_MODEL, false); String dirname = checkStringParameter(input, PARAM_DIRNAME, false); String driver = checkStringParameter(input, PARAM_DRIVER, false); ExportResults results = intfHandler.plot(model, dirname, driver, sessionId); if (results!=null) { Hashtable<String, Object> out = new Hashtable<String, Object>(); out.put(OUTPUT_DIRNAME, results.getDirname()); out.put(OUTPUT_FILENAME, results.getFilename()); return out; } return null; } private Hashtable<String, Object> actionMapkey(String sessionId, Hashtable<String, Object> input) throws JLIException { String script = checkStringParameter(input, PARAM_SCRIPT, true); int delay = checkIntParameter(input, PARAM_DELAY, false, 0); intfHandler.mapkey(script, delay, sessionId); return null; } private Hashtable<String, Object> actionExportProgram(String sessionId, Hashtable<String, Object> input) throws JLIException { String model = checkStringParameter(input, PARAM_MODEL, false); ExportResults results = intfHandler.exportProgram(model, sessionId); if (results!=null) { Hashtable<String, Object> out = new Hashtable<String, Object>(); out.put(OUTPUT_DIRNAME, results.getDirname()); out.put(OUTPUT_FILENAME, results.getFilename()); return out; } return null; } private Hashtable<String, Object> actionImportProgram(String sessionId, Hashtable<String, Object> input) throws JLIException { String dirname = checkStringParameter(input, PARAM_DIRNAME, false); String filename = checkStringParameter(input, PARAM_FILENAME, false); String model = checkStringParameter(input, PARAM_MODEL, false); if (model!=null && filename!=null) throw new JLIException("Cannot specify both model and input file"); String outModel = intfHandler.importProgram(dirname, filename, model, sessionId); if (outModel!=null) { Hashtable<String, Object> out = new Hashtable<String, Object>(); out.put(OUTPUT_MODEL, outModel); return out; } return null; } /* private Hashtable<String, Object> actionImportPV(String sessionId, Hashtable<String, Object> input) throws JLIException { // String dirname = checkStringParameter(input, PARAM_DIRNAME, false); // String filename = checkStringParameter(input, PARAM_FILENAME, false); // String newName = checkStringParameter(input, PARAM_NEWNAME, false); // String newModelType = checkStringParameter(input, PARAM_NEWMODELTYPE, false); // // String outModel = intfHandler.importPV(dirname, filename, newName, newModelType, sessionId); // // if (outModel!=null) { // Hashtable<String, Object> out = new Hashtable<String, Object>(); // out.put(OUTPUT_MODEL, outModel); // return out; // } // return null; input.put(PARAM_TYPE, TYPE_PV); return actionImportFile(sessionId, input); } */ private Hashtable<String, Object> actionImportFile(String sessionId, Hashtable<String, Object> input) throws JLIException { String type = checkStringParameter(input, PARAM_TYPE, true); String dirname = checkStringParameter(input, PARAM_DIRNAME, false); String filename = checkStringParameter(input, PARAM_FILENAME, false); String newName = checkStringParameter(input, PARAM_NEWNAME, false); String newModelType = checkStringParameter(input, PARAM_NEWMODELTYPE, false); String outModel = null; if (TYPE_PV.equalsIgnoreCase(type)) outModel = intfHandler.importPV(dirname, filename, newName, newModelType, sessionId); else if (TYPE_STEP.equalsIgnoreCase(type)) outModel = intfHandler.importSTEP(dirname, filename, newName, newModelType, sessionId); else if (TYPE_IGES.equalsIgnoreCase(type)) outModel = intfHandler.importIGES(dirname, filename, newName, newModelType, sessionId); else if (TYPE_NEUTRAL.equalsIgnoreCase(type)) outModel = intfHandler.importNeutral(dirname, filename, newName, newModelType, sessionId); if (outModel!=null) { Hashtable<String, Object> out = new Hashtable<String, Object>(); out.put(OUTPUT_MODEL, outModel); return out; } return null; } }
47.248276
147
0.716976
f589ea433ee7fae989aca524e1bd98044d357990
2,928
package com.example.ratingapp.service; import com.example.ratingapp.model.Post; import com.example.ratingapp.model.User; import com.example.ratingapp.repository.PostRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Created by Bajtek on 27.05.2017. */ @Service @Transactional public class PostServiceImpl implements PostService { private static final int PAGE_SIZE = 3; @Autowired private PostRepository postRepository; @Override public void save(Post post) { // post.setLikes(0); // post.setDislikes(0); //post.setCategory(post.getCategory()); postRepository.save(post); } @Override public List<Post> getPostList() { return postRepository.findAll(); } @Override public Page<Post> getPostLog(Integer pageNumber) { PageRequest request = new PageRequest(pageNumber - 1, PAGE_SIZE); return postRepository.findAll(request); } @Override public Post findById(String id) { return postRepository.findOne(Long.parseLong(id)); } @Override public void addLike(Post post) { Post tmp = postRepository.findOne(post.getId()); tmp.setLikes(post.getLikes() + 1); postRepository.save(tmp); } @Override public void addDislike(Post post) { Post tmp = postRepository.findOne(post.getId()); tmp.setDislikes(post.getDislikes() + 1); postRepository.save(tmp); } @Override public List<Post> findByText(String searchText) { List<Post> list = new ArrayList<>(); List<Post> tmp = new ArrayList<>(); tmp = postRepository.findByTitle(searchText); for (Post p: tmp) { list.add(p); } return list; } @Override public List<Post> findByTitle(String searchText) { return postRepository.findByTitle(searchText); } @Override public List<Post> findByDescription(String searchText) { return postRepository.findByDescription(searchText); } @Override public void deletePostById(String id) { Post post = postRepository.findOne(Long.parseLong(id)); if(post != null) { postRepository.delete(post.getId()); } } @Override public void updatePost(Post post) { Post postTmp = postRepository.findOne(post.getId()); if(postTmp != null) { postTmp.setTitle(post.getTitle()); postTmp.setDescription(post.getDescription()); } postRepository.save(postTmp); } }
27.111111
73
0.665984
9706a7804ed43cd7177996fa3a53bedc8e276608
705
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.interactions.Actions; public class ContextMenuPage { private By clickableContextBox = By.id("hot-spot"); private WebDriver driver; public ContextMenuPage(WebDriver driver) { this.driver = driver; } public String getAlertText() { return driver.switchTo().alert().getText(); } public void contextClickHotSpot() { var actions = new Actions(driver); actions.moveToElement(driver.findElement(clickableContextBox)).contextClick().perform(); } public void alertClose() { driver.switchTo().alert().accept(); } }
22.03125
96
0.68227
819090fa9d85ea74402e3e26054282907b22975d
3,872
/**************************************************************** * 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.james.imap.encode; import java.io.IOException; import java.util.List; import org.apache.james.imap.api.ImapConstants; import org.apache.james.imap.api.Tag; import org.apache.james.imap.api.message.IdRange; import org.apache.james.imap.api.message.UidRange; import org.apache.james.imap.api.message.request.SearchResultOption; import org.apache.james.imap.message.response.ESearchResponse; import org.apache.james.mailbox.ModSeq; /** * Encoders IMAP4rev1 <code>ESEARCH</code> responses. */ public class ESearchResponseEncoder implements ImapResponseEncoder<ESearchResponse> { @Override public Class<ESearchResponse> acceptableMessages() { return ESearchResponse.class; } @Override public void encode(ESearchResponse response, ImapResponseComposer composer) throws IOException { Tag tag = response.getTag(); long min = response.getMinUid(); long max = response.getMaxUid(); long count = response.getCount(); IdRange[] all = response.getAll(); UidRange[] allUids = response.getAllUids(); boolean useUid = response.getUseUid(); ModSeq highestModSeq = response.getHighestModSeq(); List<SearchResultOption> options = response.getSearchResultOptions(); composer.untagged().message("ESEARCH").openParen().message("TAG").quote(tag.asString()).closeParen(); if (useUid) { composer.message(ImapConstants.UID); } if (min > -1 && options.contains(SearchResultOption.MIN)) { composer.message(SearchResultOption.MIN.name()).message(min); } if (max > -1 && options.contains(SearchResultOption.MAX)) { composer.message(SearchResultOption.MAX.name()).message(max); } if (options.contains(SearchResultOption.COUNT)) { composer.message(SearchResultOption.COUNT.name()).message(count); } if (!useUid && all != null && all.length > 0 && options.contains(SearchResultOption.ALL)) { composer.message(SearchResultOption.ALL.name()); composer.sequenceSet(all); } if (useUid && allUids != null && allUids.length > 0 && options.contains(SearchResultOption.ALL)) { composer.message(SearchResultOption.ALL.name()); composer.sequenceSet(allUids); } // Add the MODSEQ to the response if needed. // // see RFC4731 3.2. Interaction with CONDSTORE extension if (highestModSeq != null) { composer.message(ImapConstants.FETCH_MODSEQ); composer.message(highestModSeq.asLong()); } composer.end(); } }
45.552941
109
0.614669
c54319b5b4501bc4dac551aa67c74dbb6fa0ef37
361
package com.teamscale.test; import java.io.File; /** Base class that supports reading test-data files. */ public class TestDataBase { /** Read the given test-data file in the context of the current class's package. */ protected File useTestFile(String fileName) { return new File(new File("test-data", getClass().getPackage().getName()), fileName); } }
27.769231
86
0.728532
a9efc07decbbc23e10cb5d3d2d034b84b486e1a4
2,259
package com.jack.reader.bean; import java.util.List; /** * <p>Title:${type_name}</p> * <p>Description:</p> * <p>Company:北京昊唐科技有限公司</p> * * @author 徐俊 * @date zhoujunxia on 2019/4/23 11:29 */ public class ClassIndexBean { private int errno; private String msg; private ClassIndexData data; public int getErrno() { return errno; } public void setErrno(int errno) { this.errno = errno; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public ClassIndexData getData() { return data; } public void setData(ClassIndexData data) { this.data = data; } public static class ClassIndexData { private List<BannerBean.BannerData.NewBanner> banner; private List<ClassIndexType> retbooktype; public List<BannerBean.BannerData.NewBanner> getBanner() { return banner; } public void setBanner(List<BannerBean.BannerData.NewBanner> banner) { this.banner = banner; } public List<ClassIndexType> getRetbooktype() { return retbooktype; } public void setRetbooktype(List<ClassIndexType> retbooktype) { this.retbooktype = retbooktype; } public static class ClassIndexType { private String id; private String book_typename; private String img; private String num; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBook_typename() { return book_typename; } public void setBook_typename(String book_typename) { this.book_typename = book_typename; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } } } }
22.147059
77
0.534307
40ab12c6c0015cf0c30e288382d196f2a57cc6a4
1,939
package com.lwd.qjtv.mvp.ui.holder; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.jess.arms.base.App; import com.jess.arms.base.BaseHolder; import com.jess.arms.di.component.AppComponent; import com.jess.arms.widget.imageloader.ImageLoader; import com.lwd.qjtv.R; import com.lwd.qjtv.mvp.model.entity.MatchCollectionNewListBean; import com.lwd.qjtv.mvp.ui.adapter.MatchCollectionAdapter; import java.util.List; import butterknife.BindView; /** * Email:[email protected] * Created by ZhengQian on 2017/6/5. */ public class MatchCollectionListItemHolder extends BaseHolder<MatchCollectionNewListBean.DataBeanX.MatchListBean> { private AppComponent mAppComponent; private ImageLoader mImageLoader;//用于加载图片的管理类,默认使用glide,使用策略模式,可替换框架 @BindView(R.id.item_matchcollection_list_tv) TextView listTv; @BindView(R.id.item_matchcollection_list_rv) RecyclerView listRv; public MatchCollectionListItemHolder(View itemView) { super(itemView); //可以在任何可以拿到Application的地方,拿到AppComponent,从而得到用Dagger管理的单例对象 mAppComponent = ((App) itemView.getContext().getApplicationContext()).getAppComponent(); mImageLoader = mAppComponent.imageLoader(); } @Override public void setData(MatchCollectionNewListBean.DataBeanX.MatchListBean data, int position) { listTv.setText(data.getMatch_name() == null ? "" : data.getMatch_name()); List<MatchCollectionNewListBean.DataBeanX.MatchListBean.DataBean> data1 = data.getData(); MatchCollectionAdapter matchCollectionAdapter = new MatchCollectionAdapter(data1); listRv.setLayoutManager(new LinearLayoutManager(itemView.getContext(), LinearLayoutManager.VERTICAL, false)); listRv.setAdapter(matchCollectionAdapter); } @Override protected void onRelease() { } }
35.254545
117
0.771016
f74b9975a3dcff4a8fc55f9fc5e9d4da0668f52c
1,764
package co.ex.coffeeforcodeapp.Api.ShoppingCart; import android.graphics.Bitmap; public class DtoShoppingCart { int cd_prod, qt_prod, length; String email_user, nm_prod, img_prod; Bitmap img_prod_cart; float full_price_prod; float price_unit_prod; public DtoShoppingCart(){} public Bitmap getImg_prod_cart() { return img_prod_cart; } public void setImg_prod_cart(Bitmap img_prod_cart) { this.img_prod_cart = img_prod_cart; } public float getPrice_unit_prod() { return price_unit_prod; } public void setPrice_unit_prod(float price_unit_prod) { this.price_unit_prod = price_unit_prod; } public float getFull_price_prod() { return full_price_prod; } public void setFull_price_prod(float full_price_prod) { this.full_price_prod = full_price_prod; } public String getNm_prod() { return nm_prod; } public void setNm_prod(String nm_prod) { this.nm_prod = nm_prod; } public String getImg_prod() { return img_prod; } public void setImg_prod(String img_prod) { this.img_prod = img_prod; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int getCd_prod() { return cd_prod; } public void setCd_prod(int cd_prod) { this.cd_prod = cd_prod; } public int getQt_prod() { return qt_prod; } public void setQt_prod(int qt_prod) { this.qt_prod = qt_prod; } public String getEmail_user() { return email_user; } public void setEmail_user(String email_user) { this.email_user = email_user; } }
20.511628
59
0.641156
51ac93e00147ddf9035a0775534776d3eb6e4b5b
1,707
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.physics.events; import org.joml.Vector3f; import org.terasology.engine.entitySystem.entity.EntityRef; import org.terasology.engine.entitySystem.event.AbstractConsumableEvent; import org.terasology.engine.math.Side; import org.terasology.engine.network.BroadcastEvent; /** * Impact event is called whenever an item has enough speed to detect * penetration of a block or entity in the next frame. It computes the * reflection angle, speed and the next position the item should be in. */ @BroadcastEvent public class ImpactEvent extends AbstractConsumableEvent { private Vector3f impactPoint; private Vector3f impactNormal; private Vector3f impactSpeed; private float travelDistance; private EntityRef impactEntity; protected ImpactEvent() { } public ImpactEvent(Vector3f impactPoint, Vector3f impactNormal, Vector3f impactSpeed, float travelDistance, EntityRef impactEntity) { this.impactPoint = impactPoint; this.impactNormal = impactNormal; this.impactSpeed = impactSpeed; this.travelDistance = travelDistance; this.impactEntity = impactEntity; } public Vector3f getImpactPoint() { return impactPoint; } public Vector3f getImpactNormal() { return impactNormal; } public Vector3f getImpactSpeed() { return impactSpeed; } public float getTravelDistance() { return travelDistance; } public EntityRef getImpactEntity() { return impactEntity; } public Side getSide() { return Side.inDirection(impactNormal); } }
28.45
137
0.727592
0a99de2ebfceed982be6453e79749b2a3b3ac19a
155
package org.woehlke.computer.kurzweil.tabs.simulatedevolution; import java.io.Serializable; public interface SimulatedEvolution extends Serializable { }
22.142857
62
0.845161
08892a166800c92186d9df59a4c2be4bd1f7541e
238
package papers.ADFDPlus.TestClasses; /** * Point Fault Domain example for two arguments * @author (Mian and Manuel) */ public class TwoDimensionalPointFailureDomain{ public static void pointErrors (int x, int y){ int z = x/y; } }
19.833333
47
0.726891
85222d14c1a8a2cb662352bacecdd215e04b3d51
8,743
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|ddl package|; end_package begin_import import|import name|java operator|. name|io operator|. name|Serializable import|; end_import begin_import import|import name|java operator|. name|lang operator|. name|reflect operator|. name|Constructor import|; end_import begin_import import|import name|java operator|. name|lang operator|. name|reflect operator|. name|Modifier import|; end_import begin_import import|import name|java operator|. name|lang operator|. name|reflect operator|. name|ParameterizedType import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|Task import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|parse operator|. name|ExplainConfiguration operator|. name|AnalyzeState import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|api operator|. name|StageType import|; end_import begin_import import|import name|org operator|. name|reflections operator|. name|Reflections import|; end_import begin_comment comment|/** * DDLTask implementation. **/ end_comment begin_class annotation|@ name|SuppressWarnings argument_list|( literal|"rawtypes" argument_list|) specifier|public specifier|final class|class name|DDLTask extends|extends name|Task argument_list|< name|DDLWork argument_list|> implements|implements name|Serializable block|{ specifier|private specifier|static specifier|final name|long name|serialVersionUID init|= literal|1L decl_stmt|; specifier|private specifier|static specifier|final name|Map argument_list|< name|Class argument_list|< name|? extends|extends name|DDLDesc argument_list|> argument_list|, name|Class argument_list|< name|? extends|extends name|DDLOperation argument_list|> argument_list|> name|DESC_TO_OPARATION init|= operator|new name|HashMap argument_list|<> argument_list|() decl_stmt|; static|static block|{ name|Set argument_list|< name|Class argument_list|< name|? extends|extends name|DDLOperation argument_list|> argument_list|> name|operationClasses init|= operator|new name|Reflections argument_list|( literal|"org.apache.hadoop.hive.ql.ddl" argument_list|) operator|. name|getSubTypesOf argument_list|( name|DDLOperation operator|. name|class argument_list|) decl_stmt|; for|for control|( name|Class argument_list|< name|? extends|extends name|DDLOperation argument_list|> name|operationClass range|: name|operationClasses control|) block|{ if|if condition|( name|Modifier operator|. name|isAbstract argument_list|( name|operationClass operator|. name|getModifiers argument_list|() argument_list|) condition|) block|{ continue|continue; block|} name|ParameterizedType name|parameterizedType init|= operator|( name|ParameterizedType operator|) name|operationClass operator|. name|getGenericSuperclass argument_list|() decl_stmt|; annotation|@ name|SuppressWarnings argument_list|( literal|"unchecked" argument_list|) name|Class argument_list|< name|? extends|extends name|DDLDesc argument_list|> name|descClass init|= operator|( name|Class argument_list|< name|? extends|extends name|DDLDesc argument_list|> operator|) name|parameterizedType operator|. name|getActualTypeArguments argument_list|() index|[ literal|0 index|] decl_stmt|; name|DESC_TO_OPARATION operator|. name|put argument_list|( name|descClass argument_list|, name|operationClass argument_list|) expr_stmt|; block|} block|} annotation|@ name|Override specifier|public name|boolean name|requireLock parameter_list|() block|{ return|return name|this operator|. name|work operator|!= literal|null operator|&& name|this operator|. name|work operator|. name|getNeedLock argument_list|() return|; block|} annotation|@ name|Override specifier|public name|int name|execute parameter_list|() block|{ if|if condition|( name|context operator|. name|getExplainAnalyze argument_list|() operator|== name|AnalyzeState operator|. name|RUNNING condition|) block|{ return|return literal|0 return|; block|} try|try block|{ name|DDLDesc name|ddlDesc init|= name|work operator|. name|getDDLDesc argument_list|() decl_stmt|; if|if condition|( name|DESC_TO_OPARATION operator|. name|containsKey argument_list|( name|ddlDesc operator|. name|getClass argument_list|() argument_list|) condition|) block|{ name|DDLOperationContext name|ddlOperationContext init|= operator|new name|DDLOperationContext argument_list|( name|conf argument_list|, name|context argument_list|, name|this argument_list|, operator|( name|DDLWork operator|) name|work argument_list|, name|queryState argument_list|, name|queryPlan argument_list|, name|console argument_list|) decl_stmt|; name|Class argument_list|< name|? extends|extends name|DDLOperation argument_list|> name|ddlOpertaionClass init|= name|DESC_TO_OPARATION operator|. name|get argument_list|( name|ddlDesc operator|. name|getClass argument_list|() argument_list|) decl_stmt|; name|Constructor argument_list|< name|? extends|extends name|DDLOperation argument_list|> name|constructor init|= name|ddlOpertaionClass operator|. name|getConstructor argument_list|( name|DDLOperationContext operator|. name|class argument_list|, name|ddlDesc operator|. name|getClass argument_list|() argument_list|) decl_stmt|; name|DDLOperation name|ddlOperation init|= name|constructor operator|. name|newInstance argument_list|( name|ddlOperationContext argument_list|, name|ddlDesc argument_list|) decl_stmt|; return|return name|ddlOperation operator|. name|execute argument_list|() return|; block|} else|else block|{ throw|throw operator|new name|IllegalArgumentException argument_list|( literal|"Unknown DDL request: " operator|+ name|ddlDesc operator|. name|getClass argument_list|() argument_list|) throw|; block|} block|} catch|catch parameter_list|( name|Throwable name|e parameter_list|) block|{ name|failed argument_list|( name|e argument_list|) expr_stmt|; return|return literal|1 return|; block|} block|} specifier|private name|void name|failed parameter_list|( name|Throwable name|e parameter_list|) block|{ while|while condition|( name|e operator|. name|getCause argument_list|() operator|!= literal|null operator|&& name|e operator|. name|getClass argument_list|() operator|== name|RuntimeException operator|. name|class condition|) block|{ name|e operator|= name|e operator|. name|getCause argument_list|() expr_stmt|; block|} name|setException argument_list|( name|e argument_list|) expr_stmt|; name|LOG operator|. name|error argument_list|( literal|"Failed" argument_list|, name|e argument_list|) expr_stmt|; block|} annotation|@ name|Override specifier|public name|StageType name|getType parameter_list|() block|{ return|return name|StageType operator|. name|DDL return|; block|} annotation|@ name|Override specifier|public name|String name|getName parameter_list|() block|{ return|return literal|"DDL" return|; block|} comment|/* uses the authorizer from SessionState will need some more work to get this to run in parallel, however this should not be a bottle neck so might not need to parallelize this. */ annotation|@ name|Override specifier|public name|boolean name|canExecuteInParallel parameter_list|() block|{ return|return literal|false return|; block|} block|} end_class end_unit
14.547421
813
0.799954
1e0e258f7cad7d6486c9de0597f762c65781ab71
1,424
/* Copyright 2016 Goldman Sachs. 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.gs.fw.common.mithra.test.domain; public class Trial extends TrialAbstract { public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TrialAbstract)) { return false; } final TrialAbstract trialAbstract = (TrialAbstract) o; if (!getDescription().equals(trialAbstract.getDescription())) { return false; } if (!getTrialId().equals(trialAbstract.getTrialId())) { return false; } return true; } public int hashCode() { int result; result = getTrialId().hashCode(); result = 29 * result + getDescription().hashCode(); return result; } }
24.551724
70
0.602528
442a2fc8d2b91fbf682e776684adbbf318203bdb
1,142
package com.siyeh.ig.logging; import com.intellij.codeInspection.LocalInspectionTool; import com.siyeh.ig.LightInspectionTestCase; public class StringConcatenationArgumentToLogCallInspectionTest extends LightInspectionTestCase { @Override protected LocalInspectionTool getInspection() { return new StringConcatenationArgumentToLogCallInspection(); } @Override protected String[] getEnvironmentClasses() { return new String[]{ "package org.slf4j; public interface Logger { void debug(String format); }", "package org.slf4j; public class LoggerFactory { public static Logger getLogger(Class clazz) { return null; }}"}; } public void testBasic() { doTest("import org.slf4j.*;\n" + "class X {\n" + " void foo() {\n" + " Logger logger = LoggerFactory.getLogger(X.class);\n" + " final String CONST = \"const\";\n" + " String var = \"var\";\n" + " logger./*Non-constant string concatenation as argument to 'debug()' logging call*/debug/**/(\"string \" + var + CONST);\n" + " }\n" + "}" ); } }
36.83871
140
0.635727
590fed33ad6c9f6fd5e0218fdae4f6679dcb78ee
22,891
package com.guideme.guideme.home; import android.Manifest; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.graphics.Color; import android.location.Location; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QuerySnapshot; import com.guideme.guideme.R; import com.guideme.guideme.api.DataParser; import com.guideme.guideme.api.DownloadUrl; import com.guideme.guideme.model.ActiveUser; import com.guideme.guideme.model.Category; import com.guideme.guideme.model.User; import com.guideme.guideme.nearest.NearestPlaceActivity; import com.guideme.guideme.utils.ToastUtils; import com.karumi.dexter.Dexter; import com.karumi.dexter.MultiplePermissionsReport; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.multi.MultiplePermissionsListener; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatSpinner; import androidx.appcompat.widget.Toolbar; import androidx.core.app.NotificationCompat; import androidx.core.content.ContextCompat; import io.nlopez.smartlocation.OnLocationUpdatedListener; import io.nlopez.smartlocation.SmartLocation; import io.nlopez.smartlocation.location.config.LocationAccuracy; import io.nlopez.smartlocation.location.config.LocationParams; public class HomeActivity extends AppCompatActivity implements OnMapReadyCallback { private static final String TAG = HomeActivity.class.getName(); private GoogleMap mMap; private int radius = 500; private boolean mLocationPermissionGranted; private Circle circle; private LocationCallback mLocationCallback; private Location lastLocation; private Marker currentUserLocationMarker; private User user; private CollectionReference mActiveUserCollectionRef; private List<HashMap<String, String>> nearByPlacesList; private Category category = Category.TEMPLE; private HashMap<String, Marker> currentMarkers = new HashMap<>(); private Polyline shortestPath; private AppCompatSpinner mCategorySpinner; private OnLocationUpdatedListener locationUpdatedListener = new OnLocationUpdatedListener() { @Override public void onLocationUpdated(Location location) { if (location == null) return; updateMap(location); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); Bundle extras = getIntent().getExtras(); if (extras != null) { user = (User) extras.getSerializable("user"); getSupportActionBar().setSubtitle("Welcome, " + user.getName()); } FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { RadiusFragment radiusFragment = RadiusFragment.newInstance(); radiusFragment.registerActionCallback(new RadiusFragment.OnActionCallBack() { @Override public void onPostButtonClicked(View v, int r) { Log.d(TAG, "Radius set to: " + radius); radius = r; updateRadius(); } }); radiusFragment.show(getSupportFragmentManager(), "Radius Fragment"); } }); mCategorySpinner = findViewById(R.id.category_spinner); mCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { category = (Category) mCategorySpinner.getSelectedItem(); Log.d(TAG, "Category selected: " + category); if (lastLocation != null) fetchNearbyPlaces(lastLocation); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mActiveUserCollectionRef = FirebaseFirestore.getInstance().collection("active_users"); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); initCategorySpinner(); } @Override protected void onSaveInstanceState(Bundle outState) { if (user != null) outState.putSerializable("user", user); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { Serializable user = savedInstanceState.getSerializable("user"); if (user != null) { this.user = (User) user; getSupportActionBar().setSubtitle("Welcome, " + this.user.getName()); } super.onRestoreInstanceState(savedInstanceState); } private void initCategorySpinner() { List<Category> categories = new ArrayList<>(); categories.add(Category.TEMPLE); categories.add(Category.ZOO); categories.add(Category.STADIUM); categories.add(Category.CHURCH); categories.add(Category.MUSEUM); categories.add(Category.MOSQUE); categories.add(Category.NIGHTCLUB); categories.add(Category.SYNAGOGUE); ArrayAdapter<Category> dataAdapter = new ArrayAdapter<>(this, R.layout.spinner_item, categories); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner mCategorySpinner.setAdapter(dataAdapter); mCategorySpinner.setSelection(Category.TEMPLE.ordinal()); } private void updateMap(Location location) { Log.d(TAG, "Location lat:" + location.getLatitude() + " lon:" + location.getLongitude()); if (lastLocation == null || lastLocation.distanceTo(location) > 20.0) { lastLocation = location; updateCircle(location); updateCurrentLocationMarker(location); fetchNearbyPlaces(location); } } private void fetchNearbyPlaces(Location location) { Log.d(TAG, "fetchNearbyPlaces: lat-" + location.getLatitude() + " lon-" + location.getLongitude()); GetNearbyPlaces getNearbyPlaces = new GetNearbyPlaces(); String url = getUrl(location.getLatitude(), location.getLongitude(), category.getValue()); getNearbyPlaces.execute(url); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker marker) { HashMap<String, String> markerPlace = (HashMap<String, String>) marker.getTag(); addActiveUserInfo(markerPlace, marker); Intent placeDetailIntent = getPlaceDetailIntent(markerPlace); startActivity(placeDetailIntent); } }); } private void updateCurrentLocationMarker(Location location) { LatLng current = new LatLng(location.getLatitude(), location.getLongitude()); if (currentUserLocationMarker != null) { currentUserLocationMarker.remove(); } currentUserLocationMarker = mMap.addMarker(new MarkerOptions().position(current).title("Current Location")); mMap.moveCamera(CameraUpdateFactory.newLatLng(current)); CameraUpdate zoom = CameraUpdateFactory.zoomTo(13); mMap.animateCamera(zoom); } private void updateCircle(Location location) { Log.d(TAG, "update circle"); LatLng current = new LatLng(location.getLatitude(), location.getLongitude()); if (circle == null) { Log.d(TAG, "Adding circle"); circle = mMap.addCircle(new CircleOptions() .center(current) .radius(radius) .strokeColor(ContextCompat.getColor(HomeActivity.this, R.color.colorPrimary)) .fillColor(ContextCompat.getColor(HomeActivity.this, R.color.radiusColor))); } else { circle.setCenter(current); } } private void updateRadius() { if (circle != null) { circle.setRadius(radius); fetchNearbyPlaces(lastLocation); } } private void requestPermission() { Dexter.withActivity(this) .withPermissions( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) .withListener(new MultiplePermissionsListener() { @Override public void onPermissionsChecked(MultiplePermissionsReport report) { if (report.areAllPermissionsGranted()) { mLocationPermissionGranted = true; startLocationUpdates(); } } @Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) { token.continuePermissionRequest(); } }).check(); } @Override protected void onResume() { super.onResume(); requestPermission(); } @Override protected void onPause() { super.onPause(); stopLocationUpdates(); } private void stopLocationUpdates() { SmartLocation.with(this).location().stop(); } private void startLocationUpdates() { if (SmartLocation.with(this).location().state().isNetworkAvailable()) { SmartLocation.with(this) .location() .config(new LocationParams.Builder() .setAccuracy(LocationAccuracy.HIGH) .setDistance(10) .setInterval(1000) .build()) .start(locationUpdatedListener); } else { ToastUtils.show(this, "Please enable location service for Internet"); } } private String getUrl(double latitide, double longitude, String type) { //去 https://developers.google.com/places/web-service/search 看文件 StringBuilder googleURL = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"); googleURL.append("location=" + latitide + "," + longitude); googleURL.append("&radius=" + radius); googleURL.append("&type=" + type); googleURL.append("&sensor=true"); googleURL.append("&key=" + "AIzaSyC_bxHoTmjKPhmiiIdSRmYVQ_l5x2Froyw"); //AIzaSyC_bxHoTmjKPhmiiIdSRmYVQ_l5x2Froyw Log.d(TAG, "url = " + googleURL.toString()); return googleURL.toString(); } private void resetCurrentMarkers() { Set<String> keys = currentMarkers.keySet(); for (String key : keys) { currentMarkers.get(key).remove(); } } private void addActiveUserInfo(final HashMap<String, String> shortestPlace, final Marker marker) { String place_id = shortestPlace.get("id"); mActiveUserCollectionRef .document(place_id) .collection("users") .get() .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot snapshot) { int size = snapshot.getDocuments().size(); int activeUsers = snapshot.getDocuments().size(); shortestPlace.put("active_user", String.valueOf(activeUsers)); marker.setSnippet(marker.getSnippet() + "," + "Active User: " + String.valueOf(activeUsers)); } }); } private void removeFromActiveUser(HashMap<String, String> shortestPlace) { String place_id = shortestPlace.get("id"); ActiveUser activeUser = new ActiveUser(); activeUser.placeID = place_id; activeUser.userID = user.getId(); mActiveUserCollectionRef.document(place_id) .collection("users") .document(user.getId()) .delete() .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "onSuccess"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { Log.e(TAG, "onFailure", e); } }); } private void addActiveUser(HashMap<String, String> shortestPlace) { String place_id = shortestPlace.get("id"); ActiveUser activeUser = new ActiveUser(); activeUser.placeID = place_id; activeUser.userID = user.getId(); mActiveUserCollectionRef .document(place_id) .collection("users") .document(user.getId()) .set(activeUser) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void v) { Log.d(TAG, "onSuccess"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { Log.e(TAG, "onFailure", e); } }); } private void drawPathToNearestPlace(HashMap<String, String> shortestPlace) { final double toLat = Double.parseDouble(shortestPlace.get("lat")); final double toLan = Double.parseDouble(shortestPlace.get("lng")); if (shortestPath != null) shortestPath.remove(); shortestPath = mMap.addPolyline(new PolylineOptions() .add(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), new LatLng(toLat, toLan)) .width(5) .color(Color.RED)); } private void sendNotification(HashMap<String, String> shortestPlace) { Log.d(TAG, "Shortest path: " + shortestPlace.get("place_name")); final String notification_title = shortestPlace.get("place_name"); final String activeUser = shortestPlace.get("active_user"); final String address = shortestPlace.get("vicinity"); final String notification_msg = "Shortest place: " + address; NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); String NOTIFICATION_CHANNEL_ID = "channel_id_01"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH); // Configure the notification channel. notificationChannel.setDescription("Channel description"); notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.BLUE); notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000}); notificationChannel.enableVibration(true); notificationManager.createNotificationChannel(notificationChannel); } Intent intent = getPlaceDetailIntent(shortestPlace); final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); notificationBuilder .setAutoCancel(true) .setDefaults(Notification.DEFAULT_ALL) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.drawable.ic_launcher_background) .setPriority(Notification.PRIORITY_MAX) .setContentTitle(notification_title) .setContentText(notification_msg) .setContentInfo("Info") .setContentIntent(pendingIntent); int mNotificationId = (int) System.currentTimeMillis(); notificationManager.notify(mNotificationId, notificationBuilder.build()); } private Intent getPlaceDetailIntent(HashMap<String, String> markerPlace) { Intent intent = new Intent(this, NearestPlaceActivity.class); intent.putExtra("place_id", markerPlace.get("id")); intent.putExtra("place_title", markerPlace.get("place_name")); intent.putExtra("address", markerPlace.get("vicinity")); intent.putExtra("icon", markerPlace.get("icon")); intent.putExtra("rating", markerPlace.get("rating")); intent.putExtra("place_lat", Double.parseDouble(markerPlace.get("lat"))); intent.putExtra("place_lng", Double.parseDouble(markerPlace.get("lng"))); intent.putExtra("current_lat", lastLocation.getLatitude()); intent.putExtra("current_lan", lastLocation.getLongitude()); intent.putExtra("user", user); intent.putExtra("active_user", markerPlace.get("active_user")); return intent; } class GetNearbyPlaces extends AsyncTask<Object, String, String> { private String googleplaceData, url; @Override protected String doInBackground(Object... objects) { Log.d(TAG, "fetching data"); url = (String) objects[0]; DownloadUrl downloadUrl = new DownloadUrl(); try { googleplaceData = downloadUrl.ReadTheURL(url); } catch (IOException e) { e.printStackTrace(); } return googleplaceData; } @Override protected void onPostExecute(String s) { Log.d(TAG, "Data received"); DataParser dataParser = new DataParser(); nearByPlacesList = dataParser.parse(s); if (nearByPlacesList != null && nearByPlacesList.size() > 0) { resetCurrentMarkers(); displayNearbyPlaces(nearByPlacesList); } } private void displayNearbyPlaces(List<HashMap<String, String>> nearByPlacesList) { Log.d(TAG, "displayNearbyPlaces: size-" + nearByPlacesList.size()); float shortestDistance = 0; int shortDistanceIndex = -1; for (int i = 0; i < nearByPlacesList.size(); i++) { HashMap<String, String> googleNearbyPlace = nearByPlacesList.get(i); String placeId = googleNearbyPlace.get("id"); String nameOfPlace = googleNearbyPlace.get("place_name"); String vicinity = googleNearbyPlace.get("vicinity"); double lat = Double.parseDouble(googleNearbyPlace.get("lat")); double lng = Double.parseDouble(googleNearbyPlace.get("lng")); LatLng latLng = new LatLng(lat, lng); Location location = new Location(nameOfPlace); location.setLatitude(lat); location.setLongitude(lng); final int distance = (int) location.distanceTo(lastLocation); Marker marker = mMap.addMarker(new MarkerOptions() .position(latLng) .title(nameOfPlace + ": " + vicinity) .snippet("Distance: " + distance + "M") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))); marker.setTag(googleNearbyPlace); if (distance < 200) { addActiveUser(googleNearbyPlace); } else { removeFromActiveUser(googleNearbyPlace); } if (i == 0) { shortestDistance = distance; shortDistanceIndex = i; } else { if (distance < shortestDistance) { shortestDistance = distance; shortDistanceIndex = i; } } addActiveUserInfo(googleNearbyPlace, marker); currentMarkers.put(placeId, marker); Log.d(TAG, "place = " + nameOfPlace); } if (shortDistanceIndex != -1) { drawPathToNearestPlace(nearByPlacesList.get(shortDistanceIndex)); sendNotification(nearByPlacesList.get(shortDistanceIndex)); } mMap.moveCamera(CameraUpdateFactory.newLatLng( new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()))); CameraUpdate zoom = CameraUpdateFactory.zoomTo(15); mMap.animateCamera(zoom); } } }
40.876786
160
0.628369
d4e66b16486d349771c3e36ecf81e115c0b549e6
6,585
package com.kaltiz.dsTitle.storage; import com.kaltiz.dsTitle.TitleManager; import denniss17.dsTitle.DSTitle; import denniss17.dsTitle.objects.Title; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import java.sql.*; import java.util.UUID; import java.util.logging.Level; public class SQLTitleStorage extends TitleStorage { protected DatabaseType driver; protected String url = ""; protected String username = ""; protected String password = ""; private DSTitle plugin; private Connection conn = null; public SQLTitleStorage(DSTitle plugin, TitleManager manager) throws SQLException { super(plugin,manager); this.plugin = plugin; this.driver = DatabaseType.match(plugin.getConfig().getString(("storage.database.driver"))); if(this.driver!=null) { if(this.driver.equals(DatabaseType.SQLITE)){ this.url = "jdbc:sqlite:" + plugin.getDataFolder().getAbsolutePath() + System.getProperty("file.separator") + plugin.getConfig().getString("storage.database.url"); }else{ if(plugin.getConfig().getString("storage.database.autoReconnect").equalsIgnoreCase("true")) this.url = "jdbc:" + plugin.getConfig().getString("storage.database.url") + plugin.getConfig().getString("storage.database.database") + "?useSSL=" + plugin.getConfig().getString("storage.database.useSSL") + "&autoReconnect=true"; else this.url = "jdbc:" + plugin.getConfig().getString("storage.database.url") + plugin.getConfig().getString("storage.database.database") + "?useSSL=" + plugin.getConfig().getString("storage.database.useSSL"); } this.username = plugin.getConfig().getString("storage.database.username"); this.password = plugin.getConfig().getString("storage.database.password"); if (!loadDriver()) { throw new SQLException("Couldn't load driver"); } this.conn = getConnection(); if (conn==null) { throw new SQLException("Couldn't connect to the database"); } // Create table String qry = "CREATE TABLE IF NOT EXISTS `players` (`uuid` VARCHAR(64) NOT NULL PRIMARY KEY, `prefix` VARCHAR(32), `suffix` VARCHAR(32));"; Statement stmt = this.conn.createStatement(); stmt.execute(qry); }else { plugin.getLogger().info("Database needs a type set. Possible values: H2, MYSQL, POSTGRE, SQLITE"); } } private boolean loadDriver() { try { this.getClass().getClassLoader().loadClass(this.driver.driver).newInstance(); return true; } catch (IllegalAccessException e) { // Constructor is private, OK for DriverManager contract return true; } catch (Exception e) { return false; } } private Connection getConnection() throws SQLException{ /*if (conn != null) { // Make a dummy query to check the connection is alive. try { if (conn.isClosed()) { conn = null; } else { conn.prepareStatement("SELECT 1;").execute(); } } catch (SQLException ex) { } }*/ if (conn == null || conn.isClosed()) { conn = (username.isEmpty() && password.isEmpty()) ? DriverManager.getConnection(url) : DriverManager.getConnection(url, username, password); } // The connection could be null here (!) return conn; } public void closeConnection() throws SQLException{ if (conn != null && !conn.isClosed()) conn.close(); } @Override public void loadTitlesPlayer(OfflinePlayer target) { String prefix = plugin.getTitleManager().titlesConfig.getDefaultPrefix(); String suffix = plugin.getTitleManager().titlesConfig.getDefaultSuffix(); String qry = "SELECT * FROM `players` WHERE `uuid` = ?;"; try { PreparedStatement stmt = this.getConnection().prepareStatement(qry); stmt.setString(1, target.getUniqueId().toString()); ResultSet result = stmt.executeQuery(); if(result.next()) { prefix = result.getString("prefix"); suffix = result.getString("suffix"); } } catch (SQLException ex) { plugin.getLogger().log(Level.SEVERE,"Could not load titles of player " + target.getName()); plugin.getLogger().log(Level.SEVERE,"Reason: " + ex.getMessage()); } manager.setPlayerPrefix(prefix, target); manager.setPlayerSuffix(suffix, target); } @Override public void saveTitlesPlayer(OfflinePlayer target) { Title p = manager.getPlayerPrefix(target); Title s = manager.getPlayerSuffix(target); Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> saveAsync(p, s, target.getUniqueId())); } @SuppressWarnings("resource") private void saveAsync(Title p, Title s, UUID id) { String prefix = p == null ? null : p.name; String suffix = s == null ? null : s.name; // Check if the Player has an Existing Row try{ String existing; String qry = "SELECT `uuid` FROM `players` WHERE `uuid` = ?;"; PreparedStatement stmt = this.conn.prepareStatement(qry); stmt.setString(1, id.toString()); ResultSet result = stmt.executeQuery(); existing = result.next() ? result.getString("uuid") : null; stmt.close(); if(existing != null){ stmt = this.getConnection().prepareStatement("UPDATE `players` SET `prefix` = ?, `suffix` = ? WHERE `uuid` = ?;"); stmt.setString(1, prefix); stmt.setString(2, suffix); stmt.setString(3, id.toString()); }else{ stmt = this.getConnection().prepareStatement("INSERT INTO `players` VALUES (?, ?, ?);"); stmt.setString(1, id.toString()); stmt.setString(2, prefix); stmt.setString(3, suffix); } stmt.executeUpdate(); stmt.close(); } catch (SQLException ex) { plugin.getLogger().log(Level.SEVERE,"Could not save titles of player " + id.toString()); plugin.getLogger().log(Level.SEVERE,"Reason: " + ex.getMessage()); } } }
39.196429
243
0.58861
fcc06ab448dd121317cbfb37fa3c0fe79f3a71bb
90
package com.example.async.cdi_events.entity; public class Specification { // ... }
11.25
44
0.688889
060eae4e49a858349c4475b7d62f6c39b50bb647
1,496
package jp.gr.java_conf.ya.yumura.Twitter; // Copyright (c) 2013-2017 YA <[email protected]> All rights reserved. --><!-- This software includes the work that is distributed in the Apache License 2.0 import android.support.v7.util.SortedList; import twitter4j.Status; public final class BinarySearchUtil { public static final int binary_search_time(final long needle, final SortedList<Status> tweets, int position) { int low = (position > -1) ? position : 0; int high = (tweets.size() > 1) ? (tweets.size() - 1) : 0; int mid = (low + high) / 2, preMid = -1; while (low <= high) { mid = (low + high) / 2; if (mid == preMid) { return mid; } else if (needle > tweets.get(mid).getCreatedAt().getTime()) { high = mid + 1; } else { low = mid - 1; } preMid = mid; } return mid; } public static final int binary_search_id(final long needle, final SortedList<Status> tweets) { int low = 0; int high = tweets.size() - 1; int mid = (low + high) / 2; while (low <= high) { mid = (low + high) / 2; if (needle == tweets.get(mid).getId()) { return mid; } else if (needle > tweets.get(mid).getId()) { high = mid - 1; } else { low = mid + 1; } } return mid; } }
34
205
0.511364
f8a514287b43ac9f16c2dc0f50017ebcd2964117
2,676
/* An abbreviation of a word follows the form <first letter><number><last letter>. Below are some examples of word abbreviations: a) it --> it (no abbreviation) 1 b) d|o|g --> d1g 1 1 1 1---5----0----5--8 c) i|nternationalizatio|n --> i18n 1 1---5----0 d) l|ocalizatio|n --> l10n Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. Example: Given dictionary = [ "deer", "door", "cake", "card" ] isUnique("dear") -> false isUnique("cart") -> true isUnique("cane") -> false isUnique("make") -> true */ public class ValidWordAbbr { HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();//用list作为值!! public ValidWordAbbr(String[] dictionary) { int size = dictionary.length; for(int i = 0; i < size; i++) { if(dictionary[i].length() <= 2) { if(!hm.containsKey(dictionary[i])) { ArrayList<String> al = new ArrayList<String>(); al.add(dictionary[i]); hm.put(dictionary[i], al); } } else { String tmp = dictionary[i].charAt(0) + "" + (dictionary[i].length() - 2) + "" + dictionary[i].charAt(dictionary[i].length() - 1); if(!hm.containsKey(tmp)) { ArrayList<String> al = new ArrayList<String>(); al.add(dictionary[i]); hm.put(tmp, al); } else { ArrayList<String> al = hm.get(tmp); if(!al.contains(dictionary[i])) { al.add(dictionary[i]); } } } } } public boolean isUnique(String word) { String tmp; if(word.length() <= 2) { tmp = word; } else { tmp = word.charAt(0) + "" + (word.length() - 2) + "" + word.charAt(word.length() - 1); } if(hm.containsKey(tmp)) { ArrayList<String> al = hm.get(tmp); if(al.contains(word) && al.size() == 1) {//如果一个词的结构对应的词有多个词,则返回false,如果这个词对应的结构所对应的词只有一个,返回true return true; } else { return false; } } else { return true; } } } // Your ValidWordAbbr object will be instantiated and called as such: // ValidWordAbbr vwa = new ValidWordAbbr(dictionary); // vwa.isUnique("Word"); // vwa.isUnique("anotherWord");
34.307692
201
0.508221
79c1ebd3b3ef723f5b0848eafd5c50fbedefb63e
2,559
import helpers.DnsImageTagResolver; import io.homecentr.testcontainers.containers.GenericContainerEx; import io.homecentr.testcontainers.images.PullPolicyEx; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.output.Slf4jLogConsumer; import org.testcontainers.containers.wait.strategy.Wait; import org.xbill.DNS.*; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class DnsContainerShould { private static final Logger logger = LoggerFactory.getLogger(DnsContainerShould.class); private static GenericContainerEx _container; @BeforeClass public static void setUp() { _container = new GenericContainerEx<>(new DnsImageTagResolver()) .withRelativeFileSystemBind(Paths.get("..", "example"), "/config") .withImagePullPolicy(PullPolicyEx.never()) .waitingFor(Wait.forHealthcheck()); _container.start(); _container.followOutput(new Slf4jLogConsumer(logger)); } @AfterClass public static void cleanUp() { _container.close(); } @Test public void resolveExternalZoneViaForwarders() throws UnknownHostException, TextParseException { Lookup lookup = new Lookup("google.com", Type.A); lookup.setResolver(createResolver()); Record[] results = lookup.run(); assertEquals("google.com.", results[0].getName().toString()); assertEquals(Type.A, results[0].getType()); } @Test public void resolveInternallyDefinedZone() throws TextParseException, UnknownHostException { Lookup lookup = new Lookup("some-record.test", Type.A); lookup.setResolver(createResolver()); Record[] results = lookup.run(); assertTrue(results[0] instanceof ARecord); ARecord aRecord = (ARecord)results[0]; assertEquals("some-record.test.", aRecord.getName().toString()); assertEquals(Type.A, aRecord.getType()); // The address is configured in the example configs assertEquals(InetAddress.getByName("127.0.0.122"), aRecord.getAddress()); } private SimpleResolver createResolver() throws UnknownHostException { SimpleResolver resolver = new SimpleResolver("127.0.0.1"); resolver.setPort(_container.getMappedUdpPort(53)); return resolver; } }
33.233766
100
0.709652
2ca8c14549b675298eeed66869438a8d95431e0c
5,473
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.gradle; import com.google.common.base.Joiner; import org.gradle.api.Action; import org.gradle.api.file.Directory; import org.gradle.api.file.DirectoryProperty; import org.gradle.api.file.ProjectLayout; import org.gradle.api.file.SourceDirectorySet; import org.gradle.api.model.ObjectFactory; import org.gradle.api.provider.ListProperty; import org.gradle.api.provider.Property; import org.gradle.api.provider.Provider; import javax.inject.Inject; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * Implements the 'thrifty' Gradle extension. * * This is the public interface of our Gradle plugin to build scripts. Renaming * or removing a method is a breaking change! */ @SuppressWarnings("UnstableApiUsage") public abstract class ThriftyExtension { private static final String DEFAULT_SOURCE_DIR = Joiner.on(File.separator).join("src", "main", "thrift"); private static final String DEFAULT_OUTPUT_DIR = Joiner.on(File.separator).join("generated", "sources", "thrifty"); private final ObjectFactory objects; private final ProjectLayout layout; private final ListProperty<Directory> includePathEntries; private final ListProperty<DefaultThriftSourceDirectory> sources; private final Property<ThriftOptions> thriftOptions; private final DirectoryProperty outputDirectory; private final Property<String> thriftyVersion; @Inject public ThriftyExtension(ObjectFactory objects, ProjectLayout layout) { this.objects = objects; this.layout = layout; this.includePathEntries = objects.listProperty(Directory.class); this.sources = objects.listProperty(DefaultThriftSourceDirectory.class) .convention(Collections.singletonList( new DefaultThriftSourceDirectory( getDefaultSourceDirectorySet()))); this.thriftOptions = objects.property(ThriftOptions.class).convention(new KotlinThriftOptions()); this.outputDirectory = objects.directoryProperty().convention(layout.getBuildDirectory().dir(DEFAULT_OUTPUT_DIR)); this.thriftyVersion = objects.property(String.class); } private SourceDirectorySet getDefaultSourceDirectorySet() { return (SourceDirectorySet) objects.sourceDirectorySet("thrift-sources", "Thrift Sources") .srcDir(DEFAULT_SOURCE_DIR) .include("**/*.thrift"); } public Provider<List<Directory>> getIncludePathEntries() { return includePathEntries; } public Provider<List<DefaultThriftSourceDirectory>> getSources() { return sources; } public Provider<ThriftOptions> getThriftOptions() { return thriftOptions; } public Provider<Directory> getOutputDirectory() { return outputDirectory; } public Property<String> getThriftyVersion() { return thriftyVersion; } public ThriftSourceDirectory sourceDir(String path) { SourceDirectorySet sd = objects.sourceDirectorySet("thrift-sources", "Thrift Sources"); sd.srcDir(path); DefaultThriftSourceDirectory dtsd = objects.newInstance(DefaultThriftSourceDirectory.class, sd); sources.add(dtsd); return dtsd; } public ThriftSourceDirectory sourceDir(String path, Action<ThriftSourceDirectory> action) { ThriftSourceDirectory tsd = sourceDir(path); action.execute(tsd); return tsd; } public List<ThriftSourceDirectory> sourceDirs(String... paths) { return Arrays.stream(paths).map(this::sourceDir).collect(Collectors.toList()); } public void includePath(String... paths) { for (String path : paths) { Directory dir = layout.getProjectDirectory().dir(path); if (!dir.getAsFile().isDirectory()) { throw new IllegalArgumentException("Include-path entries must be directories"); } includePathEntries.add(dir); } } public void outputDir(String path) { File f = new File(path); if (f.isAbsolute()) { outputDirectory.fileValue(f); } else { outputDirectory.value(layout.getProjectDirectory().dir(path)); } } public void kotlin(Action<KotlinThriftOptions> action) { KotlinThriftOptions opts = objects.newInstance(KotlinThriftOptions.class); action.execute(opts); thriftOptions.set(opts); } public void java(Action<JavaThriftOptions> action) { JavaThriftOptions opts = objects.newInstance(JavaThriftOptions.class); action.execute(opts); thriftOptions.set(opts); } }
35.771242
122
0.705463
0fdb24a5b98acda11fc6065f171d56da409f866e
670
package tech.weiyi.dynamic.bytecode.compiler; import javax.tools.SimpleJavaFileObject; import java.net.URI; public class JavaSourceCode extends SimpleJavaFileObject { private String clazzName; private String sourceCode; protected JavaSourceCode(String clazzName, String sourceCode) { super(URI.create("string:///" + clazzName.replaceAll("\\.", "/") + Kind.SOURCE.extension), Kind.SOURCE); this.clazzName = clazzName; this.sourceCode = sourceCode; } public CharSequence getCharContent(boolean ignoreEncodingErrors) { return this.sourceCode; } public String getName() { return clazzName; } }
24.814815
112
0.7
c03d820dd3764354f79550c6b84938be0e7a614b
2,261
/* * Copyright 2013, 2014 Megion Research & Development GmbH * * 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.mrd.bitlib.model; import java.io.Serializable; import java.io.UnsupportedEncodingException; import com.mrd.bitlib.util.HashUtils; public class ScriptOutputMsg extends ScriptOutput implements Serializable { private static final long serialVersionUID = 1L; private byte[] _messageBytes; private byte[] _publicKeyBytes; protected ScriptOutputMsg(byte[][] chunks, byte[] scriptBytes) { super(scriptBytes); _messageBytes = chunks[0]; _publicKeyBytes = chunks[2]; } protected static boolean isScriptOutputMsg(byte[][] chunks) { if (chunks.length != 4) { return false; } if (!Script.isOP(chunks[1], OP_DROP)) { return false; } if (!Script.isOP(chunks[3], OP_CHECKSIG)) { return false; } return true; } /** * Get the bytes for the message contained in this output. * * @return The message bytes of this output. */ public byte[] getMessageBytes() { return _messageBytes; } public String getMessage() { try { return new String(getMessageBytes(), "US-ASCII"); } catch (UnsupportedEncodingException e) { return ""; } } /** * Get the public key bytes that this output is for. * * @return The public key bytes that this output is for. */ public byte[] getPublicKeyBytes() { return _publicKeyBytes; } @Override public Address getAddress(NetworkParameters network) { byte[] addressBytes = HashUtils.addressHash(getPublicKeyBytes()); return Address.fromStandardBytes(addressBytes, network); } }
27.573171
75
0.671384
292d589f69221150b768784a7906c8ef8da14363
970
package software.amazon.awssdk.crt.s3; import software.amazon.awssdk.crt.http.HttpHeader; import java.nio.ByteBuffer; class S3MetaRequestResponseHandlerNativeAdapter { private S3MetaRequestResponseHandler responseHandler; S3MetaRequestResponseHandlerNativeAdapter(S3MetaRequestResponseHandler responseHandler) { this.responseHandler = responseHandler; } int onResponseBody(ByteBuffer bodyBytesIn, long objectRangeStart, long objectRangeEnd) { byte[] payload = new byte[bodyBytesIn.limit()]; bodyBytesIn.get(payload); return this.responseHandler.onResponseBody(payload, objectRangeStart, objectRangeEnd); } void onFinished(int errorCode) { this.responseHandler.onFinished(errorCode); } void onResponseHeaders(final int statusCode, final ByteBuffer headersBlob) { responseHandler.onResponseHeaders(statusCode, HttpHeader.loadHeadersFromMarshalledHeadersBlob(headersBlob)); } }
34.642857
116
0.770103
73c3463cb3f2734c31e9928cbef1526b6bcd488e
1,913
package com.infogen.etl; import org.apache.commons.cli.ParseException; import com.infogen.mapper.InfoGen_Mapper; import com.infogen.yarn.InfoGen_Container; import com.infogen.yarn.Job_Configuration; /** * 独立部署示例程序,可以直接传入参数启动 * * @author larry/[email protected]/创建时间 2015年12月21日 下午1:12:07 * @since 1.0 * @version 1.0 */ public class Kafka_To_Hdfs_Standalone { public static void main(String[] args) throws InterruptedException, ClassNotFoundException, ParseException { Job_Configuration job_configuration = Job_Configuration.get_configuration(args); // props.put("serializer.class", "kafka.serializer.StringEncoder"); // props.put("metadata.broker.list", "192.168.202.34:9092,192.168.202.35:9092,192.168.202.36:9092"); // props.put("zk.connect", "192.168.202.16:2181,192.168.202.17:2181,192.168.202.18:2181"); // job_configuration.zookeeper = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183"; // job_configuration.topic = "topic6"; // job_configuration.group = "group1"; job_configuration.zookeeper = "192.168.202.16:2181,192.168.202.17:2181,192.168.202.18:2181";//"172.16.8.97:2181,172.16.8.98:2181,172.16.8.99:2181"; job_configuration.topic = "infogen_topic_tracking"; job_configuration.group = "infogen_etl"; @SuppressWarnings("unchecked") Class<? extends InfoGen_Mapper> mapper_clazz = (Class<? extends InfoGen_Mapper>) Class.forName("com.infogen.etl.Kafka_To_Hdfs_Mapper"); job_configuration.mapper = mapper_clazz; job_configuration.output = "hdfs://spark101:8020/infogen/output_uat/"; job_configuration.numContainers = 5; for (int i = 0; i < job_configuration.numContainers; i++) { new Thread(() -> { try { InfoGen_Container infogen_container = new InfoGen_Container(job_configuration); infogen_container.submit(); } catch (Exception e) { e.printStackTrace(); } }).start(); } Thread.currentThread().join(); } }
39.040816
149
0.728176
118a21bbd1b925571a8545a870bb984b54dc5578
9,005
package com.appiaries.baas.sdk; import android.content.Context; import android.support.test.runner.AndroidJUnit4; import android.test.InstrumentationTestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import java.util.HashMap; import java.util.Map; @RunWith(AndroidJUnit4.class) public class ABSequenceTest extends InstrumentationTestCase { ABSequence sequence; private Context getApplicationContext() { return this.getInstrumentation().getTargetContext().getApplicationContext(); } @Before public void setUp() throws Exception { AB.Config.setDatastoreID("ds"); AB.Config.setApplicationID("app"); AB.Config.setApplicationToken("tokentokentokentokentokentokentokentokentokentokentoken"); AB.activate(getApplicationContext()); } @After public void tearDown() throws Exception { } @Test public void test__constructor__default() throws Exception { sequence = new ABSequence(); //NOTE: protected assertEquals(ABSequence.class, sequence.getClass()); assertEquals(ABSequence.class.getName(), sequence.getCollectionID()); assertEquals(0, sequence.getEstimatedData().size()); assertEquals(0, sequence.getFilteredEstimatedData().size()); assertEquals(0, sequence.getOriginalData().size()); assertEquals(0, sequence.getAddedKeys().size()); assertEquals(0, sequence.getAddedKeysAndValues().size()); assertEquals(0, sequence.getUpdatedKeys().size()); assertEquals(0, sequence.getUpdatedKeysAndValues().size()); assertEquals(0, sequence.getRemovedKeys().size()); assertEquals(0, sequence.getRemovedKeysAndValues().size()); assertTrue(sequence.isNew()); assertFalse(sequence.isDirty()); assertNull(sequence.getID()); assertNull(sequence.getCreated()); assertNull(sequence.getCreatedBy()); assertNull(sequence.getUpdated()); assertNull(sequence.getUpdatedBy()); } @Test public void test__constructor__collectionID() throws Exception { sequence = new ABSequence("MySequence"); assertEquals(ABSequence.class, sequence.getClass()); assertEquals("MySequence", sequence.getCollectionID()); //XXX: ABDeviceはコレクションを持たないので常に com.appiaries.baas.sdk.ABDevice が返されるはずなんですが。。。 assertEquals(0, sequence.getEstimatedData().size()); assertEquals(0, sequence.getFilteredEstimatedData().size()); assertEquals(0, sequence.getOriginalData().size()); assertEquals(0, sequence.getAddedKeys().size()); assertEquals(0, sequence.getAddedKeysAndValues().size()); assertEquals(0, sequence.getUpdatedKeys().size()); assertEquals(0, sequence.getUpdatedKeysAndValues().size()); assertEquals(0, sequence.getRemovedKeys().size()); assertEquals(0, sequence.getRemovedKeysAndValues().size()); assertTrue(sequence.isNew()); assertFalse(sequence.isDirty()); assertNull(sequence.getID()); assertNull(sequence.getCreated()); assertNull(sequence.getCreatedBy()); assertNull(sequence.getUpdated()); assertNull(sequence.getUpdatedBy()); } @Test public void test__constructor__collectionID__map() throws Exception { Map<String, Object> map = new HashMap<String, Object>(){ { put(ABSequence.Field.ID.getKey(), "fdfccb76fedede56e9e494a31139b73f59c0Aed613596b3b8cec8f67da2b7a79"); put(ABFile.Field.CREATED.getKey(), new Date(){{ setTime(1436951840123L / 1000); }}.getTime() * 1000); put(ABFile.Field.CREATED_BY.getKey(), "fooman"); put(ABFile.Field.UPDATED.getKey(), new Date(){{ setTime(1436951850987L / 1000); }}.getTime() * 1000); put(ABFile.Field.UPDATED_BY.getKey(), "barman"); put(ABSequence.Field.VALUE.getKey(), 100L); put(ABSequence.Field.INITIAL_VALUE.getKey(), 1L); } }; sequence = new ABSequence("MySequence", map); assertEquals(ABSequence.class, sequence.getClass()); assertEquals("MySequence", sequence.getCollectionID()); //XXX: ABDeviceはコレクションを持たないので常に com.appiaries.baas.sdk.ABDevice が返されるはずなんですが。。。 assertEquals(7, sequence.getEstimatedData().size()); assertEquals(7, sequence.getFilteredEstimatedData().size()); assertEquals(7, sequence.getOriginalData().size()); assertEquals(0, sequence.getAddedKeys().size()); assertEquals(0, sequence.getAddedKeysAndValues().size()); assertEquals(0, sequence.getUpdatedKeys().size()); assertEquals(0, sequence.getUpdatedKeysAndValues().size()); assertEquals(0, sequence.getRemovedKeys().size()); assertEquals(0, sequence.getRemovedKeysAndValues().size()); assertTrue(sequence.isNew()); assertFalse(sequence.isDirty()); assertEquals("fdfccb76fedede56e9e494a31139b73f59c0Aed613596b3b8cec8f67da2b7a79", sequence.getID()); assertEquals(1436951840123L / 1000, sequence.getCreated().getTime()); assertEquals("fooman", sequence.getCreatedBy()); assertEquals(1436951850987L / 1000, sequence.getUpdated().getTime()); assertEquals("barman", sequence.getUpdatedBy()); assertEquals(100L, sequence.getValue()); assertEquals(1L, sequence.getInitialValue()); } @Test public void test__constructor__map() throws Exception { Map<String, Object> map = new HashMap<String, Object>(){ { put(ABSequence.Field.ID.getKey(), "fdfccb76fedede56e9e494a31139b73f59c0Aed613596b3b8cec8f67da2b7a79"); put(ABFile.Field.CREATED.getKey(), new Date(){{ setTime(1436951840123L / 1000); }}.getTime() * 1000); put(ABFile.Field.CREATED_BY.getKey(), "fooman"); put(ABFile.Field.UPDATED.getKey(), new Date(){{ setTime(1436951850987L / 1000); }}.getTime() * 1000); put(ABFile.Field.UPDATED_BY.getKey(), "barman"); put(ABSequence.Field.VALUE.getKey(), 100L); put(ABSequence.Field.INITIAL_VALUE.getKey(), 1L); } }; sequence = new ABSequence(map); assertEquals(ABSequence.class, sequence.getClass()); assertEquals(ABSequence.class.getName(), sequence.getCollectionID()); //NOTE: ABDeviceはコレクションを持たないので常に com.appiaries.baas.sdk.ABDevice が返される。 assertEquals(7, sequence.getEstimatedData().size()); assertEquals(7, sequence.getFilteredEstimatedData().size()); assertEquals(7, sequence.getOriginalData().size()); assertEquals(0, sequence.getAddedKeys().size()); assertEquals(0, sequence.getAddedKeysAndValues().size()); assertEquals(0, sequence.getUpdatedKeys().size()); assertEquals(0, sequence.getUpdatedKeysAndValues().size()); assertEquals(0, sequence.getRemovedKeys().size()); assertEquals(0, sequence.getRemovedKeysAndValues().size()); assertTrue(sequence.isNew()); assertFalse(sequence.isDirty()); assertEquals("fdfccb76fedede56e9e494a31139b73f59c0Aed613596b3b8cec8f67da2b7a79", sequence.getID()); assertEquals(1436951840123L / 1000, sequence.getCreated().getTime()); assertEquals("fooman", sequence.getCreatedBy()); assertEquals(1436951850987L / 1000, sequence.getUpdated().getTime()); assertEquals("barman", sequence.getUpdatedBy()); assertEquals(100L, sequence.getValue()); assertEquals(1L, sequence.getInitialValue()); } /*@Test public void test__fetchSynchronously() throws Exception { } @Test public void test__fetchSynchronously1() throws Exception { } @Test public void test__fetch() throws Exception { } @Test public void test__fetch1() throws Exception { } @Test public void test__fetch2() throws Exception { } @Test public void test__fetch3() throws Exception { } @Test public void test__addSynchronously() throws Exception { } @Test public void test__addSynchronously1() throws Exception { } @Test public void test__add() throws Exception { } @Test public void test__add1() throws Exception { } @Test public void test__add2() throws Exception { } @Test public void test__add3() throws Exception { } @Test public void test__resetSynchronously() throws Exception { } @Test public void test__resetSynchronously1() throws Exception { } @Test public void test__reset() throws Exception { } @Test public void test__reset1() throws Exception { } @Test public void test__reset2() throws Exception { } @Test public void test__reset3() throws Exception { } @Test public void test__query() throws Exception { }*/ }
35.592885
149
0.667407
338f2e517f336559e004e56758665cf56109af19
7,572
/* * Copyright 2021 EPAM Systems, Inc * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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.epam.deltix.test.qsrv.hf.tickdb.http.rest; import com.epam.deltix.qsrv.hf.tickdb.StreamConfigurationHelper; import com.epam.deltix.qsrv.test.messages.BarMessage; import com.epam.deltix.streaming.MessageChannel; import com.epam.deltix.test.qsrv.hf.tickdb.http.BaseTest; import com.epam.deltix.test.qsrv.hf.tickdb.http.HTTPCursor; import com.epam.deltix.qsrv.hf.pub.RawMessage; import com.epam.deltix.qsrv.hf.pub.TypeLoaderImpl; import com.epam.deltix.qsrv.hf.pub.codec.CodecFactory; import com.epam.deltix.qsrv.hf.pub.codec.FixedBoundEncoder; import com.epam.deltix.qsrv.hf.pub.md.RecordClassDescriptor; import com.epam.deltix.qsrv.hf.pub.md.RecordClassSet; import com.epam.deltix.qsrv.hf.tickdb.http.*; import com.epam.deltix.qsrv.hf.tickdb.pub.StreamOptions; import com.epam.deltix.qsrv.hf.tickdb.pub.StreamScope; import com.epam.deltix.util.memory.MemoryDataOutput; import com.epam.deltix.util.time.GMT; import com.epam.deltix.util.time.TimeConstants; import org.junit.Test; import javax.xml.bind.JAXBException; import java.io.*; import java.net.HttpURLConnection; import java.util.zip.GZIPInputStream; /** * */ public class TestRESTLoad extends BaseTest { private static final String[] SYMBOLS = {"AAPL-HTTP"}; @Test public void loadRestBars() throws Exception { loadRestBars(true, false, null, null); } @Test public void loadOutBars() throws Exception { loadOutOfOrder(false, false, null, null); } private static void loadRestBars(boolean useCompression, boolean isBigEndian, String user, String password) throws Exception { String streamName = "1min"; StreamOptions options = StreamOptions.fixedType(StreamScope.DURABLE, streamName, null, 0, StreamConfigurationHelper.mkUniversalBarMessageDescriptor()); createStream(streamName, options); final BarMessage bar = new BarMessage(); bar.setTimeStampMs(GMT.parseDateTime("2013-10-08 09:00:00").getTime()); bar.setOpen(1.0); bar.setClose(1.0); bar.setHigh(1.0); bar.setLow(1.0); bar.setVolume(1.0); final RecordClassSet rcs = Utils.requestSchema(getPath("tb/xml"), streamName, user, password); final RecordClassDescriptor type = rcs.getTopType(0); final FixedBoundEncoder encoder = CodecFactory.COMPILED.createFixedBoundEncoder(TypeLoaderImpl.DEFAULT_INSTANCE, type); final MemoryDataOutput mdo = new MemoryDataOutput(); final MessageChannel<RawMessage> loader = Utils.getRestLoader( TB_HOST, runner.getPort(), useCompression, isBigEndian, streamName, rcs.getTopTypes(), user, password); RawMessage raw = new RawMessage(); raw.type = type; for (int i = 0; i < 5000000; i++) { for (String symbol : SYMBOLS) { bar.setSymbol(symbol); mdo.reset(); encoder.encode(bar, mdo); raw.setSymbol(bar.getSymbol()); raw.setTimeStampMs(bar.getTimeStampMs()); raw.setBytes(mdo); loader.send(raw); bar.setOpen(bar.getOpen() + 1); } bar.setTimeStampMs(bar.getTimeStampMs() + TimeConstants.MINUTE); bar.setHigh(bar.getHigh() + 1); bar.setLow(bar.getLow() + 0.1); } loader.close(); //assert selectCount("1min") == 5000000; } private static void loadOutOfOrder(boolean useCompression, boolean isBigEndian, String user, String password) throws Exception { String streamName = "1minOutOfOrder"; StreamOptions options = StreamOptions.fixedType(StreamScope.DURABLE, streamName, null, 0, StreamConfigurationHelper.mkUniversalBarMessageDescriptor()); createStream(streamName, options); final RecordClassSet rcs = Utils.requestSchema(getPath("tb/xml"), streamName, user, password); final BarMessage bar = new BarMessage(); bar.setSymbol(SYMBOLS[0]); bar.setTimeStampMs(GMT.parseDateTime("2013-10-08 09:00:00").getTime()); bar.setOpen(1.0); bar.setClose(1.0); bar.setHigh(1.0); bar.setLow(1.0); bar.setVolume(1.0); final RecordClassDescriptor type = rcs.getTopType(0); final FixedBoundEncoder encoder = CodecFactory.COMPILED.createFixedBoundEncoder(TypeLoaderImpl.DEFAULT_INSTANCE, type); final MemoryDataOutput mdo = new MemoryDataOutput(); final MessageChannel<RawMessage> loader = Utils.getRestLoader( TB_HOST, runner.getPort(), useCompression, isBigEndian, streamName, rcs.getTopTypes(), user, password); RawMessage raw = new RawMessage(); raw.type = type; for (int i = 0; i < 5; i++) { mdo.reset(); encoder.encode(bar, mdo); raw.setSymbol(bar.getSymbol()); raw.setTimeStampMs(bar.getTimeStampMs()); raw.setBytes(mdo); loader.send(raw); bar.setOpen(bar.getOpen() + 1); bar.setTimeStampMs(bar.getTimeStampMs() - TimeConstants.MINUTE); bar.setHigh(bar.getHigh() + 1); bar.setLow(bar.getLow() + 0.1); } loader.close(); } //data selection public static int selectCount(String key) throws JAXBException, IOException { SelectRequest sr = new SelectRequest(); sr.streams = new String[] { key }; sr.reverse = true; sr.symbols = null; sr.isBigEndian = false; sr.useCompression = false; sr.typeTransmission = TypeTransmission.DEFINITION; sr.from = Long.MIN_VALUE; sr.to = Long.MAX_VALUE; final long ts0 = System.currentTimeMillis(); RecordClassSet set = runner.getTickDb().getStream(key).getStreamOptions().getMetaData(); //int count = selectCount(sr, ); int count = 0; try (HTTPCursor cursor = select(sr)) { cursor.setRecordClassSet(set); while (cursor.next()) { count++; } cursor.close(); } return count; } private static HTTPCursor select(SelectRequest select) throws IOException, JAXBException { final HttpURLConnection conn = (HttpURLConnection) URL.openConnection(); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); marshaller.marshal(select, os); int rc = conn.getResponseCode(); if (rc != 200) { System.out.println("HTTP rc=" + rc + " " + conn.getResponseMessage()); return null; } // Content-Encoding [gzip] final InputStream is = HTTPProtocol.GZIP.equals(conn.getHeaderField(HTTPProtocol.CONTENT_ENCODING)) ? new GZIPInputStream(conn.getInputStream()) : conn.getInputStream(); return new HTTPCursor(is, select); } }
38.050251
159
0.661912
a2c8b25f4ea5a783b2518c26856f6d675180c8c3
5,073
/* * Copyright Terracotta, 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 org.terracotta.dynamic_config.api.json; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.module.SimpleModule; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.terracotta.dynamic_config.api.model.Cluster; import org.terracotta.dynamic_config.api.model.License; import org.terracotta.dynamic_config.api.model.Node; import org.terracotta.dynamic_config.api.model.NodeContext; import org.terracotta.dynamic_config.api.model.Scope; import org.terracotta.dynamic_config.api.model.Stripe; import org.terracotta.dynamic_config.api.model.UID; import java.net.InetSocketAddress; import java.nio.file.Path; import java.time.LocalDate; import java.util.Collections; import java.util.Map; import java.util.Optional; /** * This module can be added to the existing ones and will override some definitions to make the object mapper compatible with V1 * * @author Mathieu Carbou * @deprecated old V1 format. Do not use anymore. Here for reference and backward compatibility. */ @Deprecated public class DynamicConfigModelJsonModuleV1 extends SimpleModule { private static final long serialVersionUID = 1L; public DynamicConfigModelJsonModuleV1() { super(DynamicConfigModelJsonModuleV1.class.getSimpleName(), new Version(1, 0, 0, null, null, null)); setMixInAnnotation(Node.class, NodeMixinV1.class); setMixInAnnotation(License.class, LicenseMixin.class); setMixInAnnotation(NodeContext.class, NodeContextMixin.class); } public static class NodeContextMixin extends NodeContext { @JsonCreator public NodeContextMixin(@JsonProperty(value = "cluster", required = true) Cluster cluster, @JsonProperty(value = "stripeId", required = false) int stripeId, @JsonProperty(value = "nodeName", required = true) String nodeName) { super(cluster, cluster.getNodeByName(nodeName).get().getUID()); } @JsonIgnore @Override public Node getNode() { return super.getNode(); } @JsonIgnore @Override public Stripe getStripe() { return super.getStripe(); } @JsonIgnore @Override public UID getStripeUID() { return super.getStripeUID(); } } @SuppressFBWarnings("EQ_DOESNT_OVERRIDE_EQUALS") public static class NodeMixinV1 extends Node { @JsonProperty("nodeName") String name; @JsonProperty("nodeHostname") String hostname; @JsonProperty("nodePublicHostname") String publicHostname; @JsonProperty("nodePort") Integer port; @JsonProperty("nodePublicPort") Integer publicPort; @JsonProperty("nodeGroupPort") Integer groupPort; @JsonProperty("nodeBindAddress") String bindAddress; @JsonProperty("nodeGroupBindAddress") String groupBindAddress; @JsonProperty("nodeMetadataDir") Path metadataDir; @JsonProperty("nodeLogDir") Path logDir; @JsonProperty("nodeBackupDir") Path backupDir; @JsonProperty("nodeLoggerOverrides") Map<String, String> loggerOverrides; @JsonIgnore @Override public Scope getScope() { return super.getScope(); } @JsonIgnore @Override public InetSocketAddress getBindSocketAddress() { return super.getBindSocketAddress(); } @JsonIgnore @Override public InetSocketAddress getInternalSocketAddress() { return super.getInternalSocketAddress(); } @JsonIgnore @Override public Optional<InetSocketAddress> getPublicSocketAddress() { return super.getPublicSocketAddress(); } @JsonIgnore @Override public Endpoint getBindEndpoint() { return super.getBindEndpoint(); } @JsonIgnore @Override public Endpoint getInternalEndpoint() { return super.getInternalEndpoint(); } @JsonIgnore @Override public Optional<Endpoint> getPublicEndpoint() { return super.getPublicEndpoint(); } } public static class LicenseMixin extends License { @JsonCreator public LicenseMixin(@JsonProperty(value = "capabilities", required = true) Map<String, Long> capabilityLimitMap, @JsonProperty(value = "expiryDate", required = true) LocalDate expiryDate) { super(capabilityLimitMap, Collections.emptyMap(), expiryDate); } } }
31.122699
128
0.725212
029bcc10c7bf5101f9eb1b8f80d40fb7bc75827b
243
package com.netflix.conductor.dyno; import com.netflix.conductor.core.config.SystemPropertiesConfiguration; public class SystemPropertiesDynomiteConfiguration extends SystemPropertiesConfiguration implements DynomiteConfiguration {}
34.714286
88
0.860082
c36809eef9617887938b925b2181c92b8ad96a51
1,809
package problem; public class NumberOfIslands { public static void main(String[] args) { NumberOfIslands solver = new NumberOfIslands(); int[][] grid = new int[][]{ {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0 }, {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, {0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0 }, {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0 }, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0 }, {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 }}; int[][] grid2 = new int[][] {{0,0,0,0,0,0,0,0}}; assert solver.countIslands(grid) == 6; assert solver.countIslands(grid2) == 0; } public int countIslands(int[][] grid) { int islands = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (grid[i][j] == 1) { islands++; discover(grid, i, j); } } } return islands; } private void discover(int[][] grid, int row, int col) { grid[row][col] = 2; for (int i = - 1; i < 2; i++) { for (int j = - 1; j < 2; j++) { if (Math.abs(j) == Math.abs(i)) continue; if (isViable(grid, row + i, col + j)) { discover(grid, row + i, col +j); } } } } private boolean isViable(int[][] grid, int row, int col) { if (row < 0 || row >= grid.length) return false; if (col < 0 || col >= grid[row].length) return false; return grid[row][col] == 1; } }
30.15
63
0.381426
67483d77f1b0fc655b5a7682a20b20af0b795274
1,992
package com.drumonii.loltrollbuild.repository; import com.drumonii.loltrollbuild.model.GameMap; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import java.util.List; import java.util.Optional; /** * JPA repository to the MAP table. */ @CacheConfig(cacheNames = "maps") public interface MapsRepository extends JpaRepository<GameMap, Integer>, JpaSpecificationExecutor<GameMap> { /** * Gets {@link List} of all {@link GameMap}s that are eligible for the troll build. Eligible maps: Twisted Treeline, * Summoner's Rift, and Proving Grounds. * * @return only the eligible {@link List} of {@link GameMap}s */ @Query("select m from GameMap m where m.mapId in ('10', '11', '12') order by m.mapName") @Cacheable(key = "#root.methodName", unless = "#result.isEmpty()") List<GameMap> forTrollBuild(); @Cacheable(unless = "#result.isEmpty()") @Override List<GameMap> findAll(); @CacheEvict(allEntries = true) @Override <S extends GameMap> List<S> saveAll(Iterable<S> entities); @CacheEvict(allEntries = true) @Override <S extends GameMap> S save(S entity); @Cacheable(unless = "#result == null") @Override Optional<GameMap> findById(Integer integer); @CacheEvict(allEntries = true) @Override void deleteById(Integer integer); @CacheEvict(allEntries = true) @Override void deleteAll(Iterable<? extends GameMap> entities); @CacheEvict(allEntries = true) @Override void deleteAll(); @Cacheable(key = "{#spec.example.probe, #sort}", unless = "#result.isEmpty()") @Override List<GameMap> findAll(Specification<GameMap> example, Sort sort); }
30.646154
117
0.756024
465dcb7da08ab093458b17ec922bfb8b588500c7
1,844
package rs.ac.uns.ftn.informatika.mbs2.vezbe09.primer01.server.session; import java.util.Date; import javax.ejb.EJB; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import rs.ac.uns.ftn.informatika.mbs2.vezbe09.primer01.server.entity.Admin; import rs.ac.uns.ftn.informatika.mbs2.vezbe09.primer01.server.entity.Category; import rs.ac.uns.ftn.informatika.mbs2.vezbe09.primer01.server.entity.Offer; import rs.ac.uns.ftn.informatika.mbs2.vezbe09.primer01.server.entity.Seller; @Stateless(name="InitBean") @Remote(Init.class) public class InitBean implements Init { @PersistenceContext(unitName = "Vezbe09") EntityManager em; @EJB SellerDaoLocal dao; public void init() { //Admin admin = new Admin("Admin", "Admin", "admin", "admin"); Category cat = new Category("cat1", "asdas"); Seller s = dao.findById(2); Seller s1 = new Seller("roto", "roic","rot","rot", "a", "a"); Offer offer = new Offer("offer1", new Date(), new Date(), new Date(), new Date(), 12, 10, 30, " asd", 5, true, s, cat); Offer offer2 = new Offer("offer2", new Date(), new Date(), new Date(), new Date(), 12, 10, 30, " asd", 5, false, s, cat); Offer offer3 = new Offer("offer3", new Date(), new Date(), new Date(), new Date(), 12, 10, 30, " asd", 5, true, s, cat); Offer offer4 = new Offer("offer3", new Date(), new Date(), new Date(), new Date(), 12, 10, 30, " asd", 5, true, s1, cat); Offer offer5 = new Offer("offer3", new Date(), new Date(), new Date(), new Date(), 12, 10, 30, " asd", 5, true, s, cat); //em.persist(admin); dao.persist(s1); System.out.println("cacaca"); em.persist(cat); System.out.println("cacacalalala"); em.persist(offer4); em.persist(offer5); em.persist(offer); em.persist(offer2); em.persist(offer3); } }
37.632653
124
0.682755
828f12efc1c196cebd784526868189005737e724
1,088
package com.xoozi.apiguides.gl.objects; import java.util.List; import com.xoozi.apiguides.gl.data.VertexArray; import com.xoozi.apiguides.gl.glutil.Geometry.Ray; import com.xoozi.apiguides.gl.objects.ObjectBuilder.GenerateData; import com.xoozi.apiguides.gl.objects.ObjectBuilder.DrawCommand; import com.xoozi.apiguides.gl.programs.RayShaderProgram; /** * 用来指示触摸的射线 */ public class TouchRay { private static final int POSITION_COMPONENT_COUNT = 3; private final VertexArray _vertexArray; private final List<DrawCommand> _drawList; public TouchRay(Ray ray){ GenerateData generatedData = ObjectBuilder.createRay(ray); _vertexArray = new VertexArray(generatedData.vertexData); _drawList = generatedData.drawList; } public void bindData(RayShaderProgram rayProgram){ _vertexArray.setVertexAttributePointer(0, rayProgram.getPositionAttributeLocation(), POSITION_COMPONENT_COUNT, 0); } public void draw(){ for(DrawCommand dc: _drawList){ dc.draw(); } } }
28.631579
66
0.715993
094e0b13459dc0407ea76851f27122d2cdf0b27d
2,386
package com.bluebirdme.mes.platform.dao.impl; import com.bluebirdme.mes.core.base.dao.BaseDaoImpl; import com.bluebirdme.mes.core.base.entity.Filter; import com.bluebirdme.mes.core.base.entity.Page; import com.bluebirdme.mes.platform.dao.IMessageDao; import com.bluebirdme.mes.platform.entity.Message; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * @author qianchen * @date 2020/05/21 */ @Repository public class MessageDaoImpl extends BaseDaoImpl implements IMessageDao { @Resource SessionFactory factory; @Override public Session getSession() { return this.factory.getCurrentSession(); } @Override public <T> Map<String, Object> findPageInfo(final Filter filter, final Page page) throws Exception { return this.findPageInfo(filter, page, "message-all-list"); } @Override public <T> Map<String, Object> findReadedMessage(final Filter filter, final Page page) throws Exception { return this.findPageInfo(filter, page, "message-readed-list"); } @Override public <T> Map<String, Object> findUnreadMessage(final Filter filter, final Page page) throws Exception { return this.findPageInfo(filter, page, "message-unread-list"); } @Override public List<Message> myMessage(final Integer topCount, final Long uid, final Integer readSign) { final StringBuffer sql = new StringBuffer("select m.*,u.userName as sender from platform_message m left join platform_message_status ms on m.id=ms.msgid left join platform_user u on m.fromUser=u.id where m.toUser=" + uid); switch ((readSign == null) ? -1 : readSign) { case 0: { sql.append(" and ms.status is null or ms.status=0"); break; } case 1: { sql.append(" and ms.status=1"); break; } default: { break; } } sql.append(" and isDeleted=0"); final SQLQuery query = this.getSession().createSQLQuery(sql.toString()).addEntity(Message.class); query.setFirstResult(0); query.setMaxResults(topCount); return (List<Message>) query.list(); } }
34.57971
230
0.671417
f51686ddf82274432af1fb2b2dc0783ba9250a1a
1,995
package in.co.air.line.ticket.bean; import java.util.Date; public class BookBean extends BaseBean { private long flightId; private String flightName; private String firstName; private String lastName; private String mobileNo; private String emailId; private String address; private long noOfPerson; private long price; private long finalPrice; private Date bookDate; public Date getBookDate() { return bookDate; } public void setBookDate(Date bookDate) { this.bookDate = bookDate; } public long getFlightId() { return flightId; } public void setFlightId(long flightId) { this.flightId = flightId; } public String getFlightName() { return flightName; } public void setFlightName(String flightName) { this.flightName = flightName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getMobileNo() { return mobileNo; } public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public long getNoOfPerson() { return noOfPerson; } public void setNoOfPerson(long noOfPerson) { this.noOfPerson = noOfPerson; } public long getPrice() { return price; } public void setPrice(long price) { this.price = price; } public long getFinalPrice() { return finalPrice; } public void setFinalPrice(long finalPrice) { this.finalPrice = finalPrice; } public String getKey() { // TODO Auto-generated method stub return null; } public String getValue() { // TODO Auto-generated method stub return null; } }
15.465116
47
0.711278
8cd959ededaaa2c5b5251bebefe74f2ed498fb2a
1,786
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.test.integration; import org.elasticsearch.common.io.Streams; import java.io.*; public class PathAccessor { public static byte[] bytesFromPath(String path, Class<?> aClass) throws IOException { try (InputStream is = getInputStream(path, aClass); ByteArrayOutputStream out = new ByteArrayOutputStream()) { Streams.copy(is, out); return out.toByteArray(); } } public static InputStream getInputStream(String path, Class<?> aClass) throws FileNotFoundException { InputStream is = aClass.getResourceAsStream(path); if (is == null) { throw new FileNotFoundException("Resource [" + path + "] not found in classpath"); } return is; } }
38
105
0.712766
3a35bf8e182a437e498d16105166bb72e7a3a90b
2,885
package net; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; public class EasyX509TrustManager implements X509TrustManager { private X509TrustManager standardTrustManager = null; private EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException { super(); TrustManagerFactory factory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(keystore); TrustManager[] trustmanagers = factory.getTrustManagers(); if (trustmanagers.length == 0) { throw new NoSuchAlgorithmException("no trust manager found"); } this.standardTrustManager = (X509TrustManager) trustmanagers[0]; } public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException { standardTrustManager.checkClientTrusted(certificates, authType); } public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { if ((certificates != null) && (certificates.length == 1)) { certificates[0].checkValidity(); } else { standardTrustManager.checkServerTrusted(certificates, authType); } } public X509Certificate[] getAcceptedIssuers() { return this.standardTrustManager.getAcceptedIssuers(); } /** * 信任所有的证书 */ public static void checkSSL() { try { HttpsURLConnection .setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { // return true; return hostname.equals(session.getPeerHost()); } }); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext .init(null, new TrustManager[]{new EasyX509TrustManager( null)}, null); SSLSocketFactory ssf = sslContext.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(ssf); } catch (Exception e) { e.printStackTrace(); } } }
36.987179
81
0.632929
7b98227966b6a045a468c9a6a3a482b03e123d4d
1,229
package com.wordnik.swagger.models.properties; import com.wordnik.swagger.models.Xml; public class IntegerProperty extends AbstractNumericProperty implements Property { protected Integer _default; public IntegerProperty() { super.type = "integer"; super.format = "int32"; } public IntegerProperty xml(Xml xml) { this.setXml(xml); return this; } public IntegerProperty example(Integer example) { this.setExample(String.valueOf(example)); return this; } public IntegerProperty _default(String _default) { if(_default != null) { try { this._default = Integer.parseInt(_default); } catch (NumberFormatException e) { // continue; } } return this; } public IntegerProperty _default(Integer _default) { this.setDefault(_default); return this; } public static boolean isType(String type, String format) { if("integer".equals(type) && "int32".equals(format)) return true; else return false; } public Integer getDefault() { return _default; } public void setDefault(Integer _default) { this._default = _default; } public void setDefault(String _default) { this._default(_default); } }
23.188679
82
0.676973
134aae7922920186c5023d408a4eedf49b50d541
1,196
package com.bolingcavalry.db.service; import com.bolingcavalry.db.entity.City; import com.bolingcavalry.db.entity.Country; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.transaction.Transactional; import java.util.List; /** * @author will */ @ApplicationScoped public class CityService { @Inject EntityManager entityManager; public City getSingle(Integer id) { return entityManager.find(City.class, id); } public List<City> get() { return entityManager.createNamedQuery("City.findAll", City.class) .getResultList(); } @Transactional public void create(City fruit) { entityManager.persist(fruit); } @Transactional public void update(Integer id, City fruit) { City entity = entityManager.find(City.class, id); if (null!=entity) { entity.setName(fruit.getName()); } } @Transactional public void delete(Integer id) { City entity = entityManager.getReference(City.class, id); if (null!=entity) { entityManager.remove(entity); } } }
23
73
0.663043
e5773e4b446ac21252da0f1e75490b196e2c31d7
808
package net.minecraft.world.level.block.state; import com.google.common.collect.ImmutableMap; import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; import net.minecraft.core.Registry; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.properties.Property; public class BlockState extends BlockBehaviour.BlockStateBase implements net.minecraftforge.common.extensions.IForgeBlockState { public static final Codec<BlockState> CODEC = codec(Registry.BLOCK.byNameCodec(), Block::defaultBlockState).stable(); public BlockState(Block p_61042_, ImmutableMap<Property<?>, Comparable<?>> p_61043_, MapCodec<BlockState> p_61044_) { super(p_61042_, p_61043_, p_61044_); } protected BlockState asState() { return this; } }
38.47619
128
0.790842
59a99e4d8eaff529e6487d3ff692533d4a11a186
2,034
/* * 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 io.kareldb.schema; import org.apache.calcite.linq4j.Enumerator; import java.util.Iterator; import java.util.concurrent.atomic.AtomicBoolean; class TableEnumerator<E> implements Enumerator<E> { private final Iterator<?> rows; private final AtomicBoolean cancelFlag; private final boolean alwaysReturnArray; private E current; TableEnumerator(Iterator<?> rows, AtomicBoolean cancelFlag, boolean alwaysReturnArray) { this.rows = rows; this.cancelFlag = cancelFlag; this.alwaysReturnArray = alwaysReturnArray; } public E current() { return current; } public boolean moveNext() { if (cancelFlag.get()) { return false; } final Object[] row = rows.hasNext() ? Table.toArray(rows.next()) : null; if (row == null) { current = null; return false; } current = convertRow(row); return true; } @SuppressWarnings("unchecked") private E convertRow(Object[] row) { return alwaysReturnArray || row.length > 1 ? (E) row : (E) row[0]; } public void reset() { throw new UnsupportedOperationException(); } public void close() { } }
31.292308
92
0.676991
e6b4b1dd1b50164f428b4a06566a4eef4df9e36b
2,512
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2019 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.export; import net.sf.jasperreports.annotations.properties.Property; import net.sf.jasperreports.annotations.properties.PropertyScope; import net.sf.jasperreports.engine.JRPropertiesUtil; import net.sf.jasperreports.properties.PropertyConstants; /** * @author Teodor Danciu ([email protected]) */ public interface CommonExportConfiguration { /** * A global (per context) property that serves as default value for the {@link ReportExportConfiguration#isOverrideHints()} setting * and establishes the priority of export configuration settings against report hints. * * If the property is true, export configuration settings override report hints; this is the * default behavior. * * This property cannot be used as a report export hint. */ @Property( category = PropertyConstants.CATEGORY_EXPORT, defaultValue = PropertyConstants.BOOLEAN_TRUE, scopes = {PropertyScope.CONTEXT}, sinceVersion = PropertyConstants.VERSION_5_5_1, valueType = Boolean.class ) public static final String PROPERTY_EXPORT_CONFIGURATION_OVERRIDE_REPORT_HINTS = JRPropertiesUtil.PROPERTY_PREFIX + "export.configuration.override.report.hints"; /** * Specifies whether the settings provided by this exporter configuration object are supposed to override the equivalent exporter * hints specified in the reports themselves using configuration properties. * @see #PROPERTY_EXPORT_CONFIGURATION_OVERRIDE_REPORT_HINTS */ public Boolean isOverrideHints(); }
39.873016
133
0.77707
e3f75e02e600544dc07fccb3793241979d7b61f6
5,377
package uk.gov.ons.ctp.integration.contactcentresvc.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.bcpg.CompressionAlgorithmTags; import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPCompressedDataGenerator; import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPLiteralData; import org.bouncycastle.openpgp.PGPLiteralDataGenerator; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.jcajce.JcaPGPPublicKeyRingCollection; import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator; import org.bouncycastle.util.io.Streams; import org.springframework.core.io.Resource; /** PGP encryption using one or more ascii armoured public keys. */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class PgpEncrypt { private static final BouncyCastleProvider PROVIDER = new BouncyCastleProvider(); public static String encrypt(String clearMsg, Collection<Resource> publicKeyResources) { try { Collection<PGPPublicKey> publicPgpKeys = getPublicKeys(publicKeyResources); byte[] encyptedFileContents = encrypt(publicPgpKeys, clearMsg); return new String(encyptedFileContents); } catch (PGPException | IOException e) { throw new RuntimeException("failed to encrypt contents", e); } } private static byte[] encrypt(Collection<PGPPublicKey> publicPgpKeys, String clearMsg) throws IOException, PGPException { final byte[] compressedContents = compress(clearMsg); final PGPEncryptedDataGenerator generator = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256) .setWithIntegrityPacket(true) .setSecureRandom(new SecureRandom()) .setProvider(PROVIDER)); for (PGPPublicKey publicKey : publicPgpKeys) { generator.addMethod( new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setProvider(PROVIDER)); } final ByteArrayOutputStream encryptedBytes = new ByteArrayOutputStream(); try (OutputStream armoredOutputStream = new ArmoredOutputStream(encryptedBytes); OutputStream encryptedOut = generator.open(armoredOutputStream, compressedContents.length)) { encryptedOut.write(compressedContents); } return encryptedBytes.toByteArray(); } private static Collection<PGPPublicKey> getPublicKeys(Collection<Resource> publicKeyResources) throws IOException, PGPException { var publicKeys = new ArrayList<PGPPublicKey>(); for (Resource resource : publicKeyResources) { PGPPublicKey publicPgpKey = getPublicKey(resource); publicKeys.add(publicPgpKey); } return publicKeys; } private static PGPPublicKey getPublicKey(Resource pgpKey) throws IOException, PGPException { InputStream input = PGPUtil.getDecoderStream(pgpKey.getInputStream()); JcaPGPPublicKeyRingCollection pgpPublicKeyRingCollection = new JcaPGPPublicKeyRingCollection(input); input.close(); PGPPublicKey key = null; PGPPublicKey masterKey = null; Iterator<PGPPublicKeyRing> keyRings = pgpPublicKeyRingCollection.getKeyRings(); while (key == null && keyRings.hasNext()) { PGPPublicKeyRing nextKeyRing = keyRings.next(); Iterator<PGPPublicKey> publicKeys = nextKeyRing.getPublicKeys(); while (key == null && publicKeys.hasNext()) { PGPPublicKey k = publicKeys.next(); if (k.isEncryptionKey() && !k.isMasterKey()) { key = k; } else if (k.isEncryptionKey() && k.isMasterKey()) { masterKey = k; // should only ever be set if there is no subkey for encryption } } if (key == null && masterKey != null) { key = masterKey; } } return key; } private static byte[] compress(String clearMsg) throws IOException { try (final ByteArrayInputStream inputStream = new ByteArrayInputStream(clearMsg.getBytes()); final ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream()) { final PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP); final PGPLiteralDataGenerator literal = new PGPLiteralDataGenerator(); final OutputStream outputStream = literal.open( compressedDataGenerator.open(byteOutputStream), PGPLiteralData.BINARY, "filename", inputStream.available(), new Date()); Streams.pipeAll(inputStream, outputStream); compressedDataGenerator.close(); return byteOutputStream.toByteArray(); } } }
42.007813
96
0.747443
cb71f3f9b8b99072c5322b212a3861ca73bbb26d
2,884
package nl.softcause.jsontemplates.types; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import lombok.Getter; import lombok.Value; @Value public class MapOf<T> implements IExpressionType<Map<String, T>> { private IExpressionType<T> baseType; @Override public String getType() { return baseType.getType().concat("[]"); } @Override public boolean isA(Object src) { if (src == null) { return true; } if (src instanceof TypedHashMap) { return baseType.isClassOfA(((TypedHashMap) src).getType()); } return isClassOfA(src.getClass()); } @Override public boolean isClassOfA(Class<?> src) { var elementType = elementClass(src); if (elementType == null) { return false; } return baseType.isClassOfA(elementType); } private Class elementOf(Object src) { if (src instanceof TypedHashMap) { return ((TypedHashMap) src).getType(); } return elementClass(src.getClass()); } private Class elementClass(Class<?> src) { if (Map.class.isAssignableFrom(src)) { try { Type sooper = src.getGenericInterfaces()[0]; Type keyType = ((ParameterizedType) sooper).getActualTypeArguments()[0]; if (!keyType.equals(String.class)) { throw TypeException.onlyMapWithStringKeysSupported(src); } return (Class) ((ParameterizedType) sooper).getActualTypeArguments()[1]; } catch (Exception e) { throw TypeException.firstClassMapOnly(src); } } return null; } @Override @SuppressWarnings("unchecked") public Map<String, T> convert(Object src) { if (!isA(src)) { throw TypeException.invalidCast(src, this); } if (src == null) { return null; } var yield = new TypedHashMap<T>(elementOf(src)); if (src instanceof Map) { var iter = (Map) src; iter.forEach((key, value) -> yield.put((String) key, baseType.convert(value))); } return yield; } @Override public IExpressionType baseType() { return baseType == Types.OBJECT ? baseType : Types.byName(Optional.name(baseType)); } @Override public IExpressionType<Map<String, T>> infuse(Class<?> src) { return new MapOf<>(baseType.infuse(src)); } @Override public String toString() { return getType(); } private static class TypedHashMap<E> extends HashMap<String, E> { @Getter private final Class<E> type; private TypedHashMap(Class<E> type) { this.type = type; } } }
27.466667
91
0.57975