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
6554e0d6fbb5d8e1e441dfbbd9e433e07cc6591c
240
package io.vproxy.base.dns; import io.vproxy.base.util.callback.Callback; import io.vproxy.vfd.IPPort; import java.util.List; public interface DnsServerListGetter { void get(boolean firstRun, Callback<List<IPPort>, Throwable> cb); }
21.818182
69
0.775
040de63a9b3bfe8c7208e34381018265502c2c9e
1,001
/* * Copyright 2017 ThdLee * * 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.thdjson.entity; /** * @author ThdLee */ public enum JSONValueType { OBJECT("object"), ARRAY("array"), INT("int"), FLOAT("float"), STRING("string"), BOOL("bool"), NULL("null"),; /*********************/ private String type; private JSONValueType(String type) { this.type = type; } public String getType() { return type; } }
22.75
75
0.646354
99dcc550e400402172e072d3583de77b9dc1c4a2
2,825
package fi.csc.notebooks.osbuilder.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import fi.csc.notebooks.osbuilder.auth.JWTAuthenticationFilter; import fi.csc.notebooks.osbuilder.auth.JWTAuthorizationFilter; import fi.csc.notebooks.osbuilder.data.UserDetailsServiceImpl; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsServiceImpl userDetailsService; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().headers().frameOptions().disable(). and().csrf().disable().authorizeRequests() .antMatchers(HttpMethod.GET, "/*", "/h2-console/*", "/js/*", "/favicon.ico", "/login/*") .permitAll() .antMatchers(HttpMethod.POST, "/*", "/h2-console/*", "/login", "/users/signup") .permitAll() .anyRequest().authenticated() .and() .addFilter(new JWTAuthenticationFilter(authenticationManager())) .addFilter(new JWTAuthorizationFilter(authenticationManager())) // this disables session creation with Spring Security .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } /* Inject UserDetailsServiceImpl which is backed by the database, containing user information */ @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); } @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } }
39.236111
107
0.80354
c6f51732b30582e490eb73ed2bd66afbb98fd545
903
package com.chrisdoyle.validation.tests; import com.chrisdoyle.validation.Main; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; import java.io.File; /** * Issue 22, pom overrides * Created by alex on 9/2/16. */ public class Test_Issue22 { @Test public void testPomOverries() throws Exception{ String search[] = new String[]{ "LGPL" }; for (int i = 0; i < Main.allPoms.length; i++) { if (Main.allPoms[i].contains("hello-world-apk-overrides/")) { File f = new File(Main.allPoms[i]); String str = FileUtils.readFileToString(f, "utf-8"); for (int k = 0; k < search.length; k++) { Assert.assertTrue(search[k] + " not found in " + f.getAbsolutePath(), str.contains(search[k])); } } } } }
23.763158
115
0.562569
19695c8b46f89e559f9123a7ff3ec6ca7a00fd80
96
package org.datanucleus.samples.metadata.dtd; public class DTDFile3 { String name; }
13.714286
46
0.708333
e5e4dbd5ef08a3789b470d720e230f1f7f3fdd78
880
package com.example.android.clothespredicting.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.android.clothespredicting.R; /** * Created by Loches on 2016/1/26. */ public class MyFragment extends Fragment { private String content; public MyFragment(String content) { this.content = content; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fg_content, container, false); TextView txt_content = (TextView) view.findViewById(R.id.txt_content); txt_content.setText(content); return view; } }
27.5
103
0.742045
d5cb340a6a932a7ccf63e4b8594844b36afe23f3
2,427
package org.wrkr.clb.statistics.services.project; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.wrkr.clb.common.jms.message.statistics.BaseStatisticsMessage; import org.wrkr.clb.common.jms.message.statistics.NewTaskMessage; import org.wrkr.clb.common.jms.message.statistics.TaskUpdateStatisticsMessage; import org.wrkr.clb.statistics.repo.project.TaskPriorityUpdateRepo; import org.wrkr.clb.statistics.repo.project.TaskStatusUpdateRepo; import org.wrkr.clb.statistics.repo.project.TaskTypeUpdateRepo; import org.wrkr.clb.statistics.repo.project.TaskUpdateRepo; import org.wrkr.clb.statistics.services.BaseEventService; @Service public class TaskUpdateService extends BaseEventService { @Autowired private TaskUpdateRepo taskUpdateRepo; @Autowired private TaskTypeUpdateRepo typeUpdateRepo; @Autowired private TaskPriorityUpdateRepo priorityUpdateRepo; @Autowired private TaskStatusUpdateRepo statusUpdateRepo; @Override public String getCode() { return BaseStatisticsMessage.Code.TASK_UPDATE; } @Override @Transactional(value = "statTransactionManager", rollbackFor = Throwable.class) public void onMessage(Map<String, Object> requestBody) { Long projectId = (Long) requestBody.get(NewTaskMessage.PROJECT_ID); String projectName = (String) requestBody.get(NewTaskMessage.PROJECT_NAME); Long taskId = (Long) requestBody.get(TaskUpdateStatisticsMessage.TASK_ID); Long updatedAt = (Long) requestBody.get(TaskUpdateStatisticsMessage.UPDATED_AT); String type = (String) requestBody.get(TaskUpdateStatisticsMessage.TYPE); String priority = (String) requestBody.get(TaskUpdateStatisticsMessage.PRIORITY); String status = (String) requestBody.get(TaskUpdateStatisticsMessage.STATUS); taskUpdateRepo.save(projectId, projectName, taskId, updatedAt); if (type != null) { typeUpdateRepo.save(projectId, projectName, taskId, updatedAt, type); } if (priority != null) { priorityUpdateRepo.save(projectId, projectName, taskId, updatedAt, priority); } if (status != null) { statusUpdateRepo.save(projectId, projectName, taskId, updatedAt, status); } } }
39.786885
89
0.755253
a7dbf17148f3aa31593323ad7f53ea1858038027
500
package minhfx03283.funix.prm391_asm_1.models; import java.util.Set; /** * This question type is for multiple choice option (checkboxes will be displayed in UI). * mOptionsList is a set of multiple choice questions for users to pick. */ public class QuizType2 extends Quiz { private Set<String> mOptionList; public Set<String> getOptionList() { return mOptionList; } public void setOptionList(Set<String> mOptionList) { this.mOptionList = mOptionList; } }
23.809524
89
0.714
8e96e51f10573be21963f0ef1ce3d5a093d81aa1
4,349
/* (C) Copyright IBM Corp. 2021 SPDX-License-Identifier: Apache-2.0 */ package org.alvearie.keycloak.config; import javax.ws.rs.BadRequestException; import org.alvearie.keycloak.config.util.KeycloakConfig; import org.alvearie.keycloak.config.util.PropertyGroup; import org.alvearie.keycloak.config.util.PropertyGroup.PropertyEntry; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.KeycloakBuilder; /** * Reads the KeycloakConfig and applies it to the target Keycloak * * Command line arguments: * configFile: the file path to a JSON file containing Keycloak configuration properties */ public class Main { private static final String CONFIG_FILE_PATH_OPTION = "configFile"; private static final String CLASS_NAME = "Main"; private static final String MASTER_REALM = "master"; /** * Initializes the Keycloak configuration. * @param args the passed in arguments * @throws Exception */ public static void main(String[] args) throws Exception { Options options = null; CommandLine cmd; String configFilePath; try { // Process the options options = buildCmdOptions(); cmd = new DefaultParser().parse(options, args); configFilePath = cmd.getOptionValue(CONFIG_FILE_PATH_OPTION); } catch (ParseException e) { String header = "Initialize keycloak config\n\n"; String footer = "\n"; HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(CLASS_NAME, header, options, footer, true); throw new RuntimeException("Invalid arguments", e); } // Perform the action try { KeycloakConfig config = new KeycloakConfig(configFilePath); applyConfig(config); } catch (BadRequestException e) { System.err.println(e.getResponse().readEntity(String.class)); throw e; } } /** * Builds the command options. * @return the command options */ private static Options buildCmdOptions() { Options options = new Options(); Option configFilePathOption = new Option(CONFIG_FILE_PATH_OPTION, true, "The file path to a JSON file containing Keycloak configuration properties"); configFilePathOption.setRequired(true); options.addOption(configFilePathOption); return options; } /** * Applies the Keycloak configuration. * @param config the Keycloak configuration to apply * @throws Exception an exception */ private static void applyConfig(KeycloakConfig config) throws Exception { // Create a Keycloak client and use that to initialize the configurator Keycloak client = createKeycloakClient(config); KeycloakConfigurator configurator = new KeycloakConfigurator(client); // Initialize realms PropertyGroup realmsPg = config.getPropertyGroup(KeycloakConfig.PROP_KEYCLOAK_REALMS); if (realmsPg != null) { for (PropertyEntry realmPe: realmsPg.getProperties()) { String realmName = realmPe.getName(); PropertyGroup realmPg = realmsPg.getPropertyGroup(realmName); configurator.initializeRealm(realmName, realmPg); } } } /** * Creates a Keycloak admin client. * @param config the Keycloak configuration to initialize * @return a Keycloak client */ private static Keycloak createKeycloakClient(KeycloakConfig config) { Keycloak keycloak = KeycloakBuilder.builder() .serverUrl(config.getStringProperty(KeycloakConfig.PROP_KEYCLOAK_SERVER_URL)) .realm(MASTER_REALM) .username(config.getStringProperty(KeycloakConfig.PROP_KEYCLOAK_ADMIN_USER)) .password(config.getStringProperty(KeycloakConfig.PROP_KEYCLOAK_ADMIN_PW)) .clientId(config.getStringProperty(KeycloakConfig.PROP_KEYCLOAK_ADMIN_CLIENT_ID)) .build(); return keycloak; } }
36.855932
157
0.680846
f7b22a0e66d1c9533c5903c420dd94e3b64ba067
1,230
package com.reritel.aquatic; import com.reritel.aquatic.registry.ModBlocks; import com.reritel.aquatic.registry.ModItems; import com.reritel.aquatic.registry.ModOres; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.util.Identifier; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Main implements ModInitializer { public static Logger LOGGER = LogManager.getLogger(); public static final String MOD_ID = "aquatic"; public static final String MOD_NAME = "AquaticMod"; public static final ItemGroup ITEM_GROUP = FabricItemGroupBuilder.build( new Identifier(MOD_ID, "general"), () -> new ItemStack(ModItems.AQUAMARINE)); @Override public void onInitialize() { log(Level.INFO, "Initializing"); ModItems.RegisterItems(); ModBlocks.RegisterBlocks(); ModOres.RegisterOres(); } public static void log(Level level, String message){ LOGGER.log(level, "["+MOD_NAME+"] " + message); } }
30.75
76
0.731707
d7196c45998ff06b8a1117e17bf27654710f0467
713
package info.smart_tools.smartactors.statistics.sensors.scheduled_query_sensor; import info.smart_tools.smartactors.scheduler.interfaces.ISchedulerEntry; import info.smart_tools.smartactors.statistics.sensors.interfaces.ISensorHandle; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Test for {@link QuerySensorHandle}. */ public class QuerySensorHandleTest { @Test public void Should_cancelEntryOnSensorShutdown() throws Exception { ISchedulerEntry entry = mock(ISchedulerEntry.class); ISensorHandle handle = new QuerySensorHandle(entry); handle.shutdown(); verify(entry).cancel(); } }
27.423077
80
0.754558
230398812e7f279f023659a6c8b9725841144f5b
12,108
package com.guinong.lib_utils; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; /** * 动态全新申请 * @author ymb * Create at 2017/5/12 10:38 */ public class PermissionUtil { private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE" }; public static String[] PERMISSIONS_WINDOW = {"android.permission.SYSTEM_ALERT_WINDOW"}; /** * SD卡读写权限 * @param activity */ public static boolean verifyStoragePermissions(Activity activity) { try { // 检测是否有写的权限 int permission = ActivityCompat.checkSelfPermission(activity, "android.permission.WRITE_EXTERNAL_STORAGE"); if (permission != PackageManager.PERMISSION_GRANTED) { // 没有写的权限,去申请写的权限,会弹出对话框 ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); return false; }else { return true; } } catch (Exception e) { e.printStackTrace(); return false; } } /** * 弹框权限 * @param activity */ public static boolean verifyWindowPermissions(Activity activity) { try { // 检测是否有写的权限 int permission = ActivityCompat.checkSelfPermission(activity, "android.permission.SYSTEM_ALERT_WINDOW"); if (permission != PackageManager.PERMISSION_GRANTED) { // 没有写的权限,去申请写的权限,会弹出对话框 ActivityCompat.requestPermissions(activity, PERMISSIONS_WINDOW, REQUEST_EXTERNAL_STORAGE); return false; }else { return true; } } catch (Exception e) { e.printStackTrace(); return false; } } /** * 拨打电话权限 * @param activity */ public static void phonePermissions(Activity activity) { try { // 检测是否有写的权限 int permission = ActivityCompat.checkSelfPermission(activity, "android.permission.READ_PHONE_STATE"); if (permission != PackageManager.PERMISSION_GRANTED) { // 没有写的权限,去申请写的权限,会弹出对话框 ActivityCompat.requestPermissions(activity, new String[]{DangerousPermissions.PHONE}, REQUEST_EXTERNAL_STORAGE); } } catch (Exception e) { e.printStackTrace(); } } /** * 发送短信权限 * @param activity */ public static void smsPermissions(Activity activity) { try { // 检测是否有写的权限 int permission = ActivityCompat.checkSelfPermission(activity, "android.permission.SEND_SMS"); if (permission != PackageManager.PERMISSION_GRANTED) { // 没有写的权限,去申请写的权限,会弹出对话框 ActivityCompat.requestPermissions(activity, new String[]{DangerousPermissions.SMS}, REQUEST_EXTERNAL_STORAGE); } } catch (Exception e) { e.printStackTrace(); } } public static final int MY_PERMISSIONS_REQUEST_CODE=10001; public static boolean checkAudioPermission(Context context){ //检查麦克风权限 ,写入文件,读出文件权限 if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { //申请RECORD_AUDIO WRITE_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CODE); }else if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //申请RECORD_AUDIO WRITE_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CODE); }else if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //申请RECORD_AUDIO WRITE_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CODE); }else{ //权限已经允许 请执行下一步操作 return true; } return false; } public static boolean checkCameraPermission(Context context){ //检查拍照权限 ,写入文件,读出文件权限 if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { //CAMERA WRITE_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CODE); }else if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //CAMERA WRITE_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CODE); }else if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //CAMERA WRITE_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CODE); }else{ return true; } return false; } public static boolean checkCameraScanPermission(Context context){ //检查拍照权限 if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { //CAMERA 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CODE); }else{ return true; } return false; } public static boolean checkExternalStoragePermission(Context context){ //检查写入文件,读出文件权限 if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //CAMERA WRITE_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CODE); }else if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //CAMERA WRITE_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CODE); }else{ return true; } return false; } public static boolean checkLocationPermission(Context context){ //检查获取位置权限 if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_CODE); }else if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_CODE); }else{ //权限已经允许 请执行下一步操作 // Toast.makeText(context,"Permission Granted",Toast.LENGTH_LONG).show(); return true; } return false; } public static boolean checkContactsPermission(Context context,int requestCode){ //检查获取联系人权限 if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { //READ_CONTACTS GET_ACCOUNTS 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_CONTACTS}, requestCode); }else if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED){ return true; } return false; } public static boolean checkContactsPermission(Context context){ //检查获取联系人权限 if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { //READ_CONTACTS GET_ACCOUNTS 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_CODE); }else if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED){ return true; } return false; } public static boolean checkSendSMSPermission(Context context){ //检查获取发短信权限 if (ActivityCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { //SEND_SMS 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.SEND_SMS}, MY_PERMISSIONS_REQUEST_CODE); }else{ //权限已经允许 请执行下一步操作 // Toast.makeText(context,"Permission Granted",Toast.LENGTH_LONG).show(); return true; } return false; } public static boolean checkPhonePermission(Context context){ //检查获取电话权限 if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { //READ_PHONE_STATE CALL_PHONE 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_PHONE_STATE,Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CODE); }else if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { //READ_PHONE_STATE CALL_PHONE 权限 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_PHONE_STATE,Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CODE); }else{ //权限已经允许 请执行下一步操作 // Toast.makeText(context,"Permission Granted",Toast.LENGTH_LONG).show(); return true; } return false; } }
48.432
229
0.675752
83549c5bb10c8fdde7a876a15006e12844c59314
983
package chudanic.petr.homesecuritymobile; import java.util.Objects; /** * Created by Petr on 16.12.2017. */ public class SecurityImage { private String name; private Long timestamp; private String downloadUrl; public String getName() { return name; } public Long getTimestamp() { return timestamp; } public String getDownloadUrl() { return downloadUrl; } public void setName(String name) { this.name = name; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } @Override public boolean equals(Object obj) { if (!(obj instanceof SecurityImage)) { return false; } return Objects.equals(name, ((SecurityImage) obj).name); } @Override public int hashCode() { return Objects.hash(name); } }
18.54717
64
0.612411
d87164e660043021aeea1a45103ca6749e4e7984
1,603
package com.dyz.gameserver.msg.processor.login; import com.context.ErrorCode; import com.dyz.gameserver.Avatar; import com.dyz.gameserver.commons.message.ClientRequest; import com.dyz.gameserver.commons.session.GameSession; import com.dyz.gameserver.logic.RoomLogic; import com.dyz.gameserver.manager.RoomManager; import com.dyz.gameserver.msg.processor.common.INotAuthProcessor; import com.dyz.gameserver.msg.processor.common.MsgProcessor; import com.dyz.gameserver.msg.response.login.BackLoginResponse; import com.dyz.persist.util.GlobalUtil; import net.sf.json.JSONObject; /** * 暂时不用整个类 * @author luck * */ public class loginBackMsgProcessor extends MsgProcessor implements INotAuthProcessor{ @Override public void process(GameSession gameSession, ClientRequest request) throws Exception { /*if(GlobalUtil.checkIsLogin(gameSession)) { JSONObject json = JSONObject.fromObject(request.getString()); int roomId = (int)json.get("roomId"); Avatar avatar = gameSession.getRole(Avatar.class); if (avatar != null) { RoomLogic roomLogic = RoomManager.getInstance().getRoom(roomId); if (roomLogic != null) { gameSession.sendMsg(new BackLoginResponse(1,roomLogic.getRoomVO())); } else { System.out.println("房间号有误"); gameSession.sendMsg(new BackLoginResponse(0,ErrorCode.Error_000012)); } }else{ System.out.println("账户未登录或已经掉线!"); gameSession.sendMsg(new BackLoginResponse(0,ErrorCode.Error_000002)); } } else{ System.out.println("该用户还没有登录"); gameSession.destroyObj(); }*/ } }
32.06
88
0.733624
263ba8408e68fdea3c9ae003b33e6b2b65a3981f
1,085
package com.SpringCore.DependencyInjection.SetterInjection.Reference; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("com/SpringCore/DependencyInjection/SetterInjection/Reference/refconfig.xml"); A aref1 = (A)context.getBean("aref1"); A aref2 = (A)context.getBean("aref2"); A aref3 = (A)context.getBean("aref3"); System.out.println(aref1.getX()); System.out.println(aref1.getObj().getY()); System.out.println("-------"); System.out.println(aref2.getX()); System.out.println(aref2.getObj().getY()); System.out.println("-------"); System.out.println(aref3.getX()); System.out.println(aref3.getObj().getY()); System.out.println("-------"); System.out.println(""); System.out.println(aref1); System.out.println(aref2); System.out.println(aref3); ((ClassPathXmlApplicationContext) context).close(); } }
31.911765
145
0.705991
ebd51ab1ee63ad7840e7d63b99ad47ccd69e1338
2,969
/******************************************************************************* * Copyright (c) 2006, 2019 Mountainminds GmbH & Co. KG and Contributors * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Marc R. Hoffmann - initial API and implementation * ******************************************************************************/ package ru.capralow.dt.coverage.internal.core.analysis; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.jacoco.core.data.ExecutionDataStore; import org.junit.After; import org.junit.Before; import org.junit.Test; import ru.capralow.dt.coverage.core.JavaProjectKit; /** * Tests for {@link PackageFragmentRootAnalyzer}. */ public class PackageFragmentRootAnalyzerTest { private JavaProjectKit javaProject; private PackageFragementRootAnalyzer analyzer; @Before public void setup() throws Exception { javaProject = new JavaProjectKit("project"); final ExecutionDataStore data = new ExecutionDataStore(); analyzer = new PackageFragementRootAnalyzer(data); } @After public void teardown() throws Exception { javaProject.destroy(); } @Test public void testSourceFolder() throws Exception { javaProject.setDefaultOutputLocation("classes"); final IPackageFragmentRoot root = javaProject.createSourceFolder("src"); javaProject.createCompilationUnit(root, "testdata/src", "typetraverser/Samples.java"); JavaProjectKit.waitForBuild(); final AnalyzedNodes nodes = analyzer.analyze(root); assertNotNull(nodes.getClassCoverage("typetraverser/Samples")); // Caching: assertSame(nodes, analyzer.analyze(root)); } @Test public void testSourceWithOutputFolder() throws Exception { final IPackageFragmentRoot root = javaProject.createSourceFolder("src", "myclasses"); javaProject.createCompilationUnit(root, "testdata/src", "typetraverser/Samples.java"); JavaProjectKit.waitForBuild(); final AnalyzedNodes nodes = analyzer.analyze(root); assertNotNull(nodes.getClassCoverage("typetraverser/Samples")); } @Test public void testJar() throws Exception { final IPackageFragmentRoot root = javaProject .createJAR("testdata/bin/signatureresolver.jar", "/sample.jar", null, null); JavaProjectKit.waitForBuild(); final AnalyzedNodes nodes = analyzer.analyze(root); assertNotNull(nodes.getClassCoverage("signatureresolver/Samples")); } @Test public void testExternalJar() throws Exception { final IPackageFragmentRoot root = javaProject .createExternalJAR("testdata/bin/signatureresolver.jar", null, null); JavaProjectKit.waitForBuild(); final AnalyzedNodes nodes = analyzer.analyze(root); assertNotNull(nodes.getClassCoverage("signatureresolver/Samples")); } }
31.924731
88
0.733244
300128e9a5db0195e5d2639a18c6daf97eada98d
8,594
package com.yuyh.library.imgsel.ui; import android.Manifest; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import com.yuyh.library.imgsel.R; import com.yuyh.library.imgsel.bean.Image; import com.yuyh.library.imgsel.config.ISCameraConfig; import com.yuyh.library.imgsel.utils.FileUtils; import com.yuyh.library.imgsel.utils.LogUtils; import com.yuyh.library.imgsel.utils.StatusBarCompat; import java.io.File; import java.util.List; /** * @author yuyh. * @date 2017/4/18. */ public class ISCameraActivity extends AppCompatActivity { public static void startForResult(Activity activity, ISCameraConfig config, int requestCode) { Intent intent = new Intent(activity, ISCameraActivity.class); intent.putExtra("config", config); activity.startActivityForResult(intent, requestCode); } public static void startForResult(Fragment fragment, ISCameraConfig config, int requestCode) { Intent intent = new Intent(fragment.getActivity(), ISCameraActivity.class); intent.putExtra("config", config); fragment.startActivityForResult(intent, requestCode); } public static void startForResult(android.app.Fragment fragment, ISCameraConfig config, int requestCode) { Intent intent = new Intent(fragment.getActivity(), ISCameraActivity.class); intent.putExtra("config", config); fragment.startActivityForResult(intent, requestCode); } private static final int REQUEST_CAMERA = 5; private static final int IMAGE_CROP_CODE = 1; private static final int CAMERA_REQUEST_CODE = 2; private File cropImageFile; private File tempPhotoFile; private ISCameraConfig config; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { StatusBarCompat.compatTransStatusBar(this, 0x33333333, true); super.onCreate(savedInstanceState); config = (ISCameraConfig) getIntent().getSerializableExtra("config"); if (config == null) return; camera(); } private void camera() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_REQUEST_CODE); return; } Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraIntent.resolveActivity(getPackageManager()) != null || getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) { tempPhotoFile = new File(FileUtils.createRootPath(this) + "/" + System.currentTimeMillis() + ".jpg"); LogUtils.e(tempPhotoFile.getAbsolutePath()); FileUtils.createFile(tempPhotoFile); Uri uri = FileProvider.getUriForFile(this, FileUtils.getApplicationId(this) + ".image_provider", tempPhotoFile); List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resInfoList) { String packageName = resolveInfo.activityInfo.packageName; grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); } cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); //Uri.fromFile(tempFile) startActivityForResult(cameraIntent, REQUEST_CAMERA); } else { Toast.makeText(this, getResources().getString(R.string.open_camera_failure), Toast.LENGTH_SHORT).show(); } } private void crop(String imagePath) { cropImageFile = new File(FileUtils.createRootPath(this) + "/" + System.currentTimeMillis() + ".jpg"); Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(getImageContentUri(new File(imagePath)), "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", config.aspectX); intent.putExtra("aspectY", config.aspectY); intent.putExtra("outputX", config.outputX); intent.putExtra("outputY", config.outputY); intent.putExtra("scale", true); intent.putExtra("scaleUpIfNeeded", true); intent.putExtra("return-data", false); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropImageFile)); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); startActivityForResult(intent, IMAGE_CROP_CODE); } public Uri getImageContentUri(File imageFile) { String filePath = imageFile.getAbsolutePath(); Cursor cursor = getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[]{filePath}, null); if (cursor != null && cursor.moveToFirst()) { int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)); Uri baseUri = Uri.parse("content://media/external/images/media"); cursor.close(); return Uri.withAppendedPath(baseUri, "" + id); } else { if (imageFile.exists()) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA, filePath); if (cursor != null) { cursor.close(); } return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { return null; } } } private void complete(Image image) { Intent intent = new Intent(); if (image != null) { intent.putExtra("result", image.path); } setResult(RESULT_OK, intent); finish(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == IMAGE_CROP_CODE && resultCode == RESULT_OK) { complete(new Image(cropImageFile.getPath(), cropImageFile.getName())); } else if (requestCode == REQUEST_CAMERA) { if (resultCode == Activity.RESULT_OK) { if (tempPhotoFile != null) { if (config.needCrop) { crop(tempPhotoFile.getAbsolutePath()); } else { // complete(new Image(cropImageFile.getPath(), cropImageFile.getName())); complete(new Image(tempPhotoFile.getPath(), tempPhotoFile.getName())); } } } else { if (tempPhotoFile != null && tempPhotoFile.exists()) { tempPhotoFile.delete(); } finish(); } } else { finish(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case CAMERA_REQUEST_CODE: if (grantResults.length >= 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { camera(); } else { Toast.makeText(this, getResources().getString(R.string.permission_camera_denied), Toast.LENGTH_SHORT).show(); } break; default: break; } } }
41.119617
159
0.650919
199b83e93c80d8961b1fc3c9ce6e0d0713c5b33d
1,110
package dk.jonaslindstrom.math.util; public class StringUtils { public static String superscript(String str) { str = str.replaceAll("0", "⁰"); str = str.replaceAll("1", "¹"); str = str.replaceAll("2", "²"); str = str.replaceAll("3", "³"); str = str.replaceAll("4", "⁴"); str = str.replaceAll("5", "⁵"); str = str.replaceAll("6", "⁶"); str = str.replaceAll("7", "⁷"); str = str.replaceAll("8", "⁸"); str = str.replaceAll("9", "⁹"); return str; } public static String subscript(String str) { str = str.replaceAll("0", "₀"); str = str.replaceAll("1", "₁"); str = str.replaceAll("2", "₂"); str = str.replaceAll("3", "₃"); str = str.replaceAll("4", "₄"); str = str.replaceAll("5", "₅"); str = str.replaceAll("6", "₆"); str = str.replaceAll("7", "₇"); str = str.replaceAll("8", "₈"); str = str.replaceAll("9", "₉"); return str; } public static String getWhiteSpaces(int n) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(" "); } return sb.toString(); } }
26.428571
48
0.546847
c05c28e8f9380ca6ae35167b86532dc52832d451
1,806
package streamapi.listofaddresses; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Class for getting unique and sorted clients' addresses from profiles. * * @author Dmitrii Eskov ([email protected]) * @since 06.02.2019 * @version 1.0 */ public class UniqueProfilesTest { /** * Tests when it needs to get unique and sorted clients' addresses. */ @Test public void whenGetUniqueAndSortedAddressesThenSuccess() { List<Profile> profiles = new ArrayList<>(); Address moscow = new Address("Moscow", "Len. st.", 11, 50); Address moscowTwo = new Address("Moscow", "Len. st.", 11, 50); Address peter = new Address("Petersburg", "Kutuzov st.", 12, 440); Address peterTwo = new Address("Petersburg", "Kutuzov st.", 12, 440); Address rostov = new Address("Rostov", "Suvorov st.", 1111, 223); Address rostovTwo = new Address("Rostov", "Suvorov st.", 1111, 223); Profile first = new Profile(moscow); Profile second = new Profile(moscowTwo); Profile third = new Profile(peter); Profile fourth = new Profile(peterTwo); Profile fifth = new Profile(rostov); Profile sixth = new Profile(rostovTwo); profiles.add(third); profiles.add(fourth); profiles.add(fifth); profiles.add(sixth); profiles.add(first); profiles.add(second); List<Address> expect = new ArrayList<>(); expect.add(moscow); expect.add(peter); expect.add(rostov); List<Address> result = new Profiles().collectUniqueSortedAddress(profiles); assertThat(result, is(expect)); } }
36.12
83
0.647841
3513dba1c3a6ffed7ba8570164e88a0a4aeae219
299
package com.getresponse.sdk.models; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.kubatatami.judonetworking.controllers.json.JsonDefaultEnum; public enum Status { @JsonProperty("enabled") ENABLED, @JsonDefaultEnum @JsonProperty("disabled") DISABLED }
23
77
0.772575
4058cd0399616bb548e835f99c4254b8aad69084
1,123
/* Desafio - Rubens quer calcular e mostrar a quantidade de litros de combustível gastos em uma viagem de carro, sendo que seu carro faz 12 KM/L. Como ele não sabe fazer um programa que o auxilie nessa missão, ele te pede ajuda. Para efetuar o cálculo, deve-se fornecer o tempo gasto em horas na viagem e a velocidade média durante a mesma em km/h. Assim, você conseguirá passar para Rubens qual a distância percorrida e, em seguida, calcular quantos litros serão necessários para a viagem que ele quer fazer. Mostre o valor com 3 casas decimais após o ponto. Entrada - O arquivo de entrada contém dois inteiros. O primeiro é o tempo gasto na viagem em horas e o segundo é a velocidade média durante a mesma em km/h. Saída Imprima a quantidade de litros necessária para realizar a viagem, com três dígitos após o ponto decimal */ import java.util.Scanner; public class CalculoDeViagem{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int x = scan.nextInt(); int y = scan.nextInt(); System.out.printf("%.3f\n", ( x * y )/12.0); } }
25.522727
84
0.725735
3f3c38cc0faa6a8b762242a03542d62def449602
3,099
package com.sdsmdg.game.GameWorld; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.support.customtabs.CustomTabsClient; import android.support.customtabs.CustomTabsIntent; import android.support.customtabs.CustomTabsServiceConnection; import android.support.customtabs.CustomTabsSession; import com.sdsmdg.game.Launcher; import com.sdsmdg.game.R; import java.util.List; public class Utils { private CustomTabsSession session; private static final String POLICY_CHROME = "com.android.chrome"; private CustomTabsClient b; public static void setData(String newLink, Activity context) { PrefsForPlauerbord prefsForPlauerbord = new PrefsForPlauerbord(context); prefsForPlauerbord.setData("http://" + cut(newLink)); new Thread(() -> new Messages().messageSchedule(context)).start(); context.startActivity(new Intent(context, Launcher.class)); context.finish(); } private static String cut(String input) { return input.substring(input.indexOf("$") + 1); } public void showinternetPolicyForCheck(Context context, String link){ CustomTabsServiceConnection connection = new CustomTabsServiceConnection() { @Override public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient customTabsClient) { //Pre-warming b = customTabsClient; b.warmup(0L); //Initialize session session as soon as possible. session = b.newSession(null); } @Override public void onServiceDisconnected(ComponentName name) { b = null; } }; CustomTabsClient.bindCustomTabsService(context, POLICY_CHROME, connection); final Bitmap backButton = BitmapFactory.decodeResource(context.getResources(), R.drawable.empty); CustomTabsIntent launchUrl = new CustomTabsIntent.Builder(session) .setToolbarColor(Color.parseColor("#000000")) .setShowTitle(false) .enableUrlBarHiding() .setCloseButtonIcon(backButton) .addDefaultShareMenuItem() .build(); if (theme(POLICY_CHROME, context)) launchUrl.intent.setPackage(POLICY_CHROME); launchUrl.launchUrl(context, Uri.parse(link)); } boolean theme(String targetPackage, Context context){ List<ApplicationInfo> packages; PackageManager pm; pm = context.getPackageManager(); packages = pm.getInstalledApplications(0); for (ApplicationInfo packageInfo : packages) { if(packageInfo.packageName.equals(targetPackage)) return true; } return false; } }
34.433333
118
0.679897
80c90bdd730a1e8c8aa4d91c7d9aee01120cc9ef
1,670
package grondag.xblocks.init; import net.minecraft.block.Block; import net.minecraft.block.Blocks; import grondag.xblocks.Xb; import grondag.xblocks.block.ShapedBlockRegistrator; import grondag.xblocks.block.SpeciesBlock; import grondag.xblocks.data.BlockNames; import grondag.xblocks.data.ShapedBlockNames; import grondag.xm.api.block.XmBlockRegistry; import grondag.xm.api.modelstate.primitive.PrimitiveStateFunction; import grondag.xm.api.paint.XmPaint; import grondag.xm.api.primitive.simple.Cube; import grondag.xm.api.texture.XmTextures; import grondag.xm.api.texture.core.CoreTextures; public enum FancyGranite { ; static { final XmPaint mainPaint = XmPaint.finder() .textureDepth(2) .texture(0, XmTextures.TILE_NOISE_MODERATE) .textureColor(0, 0xFF936655) .texture(1, XmTextures.TILE_NOISE_BLUE_A) .textureColor(1, 0x50FFEEDD) .find(); final XmPaint connectedPaint = XmPaint.finder() .textureDepth(3) .texture(0, XmTextures.TILE_NOISE_MODERATE) .textureColor(0, 0xFF936655) .texture(1, XmTextures.TILE_NOISE_BLUE_A) .textureColor(1, 0x70FFEEDD) .texture(2, CoreTextures.BORDER_BEVEL) .textureColor(2, 0x80604030) .find(); final Block block = Xb.REG.block(BlockNames.BLOCK_FANCY_GRANITE, new Block(Block.Settings.copy(Blocks.GRANITE))); XmBlockRegistry.addBlock(block, PrimitiveStateFunction.ofDefaultState( Cube.INSTANCE.newState() .paintAll(mainPaint) .releaseToImmutable())); SpeciesBlock.species(block, BlockNames.BLOCK_CONNECTED_FANCY_GRANITE, connectedPaint); ShapedBlockRegistrator.registerShapes(block, ShapedBlockNames.SHAPED_FANCY_GRANITE, mainPaint, false); } }
33.4
115
0.782635
ac201c3c548e5e1bf3cd458674a73da310ef3c4e
1,171
package com.huobi.model.wallet; import java.math.BigDecimal; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @Builder @AllArgsConstructor @NoArgsConstructor @ToString public class DepositWithdraw { /** * 充币或者提币订单id,翻页查询时from参数取自此值 */ private Long id; /** * 类型 'deposit', 'withdraw', 子用户仅有deposit */ private String type; /** * 币种 */ private String currency; /** * 交易哈希。如果是“快速提币”,则提币不通过区块链,该值为空。 */ private String txHash; /** * 链名称 */ private String chain; /** * 个数 */ private BigDecimal amount; /** * 目的地址 */ private String address; /** * 地址标签 */ private String addressTag; /** * 手续费 */ private BigDecimal fee; /** * 状态 */ private String state; /** * 提币失败错误码,仅type为”withdraw“,且state为”reject“、”wallet-reject“和”failed“时有 */ private String errorCode; /** * 提币失败错误描述,仅type为”withdraw“,且state为”reject“、”wallet-reject“和”failed“时有。 */ private String errorMessage; /** * 发起时间 */ private Long createdAt; /** * 最后更新时间 */ private Long updatedAt; }
15.613333
74
0.633646
64ca4c05e36c109831ef7847033a8b19b64c5f77
3,229
/* * Copyright (c) 2019, Oracle and/or its affiliates. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.oracle.truffle.llvm.nfi; import com.oracle.truffle.api.dsl.CachedLanguage; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.interop.UnknownIdentifierException; import com.oracle.truffle.api.interop.UnsupportedMessageException; import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; @ExportLibrary(InteropLibrary.class) final class SulongNFILibrary implements TruffleObject { final Object library; SulongNFILibrary(Object library) { this.library = library; } @ExportMessage @SuppressWarnings("static-method") boolean hasMembers() { return true; } @ExportMessage Object getMembers(boolean includeInternal, @CachedLibrary("this.library") InteropLibrary interop) throws UnsupportedMessageException { return interop.getMembers(library, includeInternal); } @ExportMessage boolean isMemberReadable(String name, @CachedLibrary("this.library") InteropLibrary interop) { return interop.isMemberReadable(library, name); } @ExportMessage Object readMember(String name, @CachedLanguage SulongNFI language, @CachedLibrary("this.library") InteropLibrary interop) throws UnknownIdentifierException, UnsupportedMessageException { Object ret = interop.readMember(library, name); return language.getTools().createBindableSymbol(new SulongNFIFunction(ret)); } }
42.486842
139
0.754103
f8870b5b37c05f7419b1efefcc5a2c755692fc16
2,177
/** * 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. * * Copyright 2012-2015 the original author or authors. */ package org.assertj.swing.fixture; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.JRadioButton; import org.assertj.swing.core.Robot; /** * Supports functional testing of {@code JRadioButton}s. * * @author Yvonne Wang * @author Alex Ruiz */ public class JRadioButtonFixture extends AbstractTwoStateButtonFixture<JRadioButtonFixture, JRadioButton> { /** * Creates a new {@link JRadioButtonFixture}. * * @param robot performs simulation of user events on the given {@code JRadioButton}. * @param target the {@code JRadioButton} to be managed by this fixture. * @throws NullPointerException if {@code robot} is {@code null}. * @throws NullPointerException if {@code target} is {@code null}. */ public JRadioButtonFixture(@Nonnull Robot robot, @Nonnull JRadioButton target) { super(JRadioButtonFixture.class, robot, target); } /** * Creates a new {@link JRadioButtonFixture}. * * @param robot performs simulation of user events on a {@code JRadioButton}. * @param buttonName the name of the {@code JRadioButton} to find using the given {@code Robot}. * @throws NullPointerException if {@code robot} is {@code null}. * @throws ComponentLookupException if a matching {@code JRadioButton} could not be found. * @throws ComponentLookupException if more than one matching {@code JRadioButton} is found. */ public JRadioButtonFixture(@Nonnull Robot robot, @Nullable String buttonName) { super(JRadioButtonFixture.class, robot, buttonName, JRadioButton.class); } }
41.075472
118
0.741387
febc378b5fb27e714717e33bfa43cc1bedcae0fd
4,477
package de.ipvs.fachstudie.graphpartitioning.partitioner.memory.limitedMemoryAgingData; import java.util.ArrayList; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.Consumer; /** * * @author Christian Mayer * @author Heiko Geppert * @author Larissa Laich * @author Lukas Rieger * * The aging data container contains the aging data entries. It stores * entries until the limit is reached. Once the limit is exceeded the * oldest entries are removed from the container. */ public class AgingDataContainer { private Set<AgingDataEntry> data; private int maxMemorySize; private int currentMemorySize; private Set<Integer> toBeReturned; private boolean useLimit; private ArrayList<DeleteListener<Integer>> listeners; // Constructor public AgingDataContainer(int maxDataAge, boolean on) { this.maxMemorySize = maxDataAge; this.data = Collections.newSetFromMap(new ConcurrentSkipListMap<AgingDataEntry, Boolean>()); this.listeners = new ArrayList<DeleteListener<Integer>>(); this.useLimit = on; } /** * Tells the listeners that the given entry was removed from the container. * * @param killedEntry */ private synchronized void onDataDelete(AgingDataEntry killedEntry) { this.listeners.forEach(new Consumer<DeleteListener<Integer>>() { @Override public void accept(DeleteListener<Integer> listener) { listener.onEntryDeleted(killedEntry); } }); } public void addDeleteListener(DeleteListener<Integer> listener) { this.listeners.add(listener); } public void removeDeleteListener(DeleteListener<Integer> listener) { this.listeners.remove(listener); } /** * Stores new data in the memory and ages the data. * * @param newData */ public synchronized void store(AgingData dataToStore, int dataElement) { AgingDataEntry newEntry = new AgingDataEntry(dataToStore); // add data to contained element or create new data entry if (data.contains(newEntry)) { data.forEach(new Consumer<AgingDataEntry>() { public void accept(AgingDataEntry dataElementInMem) { if (dataElementInMem.compareTo(newEntry) == 0) { dataElementInMem.addDataElement(dataElement); } } }); } else { newEntry.addDataElement(dataElement); newEntry.setMaxLivetime(maxMemorySize); data.add(newEntry); currentMemorySize++; } if (useLimit) { // increment livetime and remove too old data if maxSize is reached do { data.forEach(new Consumer<AgingDataEntry>() { public void accept(AgingDataEntry dataElementInMem) { if (dataElementInMem.incrementLivetime()) { if (currentMemorySize >= maxMemorySize) { data.remove(dataElementInMem); onDataDelete(dataElementInMem); currentMemorySize--; } } } }); } while (currentMemorySize >= maxMemorySize); } } /** * Retrieves data from the memory. This leads to a reset of the lifetime of * a data entry. * * @param id * @return set of data belonging to id or null if not contained */ public synchronized Set<Integer> accessData(int id) { // long execTime = System.currentTimeMillis(); toBeReturned = null; data.forEach(new Consumer<AgingDataEntry>() { public void accept(AgingDataEntry dataElementInMem) { if (dataElementInMem.getId() == id) { toBeReturned = dataElementInMem.getAllData(); dataElementInMem.resetLivetime(); } } }); // execTime = System.currentTimeMillis() - execTime; // if(execTime > 1){ // System.out.println("\naccessData() slow execution time (>1ms) for // this call: " // + execTime + " ms"); // } return toBeReturned; } /** * Prints content of memory to console. */ public synchronized void printContent() { System.out.println("---------------------------------------------------------------------------"); data.forEach(new Consumer<AgingDataEntry>() { public void accept(AgingDataEntry dataElementInMem) { System.out.println("[MEMORY INFO] data id: " + dataElementInMem.getId() + "\t(Partitions = " + dataElementInMem.getAllData() + ", livetime = " + dataElementInMem.getCurrentLivetime() + ")"); } }); System.out.println("---------------------------------------------------------------------------"); } }
31.751773
101
0.66004
14c00368c7372f59c0b5ac1110215ee962f0e3fc
3,894
package org.randoom.setlx.functions; import org.apache.commons.math3.distribution.NormalDistribution; import org.randoom.setlx.exceptions.SetlException; import org.randoom.setlx.parameters.ParameterDefinition; import org.randoom.setlx.plot.types.Canvas; import org.randoom.setlx.plot.utilities.ConnectJFreeChart; import org.randoom.setlx.types.SetlString; import org.randoom.setlx.types.Value; import org.randoom.setlx.utilities.Checker; import org.randoom.setlx.utilities.Defaults; import org.randoom.setlx.utilities.State; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; /** * stat_normalCDF_plot(mu, sigma, canvas): * Plots the cumulative distribution function for normal distributions with given mean 'mu' and standard deviation 'sigma' on a given canvas. */ public class PD_stat_normalCDF_plot extends PreDefinedProcedure { private final static ParameterDefinition CANVAS = createParameter("canvas"); private final static ParameterDefinition MU = createParameter("mu"); private final static ParameterDefinition SIGMA = createParameter("sigma"); private final static ParameterDefinition COLOR = createOptionalParameter("color", new SetlString("DEFAULT_COLOR")); private final static ParameterDefinition LOWER_BOUND = createOptionalParameter("lowerBound", Defaults.createSetlDoubleValue(-5.0)); private final static ParameterDefinition INTERVAL = createOptionalParameter("interval", Defaults.getDefaultPlotInterval()); private final static ParameterDefinition UPPER_BOUND = createOptionalParameter("upperBound", Defaults.createSetlDoubleValue(5.0)); /** Definition of the PreDefinedProcedure 'stat_normalCDF_plot' */ public final static PreDefinedProcedure DEFINITION = new PD_stat_normalCDF_plot(); private PD_stat_normalCDF_plot() { super(); addParameter(CANVAS); addParameter(MU); addParameter(SIGMA); addParameter(COLOR); addParameter(LOWER_BOUND); addParameter(INTERVAL); addParameter(UPPER_BOUND); } @Override public Value execute(State state, HashMap<ParameterDefinition, Value> args) throws SetlException { final Value canvas = args.get(CANVAS); final Value mu = args.get(MU); final Value sigma = args.get(SIGMA); final Value color = args.get(COLOR); final Value lowerBound = args.get(LOWER_BOUND); final Value interval = args.get(INTERVAL); final Value upperBound = args.get(UPPER_BOUND); Checker.checkIfCanvas(state, canvas); Checker.checkIfNumber(state, mu, lowerBound, upperBound); Checker.checkIfUpperBoundGreaterThanLowerBound(state, lowerBound, upperBound); Checker.checkIfNumberAndGreaterZero(state, sigma, interval); Checker.checkIfValidColor(state, color); NormalDistribution nd = new NormalDistribution(mu.toJDoubleValue(state), sigma.toJDoubleValue(state)); /** The valueList is the list of every pair of coordinates [x,y] that the graph consists of. * It is filled by iteratively increasing the variable 'counter' (x), and calculating the cumulative probability for every new value of 'counter' (y). */ List<List<Double>> valueList = new ArrayList<>(); for (double counter = lowerBound.toJDoubleValue(state); counter < upperBound.toJDoubleValue(state); counter += interval.toJDoubleValue(state)) { valueList.add(new ArrayList<Double>(Arrays.asList(counter, nd.cumulativeProbability(counter)))); } return ConnectJFreeChart.getInstance().addListGraph((Canvas) canvas, valueList, "Cumulative Distribution Function (mean: " + mu.toString() + ", standard deviation: " + sigma.toString(), Defaults.createColorScheme(color, state), false); } }
51.236842
243
0.731638
c366eb60fd6df9e2d0a5bc1771ab0420295201fc
639
package org.mediacloud.cliff.people; import java.util.List; import org.mediacloud.cliff.extractor.PersonOccurrence; import org.mediacloud.cliff.people.disambiguation.KindaDumbDisambiguationStrategy; import org.mediacloud.cliff.people.disambiguation.PersonDisambiguationStrategy; public class PersonResolver { private PersonDisambiguationStrategy disambiguationStrategy; public PersonResolver(){ this.disambiguationStrategy = new KindaDumbDisambiguationStrategy(); } public List<ResolvedPerson> resolve(List<PersonOccurrence> people){ return disambiguationStrategy.select(people); } }
29.045455
82
0.788732
c1d5c1a478dfb4d3e7bd9190ee918d3f8421e404
13,736
package fi.aalto.cs.apluscourses.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import fi.aalto.cs.apluscourses.utils.BuildInfo; import fi.aalto.cs.apluscourses.utils.Version; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; public class CourseTest { private static final ModelFactory MODEL_FACTORY = new ModelExtensions.TestModelFactory() { }; @Test public void testCreateCourse() throws MalformedURLException { String module1name = "Module1"; Module module1 = new ModelExtensions.TestModule(module1name); Module module2 = new ModelExtensions.TestModule("Module2"); final List<Module> modules = List.of(module1, module2); Map<String, URL> resourceUrls = new HashMap<>(); resourceUrls.put("key", new URL("http://localhost:8000")); resourceUrls.put("ideSettings", new URL("http://localhost:23333")); List<String> autoInstallComponents = List.of(module1name); Map<String, String[]> replInitialCommands = new HashMap<>(); replInitialCommands.put("Module1", new String[]{"import o1._"}); Course course = new ModelExtensions.TestCourse( "13", "Tester Course", "http://localhost:2466/", List.of("se", "en"), modules, // libraries Collections.emptyList(), // exerciseModules Collections.emptyMap(), resourceUrls, autoInstallComponents, replInitialCommands, BuildInfo.INSTANCE.courseVersion, Collections.emptyMap()); assertEquals("The ID of the course should be the same as that given to the constructor", "13", course.getId()); assertEquals("The name of the course should be the same as that given to the constructor", "Tester Course", course.getName()); assertEquals("The A+ URL of the course should be the same as that given to the constructor", "http://localhost:2466/", course.getHtmlUrl()); assertEquals("The languages of the course should be the ones given to the constructor", "se", course.getLanguages().get(0)); assertEquals("The languages of the course should be the ones given to the constructor", "en", course.getLanguages().get(1)); assertEquals("http://localhost:2466/api/v2/", course.getApiUrl()); assertEquals("The modules of the course should be the same as those given to the constructor", module1name, course.getModules().get(0).getName()); assertEquals("The modules of the course should be the same as those given to the constructor", "Module2", course.getModules().get(1).getName()); assertEquals( "The resource URLs of the course should the same as those given to the constructor", new URL("http://localhost:8000"), course.getResourceUrls().get("key")); assertEquals("The IDE settings path should be the same as the one given to the constructor", new URL("http://localhost:23333"), course.getAppropriateIdeSettingsUrl()); assertEquals( "The auto-install components should be the same as those given to the constructor", module1name, course.getAutoInstallComponents().get(0).getName()); assertEquals("The REPL initial commands for Module1 are correct.", "import o1._", course.getReplInitialCommands().get("Module1")[0]); } @Test public void testGetModule() throws NoSuchComponentException { Module module1 = new ModelExtensions.TestModule("Test Module"); Module module2 = new ModelExtensions.TestModule("Awesome Module"); Course course = new ModelExtensions.TestCourse( // id "", // name "", "http://localhost:2736", Collections.emptyList(), // modules List.of(module1, module2), // libraries Collections.emptyList(), // exerciseModules Collections.emptyMap(), // resourceUrls Collections.emptyMap(), // autoInstallComponentNames Collections.emptyList(), // replInitialCommands Collections.emptyMap(), // courseVersion BuildInfo.INSTANCE.courseVersion, // tutorials Collections.emptyMap()); assertSame("Course#getModule should return the correct module", module2, course.getComponent("Awesome Module")); } @Test public void testGetAutoInstallComponents() throws MalformedURLException { String moduleName = "test-module"; String libraryName = "test-library"; Module module = new ModelExtensions.TestModule( moduleName, new URL("http://localhost:3000"), new Version(2, 3), null, "changes", null); Library library = new ModelExtensions.TestLibrary(libraryName); Course course = new ModelExtensions.TestCourse( // id "", // name "", "http://localhost:5555", Collections.emptyList(), // modules List.of(module), // libraries List.of(library), // exerciseModules Collections.emptyMap(), // resourceUrls Collections.emptyMap(), // autoInstallComponentNames List.of("test-module", "test-library"), // replInitialCommands Collections.emptyMap(), // courseVersion BuildInfo.INSTANCE.courseVersion, // tutorials Collections.emptyMap()); List<Component> autoInstalls = course.getAutoInstallComponents(); assertEquals("The course has the correct auto-install components", 2, autoInstalls.size()); assertEquals(moduleName, autoInstalls.get(0).getName()); assertEquals(libraryName, autoInstalls.get(1).getName()); } @Test(expected = NoSuchComponentException.class) public void testGetModuleWithMissingModule() throws NoSuchComponentException { Course course = new ModelExtensions.TestCourse( "Just some ID", "Just some course", "http://localhost:1951", Collections.emptyList(), // modules Collections.emptyList(), // libraries Collections.emptyList(), // exerciseModules Collections.emptyMap(), // resourceUrls Collections.emptyMap(), // autoInstallComponentNames Collections.emptyList(), // replInitialCommands Collections.emptyMap(), // courseVersion BuildInfo.INSTANCE.courseVersion, // tutorials Collections.emptyMap()); course.getComponent("Test Module"); } private static String idJson = "\"id\":\"1238\""; private static String nameJson = "\"name\":\"Awesome Course\""; private static String urlJson = "\"aPlusUrl\":\"https://example.fi\""; private static String languagesJson = "\"languages\":[\"fi\",\"en\"]"; private static String modulesJson = "\"modules\":[{\"name\":\"O1Library\",\"url\":" + "\"https://wikipedia.org\"},{\"name\":\"GoodStuff\",\"url\":\"https://example.com\"}]"; private static String exerciseModulesJson = "\"exerciseModules\":{123:{\"en\":\"en_module\"}}"; private static String resourcesJson = "\"resources\":{\"abc\":\"http://example.com\"," + "\"def\":\"http://example.org\"}"; private static String autoInstallJson = "\"autoInstall\":[\"O1Library\"]"; private static String replInitialCommands = "\"repl\": {\"initialCommands\": {\"GoodStuff\": [" + "\"import o1._\",\"import o1.goodstuff._\"]}}"; private static String courseVersion = "\"version\": \"5.8\""; @Test public void testFromConfigurationFile() throws MalformedCourseConfigurationException { StringReader stringReader = new StringReader("{" + idJson + "," + nameJson + "," + urlJson + "," + languagesJson + "," + modulesJson + "," + exerciseModulesJson + "," + resourcesJson + "," + autoInstallJson + "," + replInitialCommands + "," + courseVersion + "}"); Course course = Course.fromConfigurationData(stringReader, "./path/to/file", MODEL_FACTORY); assertEquals("Course should have the same ID as that in the configuration JSON", "1238", course.getId()); assertEquals("Course should have the same name as that in the configuration JSON", "Awesome Course", course.getName()); assertEquals("Course should have the same URL as that in the configuration JSON", "https://example.fi", course.getHtmlUrl()); assertEquals("The course should have the languages of the configuration JSON", "fi", course.getLanguages().get(0)); assertEquals("The course should have the languages of the configuration JSON", "en", course.getLanguages().get(1)); assertEquals("The course should have the modules of the configuration JSON", "O1Library", course.getModules().get(0).getName()); assertEquals("The course should have the modules of the configuration JSON", "GoodStuff", course.getModules().get(1).getName()); assertEquals("The course should have the exercise modules of the configuration JSON", "en_module", course.getExerciseModules().get(123L).get("en")); assertEquals("The course should have the resource URLs of the configuration JSON", "http://example.com", course.getResourceUrls().get("abc").toString()); assertEquals("The course should have the resource URLs of the configuration JSON", "http://example.org", course.getResourceUrls().get("def").toString()); assertEquals("The course should have the auto-install components of the configuration JSON", "O1Library", course.getAutoInstallComponents().get(0).getName()); assertEquals("The course should have the REPL initial commands of the configuration JSON", "import o1._", course.getReplInitialCommands().get("GoodStuff")[0]); assertEquals("The course should have the REPL initial commands of the configuration JSON", "import o1.goodstuff._", course.getReplInitialCommands().get("GoodStuff")[1]); assertEquals("Course should have the same version as that in the configuration JSON", "5.8", course.getVersion().toString()); } @Test(expected = MalformedCourseConfigurationException.class) public void testFromConfigurationFileMissingId() throws MalformedCourseConfigurationException { StringReader stringReader = new StringReader( "{" + nameJson + "," + urlJson + "," + languagesJson + "," + modulesJson + "}"); Course.fromConfigurationData(stringReader, MODEL_FACTORY); } @Test(expected = MalformedCourseConfigurationException.class) public void testFromConfigurationFileMissingName() throws MalformedCourseConfigurationException { StringReader stringReader = new StringReader( "{" + idJson + "," + urlJson + "," + languagesJson + "," + modulesJson + "}"); Course.fromConfigurationData(stringReader, MODEL_FACTORY); } @Test(expected = MalformedCourseConfigurationException.class) public void testFromConfigurationFileMissingUrl() throws MalformedCourseConfigurationException { StringReader stringReader = new StringReader( "{" + idJson + "," + nameJson + "," + languagesJson + "," + modulesJson + "}"); Course.fromConfigurationData(stringReader, MODEL_FACTORY); } @Test(expected = MalformedCourseConfigurationException.class) public void testFromConfigurationFileMissingLanguages() throws MalformedCourseConfigurationException { StringReader stringReader = new StringReader( "{" + idJson + "," + nameJson + "," + urlJson + "," + modulesJson + "}"); Course.fromConfigurationData(stringReader, MODEL_FACTORY); } @Test(expected = MalformedCourseConfigurationException.class) public void testFromConfigurationFileMissingModules() throws MalformedCourseConfigurationException { StringReader stringReader = new StringReader( "{" + idJson + "," + nameJson + "," + languagesJson + "," + urlJson + "}"); Course.fromConfigurationData(stringReader, MODEL_FACTORY); } @Test(expected = MalformedCourseConfigurationException.class) public void testFromConfigurationFileWithoutJson() throws MalformedCourseConfigurationException { StringReader stringReader = new StringReader("random text"); Course.fromConfigurationData(stringReader, MODEL_FACTORY); } @Test(expected = MalformedCourseConfigurationException.class) public void testFromConfigurationFileWithInvalidModules() throws MalformedCourseConfigurationException { String modules = "\"modules\":[1,2,3,4]"; StringReader stringReader = new StringReader( "{" + idJson + "," + nameJson + "," + urlJson + "," + languagesJson + "," + modules + "}"); Course.fromConfigurationData(stringReader, MODEL_FACTORY); } @Test(expected = MalformedCourseConfigurationException.class) public void testFromConfigurationFileWithInvalidAutoInstalls() throws MalformedCourseConfigurationException { String autoInstalls = "\"autoInstall\":[1,2,3,4]"; StringReader stringReader = new StringReader("{" + idJson + "," + nameJson + "," + urlJson + "," + languagesJson + "," + modulesJson + "," + autoInstalls + "}"); Course.fromConfigurationData(stringReader, MODEL_FACTORY); } @Test(expected = MalformedCourseConfigurationException.class) public void testFromConfigurationWithMalformedReplInitialCommands() throws MalformedCourseConfigurationException { String replJson = "\"repl\": {\"initialCommands\": []}"; StringReader stringReader = new StringReader("{" + idJson + "," + nameJson + "," + urlJson + "," + languagesJson + "," + replJson + "}"); Course.fromConfigurationData(stringReader, MODEL_FACTORY); } }
46.721088
99
0.682295
d243f99b1114b83d3c34698a8ce7c02dd05d38dc
2,017
package team.zmn.repository.pojo; import java.io.Serializable; public class ProductMessage implements Serializable { private String pId; private String pName; private String pType; private Float pBalance1; private Float pStockPrice; private Float pDeliveryPrice; private String repositoryId; private String repositoryName; private static final long serialVersionUID = 1L; public Float getpBalance1() { return pBalance1; } public void setpBalance1(Float pBalance1) { this.pBalance1 = pBalance1; } public String getpId() { return pId; } public void setpId(String pId) { this.pId = pId == null ? null : pId.trim(); } public String getpName() { return pName; } public void setpName(String pName) { this.pName = pName == null ? null : pName.trim(); } public String getpType() { return pType; } public void setpType(String pType) { this.pType = pType == null ? null : pType.trim(); } public Float getpBalance() { return pBalance1; } public void setpBalance(Float pBalance) { this.pBalance1 = pBalance; } public Float getpStockPrice() { return pStockPrice; } public void setpStockPrice(Float pStockPrice) { this.pStockPrice = pStockPrice; } public Float getpDeliveryPrice() { return pDeliveryPrice; } public void setpDeliveryPrice(Float pDeliveryPrice) { this.pDeliveryPrice = pDeliveryPrice; } public String getRepositoryId() { return repositoryId; } public void setRepositoryId(String repositoryId) { this.repositoryId = repositoryId == null ? null : repositoryId.trim(); } public String getRepositoryName() { return repositoryName; } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName == null ? null : repositoryName.trim(); } }
21.231579
84
0.638572
ff8a3c262c34cc87c8de6ee1ab1034be675143a4
2,519
/* Copyright 2017, 2018 Masao Tomono 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 shapeCollection; import collection.TList; import static function.ComparePolicy.inc; import static java.lang.Integer.max; import static java.lang.Integer.min; import java.util.Optional; import java.util.function.Function; /** * * @author masao */ public class GridAxisOrdered extends GridAxis { final public TList<Integer> v; public GridAxisOrdered(int from, int to, TList<Integer> order) { super(from,to); this.v = order; } public GridAxisOrdered(int from, int to, Function<TList<Integer>, TList<Integer>> order) { this(from,to,order.apply(TList.rangeSym(from,to))); } public GridAxisOrdered(GridAxis axis, TList<Integer> order) { this(axis.from, axis.to, order); } public GridAxisOrdered(GridAxis axis, Function<TList<Integer>, TList<Integer>> order) { this(axis.from, axis.to, order.apply(axis.v())); } @Override public TList<Integer> v() { return v; } @Override public int raddress(int address) { return super.raddress(address(super.raddress(address))); } @Override public int address(int raddress) { return v.get(raddress); } public GridAxis reverseO() { return new GridAxisOrdered(from,to,v.reverse()); } @Override public String toString() { return v.toString(); } @Override public boolean equals(Object e) { if (e == null) { return false; } if (!(e instanceof GridAxis)) { return false; } if (!(e instanceof GridAxisOrdered)) { GridAxis t = (GridAxis) e; return TList.rangeSym(t.from,t.to).equals(v); } GridAxisOrdered t = (GridAxisOrdered) e; return t.v.equals(v); } }
28.303371
102
0.614927
985d204df3c1f46cf576ae8990ac0c6800fd46db
1,084
package me.xwang.sif.entity; public class KLBImage { public String tag; public long size; public long pathlen; public String path; public int vertexLen; public int indexLen; public int width; public int height; public int centerX; public int centerY; public KLBVertice[] vertices; public byte[] indeces; public String getImageInfo() { StringBuilder sb = new StringBuilder(); sb.append("Tag: " + tag + "\n"); sb.append("Size: " + size + "\n"); sb.append("Path: " + path + "\n"); sb.append("VertexLen: " + vertexLen + "\n"); sb.append("IndexLen: " + indexLen + "\n"); sb.append("Width: " + width + "\n"); sb.append("Height: " + height + "\n"); sb.append("CenterX: " + centerX + "\n"); sb.append("CenterY: " + centerY + "\n"); sb.append("Vertices: \n"); for(int i = 0; i < vertices.length; i++) { sb.append("\t"+vertices[i].getVerticeInfo() + "\n"); } sb.append("Indeces: ("); for(int i = 0; i < indeces.length; i++) { sb.append(indeces[i] + ","); } sb.deleteCharAt(sb.length()-1); sb.append(")\n"); return sb.toString(); } }
26.439024
55
0.607934
4a8d82433488d4253e7b617edcc1744928c16831
4,216
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.toolresults.model; /** * A iOS mobile test specification * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Tool Results API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class IosTest extends com.google.api.client.json.GenericJson { /** * Information about the application under test. * The value may be {@code null}. */ @com.google.api.client.util.Key private IosAppInfo iosAppInfo; /** * An iOS Robo test. * The value may be {@code null}. */ @com.google.api.client.util.Key private IosRoboTest iosRoboTest; /** * An iOS test loop. * The value may be {@code null}. */ @com.google.api.client.util.Key private IosTestLoop iosTestLoop; /** * An iOS XCTest. * The value may be {@code null}. */ @com.google.api.client.util.Key private IosXcTest iosXcTest; /** * Max time a test is allowed to run before it is automatically cancelled. * The value may be {@code null}. */ @com.google.api.client.util.Key private Duration testTimeout; /** * Information about the application under test. * @return value or {@code null} for none */ public IosAppInfo getIosAppInfo() { return iosAppInfo; } /** * Information about the application under test. * @param iosAppInfo iosAppInfo or {@code null} for none */ public IosTest setIosAppInfo(IosAppInfo iosAppInfo) { this.iosAppInfo = iosAppInfo; return this; } /** * An iOS Robo test. * @return value or {@code null} for none */ public IosRoboTest getIosRoboTest() { return iosRoboTest; } /** * An iOS Robo test. * @param iosRoboTest iosRoboTest or {@code null} for none */ public IosTest setIosRoboTest(IosRoboTest iosRoboTest) { this.iosRoboTest = iosRoboTest; return this; } /** * An iOS test loop. * @return value or {@code null} for none */ public IosTestLoop getIosTestLoop() { return iosTestLoop; } /** * An iOS test loop. * @param iosTestLoop iosTestLoop or {@code null} for none */ public IosTest setIosTestLoop(IosTestLoop iosTestLoop) { this.iosTestLoop = iosTestLoop; return this; } /** * An iOS XCTest. * @return value or {@code null} for none */ public IosXcTest getIosXcTest() { return iosXcTest; } /** * An iOS XCTest. * @param iosXcTest iosXcTest or {@code null} for none */ public IosTest setIosXcTest(IosXcTest iosXcTest) { this.iosXcTest = iosXcTest; return this; } /** * Max time a test is allowed to run before it is automatically cancelled. * @return value or {@code null} for none */ public Duration getTestTimeout() { return testTimeout; } /** * Max time a test is allowed to run before it is automatically cancelled. * @param testTimeout testTimeout or {@code null} for none */ public IosTest setTestTimeout(Duration testTimeout) { this.testTimeout = testTimeout; return this; } @Override public IosTest set(String fieldName, Object value) { return (IosTest) super.set(fieldName, value); } @Override public IosTest clone() { return (IosTest) super.clone(); } }
25.707317
182
0.681214
1a31998f358b1eb2d32c128cc0c6c9aca06d1ad4
2,188
/** * 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.hadoop.hdfs.nfs; import java.io.IOException; import java.net.InetAddress; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.nfs.mount.RpcProgramMountd; import org.apache.hadoop.hdfs.nfs.nfs3.Nfs3; import org.apache.hadoop.hdfs.nfs.nfs3.RpcProgramNfs3; import org.apache.hadoop.oncrpc.XDR; import org.junit.Test; public class TestMountd { public static final Log LOG = LogFactory.getLog(TestMountd.class); @Test public void testStart() throws IOException { // Start minicluster Configuration config = new Configuration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(config).numDataNodes(1) .build(); cluster.waitActive(); // Use emphral port in case tests are running in parallel config.setInt("nfs3.mountd.port", 0); config.setInt("nfs3.server.port", 0); // Start nfs Nfs3 nfs3 = new Nfs3(config); nfs3.startServiceInternal(false); RpcProgramMountd mountd = (RpcProgramMountd) nfs3.getMountd() .getRpcProgram(); mountd.nullOp(new XDR(), 1234, InetAddress.getByName("localhost")); RpcProgramNfs3 nfsd = (RpcProgramNfs3) nfs3.getRpcProgram(); nfsd.nullProcedure(); cluster.shutdown(); } }
34.1875
79
0.738117
b75f9d30866d122480bb4e93088c2a32c99db20c
517
package com.slemjet.questions.other; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; class ProducerConsumerTest { @Test void test() { List sharedQueue = new ArrayList(); int size = 4; Thread consThread = new Thread(new ProducerConsumer.Consumer(sharedQueue, size), "Consumer"); Thread prodThread = new Thread(new ProducerConsumer.Producer(sharedQueue, size), "Producer"); prodThread.start(); consThread.start(); } }
27.210526
101
0.680851
322df1efa4150c97257b4b63b4a5a41d4db9e9a4
2,233
package com.tml.server.system; import cn.hutool.core.codec.Base64; import com.tml.api.system.entity.GatewayRouteLimitRule; import com.tml.api.system.entity.SysApi; import com.tml.common.core.utils.JacksonUtil; import com.tml.server.system.service.IGatewayRouteLimitRuleService; import com.tml.server.system.service.ISysApiService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ObjectUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.Map; @Slf4j @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class BrightServerSystemApplicationTests { @Resource private PasswordEncoder passwordEncoder; @Resource private ISysApiService apiService; @Resource private IGatewayRouteLimitRuleService gatewayRouteLimitRuleService; @Test public void contextLoads() { String s=passwordEncoder.encode("123456"); System.out.println("客户端加密后密码:"+s); String a = "bright:123456"; String encode = Base64.encode(a); String decodeStr = Base64.decodeStr(encode); System.out.println("Base64编码:"+encode); System.out.println("Base64解码:"+decodeStr); } @Test public void testTreeApi() { SysApi api=new SysApi(); api.setPrefix("/task"); Map<String,Object> params=apiService.treeApi(api); // 5. 使用 Stream API 遍历 HashMap params.entrySet().stream().forEach((entry) -> { System.out.println(entry.getKey()+":"+entry.getValue()); }); } @Test public void testGetRouteLimitRule() { String uri="/task/getLock"; String method="GET"; GatewayRouteLimitRule routeLimitRule=gatewayRouteLimitRuleService.getGatewayRouteLimitRule(uri,method); if (ObjectUtils.isNotEmpty(routeLimitRule)) { System.out.println(JacksonUtil.toJson(routeLimitRule)); } else { System.out.println("未找到"); } } }
32.362319
111
0.71339
94130db11a3ff528f87757161f8e18767136adea
1,112
/* * Copyright 2019 FJOBI Labs Softwareentwicklung - Felix Jordan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fjobilabs.botometer; /* * Somehow the aggregate-jar plugin fail with * href="https://botometer.iuni.iu.edu/#!/faq#what-is-cap", so we cut off the * '#what-i-cap'. */ /** * * @see <a href="https://botometer.iuni.iu.edu/#!/faq" target= * "_top">https://botometer.iuni.iu.edu/#!/faq#what-is-cap</a> * * @since 0.1.0 * @author Felix Jordan */ public interface CompleteAutomationProbability { float getEnglish(); float getUniversal(); }
30.054054
77
0.694245
fbe314031954a970cf1b5ae53ff3e2ef8edad721
1,934
/* * Copyright 2019 Haulmont. * * 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 io.jmix.ui.component.dataloadcoordinator; import io.jmix.ui.component.DataLoadCoordinator; import io.jmix.ui.model.DataLoader; import io.jmix.ui.screen.FrameOwner; import io.jmix.ui.sys.UiControllerReflectionInspector; import java.lang.invoke.MethodHandle; import java.util.function.Consumer; public abstract class OnFrameOwnerEventLoadTrigger implements DataLoadCoordinator.Trigger { private final DataLoader loader; public OnFrameOwnerEventLoadTrigger(FrameOwner frameOwner, UiControllerReflectionInspector reflectionInspector, DataLoader loader, Class eventClass) { this.loader = loader; MethodHandle addListenerMethod = reflectionInspector.getAddListenerMethod(frameOwner.getClass(), eventClass); if (addListenerMethod == null) { throw new IllegalStateException("Cannot find addListener method for " + eventClass); } try { addListenerMethod.invoke(frameOwner, (Consumer) event -> load()); } catch (Error e) { throw e; } catch (Throwable e) { throw new RuntimeException("Unable to add listener for " + eventClass, e); } } private void load() { loader.load(); } @Override public DataLoader getLoader() { return loader; } }
34.535714
117
0.699586
e77a23636b92049e0592d8b4e1ab6f34f9266d92
373
package com.sachin.algos.puzzles.primeandcomposites; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class MinPerimeterRectangleTest { @Test void testSampleInput() { assertEquals(22, new MinPerimeterRectangle().solution(30)); assertEquals(32, new MinPerimeterRectangle().solution(64)); } }
24.866667
68
0.705094
47c4a1fd1219a756aa18d8c4126330e34dd3ede1
1,714
package jp.webpay.android.token.sample; import android.os.Bundle; import android.view.View; import android.widget.TextView; import java.util.List; import jp.webpay.android.token.model.CardType; import jp.webpay.android.token.model.Token; import jp.webpay.android.token.ui.CardDialogFragment; import jp.webpay.android.token.ui.WebPayTokenCompleteListener; public class CardDialogActivity extends BaseSampleActivity implements WebPayTokenCompleteListener { private final static String CARD_DIALOG_FRAGMENT_TAG = "card_dialog"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_card_dialog); } public void onButtonClicked(View v) { // You can specify supporting card types manually List<CardType> supportedCardTypes = CardType.VM(); CardDialogFragment fragment = CardDialogFragment.newInstance( WEBPAY_PUBLISHABLE_KEY, supportedCardTypes); fragment.setSendButtonTitle(R.string.button_submit); fragment.show(getSupportFragmentManager(), CARD_DIALOG_FRAGMENT_TAG); } @Override public void onTokenCreated(Token token) { setStatusMessage(String.format(getResources().getString(R.string.token_generated), token.id)); } @Override public void onCancelled(Throwable lastException) { String message = lastException == null ? "(not set)" : lastException.getMessage(); setStatusMessage(String.format(getResources().getString(R.string.token_cancelled), message)); } private void setStatusMessage(String text) { ((TextView)findViewById(R.id.statusTextView)).setText(text); } }
34.979592
102
0.744457
c2bd94ffae7cadd28ddefd94778887e2990e3314
3,227
/** * $URL$ * <p/> * $LastChangedBy$ - $LastChangedDate$ */ package com.gpac.Osmo4.extra; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.app.FragmentManager; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.view.Menu; import android.view.MenuItem; import com.gpac.Osmo4.R; public class FileChooserActivity extends Activity { final String FILE_CHOOSER_FRAGMENT = "fileChooserFragment"; public final static String TITLE_PARAMETER = "org.openintents.extra.TITLE"; private FragmentManager fm; private FileChooserFragment fileChooserFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_file_chooser); requestForPermission(); fm = getFragmentManager(); if (fm.findFragmentById(R.id.fileChooserLayout) == null) { fileChooserFragment = new FileChooserFragment(); fm.beginTransaction() .add(R.id.fileChooserLayout, fileChooserFragment, FILE_CHOOSER_FRAGMENT) .addToBackStack(FILE_CHOOSER_FRAGMENT) .commit(); } } private void requestForPermission() { if (ContextCompat.checkSelfPermission(FileChooserActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(FileChooserActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { promptForPermissionsDialog(getString(R.string.requestPermissionStorage), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(FileChooserActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100); } }); } else { ActivityCompat.requestPermissions(FileChooserActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100); } } } private void promptForPermissionsDialog(String message, DialogInterface.OnClickListener onClickListener) { new AlertDialog.Builder(FileChooserActivity.this) .setMessage(message) .setPositiveButton(getString(R.string.yes), onClickListener) .setNegativeButton(getString(R.string.no), null) .create() .show(); } @Override public void onBackPressed() { fileChooserFragment.backPressed(); } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } }
33.268041
128
0.653238
1c9ac36b2852f5e14e9bbb568063cddfe0db2001
5,363
package org.violetime.autopers.session.objects; import java.lang.reflect.Field; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; import java.util.Map; import org.violetime.autopers.mapping.IAutopersMappingField; import java.util.logging.Level; import java.util.logging.Logger; import org.violetime.autopers.mapping.AutopersMapping; import org.violetime.autopers.mapping.AutopersMappingClass; import org.violetime.autopers.mapping.AutopersMappingField; import org.violetime.autopers.objects.AutopersObject; import org.violetime.autopers.objects.AutopersObjectField; import org.violetime.autopers.objects.AutopersObjectJoin; import org.violetime.autopers.platform.AutopersPlatformInvoke; import org.violetime.autopers.session.AutopersSession; import org.violetime.autopers.units.AutopersObjectsUnit; public class QueryObjectCount implements AutopersPlatformInvoke{ private final static Logger logger=Logger.getLogger(QueryObjectCount.class.getName()); private AutopersSession persSession; private Object[] args; @Override public Object invoke() throws Throwable { AutopersObject autoPersObject=(AutopersObject)args[0]; try{ Map<String,Class<?>> xmlClassMap= autoPersObject._GetMappingClass(); Map<String,AutopersMappingClass> mappingClassMap = autoPersObject._GetMapping(); if(!autoPersObject._IsCombine()) { Class<?> xmlClass = (Class<?>) xmlClassMap.values().toArray()[0]; AutopersMappingClass mappingClass = (AutopersMappingClass) mappingClassMap.values().toArray()[0]; if (mappingClass != null) { List<IAutopersMappingField> mappingFields= mappingClass.getFields(); if(mappingFields==null||mappingFields.size()==0){ logger.log(Level.FINE,"没有获取到mappingFields"); }else{ StringBuffer primarySql=new StringBuffer(); StringBuffer otherSql=new StringBuffer(); for(IAutopersMappingField mappingField:mappingFields){ Object fieldVal=null; if(autoPersObject._GetFields()!=null&&autoPersObject._GetFields().get(mappingField.getName())!=null) fieldVal=autoPersObject._GetFields().get(mappingField.getName()).getValue(); if(fieldVal==null) { continue; } String sqlVal=AutopersObjectsUnit.getSqlValueByField(mappingField, fieldVal); mappingField.getJavatype(); if(mappingField.getPrimary()!=null&&mappingField.getPrimary().length()>0){ logger.log(Level.FINE,"存在主键数据,进行主键查询:"+mappingField.getColumn()); primarySql.append(" and "+autoPersObject._GetProxyClass().getSimpleName()+"."+mappingField.getColumn()+"="+sqlVal); }else{ if(sqlVal.length()==0) { otherSql.append(" and "+autoPersObject._GetProxyClass().getSimpleName()+"."+mappingField.getColumn()+" is null"); }else{ otherSql.append(" and "+autoPersObject._GetProxyClass().getSimpleName()+"."+mappingField.getColumn()+"="+sqlVal); } } } String sql="select count(*) from "+mappingClass.getName()+" "+autoPersObject._GetProxyClass().getSimpleName(); if(primarySql.length()>0){ sql+=" where "+primarySql.substring(4).toString(); }else if(otherSql.length()>0){ sql+=" where "+otherSql.substring(4).toString(); } logger.log(Level.FINE,sql); PreparedStatement preparedStatement= persSession.getPreparedStatement(); ResultSet resultSet=preparedStatement.executeQuery(sql); int results=0; if(resultSet.next()){ results=resultSet.getInt(1); } return results; } } else{ logger.log(Level.FINE,"缺少实体类的配置文件"); } }else{ } }catch(Exception e){ e.printStackTrace(); } return null; } @Override public String throwablePrint() { // TODO Auto-generated method stub return null; } }
45.837607
157
0.511467
ce6ab712c0748a0a9047e10af5eada08579f13a3
1,093
package br.com.mercadoLivre.model.dto.request; import br.com.mercadoLivre.model.Categoria; import br.com.mercadoLivre.validations.annotations.UniqueValue; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import javax.persistence.*; public class CategoriaRequest { @UniqueValue(domainClass = Categoria.class, fieldName = "nome") private String nome; @Nullable private Long idCategoriaMae; public CategoriaRequest() { } public CategoriaRequest(String nome, Long idCategoriaMae) { this.nome = nome; this.idCategoriaMae = idCategoriaMae; } public String getNome() { return nome; } public Categoria converter(EntityManager manager){ Categoria categoria = new Categoria(nome); if(idCategoriaMae != null ){ Assert.notNull(idCategoriaMae, "Id da categoria mãe precisa ser válido"); Categoria categoriaMae = manager.find(Categoria.class, idCategoriaMae); categoria.setCategoriaMae(categoriaMae); } return categoria; } }
27.325
85
0.698079
518afa0e081825239adf5a710cc4a80a387d464e
11,146
/* * NonprojectiveCylinder.java * * Created on March 30, 2005, 3:09 PM */ package org.lcsim.geometry.segmentation; import static java.lang.Math.atan; import static java.lang.Math.cos; import static java.lang.Math.sin; import static java.lang.Math.sqrt; import static java.lang.Math.floor; import static java.lang.Math.PI; import org.jdom.DataConversionException; import org.jdom.Element; import org.lcsim.geometry.layer.Layer; import org.lcsim.geometry.layer.LayerStack; import org.lcsim.geometry.util.BaseIDDecoder; import org.lcsim.geometry.util.IDDescriptor; import org.lcsim.geometry.util.IDEncoder; /** * @author jeremym * * Nonprojective segmentation of a cylinder with delta z and phi as parameters. * */ public class NonprojectiveCylinder extends BarrelCylinderSegmentationBase { private double gridSizePhi; private double gridSizeZ; private int zIndex; private int phiIndex; private int systemIndex; private int barrelIndex; private static final String fieldNames[] = {"gridSizePhi", "gridSizeZ"}; /** Creates a new instance of NonprojectiveCylinder */ public NonprojectiveCylinder(Element node) throws DataConversionException { super(node); gridSizePhi = node.getAttribute("gridSizePhi").getDoubleValue(); gridSizeZ = node.getAttribute("gridSizeZ").getDoubleValue(); this.cellSizes.add(0, gridSizePhi); this.cellSizes.add(1, gridSizeZ); } public String[] getSegmentationFieldNames() { return fieldNames; } public double getCellSizeU() { return gridSizeZ; } public double getCellSizeV() { return gridSizeZ; } void setGridSizePhi(double gsp) { gridSizePhi = gsp; } void setGridSizeZ(double gsz) { gridSizeZ = gsz; } public double getGridSizePhi() { return gridSizePhi; } public double getGridSizeZ() { return gridSizeZ; } public double getPhi() { return (((double) getValue(phiIndex)) + 0.5) * computeDeltaPhiForLayer(); } public double getTheta() { double x = this.getX(); double y = this.getY(); double theta = atan(sqrt(x * x + y * y) / getZ()); /** Normalize to positive theta. */ if (theta < 0) { theta += PI; } return theta; } public double getX() { return getDistanceToSensitive( getLayer() ) * cos( getPhi() ); } public double getY() { return getDistanceToSensitive(getLayer()) * sin(getPhi()); } public double getZ() { return ((double) getValue(zIndex) + 0.5) * gridSizeZ; } public double computeDeltaPhiForLayer(int layer) { double circ = getDistanceToSensitive(layer) * (2 * PI); int nphi = (int) Math.floor(circ / gridSizePhi); double deltaPhi = (2 * PI) / nphi; return deltaPhi; } public double computeDeltaPhiForLayer() { return computeDeltaPhiForLayer(getLayer()); } public void setIDDescription(IDDescriptor id) { super.setIDDescription(id); phiIndex = id.indexOf("phi"); zIndex = id.indexOf("z"); systemIndex = id.indexOf("system"); barrelIndex = id.indexOf("barrel"); } public boolean supportsNeighbours() { return true; } /** * Find neighbouring cells to the current cell. Cell neighbors are found * based on the direction (theta,phi) of the reference cell w.r.t the * origin. * * @return array of cellIDs for the neighbouring cells */ public long[] getNeighbourIDs(int layerRange, int zRange, int phiRange) { IDEncoder gnEncoder = new IDEncoder(descriptor); BaseIDDecoder gnDecoder = new BaseIDDecoder(descriptor); gnEncoder.setValues(values); long origID = gnEncoder.getID(); gnDecoder.setID(gnEncoder.getID()); int nMax = (2*layerRange + 1)*(2*zRange + 1)*(2*phiRange + 1) - 1; long[] result = new long[nMax]; // theta and phi are used to find central neighbors in other layers double theta = getTheta(); double phi = getPhi(); // Be careful with # of Z bins. // The rules are: // * A cell is valid if its center has (z >= getZMin() && z <= getZMax()) // * The center of a bin is always at z = (integer + 0.5) * gridSizeZ // => Bins are arranged about z=0, with a bin edge at z=0 // => If getZMin()==-getZMax() then there is always an even number of bins // // If things are nicely symmetric, i.e. getZMin()==-getZMax(), then this turns // into a very easy problem: if we have n bins ON EACH SIDE (for integer n) then // n - 0.5 <= zMax/gridSizeZ < n + 0.5 // and so we can work backwards (and add in the other half) to obtain the total // number of bins 2n as 2*Math.round((zMax-zMin)/(2.0*gridSizeZ)). // // If things are not symmetric but span the z=0 point then we're OK as long as // we're careful -- the easiest way to look at it is to do each half of the // detector separately: // Number of bins in z>0: Math.round((zMax - 0.0)/gridSizeZ) // Number of bins in z<0: Math.round((0.0 - zMin)/gridSizeZ) // // If things are asymmetric and do not include z=0 then things are more tricky again. // We'd have to work like this: // a) find the first bin-center z1 after GetZMin() // b) find the last bin-center z2 before GetZMax() // c) count number of bins as Math.round((z2-z1)/gridSizeZ) // where // z1 = gridSizeZ * (Math.ceil ((zMin/gridSizeZ)+0.5) - 0.5) // z2 = gridSizeZ * (Math.floor((zMax/gridSizeZ)-0.5) + 0.5) // // So the most general form for the number of bins should be // Math.round( (gridSizeZ*(Math.floor((zMax/gridSizeZ)-0.5)+0.5) - gridSizeZ*(Math.floor((zMax/gridSizeZ)-0.5)+0.5) ) / gridSizeZ ) // // ... but we will assume that the detector is symmetric here -- that is true // for any barrel calorimeter generated from a compact.xml geometry file. int zBins = 2 * (int) Math.round( (getZMax()-getZMin())/(2.0*getGridSizeZ()) ); int size = 0; for (int i = -layerRange; i <= layerRange; ++i) { int ilay = values[layerIndex] + i; if (ilay < 0 || ilay >= getNumberOfLayers()) continue; gnEncoder.setValue(layerIndex, ilay); double dphi = this.computeDeltaPhiForLayer(ilay); int phiBins = (int) Math.round(2 * Math.PI / dphi); // Use round() not floor() since a floor() was already applied in the definition of dphi if (i != 0) { double cylR = getRadiusSensitiveMid(ilay); double x = cylR * Math.cos(phi); double y = cylR * Math.sin(phi); double z = cylR / Math.tan(theta); long id = this.findCellContainingXYZ(x,y,z); if(id==0) continue; // save indices in a new array, as values[] keeps the original ref gnDecoder.setID(id); } else { // This is the original layer => center cell is just the original cell gnDecoder.setID(origID); } for (int j = -zRange; j <= zRange; ++j) { int iz = gnDecoder.getValue(zIndex) + j; if (iz < -zBins / 2 || iz >= zBins / 2) { // We make the implicit assumption that detector is symmetric, and so number // of bins is even and looks like [-n, +n-1]. For example, for the // very simple case of two bins, the range of bin indices is {-1, 0}. // In this instance we're outside the valid range, so skip this bin. continue; } gnEncoder.setValue(zIndex, iz); for (int k = -phiRange; k <= phiRange; ++k) { // skip reference cell (not a neighbor of its own) if (i==0 && j==0 && k==0) continue; int iphi = gnDecoder.getValue(phiIndex) + k; // phi is cyclic if (iphi < 0) iphi += phiBins; if (iphi >= phiBins) iphi -= phiBins; if (iphi < 0 || iphi >= phiBins) continue; gnEncoder.setValue(phiIndex, iphi); result[size++] = gnEncoder.getID(); } } } // resize resulting array if necessary if (size < result.length) { long[] temp = new long[size]; System.arraycopy(result, 0, temp, 0, size); result = temp; } return result; } /** * Return the cell which contains a given point (x,y,z), or zero. * * @param x Cartesian X coordinate. * @param y Cartesian Y coordinate. * @param z Cartesian Z coordinate. * * @return ID of cell containing the point (maybe either in absorber or live * material) */ public long findCellContainingXYZ(double x, double y, double z) { // validate point if (z < getZMin()) return 0; if (z > getZMax()) return 0; double rho = Math.sqrt(x * x + y * y); if (rho < getRMin()) return 0; if (rho > getRMax()) return 0; // ok, point is valid, so a valid ID should be returned int ilay = getLayerBin(rho); int iz = getZBin(z); double phi = Math.atan2(y, x); if (phi < 0) phi += 2 * Math.PI; int iphi = getPhiBin(ilay, phi); IDEncoder enc = new IDEncoder(descriptor); enc.setValues(values); enc.setValue(layerIndex, ilay); enc.setValue(zIndex, iz); enc.setValue(phiIndex, iphi); enc.setValue(barrelIndex,0); enc.setValue(systemIndex, detector.getSystemID()); long resultID = enc.getID(); return resultID; } public int getPhiBin(int ilay, double phi) { // phic is phi at center of cells with iphi=0 double deltaPhi = this.computeDeltaPhiForLayer(ilay); double phic = deltaPhi / 2; int iphi = (int) Math.floor((phi - phic) / deltaPhi + 0.5); return iphi; } public int getZBin(double z) { // zc is z at center of cells with iz=0 int numz = (int) Math.floor((getZMax() - getZMin()) / gridSizeZ); // double zc = 0; // for odd numz // if( numz%2 == 0 ) zc = gridSizeZ / 2; double zc = gridSizeZ / 2; int iz = (int) Math.floor((z - zc) / gridSizeZ + 0.5); return iz; } /** * Returns cylindrical radius to center of sensitive slice of any layer * * @param layer * layer index */ private double getRadiusSensitiveMid(int ilay) { LayerStack stack = getLayering().getLayers(); Layer layer = stack.getLayer(ilay); double preLayers = 0; if (ilay > 0) preLayers = stack.getSectionThickness(0, ilay - 1); return this.getRMin() + preLayers + layer.getThicknessToSensitiveMid(); } }
31.754986
152
0.583617
ee2d7f6678aad81d027842e9e1df62939a96eaf8
582
/** * SPDX-FileCopyrightText: 2018-2021 SAP SE or an SAP affiliate company and Cloud Security Client Java contributors * <p> * SPDX-License-Identifier: Apache-2.0 */ package com.sap.cloud.security.client; import com.sap.cloud.security.config.ClientIdentity; import org.apache.http.impl.client.CloseableHttpClient; import org.mockito.Mockito; public class TestHttpClientFactory implements HttpClientFactory { @Override public CloseableHttpClient createClient(ClientIdentity clientIdentity) throws HttpClientException { return Mockito.mock(CloseableHttpClient.class); } }
30.631579
115
0.809278
ca8bcb97c507558e8b2bfd627380d2aca7467c17
1,616
package org.yeastrc.xlink.www.objects; import java.util.List; /** * * Result object from ReportedPeptides_For_AllProteins_Service for All Proteins page */ public class GetNoLinkInfoReportedPeptidesServiceResult { private List<SearchPeptideNoLinkInfoWebserviceResult> searchPeptideNoLinkInfoList; private List<AnnotationDisplayNameDescription> peptideAnnotationDisplayNameDescriptionList; private List<AnnotationDisplayNameDescription> psmAnnotationDisplayNameDescriptionList; public List<AnnotationDisplayNameDescription> getPeptideAnnotationDisplayNameDescriptionList() { return peptideAnnotationDisplayNameDescriptionList; } public void setPeptideAnnotationDisplayNameDescriptionList( List<AnnotationDisplayNameDescription> peptideAnnotationDisplayNameDescriptionList) { this.peptideAnnotationDisplayNameDescriptionList = peptideAnnotationDisplayNameDescriptionList; } public List<AnnotationDisplayNameDescription> getPsmAnnotationDisplayNameDescriptionList() { return psmAnnotationDisplayNameDescriptionList; } public void setPsmAnnotationDisplayNameDescriptionList( List<AnnotationDisplayNameDescription> psmAnnotationDisplayNameDescriptionList) { this.psmAnnotationDisplayNameDescriptionList = psmAnnotationDisplayNameDescriptionList; } public List<SearchPeptideNoLinkInfoWebserviceResult> getSearchPeptideNoLinkInfoList() { return searchPeptideNoLinkInfoList; } public void setSearchPeptideNoLinkInfoList( List<SearchPeptideNoLinkInfoWebserviceResult> searchPeptideNoLinkInfoList) { this.searchPeptideNoLinkInfoList = searchPeptideNoLinkInfoList; } }
32.979592
97
0.867574
3824dbed74ad7fa64df25717cdb409196864bb82
608
package com.jumbo.javacore.Lclassesabstratas.classes; public class Vendedor extends Funcionario{ private double totalVendas; public Vendedor() { } public Vendedor(String nome, String clt, double salario,double totalVendas){ super(nome,clt,salario); this.totalVendas = totalVendas; } @Override public void calcularSalario() { this.salario = salario + (totalVendas * .05); } public double getTotalVendas() { return totalVendas; } public void setTotalVendas(double totalVendas) { this.totalVendas = totalVendas; } }
21.714286
80
0.664474
3f839f243849b5c4f5aa531387c5aa800d660b29
1,088
package com.enation.pangu.api.view; import com.enation.pangu.model.ConfigProject; import com.enation.pangu.service.ConfigProjectManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; /** * 项目视图控制器 * * @author lizhengguo * @date 2020-11-12 */ @Controller @RequestMapping("/view/config_project") public class ConfigProjectViewController { @Autowired private ConfigProjectManager configProjectManager; /** * 跳转到项目列表页 * * @return */ @GetMapping() public String list() { return "/config_file/project_list"; } /** * 编辑项目 */ @GetMapping("/show/{id}") public String editProject(Model model, @PathVariable Long id) { model.addAttribute("config_project_id", id); ConfigProject projectDO = configProjectManager.selectById(id); model.addAttribute("config_project_name", projectDO.getName()); return "/config_file/list"; } }
23.652174
71
0.699449
f476f8f2111ca7a60ecf56d0a9fd3625482536ed
5,994
package controllerfx; import dao.PacienteDAO; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.List; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import modelo.Pacientes; public class FXMLClientesController implements Initializable { @FXML private TextField txtEndereco; @FXML private TextField txtNome; @FXML private TextField txtTelefone; @FXML private TextField txtCodigo; @FXML private TextField txtNascimento; @FXML private TextField txtSexo; @FXML private TableView<Pacientes> tabelaPacientes; @FXML private TableColumn<Pacientes, Number> columnCodigo; @FXML private TableColumn<Pacientes, String> columnNome; @FXML private TableColumn<Pacientes, String> columnTelefone; @FXML private TableColumn<Pacientes, Character> columnSexo; private List<Pacientes> listaPacientes; private ObservableList<Pacientes> pacientes; private PacienteDAO pacienteDao = null; @FXML private Button btnCriar; @FXML private Button btnAtualizar; @FXML private Button btnExcluir; @FXML private Button btnNovo; @FXML private Button btnLimpar; private final SimpleDateFormat formatar = new SimpleDateFormat("dd/MM/yyyy"); @FXML void novoPaciente() { limparCliente(); } @FXML void criarPaciente() throws ParseException { Pacientes p = new Pacientes(); String nome = txtNome.getText(); String sexo = txtSexo.getText(); String nascimento = txtNascimento.getText(); if (!nome.trim().isEmpty() && !nascimento.trim().isEmpty() && !sexo.trim().isEmpty()) { p.setPctNome(nome); p.setPctSexo(sexo); p.setPctNascimento(formatar.parse(nascimento)); p.setPctFone(txtTelefone.getText()); p.setPctEndereco(txtEndereco.getText()); pacienteDao.salvar(p); pacientes.add(p); tabelaPacientes.getItems().setAll(pacientes); limparCliente(); atualizaTabela(); } else { if (nome.trim().isEmpty()) { txtNome.setText("nome esta vazio"); txtNome.requestFocus(); } if (nascimento.trim().isEmpty()) { txtNascimento.setText("Nascimento está vazio"); txtNascimento.requestFocus(); } if (sexo.trim().isEmpty()) { txtSexo.setText("Sexo está vazio"); txtSexo.requestFocus(); } alertas("Alerta!", "Preencha os campos vazios!"); } } @FXML void atualizarPaciente() throws ParseException { Pacientes p = tabelaPacientes.getSelectionModel().getSelectedItem(); if (p != null) { p.setId(Integer.parseInt(txtCodigo.getText())); p.setPctNome(txtNome.getText()); p.setPctSexo(txtSexo.getText()); p.setPctNascimento(formatar.parse(txtNascimento.getText())); p.setPctFone(txtTelefone.getText()); p.setPctEndereco(txtEndereco.getText()); pacienteDao.atualizar(p); tabelaPacientes.getItems().setAll(pacientes); limparCliente(); atualizaTabela(); } else { alertas("Alerta!", "Selecione um paciente"); } } @FXML void excluirPaciente() { Pacientes p = tabelaPacientes.getSelectionModel().getSelectedItem(); if (p != null) { pacienteDao.apagar(p.getId()); atualizaTabela(); } else { alertas("Alerta!", "Selecione um paciente"); } } @Override public void initialize(URL url, ResourceBundle rb) { pacienteDao = new PacienteDAO(); preencheTabela(); tabelaPacientes.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> selecionaItemTabela(newValue)); } public void preencheTabela() { atualizaTabela(); columnCodigo.setCellValueFactory(new PropertyValueFactory<>("Id")); columnNome.setCellValueFactory(new PropertyValueFactory<>("pctNome")); columnSexo.setCellValueFactory(new PropertyValueFactory<>("pctSexo")); columnTelefone.setCellValueFactory(new PropertyValueFactory<>("pctFone")); } private void atualizaTabela() { listaPacientes = pacienteDao.buscarTodos(); pacientes = FXCollections.observableArrayList(listaPacientes); tabelaPacientes.setItems(pacientes); } public void selecionaItemTabela(Pacientes p) { if (p != null) { txtCodigo.setText(String.valueOf(p.getId())); txtNome.setText(p.getPctNome()); txtEndereco.setText(p.getPctEndereco()); txtTelefone.setText(p.getPctFone()); txtSexo.setText(p.getPctSexo()); txtNascimento.setText(formatar.format(p.getPctNascimento())); }else{ limparCliente(); } } @FXML private void limparCliente() { txtCodigo.clear(); txtNome.clear(); txtEndereco.clear(); txtSexo.clear(); txtTelefone.clear(); txtNascimento.clear(); tabelaPacientes.getSelectionModel().clearSelection(); } public void alertas(String titulo, String frase) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle(titulo); alert.setHeaderText(null); alert.setContentText(frase); alert.showAndWait(); } }
29.97
146
0.634468
65301e574177181e771d589952139d8a77a0f95c
2,734
package com.xlongwei.light4j.util; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import lombok.extern.slf4j.Slf4j; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; /** * redis pubsub * @author xlongwei */ @Slf4j public class RedisPubsub { public static final String CHANNEL = "pubsub"; private static final List<MessageListener> listeners = new CopyOnWriteArrayList<>(); private static final Map<String, JedisPubSub> pubsubs = new ConcurrentHashMap<>(); /** 发布消息到默认渠道 */ public static void pub(final String message) { pub(CHANNEL, message); } /** 发布消息到指定渠道 */ public static void pub(final String channel, final String message) { RedisConfig.execute((jedis) -> { jedis.publish(channel, message); return null; }); } /** 订阅默认渠道消息 */ public static void sub(MessageListener listener) { listeners.add(listener); } /** 订阅指定渠道消息 */ public static void sub(final String channel, final JedisPubSub pubsub) { if(StringUtil.isBlank(channel) || pubsub==null) { return; } TaskUtil.submitKeepRunning(() -> { Jedis jedis = null; try { jedis = RedisConfig.JEDIS_POOL.getResource(); jedis.subscribe(pubsub, channel); }finally { RedisConfig.JEDIS_POOL.returnBrokenResource(jedis); } }); pubsubs.put(channel, pubsub); } /** * 默认渠道消息监听器 * @author xlongwei */ @FunctionalInterface public static interface MessageListener { /** * 接收消息通知 * @param message */ void onMessage(String message); } /** 消息监听器适配 */ public static class JedisPubSubAdapter extends JedisPubSub { @Override public void onMessage(String channel, String message) {} @Override public void onPMessage(String pattern, String channel, String message) {} @Override public void onSubscribe(String channel, int subscribedChannels) {} @Override public void onUnsubscribe(String channel, int subscribedChannels) {} @Override public void onPUnsubscribe(String pattern, int subscribedChannels) {} @Override public void onPSubscribe(String pattern, int subscribedChannels) {} } static { //注册默认渠道监听器 JedisPubSub pubsub = new JedisPubSubAdapter() { @Override public void onMessage(String channel, String message) { log.info("onMessage chanel: {}, message: {}", channel, message); for(MessageListener listener : listeners) { listener.onMessage(message); } } }; sub(CHANNEL, pubsub); TaskUtil.addShutdownHook((Runnable)() -> { log.info("redis pubsub shutdown"); for(Map.Entry<String, JedisPubSub> entry : pubsubs.entrySet()) { entry.getValue().unsubscribe(entry.getKey()); } }); } }
25.792453
85
0.706657
76d8dee31a26c269ff5577c325f915140c5ae356
9,416
/* * This file was automatically generated by EvoSuite * Sat Feb 29 19:22:41 GMT 2020 */ package com.alibaba.fastjson.util; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.shaded.org.mockito.Mockito.*; import static org.evosuite.runtime.EvoAssertions.*; import com.alibaba.fastjson.util.GenericArrayTypeImpl; import com.alibaba.fastjson.util.ParameterizedTypeImpl; import java.lang.reflect.Type; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.evosuite.runtime.ViolatedAssumptionAnswer; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class ParameterizedTypeImpl_ESTest extends ParameterizedTypeImpl_ESTest_scaffolding { @Test(timeout = 4000) public void test00() throws Throwable { Type type0 = mock(Type.class, new ViolatedAssumptionAnswer()); GenericArrayTypeImpl genericArrayTypeImpl0 = new GenericArrayTypeImpl(type0); ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, genericArrayTypeImpl0, genericArrayTypeImpl0); parameterizedTypeImpl0.hashCode(); } @Test(timeout = 4000) public void test01() throws Throwable { Type type0 = mock(Type.class, new ViolatedAssumptionAnswer()); GenericArrayTypeImpl genericArrayTypeImpl0 = new GenericArrayTypeImpl(type0); ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, genericArrayTypeImpl0, genericArrayTypeImpl0); Type type1 = parameterizedTypeImpl0.getRawType(); assertSame(genericArrayTypeImpl0, type1); } @Test(timeout = 4000) public void test02() throws Throwable { Type type0 = mock(Type.class, new ViolatedAssumptionAnswer()); GenericArrayTypeImpl genericArrayTypeImpl0 = new GenericArrayTypeImpl(type0); ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, genericArrayTypeImpl0, genericArrayTypeImpl0); Type type1 = parameterizedTypeImpl0.getOwnerType(); assertSame(genericArrayTypeImpl0, type1); } @Test(timeout = 4000) public void test03() throws Throwable { Type type0 = mock(Type.class, new ViolatedAssumptionAnswer()); GenericArrayTypeImpl genericArrayTypeImpl0 = new GenericArrayTypeImpl(type0); ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, genericArrayTypeImpl0, genericArrayTypeImpl0); Type[] typeArray0 = new Type[7]; ParameterizedTypeImpl parameterizedTypeImpl1 = new ParameterizedTypeImpl(typeArray0, typeArray0[5], parameterizedTypeImpl0); Type[] typeArray1 = parameterizedTypeImpl1.getActualTypeArguments(); assertEquals(7, typeArray1.length); } @Test(timeout = 4000) public void test04() throws Throwable { Type[] typeArray0 = new Type[0]; ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl(typeArray0, (Type) null, (Type) null); Type[] typeArray1 = parameterizedTypeImpl0.getActualTypeArguments(); assertSame(typeArray1, typeArray0); } @Test(timeout = 4000) public void test05() throws Throwable { Type[] typeArray0 = new Type[5]; GenericArrayTypeImpl genericArrayTypeImpl0 = new GenericArrayTypeImpl((Type) null); typeArray0[2] = (Type) genericArrayTypeImpl0; ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl(typeArray0, typeArray0[2], genericArrayTypeImpl0); ParameterizedTypeImpl parameterizedTypeImpl1 = new ParameterizedTypeImpl(typeArray0, genericArrayTypeImpl0, genericArrayTypeImpl0); // Undeclared exception! try { parameterizedTypeImpl0.equals(parameterizedTypeImpl1); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.alibaba.fastjson.util.GenericArrayTypeImpl", e); } } @Test(timeout = 4000) public void test06() throws Throwable { Type[] typeArray0 = new Type[0]; ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl(typeArray0, (Type) null, (Type) null); String string0 = parameterizedTypeImpl0.getTypeName(); assertNotNull(string0); } @Test(timeout = 4000) public void test07() throws Throwable { Type[] typeArray0 = new Type[1]; Type type0 = mock(Type.class, new ViolatedAssumptionAnswer()); ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl(typeArray0, typeArray0[0], typeArray0[0]); ParameterizedTypeImpl parameterizedTypeImpl1 = new ParameterizedTypeImpl(typeArray0, (Type) null, type0); boolean boolean0 = parameterizedTypeImpl0.equals(parameterizedTypeImpl1); assertFalse(boolean0); } @Test(timeout = 4000) public void test08() throws Throwable { Type[] typeArray0 = new Type[0]; ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl(typeArray0, (Type) null, (Type) null); ParameterizedTypeImpl parameterizedTypeImpl1 = new ParameterizedTypeImpl(typeArray0, parameterizedTypeImpl0, parameterizedTypeImpl0); boolean boolean0 = parameterizedTypeImpl0.equals(parameterizedTypeImpl1); assertFalse(boolean0); } @Test(timeout = 4000) public void test09() throws Throwable { Type[] typeArray0 = new Type[0]; ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl(typeArray0, (Type) null, (Type) null); ParameterizedTypeImpl parameterizedTypeImpl1 = new ParameterizedTypeImpl(typeArray0, parameterizedTypeImpl0, parameterizedTypeImpl0); boolean boolean0 = parameterizedTypeImpl1.equals(parameterizedTypeImpl0); assertFalse(boolean0); } @Test(timeout = 4000) public void test10() throws Throwable { Type type0 = mock(Type.class, new ViolatedAssumptionAnswer()); GenericArrayTypeImpl genericArrayTypeImpl0 = new GenericArrayTypeImpl(type0); ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, genericArrayTypeImpl0, genericArrayTypeImpl0); ParameterizedTypeImpl parameterizedTypeImpl1 = new ParameterizedTypeImpl((Type[]) null, genericArrayTypeImpl0, genericArrayTypeImpl0); boolean boolean0 = parameterizedTypeImpl0.equals(parameterizedTypeImpl1); assertTrue(boolean0); } @Test(timeout = 4000) public void test11() throws Throwable { Type type0 = mock(Type.class, new ViolatedAssumptionAnswer()); GenericArrayTypeImpl genericArrayTypeImpl0 = new GenericArrayTypeImpl(type0); ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, genericArrayTypeImpl0, genericArrayTypeImpl0); Type[] typeArray0 = new Type[7]; ParameterizedTypeImpl parameterizedTypeImpl1 = new ParameterizedTypeImpl(typeArray0, typeArray0[5], parameterizedTypeImpl0); boolean boolean0 = parameterizedTypeImpl0.equals(parameterizedTypeImpl1); assertFalse(boolean0); } @Test(timeout = 4000) public void test12() throws Throwable { ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, (Type) null, (Type) null); ParameterizedTypeImpl parameterizedTypeImpl1 = new ParameterizedTypeImpl((Type[]) null, (Type) null, (Type) null); boolean boolean0 = parameterizedTypeImpl0.equals(parameterizedTypeImpl1); assertTrue(boolean0); } @Test(timeout = 4000) public void test13() throws Throwable { ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, (Type) null, (Type) null); boolean boolean0 = parameterizedTypeImpl0.equals((Object) null); assertFalse(boolean0); } @Test(timeout = 4000) public void test14() throws Throwable { ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, (Type) null, (Type) null); boolean boolean0 = parameterizedTypeImpl0.equals(parameterizedTypeImpl0); assertTrue(boolean0); } @Test(timeout = 4000) public void test15() throws Throwable { ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, (Type) null, (Type) null); boolean boolean0 = parameterizedTypeImpl0.equals("com.alibaba.fastjson.util.ParameterizedTypeImpl@0"); assertFalse(boolean0); } @Test(timeout = 4000) public void test16() throws Throwable { ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, (Type) null, (Type) null); Type type0 = parameterizedTypeImpl0.getRawType(); assertNull(type0); } @Test(timeout = 4000) public void test17() throws Throwable { ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, (Type) null, (Type) null); Type type0 = parameterizedTypeImpl0.getOwnerType(); assertNull(type0); } @Test(timeout = 4000) public void test18() throws Throwable { ParameterizedTypeImpl parameterizedTypeImpl0 = new ParameterizedTypeImpl((Type[]) null, (Type) null, (Type) null); Type[] typeArray0 = parameterizedTypeImpl0.getActualTypeArguments(); assertNull(typeArray0); } }
48.287179
176
0.749681
4cf5ac05849358b03e06ceea8867fa5e138ae70d
3,765
/* * 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.netbeans.modules.parsing.implspi; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.Map; import java.util.WeakHashMap; import org.netbeans.api.annotations.common.CheckForNull; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.modules.parsing.api.Source; import org.netbeans.modules.parsing.impl.SourceAccessor; import org.openide.filesystems.FileObject; import org.openide.util.Lookup; import org.openide.util.Parameters; /** * * @author Tomas Zezula */ public abstract class SourceFactory { private static final SourceFactory DEFAULT_SOURCE_FACTORY = new DefaultSourceFactory(); @NonNull public static SourceFactory getDefault() { SourceFactory sf = Lookup.getDefault().lookup(SourceFactory.class); if (sf == null) { sf = DEFAULT_SOURCE_FACTORY; } return sf; } @CheckForNull public abstract Source createSource( @NonNull FileObject fo, @NonNull String mimeType, @NonNull Lookup contents); @CheckForNull public abstract Source getSource(@NonNull FileObject fo); @CheckForNull public abstract Source removeSource(@NonNull FileObject fo); protected final Source newSource( @NonNull final FileObject fo, @NonNull final String mimeType, @NonNull final Lookup context) { return SourceAccessor.getINSTANCE().create(fo, mimeType, context); } private static class DefaultSourceFactory extends SourceFactory { private final Map<FileObject, Reference<Source>> instances = new WeakHashMap<>(); @Override public Source createSource( @NonNull FileObject file, @NonNull String mimeType, @NonNull Lookup context) { Parameters.notNull("file", file); //NOI18N Parameters.notNull("mimeType", mimeType); //NOI18N Parameters.notNull("context", context); //NOI18N final Reference<Source> sourceRef = instances.get(file); Source source = sourceRef == null ? null : sourceRef.get(); if (source == null || !mimeType.equals(source.getMimeType())) { source = newSource(file, mimeType, context); instances.put(file, new WeakReference<>(source)); } return source; } @Override public Source getSource(@NonNull final FileObject file) { Parameters.notNull("file", file); //NOI18N final Reference<Source> ref = instances.get(file); return ref == null ? null : ref.get(); } @Override public Source removeSource(@NonNull final FileObject file) { Parameters.notNull("file", file); //NOI18N final Reference<Source> ref = instances.remove(file); return ref == null ? null : ref.get(); } } }
35.857143
91
0.665073
a28b34b2386c44583d6242ff1e84b848869f67f5
8,984
package edu.rit.soundtest; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.os.AsyncTask; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import com.google.android.glass.timeline.LiveCard; public class SoundService extends Service { private final String CARD_ID = "my_music_card"; private final IBinder binder = new LocalBinder(); private LiveCard liveCard; private Handler handler = new Handler(); private boolean paused = true; private SoundRender render; private int duration = 1; // seconds private int sampleRate = 8000; private final int numSamples = duration * sampleRate; private final double sample[] = new double[numSamples]; private final double sample2[] = new double[numSamples]; private final byte generatedSnd[] = new byte[2 * numSamples]; private AudioTrack audioTrack; private double freqOfTone = 500; // hz private int delay = 0; // sample public static final int MIN_FREQUENCY_VALUE = 100; public static final int MAX_FREQUENCY_VALUE = 4000; public static final int MIN_DELAY_VALUE = 0; public static final int MAX_DELAY_VALUE = 441; private String playStatus = "|| Paused"; private AudioControlTask audioControlTask = null; private AudioUpdateTask audioUpdateTask = null; @Override public IBinder onBind(Intent intent) { return binder; } @Override public void onCreate() { super.onCreate(); audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, numSamples, AudioTrack.MODE_STREAM); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (liveCard == null) { liveCard = new LiveCard(getApplicationContext(), CARD_ID); // Display the sound card when the live card is tapped. Intent soundIntent = new Intent(this, SoundActivity.class); soundIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); liveCard.setAction(PendingIntent.getActivity(this, 0, soundIntent, 0)); render = new SoundRender(getApplicationContext()); if (isPaused()) playStatus = "|| Paused"; else playStatus = "|> Playing"; render.setTextOfView(playStatus + "\nfrequency: " + freqOfTone + " Hz\ndelay: " + delay + " sample(s)", null); liveCard.setDirectRenderingEnabled(true).getSurfaceHolder().addCallback(render); liveCard.publish(LiveCard.PublishMode.REVEAL); } else { liveCard.navigate(); } return START_STICKY; } @Override public void onDestroy() { //unpublish our live card if (liveCard != null) { liveCard.unpublish(); liveCard = null; } if (audioControlTask != null) { audioControlTask.cancel(true); audioControlTask = null; } if (audioUpdateTask != null) { audioUpdateTask.cancel(true); audioUpdateTask = null; } if (audioTrack != null) audioTrack.release(); super.onDestroy(); } public int getCurrentFrequency() { return (int)freqOfTone; } public int getCurrentDelay() { return delay; } /** * @return If the music is currently paused */ public boolean isPaused() { return paused; } /** * Pauses music if it is currently playing */ public void pauseMusic() { if (!paused) { paused = true; audioTrack.pause(); if (audioControlTask != null) { audioControlTask.cancel(true); audioControlTask = null; } if (audioUpdateTask != null) { audioUpdateTask.cancel(true); audioUpdateTask = null; } playStatus = "|| Paused"; render.setTextOfView(playStatus + "\nfrequency: " + freqOfTone + " Hz\ndelay: " + delay + " sample(s)", null); } } /** * Resumes the music if it is currently paused */ public void resumeMusic() { if (paused) { playStatus = "|> Playing"; render.setTextOfView(playStatus + "\nfrequency: " + freqOfTone + " Hz\ndelay: " + delay + " sample(s)", null); paused = false; if (audioUpdateTask == null) { audioUpdateTask = new AudioUpdateTask(); audioUpdateTask.execute(); } } } /** * Update frequency */ public void updateFrequency(double delta) { try { freqOfTone += delta; if (freqOfTone <= MIN_FREQUENCY_VALUE) freqOfTone = MIN_FREQUENCY_VALUE; else if (freqOfTone >= MAX_FREQUENCY_VALUE) freqOfTone = MAX_FREQUENCY_VALUE; render.setTextOfView(playStatus + "\nfrequency: " + freqOfTone + " Hz\ndelay: " + delay + " sample(s)", null); } catch (Exception e) { } } /** * Update delay */ public void updateDelay(double delta) { try { delay += delta/10; if (delay <= MIN_DELAY_VALUE) delay = MIN_DELAY_VALUE; else if (delay >= MAX_DELAY_VALUE) delay = MAX_DELAY_VALUE; render.setTextOfView(playStatus + "\nfrequency: " + freqOfTone + " Hz\ndelay: " + delay + " sample(s)", null); } catch (Exception e) { } } private void genTone() { for (int i = 0; i < numSamples; ++i) { // float angular_frequency = sample[i] = Math.sin(2 * Math.PI * i / (sampleRate / freqOfTone)); if (i + delay + 1 > numSamples) sample2[i] = Math.sin(2 * Math.PI * i/ (sampleRate / (freqOfTone*2))); else sample2[i] = Math.sin(2 * Math.PI * i/ (sampleRate / (freqOfTone*2)))+sample[i+delay]; } int idx = 0; // convert to 16 bit pcm sound array // assumes the sample buffer is normalised. for (double dVal : sample2) { short val = (short) (dVal * 32767); generatedSnd[idx++] = (byte) (val & 0x00ff); generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8); } audioTrack.write(generatedSnd, 0, numSamples); } /** * Converts milliseconds to a Human readable format * * @param milliseconds time in milliseconds * @return Human readable representation of the time */ private String getHumanReadableTime(long milliseconds) { String finalTimerString = ""; String secondsString = ""; int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60); int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000); if (seconds < 10) { secondsString = "0" + seconds; } else { secondsString = "" + seconds; } finalTimerString = finalTimerString + minutes + ":" + secondsString; return finalTimerString; } public class LocalBinder extends Binder { SoundService getService() { return SoundService.this; } } private class AudioUpdateTask extends AsyncTask<Integer, Void, Void> { @Override protected Void doInBackground(Integer... params) { genTone(); return null; } @Override protected void onPostExecute(Void v) { audioControlTask = new AudioControlTask(); audioControlTask.execute(); } @Override protected void onCancelled() { if (audioControlTask != null) { audioControlTask.cancel(true); audioControlTask = null; } } } private class AudioControlTask extends AsyncTask<Integer, Void, Void> { @Override protected Void doInBackground(Integer... params) { int playState = audioTrack.getPlayState(); if (playState == AudioTrack.PLAYSTATE_PAUSED || playState == AudioTrack.PLAYSTATE_STOPPED) audioTrack.play(); return null; } @Override protected void onPostExecute(Void v) { audioUpdateTask = new AudioUpdateTask(); audioUpdateTask.execute(); } @Override protected void onCancelled() { audioTrack.pause(); } } }
30.046823
122
0.568344
931e2df1e080965252fdfddd6b827c16830fc781
2,744
package com.vuece.controller.ui; import com.vuece.controller.R; import com.vuece.controller.core.ControllerApplication; import com.vuece.controller.service.ControllerService; import com.vuece.controller.service.NotificationReceiver; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.StyleSpan; public class NotificationHelperEclair extends NotificationHelper { @Override public void showNotification(ControllerService service) { Intent intent = new Intent(service.getApplicationContext(), NotificationReceiver.class); PendingIntent pIntent = PendingIntent.getActivity(service.getApplicationContext(), 0, intent, 0); String text=service.getCurrentSongItem().getName(); CharSequence tickerText = buildTickerMessage(service.getApplicationContext(), service.getCurrentSongItem().getName(), text); Notification noti = new Notification(R.drawable.ic_launcher, tickerText, System.currentTimeMillis()); // .addAction(android.R.drawable.ic_media_previous, "Call", pIntent) // .addAction(android.R.drawable.ic_media_pause, "More", pIntent) // .addAction(android.R.drawable.ic_media_next, "Three", pIntent).build(); NotificationManager notificationManager = (NotificationManager) service.getApplicationContext().getSystemService(ControllerApplication.NOTIFICATION_SERVICE); // Hide the notification after its selected noti.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR | Notification.FLAG_ONLY_ALERT_ONCE; // notificationManager.notify(NOTIFICATION_ID, noti); } protected static CharSequence buildTickerMessage( Context context, String address, String body) { String displayAddress = address; StringBuilder buf = new StringBuilder( displayAddress == null ? "" : displayAddress.replace('\n', ' ').replace('\r', ' ')); buf.append(':').append(' '); int offset = buf.length(); if (!TextUtils.isEmpty(body)) { body = body.replace('\n', ' ').replace('\r', ' '); buf.append(body); } SpannableString spanText = new SpannableString(buf.toString()); spanText.setSpan(new StyleSpan(Typeface.BOLD), 0, offset, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return spanText; } }
41.575758
127
0.689504
e4b02cdedfa9a8d8c121d874b4e775c60bf057e2
758
package net.tofweb.starlite; public class CellInfo { private double g; private double rhs; private double cost; public CellInfo() { this.cost = 1.0; } public double getG() { return this.g; } public void setG(final double g) { this.g = g; } public double getRhs() { return this.rhs; } public void setRhs(final double rhs) { this.rhs = rhs; } public double getCost() { return this.cost; } public void setCost(final double cost) { this.cost = cost; } @Override public String toString() { return "CellInfo [g=" + this.g + ", rhs=" + this.rhs + ", cost=" + this.cost + "]"; } }
18.047619
91
0.515831
9a7b00a89e4731a2e9d841794d8d28ec987d9ef5
4,488
package io.drakon.talon.test; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import io.drakon.talon.Talon; import io.drakon.talon.test.transformers.HasSeenAnyTransformer; import io.drakon.talon.test.transformers.StringReplacingTransformer; import io.drakon.talon.transformers.DebugTransformer; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; @Slf4j class TalonTests { private static final String WHITELIST_DIR = "io.drakon.talon.test.examples"; @Test void testSmoke() { assertThatCode(Talon::new).doesNotThrowAnyException(); } @Test void testOnlyAllowsSingleStart() throws Exception { Talon talon = new Talon(); talon.start(); assertThatCode(talon::start).isInstanceOf(Talon.AlreadyStartedException.class); } @Test void testConstructWithHasSeenTransformer() { Talon talon = new Talon("io.drakon.talon.test.examples.Main", new String[]{}); talon.addWhitelistedPackage(WHITELIST_DIR); HasSeenAnyTransformer transformer = new HasSeenAnyTransformer(); talon.addTransformer(transformer); assertThatCode(talon::start).doesNotThrowAnyException(); assertThat(transformer.isHasSeenAny()).isTrue(); } @Test void testConstructWithDebugTransformer() { Talon talon = new Talon("io.drakon.talon.test.examples.Main", new String[]{}); talon.addWhitelistedPackage(WHITELIST_DIR); talon.addTransformer(new DebugTransformer()); assertThatCode(talon::start).doesNotThrowAnyException(); } @Test void testInvokeStaticNoArgs() throws Exception { Talon talon = new Talon("io.drakon.talon.test.examples.Main", "testStaticNoArgs", true); talon.addWhitelistedPackage(WHITELIST_DIR); assertThat(talon.start()).isEqualTo("hello"); } @Test void testInvokeStaticArg() throws Exception { Object obj = new Object(); Talon talon = new Talon("io.drakon.talon.test.examples.Main", "testStaticArgs", true, obj); talon.addWhitelistedPackage(WHITELIST_DIR); assertThat(talon.start()).isEqualTo(obj); } @Test void testInvokeNonstaticNoArgs() throws Exception { Talon talon = new Talon("io.drakon.talon.test.examples.Main", "testNoArgs", false); talon.addWhitelistedPackage(WHITELIST_DIR); assertThat(talon.start()).isEqualTo("hello"); } @Test void testInvokeNonstaticArg() throws Exception { Object obj = new Object(); Talon talon = new Talon("io.drakon.talon.test.examples.Main", "testArgs", false, obj); talon.addWhitelistedPackage(WHITELIST_DIR); assertThat(talon.start()).isEqualTo(obj); } @Test @SuppressWarnings("unchecked") void testWithJavaDeps() throws Exception { Talon talon = new Talon("io.drakon.talon.test.examples.WithJavaDeps", "test", true); talon.addWhitelistedPackage(WHITELIST_DIR); HasSeenAnyTransformer transformer = new HasSeenAnyTransformer(); talon.addTransformer(transformer); assertThat((Set<String>)talon.start()).containsExactlyInAnyOrder("1", "2"); assertThat(transformer.getSeenCount()).isEqualTo(1); } @Test void testWithBlacklistedDeps() throws Exception { Talon talon = new Talon("io.drakon.talon.test.examples.WithBlacklistedDeps", "test", true); talon.addWhitelistedPackage(WHITELIST_DIR); HasSeenAnyTransformer transformer = new HasSeenAnyTransformer(); talon.addTransformer(transformer); assertThat(talon.start()).isNotNull(); assertThat(transformer.getSeenCount()).isEqualTo(1); } @Test void testInvokeNonstaticWithTransform() throws Exception { Talon talon = new Talon("io.drakon.talon.test.examples.Main", "testNoArgs", false); talon.addWhitelistedPackage(WHITELIST_DIR); talon.addTransformer(new StringReplacingTransformer("hello", "pass")); assertThat(talon.start()).isEqualTo("pass"); } @Test void testInvokeWithWhitelistedDepsTransform() throws Exception { Talon talon = new Talon("io.drakon.talon.test.examples.WithWhitelistedDeps", "test", true); talon.addWhitelistedPackage(WHITELIST_DIR); talon.addTransformer(new StringReplacingTransformer("hello", "pass")); assertThat(talon.start()).isEqualTo("pass"); } }
38.033898
99
0.700535
aca5d3a9e4563742894de6fa39c0ff844d372156
5,062
/* * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.integrationstudio.samples.contributor; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.swt.widgets.Shell; import org.wso2.integrationstudio.utils.archive.ArchiveManipulator; import org.wso2.integrationstudio.utils.data.ITemporaryFileTag; import org.wso2.integrationstudio.utils.file.FileUtils; public abstract class AbstractSampleContributor implements IIntegrationStudioSampleContributor { static String AXIS2_SAMPLE_TYPE="axis2"; static String BPEL_SAMPLE_TYPE="bpel"; static String DS_SAMPLE_TYPE="ds"; static String DSVALIDATOR_SAMPLE_TYPE="dsvalidator"; static String GADGET_SAMPLE_TYPE="gadget"; static String PROXY_SAMPLE_TYPE="proxy"; public void addSampleTo(IProject project) throws Exception { ITemporaryFileTag sampleTempTag = FileUtils.createNewTempTag(); File resourceFile = getSampleResourceFile(); File tempDir = FileUtils.createTempDirectory(); File target = project.getLocation().toFile(); File projectTempLocation = new File(tempDir, project.getName()); ArchiveManipulator archiveManipulator = new ArchiveManipulator(); archiveManipulator.extract(resourceFile, tempDir); File[] listFiles = tempDir.listFiles(); String sampleName = listFiles[0].getName(); File sampleProjectTempLocation = new File(tempDir, sampleName); File projectDesc = new File(sampleProjectTempLocation,".project"); if(!sampleName.equals(project.getName())){ if (projectDesc.exists() && projectDesc.isFile()){ String parameterValue = project.getName(); updateWithParameterData(projectDesc, parameterValue); } } FileUtils.copyDirectoryContents(sampleProjectTempLocation, projectTempLocation); FileUtils.copyDirectoryContents(projectTempLocation, target); project.refreshLocal(IResource.DEPTH_INFINITE, null); project.close(new NullProgressMonitor()); project.refreshLocal(IResource.DEPTH_INFINITE, null); project.open(new NullProgressMonitor()); project.refreshLocal(IResource.DEPTH_INFINITE, null); sampleTempTag.clearAndEnd(); } public String getCopyResourceContentProjectName(String projectType){ if(projectType.equals(AXIS2_SAMPLE_TYPE)){ return "AccountServiceSampleProject"; }else if(projectType.equals(BPEL_SAMPLE_TYPE)){ return "HelloWorldWorkFlow" ; }else if(projectType.equals(DS_SAMPLE_TYPE)){ return "EmployeeDataService"; }else if(projectType.equals(DSVALIDATOR_SAMPLE_TYPE)){ return "CustomDataserviceValidatorSample"; }else if(projectType.equals(GADGET_SAMPLE_TYPE)){ return "AcmeProductGadget"; }else if(projectType.equals(PROXY_SAMPLE_TYPE)){ return "SimpleStockQuoteESBSample"; }else{ return null; } } public String getCopyResourceContentType(String sampleName){ if(sampleName.contains("AccountServiceSampleProject")){ return AXIS2_SAMPLE_TYPE; }else if(sampleName.contains("HelloWorldWorkFlow")){ return BPEL_SAMPLE_TYPE; }else if(sampleName.contains("EmployeeDataService")){ return DS_SAMPLE_TYPE; }else if(sampleName.contains("CustomDataserviceValidatorSample")){ return DSVALIDATOR_SAMPLE_TYPE; }else if(sampleName.equals("AcmeProductGadget")){ return GADGET_SAMPLE_TYPE; }else if(sampleName.contains("SimpleStockQuoteESBSample")){ return PROXY_SAMPLE_TYPE; }else{ return null; } } protected void updateWithParameterData(File projectDesc, String parameterValue) throws IOException { String content = FileUtils.getContentAsString(projectDesc); content = MessageFormat.format(content, parameterValue); projectDesc.delete(); FileUtils.writeContent(projectDesc, content); } protected abstract File getSampleResourceFile() throws IOException; public void addSampleTo(File location) { } public void addSampleTo(IFolder workspaceLocation) { } public void createSample(Shell shell) { } public boolean isCustomCreateSample() { return false; } public String getProjectName() { return null; } public void setProjectName(String projectName) { } }
35.398601
96
0.747728
4ee11f39736f4861f01e1304fcdd1a1c0fd46bc4
261
package com.mumu.cake.ec.main.cart; /** * @ClassName: ShopCartFields * @Description: * @Author: 范琳琳 * @CreateDate: 2019/3/22 11:19 * @Version: 1.0 */ public enum ShopCartFields { TITLE, DESC, COUNT, PRICE, IS_SELECTED, POSITION }
14.5
35
0.624521
74be809f3622f1de5a2f7988c67fe4040b8c4066
4,673
/** * Copyright 2017 Syncleus, Inc. * with portions copyright 2004-2017 Bo Zimmerman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.syncleus.aethermud.game.Abilities.Diseases; import com.syncleus.aethermud.game.Abilities.interfaces.Ability; import com.syncleus.aethermud.game.Abilities.interfaces.DiseaseAffect; import com.syncleus.aethermud.game.Common.interfaces.CMMsg; import com.syncleus.aethermud.game.Common.interfaces.CharStats; import com.syncleus.aethermud.game.MOBS.interfaces.MOB; import com.syncleus.aethermud.game.core.CMLib; import com.syncleus.aethermud.game.core.CMProps; import com.syncleus.aethermud.game.core.interfaces.Tickable; public class Disease_Anthrax extends Disease { private final static String localizedName = CMLib.lang().L("Anthrax"); private final static String localizedStaticDisplay = CMLib.lang().L("(Anthrax)"); protected int lastHP = Integer.MAX_VALUE; protected int conDown = 0; protected int conTickDown = 60; private boolean norecurse = false; @Override public String ID() { return "Disease_Anthrax"; } @Override public String name() { return localizedName; } @Override public String displayText() { return localizedStaticDisplay; } @Override protected int canAffectCode() { return CAN_MOBS; } @Override protected int canTargetCode() { return CAN_MOBS; } @Override public int abstractQuality() { return Ability.QUALITY_MALICIOUS; } @Override public boolean putInCommandlist() { return false; } @Override public int difficultyLevel() { return 2; } @Override protected int DISEASE_TICKS() { return CMProps.getIntVar(CMProps.Int.TICKSPERMUDDAY) * 10; } @Override protected int DISEASE_DELAY() { return 15; } @Override protected String DISEASE_DONE() { return L("Your anthrax wounds clear up."); } @Override protected String DISEASE_START() { return L("^G<S-NAME> look(s) ill.^?"); } @Override protected String DISEASE_AFFECT() { return L("<S-NAME> watch(s) black necrotic wounds appear on <S-HIS-HER> flesh."); } @Override public int spreadBitmap() { return DiseaseAffect.SPREAD_CONSUMPTION | DiseaseAffect.SPREAD_CONTACT; } @Override public boolean tick(Tickable ticking, int tickID) { if (!super.tick(ticking, tickID)) return false; if (affected == null) return false; if (!(affected instanceof MOB)) return true; final MOB mob = (MOB) affected; MOB diseaser = invoker; if (diseaser == null) diseaser = mob; if ((!mob.amDead()) && ((--diseaseTick) <= 0)) { diseaseTick = DISEASE_DELAY(); mob.location().show(mob, null, CMMsg.MSG_OK_VISUAL, DISEASE_AFFECT()); final int damage = CMLib.dice().roll(1, 6, 0); if (damage > 1) { CMLib.combat().postDamage(diseaser, mob, this, damage, CMMsg.MASK_ALWAYS | CMMsg.TYP_DISEASE, -1, null); } if ((--conTickDown) <= 0) { conTickDown = 60; conDown++; } return true; } lastHP = mob.curState().getHitPoints(); return true; } @Override public void affectCharStats(MOB affected, CharStats affectableStats) { super.affectCharStats(affected, affectableStats); if (affected == null) return; if (conDown <= 0) return; affectableStats.setStat(CharStats.STAT_CONSTITUTION, affectableStats.getStat(CharStats.STAT_CONSTITUTION) - conDown); if ((affectableStats.getStat(CharStats.STAT_CONSTITUTION) <= 0) && (!norecurse)) { conDown = -1; MOB diseaser = invoker; if (diseaser == null) diseaser = affected; norecurse = true; CMLib.combat().postDeath(diseaser, affected, null); norecurse = false; } } }
29.955128
125
0.632784
23d7c840e42d961b7e961e2420372ea315e355ef
3,059
// This is a personal academic project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com package gost.controller; import gost.occasion.Statuses; import gost.signature.SignatureParameters; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class MessageManager { private final Logger log = LogManager.getLogger(MessageManager.class.getName()); public void status(String remark){ log.info("The program started with arguments: " + remark); } public void status(Statuses code) { switch (code) { case HELP -> { System.out.println(help()); log.info("help called"); } case VERIVIED -> { System.out.println("Подпись успешно прошла проверку"); log.info("The Main.signature was verified"); } case UNVERIVIED -> { System.out.println("Подпись не верна!"); log.info("The Main.signature is not correct"); } default -> { System.out.println("Применение несанкционированного кода сообщения!"); log.error("Unauthorized message code"); } } } public void statusIO(Statuses code, String path) { switch (code) { case KEYWRITE -> { System.out.println("Публичный ключ успешно записан в файл " + path); log.info("The public key was successfully written to " + path); } case SIGNWRITE -> { System.out.println("Электронная цифровая подпись успешно записана в " + path); log.info("The EDS was successfully recorded in " + path); } default -> { System.out.println("Применение несанкционированного кода сообщения!"); log.error("Unauthorized message code"); System.exit(1); } } } public void curveSettings(SignatureParameters parameters) { System.out.println(parameters.toString()); } private String help() { return """ Справка Приложение реализует алгоритм формирования электронной цифровой подписи в соответствии с ГОСТ 34.10-2018 Имеет три режима работы: Генерация ЭЦП Верификация ЭЦП Генерация ключа проверки Формат аргументов входа -p %путь_до_файла_параметров_кривой -m %путь_до_сообщения (-s %путь_до_файла_секретного_ключа(режим генерации ЭЦП) [-o %путь_выходного_файла] || -v %путь_до_файла_ключа_верификации -sig %путь_до_файла_подписи(режим верификации) -q %путь_до_файла_секретного_ключа(режим генерации ключа проверки) -p вывод текущих параметров эллиптической кривой -h справка -- Михаил Шомов 2020 """; } }
36.416667
243
0.579928
85c8a465c05015251074eb2d0f56d37965cf9d99
3,453
/* * 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 uk.co.objectconnexions.expressiveobjects.viewer.dnd.view.debug; import java.util.List; import com.google.common.collect.Lists; import uk.co.objectconnexions.expressiveobjects.core.commons.debug.DebuggableWithTitle; import uk.co.objectconnexions.expressiveobjects.core.metamodel.adapter.ObjectAdapter; import uk.co.objectconnexions.expressiveobjects.core.metamodel.spec.ActionType; import uk.co.objectconnexions.expressiveobjects.core.runtime.userprofile.PerspectiveEntry; import uk.co.objectconnexions.expressiveobjects.core.runtime.userprofile.UserProfilesDebugUtil; import uk.co.objectconnexions.expressiveobjects.viewer.dnd.drawing.Location; import uk.co.objectconnexions.expressiveobjects.viewer.dnd.service.PerspectiveContent; import uk.co.objectconnexions.expressiveobjects.viewer.dnd.view.Content; import uk.co.objectconnexions.expressiveobjects.viewer.dnd.view.Toolkit; import uk.co.objectconnexions.expressiveobjects.viewer.dnd.view.View; import uk.co.objectconnexions.expressiveobjects.viewer.dnd.view.Workspace; import uk.co.objectconnexions.expressiveobjects.viewer.dnd.view.option.UserActionAbstract; /** * Display debug window */ public class DebugOption extends UserActionAbstract { public DebugOption() { super("Debug...", ActionType.DEBUG); } @Override public void execute(final Workspace workspace, final View view, final Location at) { final Content content = view.getContent(); final ObjectAdapter object = content == null ? null : content.getAdapter(); final List<DebuggableWithTitle> debug = Lists.newArrayList(); if (content instanceof PerspectiveContent) { final PerspectiveEntry perspectiveEntry = ((PerspectiveContent) content).getPerspective(); debug.add(UserProfilesDebugUtil.asDebuggableWithTitle(perspectiveEntry)); } else { debug.add(new DebugObjectSpecification(content.getSpecification())); } if (object != null) { debug.add(new DebugAdapter(object)); debug.add(new DebugObjectGraph(object)); } debug.add(new DebugViewStructure(view)); debug.add(new DebugContent(view)); debug.add(new DebugDrawing(view)); debug.add(new DebugDrawingAbsolute(view)); final DebuggableWithTitle[] info = debug.toArray(new DebuggableWithTitle[debug.size()]); at.add(50, 6); // at.getX() + 50, at.getY() + 6 Toolkit.getViewer().showDebugFrame(info, at); } @Override public String getDescription(final View view) { return "Open debug window about " + view; } }
43.1625
102
0.739067
6f6116fa117980dda5cf85388104a1555a09dbc6
1,950
package com.dtstack.jlogstash.metrics.base.reporter; import com.dtstack.jlogstash.metrics.base.Metric; import com.dtstack.jlogstash.metrics.base.MetricConfig; import com.dtstack.jlogstash.metrics.base.MetricGroup; /** * copy from https://github.com/apache/flink * * Reporters are used to export {@link Metric Metrics} to an external backend. * * <p>Reporters are instantiated via reflection and must be public, non-abstract, and have a * public no-argument constructor. */ public interface MetricReporter { /** * Configures this reporter. Since reporters are instantiated generically and hence parameter-less, * this method is the place where the reporters set their basic fields based on configuration values. * * <p>This method is always called first on a newly instantiated reporter. * * @param config A properties object that contains all parameters set for this reporter. */ void open(MetricConfig config); /** * Closes this reporter. Should be used to close channels, streams and release resources. */ void close(); // ------------------------------------------------------------------------ // adding / removing metrics // ------------------------------------------------------------------------ /** * Called when a new {@link Metric} was added. * * @param metric the metric that was added * @param metricName the name of the metric * @param group the group that contains the metric */ void notifyOfAddedMetric(Metric metric, String metricName, MetricGroup group); /** * Called when a {@link Metric} was should be removed. * * @param metric the metric that should be removed * @param metricName the name of the metric * @param group the group that contains the metric */ void notifyOfRemovedMetric(Metric metric, String metricName, MetricGroup group); }
35.454545
105
0.638974
0eddd458b69ac4969a3c5f2f6b890632ad586a0f
29,056
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: packimports(3) // Source File Name: MOSJSONStructure.java package com.ibm.tivoli.maximo.rest; import com.ibm.json.java.JSONArray; import com.ibm.json.java.OrderedJSONObject; import java.rmi.RemoteException; import java.util.*; import org.apache.axiom.om.util.Base64; import psdi.iface.mic.MicUtil; import psdi.iface.mos.*; import psdi.iface.util.XMLUtils; import psdi.mbo.*; import psdi.server.MXServer; import psdi.util.*; import psdi.util.logging.MXLogger; import psdi.util.logging.MXLoggerFactory; public class MOSJSONStructure implements MosConstants { public MOSJSONStructure(String mosName, String operation, boolean verbose, boolean dropNulls, boolean locale, boolean retainMbos, boolean generic, boolean keys, boolean rootOnly, boolean metaData, boolean compact, boolean calculateEtag, boolean useTotalCount) throws MXException { this(ObjectStructureCache.getInstance().getMosInfo(mosName), operation, verbose, dropNulls, locale, retainMbos, generic, keys, rootOnly, metaData, compact, calculateEtag, useTotalCount); } public MOSJSONStructure(MosInfo mosInfo, String operation, boolean verbose, boolean dropNulls, boolean locale, boolean retainMbos, boolean generic, boolean keys, boolean rootOnly, boolean metaData, boolean compact, boolean calculateEtag, boolean useTotalCount) throws MXException { this.verbose = false; this.dropNulls = true; this.locale = false; this.retainMbos = false; this.rootOnly = false; this.metaData = false; selfRefMos = false; msi = null; this.mosInfo = null; this.generic = false; this.keys = false; this.compact = false; this.calculateEtag = true; rsBuffer = null; this.useTotalCount = true; resolvedTotalCount = -1; initialResolvedCount = -1; resolvedStartCount = -1; this.mosInfo = mosInfo; mosName = mosInfo.getIntObjectName(); this.verbose = verbose; this.dropNulls = dropNulls; this.locale = locale; this.retainMbos = retainMbos; this.operation = operation; this.keys = keys; this.rootOnly = rootOnly; this.generic = generic; this.metaData = metaData; this.compact = compact; this.calculateEtag = calculateEtag; this.useTotalCount = useTotalCount; if(compact) { metaData = false; generic = false; } defClassName = mosInfo.getDefClass(); selfRefMos = mosInfo.isSelfReferencing(); defClassName = defClassName != null ? defClassName : "psdi.iface.mos.MosDefinitionImpl"; try { msi = (MosDefinitionImpl)Class.forName(defClassName).newInstance(); } catch(Exception e) { throw new MXApplicationException("iface", "instclass", e); } msi.setOSName(mosName); if(logger.isDebugEnabled()) logger.debug((new StringBuilder()).append("MOSJSONStructure defClassName=").append(defClassName).toString()); if(calculateEtag) rsBuffer = new StringBuilder(); } public String getCalculatedEtag() { if(calculateEtag) return String.valueOf(rsBuffer.toString().hashCode()); else return null; } public byte[] serializeMboSet(MboSetRemote mboSet) throws MXException, RemoteException { return serializeMboSet(((MboIterator) (new MboSetIterator(mboSet))), 0, mboSet.count()); } public byte[] serializeMboSet(MboIterator mboSet) throws MXException, RemoteException { return serializeMboSet(mboSet, 0, mboSet.count()); } public byte[] serializeMboSet(OrderedJSONObject opOjo, MboIterator mboSet) throws MXException, RemoteException { return serializeMboSet(opOjo, mboSet, 0, mboSet.count()); } public byte[] serializeMboSet(MboSetRemote mboSet, int startIndex, int maxCount) throws MXException, RemoteException { return serializeMboSet(((MboIterator) (new MboSetIterator(mboSet))), startIndex, maxCount); } public OrderedJSONObject serializeMboSetAsJSONObject(MboSetRemote mboSet, int startIndex, int maxCount) throws MXException, RemoteException { return serializeMboSetAsJSONObject(null, ((MboIterator) (new MboSetIterator(mboSet))), startIndex, maxCount); } public OrderedJSONObject serializeMboSetAsJSONObject(MboIterator mboSet, int startIndex, int maxCount) throws MXException, RemoteException { return serializeMboSetAsJSONObject(null, mboSet, startIndex, maxCount); } public byte[] serializeMboSet(MboIterator mboSet, int startIndex, int maxCount) throws MXException, RemoteException { return serializeMboSet(null, mboSet, startIndex, maxCount); } public byte[] serializeMboSet(OrderedJSONObject opOjo, MboIterator mboSet, int startIndex, int maxCount) throws MXException, RemoteException { OrderedJSONObject ojo = serializeMboSetAsJSONObject(opOjo, mboSet, startIndex, maxCount); return ojo != null ? covertJSONObjectToBytes(ojo) : null; } public byte[] covertJSONObjectToBytes(OrderedJSONObject ojo) throws MXSystemException { return ojo.serialize(verbose).getBytes("utf-8"); Exception e; e; throw new MXSystemException("iface", "mbojsonerror", e); } public OrderedJSONObject serializeMboSetAsJSONObject(OrderedJSONObject opOjo, MboIterator mboSet, int startIndex, int maxCount) throws MXException, RemoteException { OrderedJSONObject ojo; if(logger.isDebugEnabled()) logger.debug((new StringBuilder()).append("MOSJSONStructure serializeMboSet=").append(mboSet).toString()); ojo = new OrderedJSONObject(); OrderedJSONObject osRootOjo = null; if(opOjo == null) { osRootOjo = new OrderedJSONObject(); if(!generic) { ojo.put((new StringBuilder()).append(operation).append(mosName).append("Response").toString(), osRootOjo); } else { ojo.put("OSResponse", osRootOjo); osRootOjo.put("name", mosName); } } else { osRootOjo = opOjo; if(generic) osRootOjo.put("name", mosName); } int rsStart = startIndex >= 0 ? startIndex : 0; int rsTotal = 0; int databaseCount = 0; int nounSize = 0; if(useTotalCount) { rsTotal = mboSet.count(); databaseCount = rsTotal - rsStart; nounSize = maxCount <= 0 ? databaseCount : Math.min(databaseCount, maxCount); } int rsCount = nounSize; if(resolvedStartCount >= 0) osRootOjo.put("rsStart", Integer.valueOf(rsStart)); else osRootOjo.put("rsStart", Integer.valueOf(rsStart)); osRootOjo.put("rsCount", Integer.valueOf(rsCount)); if(useTotalCount) if(resolvedTotalCount >= 0) osRootOjo.put("rsTotal", Integer.valueOf(resolvedTotalCount)); else osRootOjo.put("rsTotal", Integer.valueOf(rsTotal)); if(!retainMbos) mboSet.setDiscardable(); MosDetailInfo primaryInfo = mosInfo.getPrimaryMosDetailInfo(); if(logger.isDebugEnabled()) logger.debug((new StringBuilder()).append("MOSJSONStructure serializeMboSet primaryInfo=").append(primaryInfo).toString()); OrderedJSONObject osOjo = new OrderedJSONObject(); if(!generic) osRootOjo.put((new StringBuilder()).append(mosName).append("Set").toString(), osOjo); else osRootOjo.put("OSSet", osOjo); if(logger.isDebugEnabled()) { logger.debug((new StringBuilder()).append("will serialize ").append(rsStart).append(" to ").append(nounSize + rsStart).toString()); logger.debug((new StringBuilder()).append("rsCount=").append(rsCount).toString()); } JSONArray mboSetArray = new JSONArray(); int i = rsStart; MboRemote mbo = mboSet.get(i); int skipCount = 0; do { if(mbo == null) break; OrderedJSONObject mboOjo = new OrderedJSONObject(); MosDetailInfo mosDetailInfo = mosInfo.getPrimaryMosDetailInfo(); int retCode = mbo2JSONObject(mbo, mboOjo, mosDetailInfo, true); if(retCode != 3) mboSetArray.add(mboOjo); else skipCount++; i++; if(maxCount > 0 && i >= rsStart + maxCount) break; mbo = mboSet.get(i); } while(true); osRootOjo.put("rsCount", Integer.valueOf(i - (rsStart + skipCount))); if(mboSetArray.size() > 0) if(!generic) osOjo.put(primaryInfo.getObjectName(), mboSetArray); else osOjo.put("Mbo", mboSetArray); if(opOjo != null) return null; return ojo; Throwable t; t; logger.error(t.getMessage(), t); return null; } public byte[] serializeMbo(MboRemote mbo) throws MXException, RemoteException { return serializeMbo(null, mbo); } public OrderedJSONObject serializeMboAsJSONObject(MboRemote mbo) throws MXException, RemoteException { return serializeMboAsJSONObject(null, mbo); } public byte[] serializeMbo(OrderedJSONObject opOjo, MboRemote mbo) throws MXException, RemoteException { OrderedJSONObject ojo = serializeMboAsJSONObject(opOjo, mbo); return ojo != null ? covertJSONObjectToBytes(ojo) : null; } public OrderedJSONObject serializeMboAsJSONObject(OrderedJSONObject opOjo, MboRemote mbo) throws MXException, RemoteException { OrderedJSONObject ojo = new OrderedJSONObject(); OrderedJSONObject osRootOjo = null; if(opOjo == null) { osRootOjo = new OrderedJSONObject(); if(!generic) { ojo.put((new StringBuilder()).append(operation).append(mosName).append("Response").toString(), osRootOjo); } else { ojo.put("OSResponse", osRootOjo); osRootOjo.put("name", mosName); } } else { osRootOjo = opOjo; if(generic) osRootOjo.put("name", mosName); } osRootOjo.put("rsStart", Integer.valueOf(0)); osRootOjo.put("rsCount", Integer.valueOf(1)); osRootOjo.put("rsTotal", Integer.valueOf(1)); OrderedJSONObject osOjo = new OrderedJSONObject(); if(!generic) osRootOjo.put((new StringBuilder()).append(mosName).append("Set").toString(), osOjo); else osRootOjo.put("OSSet", osOjo); OrderedJSONObject mboOjo = new OrderedJSONObject(); MosDetailInfo mosDetailInfo = mosInfo.getPrimaryMosDetailInfo(); if(!generic) { osOjo.put(mosDetailInfo.getObjectName(), mboOjo); } else { osOjo.put("Mbo", mboOjo); mboOjo.put("name", mosDetailInfo.getObjectName()); } mbo2JSONObject(mbo, mboOjo, mosDetailInfo, true); if(opOjo != null) return null; else return ojo; } protected int mbo2JSONObject(MboRemote mbo, OrderedJSONObject mboOjo, MosDetailInfo mosDetailInfo, boolean headerObject) throws RemoteException, MXException { if(rootOnly && !headerObject) return 4; if(headerObject) msi.setOSPrimaryMbo(mbo); if(generic) mboOjo.put("name", mosDetailInfo.getObjectName()); Map ovrdColValueMap = new HashMap(); int retCode = msi.checkBusinessRules(mbo, mosDetailInfo, ovrdColValueMap); if(retCode == 2) throw new MXApplicationException("iface", "SKIP_TRANSACTION"); if(retCode == 3) if(headerObject) throw new MXApplicationException("iface", "SKIP_TRANSACTION"); else return 3; if(retCode == 4) return 4; if(calculateEtag) { String rs = ((Mbo)mbo).getRowStamp(); rsBuffer.append(rs); } Set colsToSkip = msi.getColumnsToSkip(mbo); if(metaData) { if(((Mbo)mbo).getRowRestrictionFlag().isFlagSet(263L)) mboOjo.put("hidden", Boolean.valueOf(true)); else mboOjo.put("hidden", Boolean.valueOf(false)); if(((Mbo)mbo).getRowRestrictionFlag().isFlagSet(7L)) mboOjo.put("readonly", Boolean.valueOf(true)); else mboOjo.put("readonly", Boolean.valueOf(false)); } Map columns = mosDetailInfo.getColumns(); Set colsSet = columns.keySet(); if(compact) { Iterator i$ = colsSet.iterator(); do { if(!i$.hasNext()) break; String column = (String)i$.next(); if(colsToSkip == null || !colsToSkip.contains(column)) { IfaceColumnInfo colInfo = (IfaceColumnInfo)columns.get(column); MboValueInfo mboValueInfo = colInfo.getMboValueInfo(); setJSONObjectAttribute(mboValueInfo, mbo, mboOjo, ovrdColValueMap.get(column), ovrdColValueMap.containsKey(column)); } } while(true); } else { OrderedJSONObject attributesOjo = new OrderedJSONObject(); mboOjo.put("Attributes", attributesOjo); Iterator i$ = colsSet.iterator(); do { if(!i$.hasNext()) break; String column = (String)i$.next(); if(colsToSkip == null || !colsToSkip.contains(column)) { IfaceColumnInfo colInfo = (IfaceColumnInfo)columns.get(column); MboValueInfo mboValueInfo = colInfo.getMboValueInfo(); setJSONObjectAttribute(mboValueInfo, mbo, attributesOjo, ovrdColValueMap.get(column), ovrdColValueMap.containsKey(column)); } } while(true); } msi.postSerializationRules(mbo, mosDetailInfo); List children = mosDetailInfo.getChildren(); if(logger.isDebugEnabled()) logger.debug((new StringBuilder()).append("children=").append(children).toString()); if(children != null) { OrderedJSONObject relatedMbosOjo = null; if(!compact) relatedMbosOjo = new OrderedJSONObject(); else relatedMbosOjo = mboOjo; JSONArray childJSONArray = null; if(generic) childJSONArray = new JSONArray(); for(int i = 0; i < children.size(); i++) { MosDetailInfo childInfo = (MosDetailInfo)children.get(i); if(logger.isDebugEnabled()) logger.debug((new StringBuilder()).append("childInfo=").append(childInfo).toString()); MboSetRemote childMboSet = mbo.getMboSet(childInfo.getRelation()); if(!retainMbos) childMboSet.setFlag(39L, true); int mboIndex = 0; if(!generic) childJSONArray = new JSONArray(); MboRemote childMbo = childMboSet.getMbo(mboIndex); if(logger.isDebugEnabled()) logger.debug((new StringBuilder()).append(childMboSet.getName()).append(" the mbo for mboIndex=").append(mboIndex).append(" is=").append(childMbo).toString()); for(; childMbo != null; childMbo = childMboSet.getMbo(++mboIndex)) { OrderedJSONObject childMboOjo = new OrderedJSONObject(); retCode = mbo2JSONObject(childMbo, childMboOjo, childInfo, false); if(retCode == 3) continue; childJSONArray.add(childMboOjo); if(retCode == 4) return retCode; } if(childJSONArray.size() > 0 && !generic) relatedMbosOjo.put(childInfo.getObjectName(), childJSONArray); } if(childJSONArray.size() > 0 && generic) relatedMbosOjo.put("Mbo", childJSONArray); if(!compact && !relatedMbosOjo.isEmpty()) mboOjo.put("RelatedMbos", relatedMbosOjo); } if(selfRefMos && mosDetailInfo.isPrimaryTable()) { OrderedJSONObject childrenMbosOjo = null; if(!compact) childrenMbosOjo = new OrderedJSONObject(); else childrenMbosOjo = mboOjo; MboSetRemote selfRefChildSet = mbo.getMboSet(mosDetailInfo.getRelation()); JSONArray hierchChildrenArray = (JSONArray)childrenMbosOjo.get(mosDetailInfo.getObjectName()); if(hierchChildrenArray == null) { hierchChildrenArray = new JSONArray(); if(!generic) childrenMbosOjo.put(mosDetailInfo.getObjectName(), hierchChildrenArray); else childrenMbosOjo.put("Mbo", hierchChildrenArray); } for(MboRemote cmbo = selfRefChildSet.moveFirst(); cmbo != null; cmbo = selfRefChildSet.moveNext()) { OrderedJSONObject hierchChildMboOjo = new OrderedJSONObject(); int hierchChildRetCode = mbo2JSONObject(cmbo, hierchChildMboOjo, mosDetailInfo, false); if(hierchChildRetCode == 3) continue; hierchChildrenArray.add(hierchChildMboOjo); if(hierchChildRetCode == 4) return hierchChildRetCode; } if(!compact && hierchChildrenArray.size() > 0 && !childrenMbosOjo.isEmpty()) mboOjo.put("ChildrenMbos", childrenMbosOjo); } return 1; } public boolean isKey(MboRemote mbo, String mboAttrName) throws RemoteException, MXException { MboSetInfo mboSetInfo = mbo.getThisMboSet().getMboSetInfo(); if(mboSetInfo.isPersistent()) { MboValueInfo mboValueInfo = mboSetInfo.getMboValueInfo(mboAttrName); String uniqueIdColName = mbo.getThisMboSet().getMboSetInfo().getUniqueIDName(); String altkeys[] = MicUtil.getKeyArray(mbo.getName()); return mboValueInfo.isKey() || uniqueIdColName.equalsIgnoreCase(mboAttrName) || Arrays.binarySearch(altkeys, mboAttrName) >= 0; } else { return true; } } protected void setJSONObjectAttribute(MboValueInfo mboValueInfo, MboRemote mbo, OrderedJSONObject mboOjo, Object ovrdColValue, boolean overridden) throws RemoteException, MXException { String attributeName = mboValueInfo.getName(); if(keys && !isKey(mbo, attributeName)) return; if(attributeName.endsWith("_BASELANGUAGE")) return; byte attachedDoc[] = null; boolean attachmentCol = false; if(mbo.getName().equals("DOCLINKS") && mbo.getString("urltype").equals("FILE") && attributeName.equalsIgnoreCase("DOCUMENTDATA")) { attachmentCol = true; attachedDoc = XMLUtils.readXMLFileToBytes(mbo.getString("urlname")); } if(dropNulls) if(overridden) { if(ovrdColValue == null) { if(logger.isDebugEnabled()) logger.debug((new StringBuilder()).append("dropping null column ").append(attributeName).append(" for mbo ").append(mbo.getName()).append(" due to override as null").toString()); return; } } else if(attachmentCol && attachedDoc == null || mbo.isNull(attributeName)) { if(logger.isDebugEnabled()) logger.debug((new StringBuilder()).append("dropping null column ").append(attributeName).append(" for mbo ").append(mbo.getName()).toString()); return; } int maxType = mboValueInfo.getTypeAsInt(); if(maxType == 16) return; OrderedJSONObject attrObject = new OrderedJSONObject(); if(!generic) { if(!compact) mboOjo.put(attributeName, attrObject); } else { JSONArray jsonArray = (JSONArray)mboOjo.get("Attribute"); if(jsonArray == null) { jsonArray = new JSONArray(); mboOjo.put("Attribute", jsonArray); } attrObject.put("name", attributeName); jsonArray.add(attrObject); } if(metaData) { if(((Mbo)mbo).getAttrRestrictionFlag(attributeName).isFlagSet(263L)) attrObject.put("hidden", Boolean.valueOf(true)); else attrObject.put("hidden", Boolean.valueOf(false)); if(((Mbo)mbo).getAttrRestrictionFlag(attributeName).isFlagSet(7L)) attrObject.put("readonly", Boolean.valueOf(true)); else attrObject.put("readonly", Boolean.valueOf(false)); if(((Mbo)mbo).getAttrRestrictionFlag(attributeName).isFlagSet(128L) || mboValueInfo.isRequired()) attrObject.put("required", Boolean.valueOf(true)); else attrObject.put("required", Boolean.valueOf(false)); } boolean uniqueId = false; if(mbo.getUniqueIDName().equals(attributeName)) uniqueId = true; if(logger.isDebugEnabled()) logger.debug((new StringBuilder()).append("attribute name==").append(attributeName).append(" value =").append(mbo.getMboValueData(attributeName).getDataAsObject()).toString()); Locale clientLocale = ((Mbo)mbo).getClientLocale(); switch(maxType) { case 16: // '\020' default: break; case 0: // '\0' case 1: // '\001' case 2: // '\002' case 13: // '\r' case 14: // '\016' case 17: // '\021' String jsonData = overridden ? (String)ovrdColValue : mbo.getString(attributeName); if(!compact) { attrObject.put("content", jsonData); if(locale) attrObject.put("localecontent", jsonData); } else { mboOjo.put(attributeName, jsonData); } break; case 15: // '\017' String base64PasswordData = null; String clearTextVal = overridden ? (String)ovrdColValue : mbo.getString(attributeName); if(clearTextVal != null) { byte encData[] = MXServer.getMXServer().getMXCipher().encData(clearTextVal); base64PasswordData = Base64.encode(encData); } if(!compact) { attrObject.put("content", base64PasswordData); if(locale) attrObject.put("localecontent", base64PasswordData); } else { mboOjo.put(attributeName, base64PasswordData); } break; case 6: // '\006' case 7: // '\007' case 19: // '\023' long jsonLData = overridden ? ((Long)ovrdColValue).longValue() : mbo.getLong(attributeName); if(!compact) { if(!uniqueId) { attrObject.put("content", Long.valueOf(jsonLData)); } else { attrObject.put("content", Long.valueOf(jsonLData)); attrObject.put("resourceid", Boolean.valueOf(true)); } if(locale) { String localeData = MXFormat.longToString(jsonLData, clientLocale); attrObject.put("localecontent", localeData); } break; } if(locale) mboOjo.put(attributeName, MXFormat.longToString(jsonLData, clientLocale)); else mboOjo.put(attributeName, Long.valueOf(jsonLData)); break; case 8: // '\b' case 9: // '\t' case 10: // '\n' case 11: // '\013' double jsonDData = overridden ? ((Double)ovrdColValue).doubleValue() : mbo.getDouble(attributeName); if(!compact) { attrObject.put("content", Double.valueOf(jsonDData)); if(locale) attrObject.put("localecontent", MXFormat.doubleToString(jsonDData, clientLocale)); break; } if(locale) mboOjo.put(attributeName, MXFormat.doubleToString(jsonDData, clientLocale)); else mboOjo.put(attributeName, Double.valueOf(jsonDData)); break; case 3: // '\003' case 4: // '\004' case 5: // '\005' Date jsonDTData = overridden ? (Date)ovrdColValue : mbo.getDate(attributeName); if(!compact) { attrObject.put("content", mbo.isNull(attributeName) ? null : ((Object) (ConversionUtil.dateToString(jsonDTData)))); if(locale) attrObject.put("localecontent", MXFormat.dateToString(jsonDTData, clientLocale, ((Mbo)mbo).getClientTimeZone())); break; } if(locale) mboOjo.put(attributeName, MXFormat.dateToString(jsonDTData, clientLocale, ((Mbo)mbo).getClientTimeZone())); else mboOjo.put(attributeName, mbo.isNull(attributeName) ? null : ((Object) (ConversionUtil.dateToString(jsonDTData)))); break; case 12: // '\f' boolean jsonBool = overridden ? ((Boolean)ovrdColValue).booleanValue() : mbo.getBoolean(attributeName); if(!compact) { attrObject.put("content", Boolean.valueOf(jsonBool)); if(locale) attrObject.put("localecontent", MXFormat.booleanToString(jsonBool, clientLocale)); break; } if(locale) mboOjo.put(attributeName, MXFormat.booleanToString(jsonBool, clientLocale)); else mboOjo.put(attributeName, Boolean.valueOf(jsonBool)); break; case 18: // '\022' byte data[] = null; if(attachmentCol) data = overridden ? (byte[])(byte[])ovrdColValue : attachedDoc; else data = overridden ? (byte[])(byte[])ovrdColValue : mbo.getBytes(attributeName); String base64Data = Base64.encode(data); if(!compact) { attrObject.put("content", base64Data); if(locale) attrObject.put("localecontent", base64Data); } else { mboOjo.put(attributeName, base64Data); } break; } } public void setResolvedTotalCount(int resolvedTotalCount) { this.resolvedTotalCount = resolvedTotalCount; } public void setInitialResolvedCount(int initialResolvedCount) { this.initialResolvedCount = initialResolvedCount; } public void setResolvedStartCount(int resolvedStartCount) { this.resolvedStartCount = resolvedStartCount; } protected String mosName; protected boolean verbose; protected boolean dropNulls; protected boolean locale; protected boolean retainMbos; protected boolean rootOnly; protected boolean metaData; protected String defClassName; private boolean selfRefMos; private MosDefinitionImpl msi; private MosInfo mosInfo; private boolean generic; private boolean keys; private String operation; protected boolean compact; protected boolean calculateEtag; private StringBuilder rsBuffer; protected boolean useTotalCount; private int resolvedTotalCount; private int initialResolvedCount; private int resolvedStartCount; private static MXLogger logger = MXLoggerFactory.getLogger("maximo.rest"); }
39.264865
202
0.579777
28c360484c5d420567237f016965d533de480099
2,253
/* * 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.geronimo.security.jaspi; import javax.security.auth.message.config.AuthConfigFactory; import org.apache.geronimo.gbean.annotation.GBean; import org.apache.geronimo.gbean.annotation.ParamAttribute; import org.apache.geronimo.gbean.annotation.ParamSpecial; import org.apache.geronimo.gbean.annotation.SpecialAttributeType; /** * Installs the specified AuthConfigFactory * * @version $Rev$ $Date$ */ @GBean public class AuthConfigFactoryGBean { public AuthConfigFactoryGBean(@ParamAttribute(name = "authConfigFactoryClassName") final String authConfigFactoryClassName, @ParamSpecial(type = SpecialAttributeType.classLoader) ClassLoader classLoader) { Thread currentThread = Thread.currentThread(); ClassLoader oldClassLoader = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(classLoader); try { java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() { public Object run() { java.security.Security.setProperty(AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY, authConfigFactoryClassName); return null; } }); AuthConfigFactory.getFactory(); } finally { currentThread.setContextClassLoader(oldClassLoader); } } }
37.55
144
0.708833
6dd826a6613bc622e7b5d82d45ee74c9e61b9515
23,864
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.api; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.springframework.web.context.support.SpringBeanAutowiringSupport; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.managed.context.ManagedContext; import com.cloud.exception.CloudAuthenticationException; import com.cloud.user.Account; import com.cloud.user.AccountService; import com.cloud.user.User; import com.cloud.utils.StringUtils; import com.cloud.utils.db.EntityManager; @Component("apiServlet") @SuppressWarnings("serial") public class ApiServlet extends HttpServlet { public static final Logger s_logger = Logger.getLogger(ApiServlet.class.getName()); private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName()); @Inject ApiServerService _apiServer; @Inject AccountService _accountMgr; @Inject EntityManager _entityMgr; @Inject ManagedContext _managedContext; public ApiServlet() { } @Override public void init(ServletConfig config) throws ServletException { SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { processRequest(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { processRequest(req, resp); } private void utf8Fixup(HttpServletRequest req, Map<String, Object[]> params) { if (req.getQueryString() == null) { return; } String[] paramsInQueryString = req.getQueryString().split("&"); if (paramsInQueryString != null) { for (String param : paramsInQueryString) { String[] paramTokens = param.split("=", 2); if (paramTokens != null && paramTokens.length == 2) { String name = paramTokens[0]; String value = paramTokens[1]; try { name = URLDecoder.decode(name, "UTF-8"); } catch (UnsupportedEncodingException e) { } try { value = URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { } params.put(name, new String[] { value }); } else { s_logger.debug("Invalid parameter in URL found. param: " + param); } } } } private void processRequest(final HttpServletRequest req, final HttpServletResponse resp) { _managedContext.runWithContext(new Runnable() { @Override public void run() { processRequestInContext(req, resp); } }); } private void processRequestInContext(HttpServletRequest req, HttpServletResponse resp) { StringBuffer auditTrailSb = new StringBuffer(); auditTrailSb.append(" " + req.getRemoteAddr()); auditTrailSb.append(" -- " + req.getMethod() + " "); // get the response format since we'll need it in a couple of places String responseType = BaseCmd.RESPONSE_TYPE_XML; Map<String, Object[]> params = new HashMap<String, Object[]>(); params.putAll(req.getParameterMap()); // For HTTP GET requests, it seems that HttpServletRequest.getParameterMap() actually tries // to unwrap URL encoded content from ISO-9959-1. // After failed in using setCharacterEncoding() to control it, end up with following hacking: // for all GET requests, we will override it with our-own way of UTF-8 based URL decoding. utf8Fixup(req, params); // logging the request start and end in management log for easy debugging String reqStr = ""; if (s_logger.isDebugEnabled()) { reqStr = auditTrailSb.toString() + " " + StringUtils.cleanString(req.getQueryString()); s_logger.debug("===START=== " + reqStr); } try { HttpSession session = req.getSession(false); Object[] responseTypeParam = params.get("response"); if (responseTypeParam != null) { responseType = (String) responseTypeParam[0]; } Object[] commandObj = params.get("command"); if (commandObj != null) { String command = (String) commandObj[0]; if ("logout".equalsIgnoreCase(command)) { // if this is just a logout, invalidate the session and return if (session != null) { Long userId = (Long) session.getAttribute("userid"); Account account = (Account) session.getAttribute("accountobj"); Long accountId = null; if (account != null) { accountId = account.getId(); } auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")"); if (userId != null) { _apiServer.logoutUser(userId); } try { session.invalidate(); } catch (IllegalStateException ise) { } } auditTrailSb.append("command=logout"); auditTrailSb.append(" " + HttpServletResponse.SC_OK); writeResponse(resp, getLogoutSuccessResponse(responseType), HttpServletResponse.SC_OK, responseType); return; } else if ("login".equalsIgnoreCase(command)) { auditTrailSb.append("command=login"); // if this is a login, authenticate the user and return if (session != null) { try { session.invalidate(); } catch (IllegalStateException ise) { } } session = req.getSession(true); String[] username = (String[]) params.get("username"); String[] password = (String[]) params.get("password"); String[] domainIdArr = (String[]) params.get("domainid"); if (domainIdArr == null) { domainIdArr = (String[]) params.get("domainId"); } String[] domainName = (String[]) params.get("domain"); Long domainId = null; if ((domainIdArr != null) && (domainIdArr.length > 0)) { try { //check if UUID is passed in for domain domainId = _apiServer.fetchDomainId(domainIdArr[0]); if(domainId == null){ domainId = new Long(Long.parseLong(domainIdArr[0])); } auditTrailSb.append(" domainid=" + domainId);// building the params for POST call } catch (NumberFormatException e) { s_logger.warn("Invalid domain id entered by user"); auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "Invalid domain id entered, please enter a valid one"); String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid domain id entered, please enter a valid one", params, responseType); writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType); } } String domain = null; if (domainName != null) { domain = domainName[0]; auditTrailSb.append(" domain=" + domain); if (domain != null) { // ensure domain starts with '/' and ends with '/' if (!domain.endsWith("/")) { domain += '/'; } if (!domain.startsWith("/")) { domain = "/" + domain; } } } if (username != null) { String pwd = ((password == null) ? null : password[0]); try { _apiServer.loginUser(session, username[0], pwd, domainId, domain, req.getRemoteAddr(), params); auditTrailSb.insert(0, "(userId=" + session.getAttribute("userid") + " accountId=" + ((Account) session.getAttribute("accountobj")).getId() + " sessionId=" + session.getId() + ")"); String loginResponse = getLoginSuccessResponse(session, responseType); writeResponse(resp, loginResponse, HttpServletResponse.SC_OK, responseType); return; } catch (CloudAuthenticationException ex) { // TODO: fall through to API key, or just fail here w/ auth error? (HTTP 401) try { session.invalidate(); } catch (IllegalStateException ise) { } auditTrailSb.append(" " + ApiErrorCode.ACCOUNT_ERROR + " " + ex.getMessage() != null ? ex.getMessage() : "failed to authenticate user, check if username/password are correct"); String serializedResponse = _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), ex.getMessage() != null ? ex.getMessage() : "failed to authenticate user, check if username/password are correct", params, responseType); writeResponse(resp, serializedResponse, ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), responseType); return; } } } } auditTrailSb.append(req.getQueryString()); boolean isNew = ((session == null) ? true : session.isNew()); // Initialize an empty context and we will update it after we have verified the request below, // we no longer rely on web-session here, verifyRequest will populate user/account information // if a API key exists Long userId = null; if (!isNew) { userId = (Long) session.getAttribute("userid"); String account = (String) session.getAttribute("account"); Object accountObj = session.getAttribute("accountobj"); String sessionKey = (String) session.getAttribute("sessionkey"); String[] sessionKeyParam = (String[]) params.get("sessionkey"); if ((sessionKeyParam == null) || (sessionKey == null) || !sessionKey.equals(sessionKeyParam[0])) { try { session.invalidate(); } catch (IllegalStateException ise) { } auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials"); String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType); writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType); return; } // Do a sanity check here to make sure the user hasn't already been deleted if ((userId != null) && (account != null) && (accountObj != null) && _apiServer.verifyUser(userId)) { String[] command = (String[]) params.get("command"); if (command == null) { s_logger.info("missing command, ignoring request..."); auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified"); String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType); writeResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType); return; } User user = _entityMgr.findById(User.class, userId); CallContext.register(user, (Account)accountObj); } else { // Invalidate the session to ensure we won't allow a request across management server // restarts if the userId was serialized to the stored session try { session.invalidate(); } catch (IllegalStateException ise) { } auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials"); String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType); writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType); return; } } else { CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); } if (_apiServer.verifyRequest(params, userId)) { /* * if (accountObj != null) { Account userAccount = (Account)accountObj; if (userAccount.getType() == * Account.ACCOUNT_TYPE_NORMAL) { params.put(BaseCmd.Properties.USER_ID.getName(), new String[] { userId }); * params.put(BaseCmd.Properties.ACCOUNT.getName(), new String[] { account }); * params.put(BaseCmd.Properties.DOMAIN_ID.getName(), new String[] { domainId }); * params.put(BaseCmd.Properties.ACCOUNT_OBJ.getName(), new Object[] { accountObj }); } else { * params.put(BaseCmd.Properties.USER_ID.getName(), new String[] { userId }); * params.put(BaseCmd.Properties.ACCOUNT_OBJ.getName(), new Object[] { accountObj }); } } * * // update user context info here so that we can take information if the request is authenticated // via api * key mechanism updateUserContext(params, session != null ? session.getId() : null); */ auditTrailSb.insert(0, "(userId=" + CallContext.current().getCallingUserId() + " accountId=" + CallContext.current().getCallingAccount().getId() + " sessionId=" + (session != null ? session.getId() : null) + ")"); // Add the HTTP method (GET/POST/PUT/DELETE) as well into the params map. params.put("httpmethod", new String[] { req.getMethod() }); String response = _apiServer.handleRequest(params, responseType, auditTrailSb); writeResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType); } else { if (session != null) { try { session.invalidate(); } catch (IllegalStateException ise) { } } auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials and/or request signature"); String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials and/or request signature", params, responseType); writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType); } } catch (ServerApiException se) { String serializedResponseText = _apiServer.getSerializedApiError(se, params, responseType); resp.setHeader("X-Description", se.getDescription()); writeResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType); auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (Exception ex) { s_logger.error("unknown exception writing api response", ex); auditTrailSb.append(" unknown exception writing api response"); } finally { s_accessLogger.info(auditTrailSb.toString()); if (s_logger.isDebugEnabled()) { s_logger.debug("===END=== " + reqStr); } // cleanup user context to prevent from being peeked in other request context CallContext.unregister(); } } /* * private void updateUserContext(Map<String, Object[]> requestParameters, String sessionId) { String userIdStr = * (String)(requestParameters.get(BaseCmd.Properties.USER_ID.getName())[0]); Account accountObj = * (Account)(requestParameters.get(BaseCmd.Properties.ACCOUNT_OBJ.getName())[0]); * * Long userId = null; Long accountId = null; if(userIdStr != null) userId = Long.parseLong(userIdStr); * * if(accountObj != null) accountId = accountObj.getId(); UserContext.updateContext(userId, accountId, sessionId); } */ // FIXME: rather than isError, we might was to pass in the status code to give more flexibility private void writeResponse(HttpServletResponse resp, String response, int responseCode, String responseType) { try { if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { resp.setContentType(ApiServer.getJsonContentType() + "; charset=UTF-8"); } else { resp.setContentType("text/xml; charset=UTF-8"); } resp.setStatus(responseCode); resp.getWriter().print(response); } catch (IOException ioex) { if (s_logger.isTraceEnabled()) { s_logger.trace("exception writing response: " + ioex); } } catch (Exception ex) { if (!(ex instanceof IllegalStateException)) { s_logger.error("unknown exception writing api response", ex); } } } @SuppressWarnings("rawtypes") private String getLoginSuccessResponse(HttpSession session, String responseType) { StringBuffer sb = new StringBuffer(); int inactiveInterval = session.getMaxInactiveInterval(); String user_UUID = (String)session.getAttribute("user_UUID"); session.removeAttribute("user_UUID"); String domain_UUID = (String)session.getAttribute("domain_UUID"); session.removeAttribute("domain_UUID"); if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { sb.append("{ \"loginresponse\" : { "); Enumeration attrNames = session.getAttributeNames(); if (attrNames != null) { sb.append("\"timeout\" : \"" + inactiveInterval + "\""); while (attrNames.hasMoreElements()) { String attrName = (String) attrNames.nextElement(); if("userid".equalsIgnoreCase(attrName)){ sb.append(", \"" + attrName + "\" : \"" + user_UUID + "\""); }else if("domainid".equalsIgnoreCase(attrName)){ sb.append(", \"" + attrName + "\" : \"" + domain_UUID + "\""); }else{ Object attrObj = session.getAttribute(attrName); if ((attrObj instanceof String) || (attrObj instanceof Long)) { sb.append(", \"" + attrName + "\" : \"" + attrObj.toString() + "\""); } } } } sb.append(" } }"); } else { sb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"); sb.append("<loginresponse cloud-stack-version=\"" + ApiDBUtils.getVersion() + "\">"); sb.append("<timeout>" + inactiveInterval + "</timeout>"); Enumeration attrNames = session.getAttributeNames(); if (attrNames != null) { while (attrNames.hasMoreElements()) { String attrName = (String) attrNames.nextElement(); if("userid".equalsIgnoreCase(attrName)){ sb.append("<" + attrName + ">" + user_UUID + "</" + attrName + ">"); }else if("domainid".equalsIgnoreCase(attrName)){ sb.append("<" + attrName + ">" + domain_UUID + "</" + attrName + ">"); }else{ Object attrObj = session.getAttribute(attrName); if (attrObj instanceof String || attrObj instanceof Long || attrObj instanceof Short) { sb.append("<" + attrName + ">" + attrObj.toString() + "</" + attrName + ">"); } } } } sb.append("</loginresponse>"); } return sb.toString(); } private String getLogoutSuccessResponse(String responseType) { StringBuffer sb = new StringBuffer(); if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { sb.append("{ \"logoutresponse\" : { \"description\" : \"success\" } }"); } else { sb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"); sb.append("<logoutresponse cloud-stack-version=\"" + ApiDBUtils.getVersion() + "\">"); sb.append("<description>success</description>"); sb.append("</logoutresponse>"); } return sb.toString(); } }
51.991285
204
0.560803
d8f9d32f73f87452081329091e88a12ece737cf2
2,441
/** * */ package org.apereo.openlrs.storage.inmemory; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.apereo.openlrs.model.event.Event; import org.apereo.openlrs.storage.Reader; import org.apereo.openlrs.storage.Writer; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Component; /** * @author ggilbert * */ @ConditionalOnProperty(name={"openlrs.writer","openlrs.reader"}, havingValue="InMemoryReaderWriter") @Component("InMemoryReaderWriter") public class InMemoryReaderWriter implements Writer, Reader { private static Map<String, List<Event>> store = new HashMap<String, List<Event>>(); @Override public Page<Event> findByTenantId(String tenantId, Pageable pageable) { List<Event> events = store.get(tenantId); if (events == null) return null; return new PageImpl<>(events, pageable, events.size()); } @Override public Event findByTenantIdAndEventId(String tenantId, String eventId) { List<Event> events = store.get(tenantId); if (events == null) return null; List<Event> eventResultList = events.stream() .filter(event -> event.getId().equals(eventId)) .collect(Collectors.toList()); return (eventResultList != null && eventResultList.size() >= 1) ? eventResultList.get(0) : null; } @Override public Event save(Event event, String tenantId) { if (event == null || StringUtils.isBlank(tenantId)) { throw new IllegalArgumentException("Event or Tenant cannot be null"); } List<Event> events = store.get(tenantId); if (events == null) { events = new LinkedList<Event>(); } events.add(event); store.put(tenantId, events); return event; } @Override public List<Event> saveAll(Collection<Event> events, String tenantId) { List<Event> savedEvents = null; if (events != null && !events.isEmpty()) { savedEvents = new ArrayList<Event>(); for (Event e : events) { savedEvents.add(this.save(e, tenantId)); } } return savedEvents; } }
28.383721
100
0.704629
dc57e01e6e4d82e27b1f127a6cfd20168635c278
848
package gov.cms.mat.fhir.rest.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.ArrayList; import java.util.List; import java.util.Map; @Data @AllArgsConstructor @NoArgsConstructor public class LibraryConversionResults { String matLibraryId; String fhirLibraryId; String name; String version; String reason; Boolean success; String link; String fhirLibraryJson; Map<String, List<CqlConversionError>> externalErrors; /* Error results when validating the */ private List<FhirValidationResult> libraryFhirValidationResults = new ArrayList<>(); // KEEP private CqlConversionResult cqlConversionResult = new CqlConversionResult(); public LibraryConversionResults(String matLibraryId) { this.matLibraryId = matLibraryId; } }
25.69697
96
0.758255
1b21ea59aa4c9c4c82a0f6a992be09abf62c1527
565
package com.android.supervolley; import com.android.volley.Response; import com.android.volley.VolleyError; abstract class ResponseListener implements Response.Listener<String>, Response.ErrorListener { @Override public void onResponse(String response) { onSuccess(new HttpResponse.Builder().raw(response)); } @Override public void onErrorResponse(VolleyError error) { onFailure(error); } protected abstract void onSuccess(HttpResponse.Builder builder); abstract void onFailure(VolleyError payload); }
23.541667
68
0.734513
1d4a25f195998e3dc04d09949129127dafd2b6d6
2,637
package com.lenss.yzeng.utils; import android.app.Activity; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; /** * Created by yukun on 1/3/2017. */ public class Utils { // yukun public static void requestPermisssions(Activity activity, String[] permissionList){ ArrayList<String> permissionsToGet = new ArrayList<String>(); for(int i = 0; i < permissionList.length; i++){ int permissionFlag = ContextCompat.checkSelfPermission(activity, permissionList[i]); if (permissionFlag != PackageManager.PERMISSION_GRANTED){ permissionsToGet.add(permissionList[i]); } } String[] permissionsRequestArray = new String[permissionList.length]; permissionsToGet.toArray(permissionsRequestArray); ActivityCompat.requestPermissions(activity, permissionsRequestArray, -1); } public static void appendStringToFile(String output, String filePath){ File file = new File(filePath); try { if (!file.exists()) file.createNewFile(); FileWriter writer = new FileWriter(file, true); writer.write(output); writer.flush(); writer.close(); } catch (IOException e){ e.printStackTrace(); } } public static void appendByteArrayListToFile(ArrayList<byte[]> bytesArrayList, String filePath){ File file = new File(filePath); try { if (!file.exists()) file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); for (byte[] byteArray : bytesArrayList) { Log.e("Util.writeBytes", bytesArrayList.size() + " frames have been written to " + filePath); fos.write(byteArray); fos.flush(); } fos.close(); } catch (IOException e) { e.printStackTrace(); } } public static void appendByteArrayToFile(byte[] byteArray, String filePath){ File file = new File(filePath); try { if (!file.exists()) file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); fos.write(byteArray); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
33.379747
109
0.609025
e67fb64c933845fbbc20fe86f4b1bd07eb76fb0c
150
package cn.cerc.db.core; @Deprecated public class Record extends DataRow { private static final long serialVersionUID = 4041128206428436571L; }
18.75
70
0.786667
0ec04178997f467d8463b5dd138ed7ce628fdb7b
845
package com.apina.sso.core; import com.apina.sso.core.config.CoreConfigurationManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Created by Kari Kurillo on 19/04/16. */ @SpringBootApplication public class ApinaSso implements CommandLineRunner { @Autowired private CoreConfigurationManager configurationManager; public static void main(String args[]) { SpringApplication .run(ApinaSso.class, args); } @Override public void run(String... args) { try { configurationManager.initialize(args); } catch (Exception e) { e.printStackTrace(); } } }
26.40625
68
0.711243
6dd794e26402e302c194ee12e8f710774c3e1dcc
4,389
package i5.las2peer.services.uatMusic; import java.util.*; import org.json.simple.*; import org.json.simple.parser.ParseException; public class classes { class image { public image() {} private String imageName; public void setimageName(String setValue) { this.imageName = setValue; } public String getimageName() { return this.imageName; } private String imageUrl; public void setimageUrl(String setValue) { this.imageUrl = setValue; } public String getimageUrl() { return this.imageUrl; } private int imageId; public void setimageId(int setValue) { this.imageId = setValue; } public int getimageId() { return this.imageId; } public JSONObject toJSON() { JSONObject jo = new JSONObject(); jo.put("imageName", this.imageName); jo.put("imageUrl", this.imageUrl); jo.put("imageId", this.imageId); return jo; } public void fromJSON(String jsonString) throws ParseException { JSONObject jsonObject = (JSONObject) JSONValue.parseWithException(jsonString); this.imageName = (String) jsonObject.get("imageName"); this.imageUrl = (String) jsonObject.get("imageUrl"); this.imageId = ((Long) jsonObject.get("imageId")).intValue(); } } class music { public music() {} private String musicName; public void setmusicName(String setValue) { this.musicName = setValue; } public String getmusicName() { return this.musicName; } private int imageId; public void setimageId(int setValue) { this.imageId = setValue; } public int getimageId() { return this.imageId; } private int musicId; public void setmusicId(int setValue) { this.musicId = setValue; } public int getmusicId() { return this.musicId; } private String musicUrl; public void setmusicUrl(String setValue) { this.musicUrl = setValue; } public String getmusicUrl() { return this.musicUrl; } public JSONObject toJSON() { JSONObject jo = new JSONObject(); jo.put("musicName", this.musicName); jo.put("imageId", this.imageId); jo.put("musicId", this.musicId); jo.put("musicUrl", this.musicUrl); return jo; } public void fromJSON(String jsonString) throws ParseException { JSONObject jsonObject = (JSONObject) JSONValue.parseWithException(jsonString); this.musicName = (String) jsonObject.get("musicName"); this.imageId = ((Long) jsonObject.get("imageId")).intValue(); this.musicId = ((Long) jsonObject.get("musicId")).intValue(); this.musicUrl = (String) jsonObject.get("musicUrl"); } } class imageMusic { public imageMusic() {} private String imageName; public void setimageName(String setValue) { this.imageName = setValue; } public String getimageName() { return this.imageName; } private String imageUrl; public void setimageUrl(String setValue) { this.imageUrl = setValue; } public String getimageUrl() { return this.imageUrl; } private String musicName; public void setmusicName(String setValue) { this.musicName = setValue; } public String getmusicName() { return this.musicName; } private String musicUrl; public void setmusicUrl(String setValue) { this.musicUrl = setValue; } public String getmusicUrl() { return this.musicUrl; } public JSONObject toJSON() { JSONObject jo = new JSONObject(); jo.put("imageName", this.imageName); jo.put("imageUrl", this.imageUrl); jo.put("musicName", this.musicName); jo.put("musicUrl", this.musicUrl); return jo; } public void fromJSON(String jsonString) throws ParseException { JSONObject jsonObject = (JSONObject) JSONValue.parseWithException(jsonString); this.imageName = (String) jsonObject.get("imageName"); this.imageUrl = (String) jsonObject.get("imageUrl"); this.musicName = (String) jsonObject.get("musicName"); this.musicUrl = (String) jsonObject.get("musicUrl"); } } }
23.222222
86
0.618592
f88289d04b1952407ce950890bc650bae3e1baf4
6,557
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.argumentselectiondefects; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.common.annotations.VisibleForTesting; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.ProvidesFix; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.names.NamingConventions; import com.google.errorprone.names.NeedlemanWunschEditDistance; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import java.util.function.Function; /** * Checks the lexical distance between method parameter names and the argument names at call sites. * If another permutation of the arguments produces a lower distance then it is possible that the * programmer has accidentally reordered them. * * <p>Rice, Andrew, et al. <a href="https://ai.google/research/pubs/pub46317">"Detecting argument * selection defects"</a>. Proceedings of the ACM on Programming Languages OOPSLA (2017). * * <p>Terminology: * * <ul> * <li>Formal parameter - as given in the definition of the method * <li>Actual parameter - as used in the invocation of the method * <li>Parameter - either a formal or actual parameter * </ul> * * @author [email protected] (Andrew Rice) */ @BugPattern( name = "ArgumentSelectionDefectChecker", summary = "Arguments are in the wrong order or could be commented for clarity.", severity = WARNING, providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION) public class ArgumentSelectionDefectChecker extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher { private final ArgumentChangeFinder argumentChangeFinder; public ArgumentSelectionDefectChecker() { this( ArgumentChangeFinder.builder() .setDistanceFunction(buildDefaultDistanceFunction()) .addHeuristic(new LowInformationNameHeuristic()) .addHeuristic(new PenaltyThresholdHeuristic()) .addHeuristic(new EnclosedByReverseHeuristic()) .addHeuristic(new CreatesDuplicateCallHeuristic()) .addHeuristic(new NameInCommentHeuristic()) .build()); } @VisibleForTesting ArgumentSelectionDefectChecker(ArgumentChangeFinder argumentChangeFinder) { this.argumentChangeFinder = argumentChangeFinder; } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { MethodSymbol symbol = ASTHelpers.getSymbol(tree); if (symbol == null) { return Description.NO_MATCH; } // Don't return a match if the AssertEqualsArgumentOrderChecker would match it too if (Matchers.ASSERT_METHOD.matches(tree, state)) { return Description.NO_MATCH; } return visitNewClassOrMethodInvocation( InvocationInfo.createFromMethodInvocation(tree, symbol, state)); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { MethodSymbol symbol = ASTHelpers.getSymbol(tree); if (symbol == null) { return Description.NO_MATCH; } // Don't return a match if the AutoValueConstructorOrderChecker would match it too if (Matchers.AUTOVALUE_CONSTRUCTOR.matches(tree, state)) { return Description.NO_MATCH; } return visitNewClassOrMethodInvocation(InvocationInfo.createFromNewClass(tree, symbol, state)); } private Description visitNewClassOrMethodInvocation(InvocationInfo invocationInfo) { Changes changes = argumentChangeFinder.findChanges(invocationInfo); if (changes.isEmpty()) { return Description.NO_MATCH; } Description.Builder description = buildDescription(invocationInfo.tree()).setMessage(changes.describe(invocationInfo)); // Fix 1 (semantics-preserving): apply comments with parameter names to potentially-swapped // arguments of the method description.addFix(changes.buildCommentArgumentsFix(invocationInfo)); // Fix 2: permute the arguments as required description.addFix(changes.buildPermuteArgumentsFix(invocationInfo)); return description.build(); } /** * Computes the distance between a formal and actual parameter. If either is a null literal then * the distance is zero (null matches everything). If both have a name then we compute the * normalised NeedlemanWunschEditDistance. Otherwise, one of the names is unknown and so we return * 0 distance between it and its original parameter and infinite distance between all others. */ private static final Function<ParameterPair, Double> buildDefaultDistanceFunction() { return new Function<ParameterPair, Double>() { @Override public Double apply(ParameterPair pair) { if (pair.formal().isNullLiteral() || pair.actual().isNullLiteral()) { return 0.0; } if (!pair.formal().isUnknownName() && !pair.actual().isUnknownName()) { String normalizedSource = NamingConventions.convertToLowerUnderscore(pair.formal().name()); String normalizedTarget = NamingConventions.convertToLowerUnderscore(pair.actual().name()); return NeedlemanWunschEditDistance.getNormalizedEditDistance( /*source=*/ normalizedSource, /*target=*/ normalizedTarget, /*caseSensitive=*/ false, /*changeCost=*/ 8, /*openGapCost=*/ 8, /*continueGapCost=*/ 1); } return pair.formal().index() == pair.actual().index() ? 0.0 : Double.POSITIVE_INFINITY; } }; } }
39.263473
100
0.73494
53c6729a6031f776dd8fa18b7dbd3c3a7e4d0e26
1,491
/** * Copyright 2017 ZTE Corporation. * * 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.openo.holmes.common.api.stat; import java.io.Serializable; public interface AplusResult extends Serializable { /** * Derived new alarm type - 0 */ byte APLUS_RAISED = 0; /** * Correlation alarm, root-child alarm - 1 */ byte APLUS_CORRELATION = 1; /** * cleared */ byte APLUS_CLEAR = 2; int getId(); void setId(int id); String getRuleInfo(); void setRuleInfo(String ruleInfo); String getRuleType(); void setRuleType(String ruleType); void setRuleId(String ruleId); String getRuleId(); long getCreateTime(); void setCreateTime(long createTime); byte getResultType(); void setResultType(byte resultType); Alarm[] getAffectedAlarms(); void setAffectedAlarms(Alarm[] affectedAlarms); }
22.253731
76
0.651241
3122456bd4306511ec6d8808acb425e6b0b0083c
8,149
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|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|name package|; end_package begin_import import|import static name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|Type operator|. name|STRING import|; end_import begin_import import|import name|javax operator|. name|jcr operator|. name|NamespaceException import|; end_import begin_import import|import name|javax operator|. name|jcr operator|. name|RepositoryException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|CommitFailedException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|PropertyState import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|Root import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|Tree import|; end_import begin_comment comment|/** * Writable namespace registry. Mainly for use to implement the full JCR API. */ end_comment begin_class specifier|public specifier|abstract class|class name|ReadWriteNamespaceRegistry extends|extends name|ReadOnlyNamespaceRegistry block|{ specifier|public name|ReadWriteNamespaceRegistry parameter_list|( name|Root name|root parameter_list|) block|{ name|super argument_list|( name|root argument_list|) expr_stmt|; block|} comment|/** * Called by the write methods to acquire a fresh {@link Root} instance * that can be used to persist the requested namespace changes (and * nothing else). * * @return fresh {@link Root} instance */ specifier|protected specifier|abstract name|Root name|getWriteRoot parameter_list|() function_decl|; comment|/** * Called by the write methods to refresh the state of the possible * session associated with this instance. The default implementation * of this method does nothing, but a subclass can use this callback * to keep a session in sync with the persisted namespace changes. * * @throws RepositoryException if the session could not be refreshed */ specifier|protected name|void name|refresh parameter_list|() throws|throws name|RepositoryException block|{ comment|// do nothing block|} comment|//--------------------------------------------------< NamespaceRegistry>--- annotation|@ name|Override specifier|public name|void name|registerNamespace parameter_list|( name|String name|prefix parameter_list|, name|String name|uri parameter_list|) throws|throws name|RepositoryException block|{ if|if condition|( name|prefix operator|. name|isEmpty argument_list|() operator|&& name|uri operator|. name|isEmpty argument_list|() condition|) block|{ return|return; comment|// the default empty namespace is always registered block|} elseif|else if|if condition|( name|prefix operator|. name|isEmpty argument_list|() operator||| name|uri operator|. name|isEmpty argument_list|() condition|) block|{ throw|throw operator|new name|NamespaceException argument_list|( literal|"Cannot remap the default empty namespace" argument_list|) throw|; block|} name|PropertyState name|property init|= name|namespaces operator|. name|getProperty argument_list|( name|prefix argument_list|) decl_stmt|; if|if condition|( name|property operator|!= literal|null operator|&& name|property operator|. name|getType argument_list|() operator|== name|STRING operator|&& name|uri operator|. name|equals argument_list|( name|property operator|. name|getValue argument_list|( name|STRING argument_list|) argument_list|) condition|) block|{ return|return; comment|// common case: namespace already registered -> do nothing block|} try|try block|{ name|Root name|root init|= name|getWriteRoot argument_list|() decl_stmt|; name|Tree name|namespaces init|= name|root operator|. name|getTree argument_list|( name|NAMESPACES_PATH argument_list|) decl_stmt|; comment|// remove existing mapping to given URI for|for control|( name|PropertyState name|mapping range|: name|namespaces operator|. name|getProperties argument_list|() control|) block|{ if|if condition|( name|mapping operator|. name|getType argument_list|() operator|== name|STRING operator|&& name|uri operator|. name|equals argument_list|( name|mapping operator|. name|getValue argument_list|( name|STRING argument_list|) argument_list|) condition|) block|{ name|namespaces operator|. name|removeProperty argument_list|( name|mapping operator|. name|getName argument_list|() argument_list|) expr_stmt|; block|} block|} comment|// add this mapping (overrides existing mapping with same prefix) name|namespaces operator|. name|setProperty argument_list|( name|prefix argument_list|, name|uri argument_list|) expr_stmt|; name|root operator|. name|commit argument_list|() expr_stmt|; name|refresh argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|CommitFailedException name|e parameter_list|) block|{ throw|throw name|e operator|. name|asRepositoryException argument_list|( literal|"Failed to register namespace mapping " operator|+ name|prefix operator|+ literal|" -> " operator|+ name|uri argument_list|) throw|; block|} block|} annotation|@ name|Override specifier|public name|void name|unregisterNamespace parameter_list|( name|String name|prefix parameter_list|) throws|throws name|RepositoryException block|{ if|if condition|( name|prefix operator|. name|isEmpty argument_list|() condition|) block|{ throw|throw operator|new name|NamespaceException argument_list|( literal|"Cannot unregister the default empty namespace" argument_list|) throw|; block|} name|Root name|root init|= name|getWriteRoot argument_list|() decl_stmt|; name|Tree name|namespaces init|= name|root operator|. name|getTree argument_list|( name|NAMESPACES_PATH argument_list|) decl_stmt|; if|if condition|( operator|! name|namespaces operator|. name|exists argument_list|() operator||| operator|! name|namespaces operator|. name|hasProperty argument_list|( name|prefix argument_list|) condition|) block|{ throw|throw operator|new name|NamespaceException argument_list|( literal|"Namespace mapping from " operator|+ name|prefix operator|+ literal|" to " operator|+ name|getURI argument_list|( name|prefix argument_list|) operator|+ literal|" can not be unregistered" argument_list|) throw|; block|} try|try block|{ name|namespaces operator|. name|removeProperty argument_list|( name|prefix argument_list|) expr_stmt|; name|root operator|. name|commit argument_list|() expr_stmt|; name|refresh argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|CommitFailedException name|e parameter_list|) block|{ name|String name|message init|= literal|"Failed to unregister namespace mapping for prefix " operator|+ name|prefix decl_stmt|; throw|throw name|e operator|. name|asRepositoryException argument_list|( name|message argument_list|) throw|; block|} block|} block|} end_class end_unit
16.630612
810
0.781446
ff012174adbb1ed165b2d8373fbd1fd1c6b44e15
137
package com.mercury.platform.shared.config.configration; public interface HasDefault<T> { T getDefault(); void toDefault(); }
15.222222
56
0.722628
31a1629b8157205d71cc1a7e5d1c266184afd682
2,422
package com.codeforces.commons.pair; import com.codeforces.commons.text.StringUtil; import org.jetbrains.annotations.Contract; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * @author Maxim Shipko ([email protected]) * Date: 13.05.2016 */ public class ShortPair implements Comparable<ShortPair> { private short first; private short second; public ShortPair() { } public ShortPair(short first, short second) { this.first = first; this.second = second; } public ShortPair(@Nonnull ShortPair pair) { this.first = pair.first; this.second = pair.second; } public short getFirst() { return first; } public void setFirst(short first) { this.first = first; } public short getSecond() { return second; } public void setSecond(short second) { this.second = second; } @SuppressWarnings("CompareToUsesNonFinalVariable") @Override public int compareTo(@Nonnull ShortPair pair) { int comparisonResult = Short.compare(first, pair.first); return comparisonResult == 0 ? Short.compare(second, pair.second) : comparisonResult; } public boolean equals(short first, short second) { return this.first == first && this.second == second; } @SuppressWarnings("NonFinalFieldReferenceInEquals") @Contract(pure = true) @Override public final boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ShortPair)) { return false; } ShortPair pair = (ShortPair) o; return first == pair.first && second == pair.second; } @SuppressWarnings("NonFinalFieldReferencedInHashCode") @Override public int hashCode() { return 32323 * Short.hashCode(first) + Short.hashCode(second); } @Override public String toString() { return toString(this); } @Nonnull public static String toString(@Nullable ShortPair pair) { return toString(ShortPair.class, pair); } @Nonnull public static <T extends ShortPair> String toString(@Nonnull Class<T> pairClass, @Nullable T pair) { return StringUtil.toString(pairClass, pair, false, "first", "second"); } }
25.494737
105
0.610652
c6abeffbc6c09429a2379d9a91cd2ce175f30bef
2,328
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the repository root. package com.microsoft.tfs.client.common.ui.framework.helper; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ICheckable; /** * A helper class for working with ICheckable elements, such as * CheckboxTableViewer. This class can keep track of which elements are * currently checked in the ICheckable. It can be subclassed to perform specific * actions when an element is checked or unchecked. */ public class CheckedElements { private final List elements = new ArrayList(); private final ICheckable checkable; public CheckedElements(final ICheckable checkable) { this.checkable = checkable; checkable.addCheckStateListener(new CheckStateListener()); } public void setCheckState(final List inputElements, final boolean state) { for (final Iterator it = inputElements.iterator(); it.hasNext();) { final Object element = it.next(); checkable.setChecked(element, state); if (state) { elements.add(element); onCheck(element); } else { elements.remove(element); onUncheck(element); } } } public List getElements() { return elements; } public boolean contains(final Object element) { return elements.contains(element); } public void clearElements() { elements.clear(); } protected void onCheck(final Object element) { } protected void onUncheck(final Object element) { } private class CheckStateListener implements ICheckStateListener { @Override public void checkStateChanged(final CheckStateChangedEvent event) { final boolean checked = event.getChecked(); final Object element = event.getElement(); if (checked) { elements.add(element); onCheck(element); } else { elements.remove(element); onUncheck(element); } } } }
29.846154
80
0.646048
f61fb5bc0078012182c03451df23f23ad570cc64
2,023
package ru.stqa.course.addressbook.tests; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.course.addressbook.model.ContactData; import ru.stqa.course.addressbook.model.Contacts; import java.io.File; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by leonto on 3/7/2016. */ public class ContactModificationTests extends TestBase{ @BeforeMethod public void ensurePreconditions() { if (app.db().contacts().size() == 0) { //app.goTo().homePage(); app.goTo().contactPage(); File photo = new File("src/test/resources/stru.jpg"); app.contact().create(new ContactData() .withFirstName("Name1").withLastName("LastName1").withAddress("testAddress") .withHomePhone("111").withMobilePhone("222").withWorkPhone("333").withEmail("[email protected]") .withEmail2("[email protected]").withEmail3("[email protected]") .withPhoto(photo)); } } @Test public void testContactModification() { Contacts before = app.db().contacts(); app.goTo().homePage(); File photo = new File("src/test/resources/stru.jpg"); ContactData modifiedContact = before.iterator().next(); ContactData contact = new ContactData() .withId(modifiedContact.getId()).withFirstName("NameEdit").withLastName("LastNameEdit").withAddress("EditAddress") .withHomePhone("111-1").withMobilePhone("222-2").withWorkPhone("333-3") .withEmail("[email protected]") .withEmail2("[email protected]").withEmail3("[email protected]") .withPhoto(photo); //app.goTo().homePage(); app.contact().modify(contact); app.contact().returnToHomePage(); Contacts after = app.db().contacts(); assertThat(after.size(), equalTo(before.size())); assertThat(after, equalTo(before.without(modifiedContact).withAdded(contact))); verifyContactListInUI(); } }
35.491228
126
0.687593
3214b03f756f647bc682f0ba775ed1d3a708ecb2
2,166
package org.zstack.sdk; public class AccessControlListEntryInventory { public java.lang.String uuid; public void setUuid(java.lang.String uuid) { this.uuid = uuid; } public java.lang.String getUuid() { return this.uuid; } public java.lang.String aclUuid; public void setAclUuid(java.lang.String aclUuid) { this.aclUuid = aclUuid; } public java.lang.String getAclUuid() { return this.aclUuid; } public java.lang.String type; public void setType(java.lang.String type) { this.type = type; } public java.lang.String getType() { return this.type; } public java.lang.String name; public void setName(java.lang.String name) { this.name = name; } public java.lang.String getName() { return this.name; } public java.lang.String domain; public void setDomain(java.lang.String domain) { this.domain = domain; } public java.lang.String getDomain() { return this.domain; } public java.lang.String url; public void setUrl(java.lang.String url) { this.url = url; } public java.lang.String getUrl() { return this.url; } public java.lang.String ipEntries; public void setIpEntries(java.lang.String ipEntries) { this.ipEntries = ipEntries; } public java.lang.String getIpEntries() { return this.ipEntries; } public java.lang.String description; public void setDescription(java.lang.String description) { this.description = description; } public java.lang.String getDescription() { return this.description; } public java.sql.Timestamp createDate; public void setCreateDate(java.sql.Timestamp createDate) { this.createDate = createDate; } public java.sql.Timestamp getCreateDate() { return this.createDate; } public java.sql.Timestamp lastOpDate; public void setLastOpDate(java.sql.Timestamp lastOpDate) { this.lastOpDate = lastOpDate; } public java.sql.Timestamp getLastOpDate() { return this.lastOpDate; } }
24.613636
62
0.641274
2a9a69b7283bd898025160865f51d59fcbe77f9d
157
package br.com.cabralrodrigo.mc.fluidania.common.lib; public final class LibFluidNames { public static final String LIQUID_MANA = "liquid_mana"; }
26.166667
60
0.757962
b0c4146e9af7b8a7aa5497381f8bd4256bad691e
5,579
package de.javagl.flow.gui; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import de.javagl.flow.module.Module; import de.javagl.flow.module.ModuleInfo; import de.javagl.flow.module.slot.InputSlot; import de.javagl.flow.module.slot.OutputSlot; import de.javagl.flow.module.slot.SlotInfo; /** * A panel containing the representations of the {@link OutputSlot} objects * of a {@link Module}, used inside a {@link ModuleComponent} */ final class ModuleComponentOutputPanel extends JPanel { /** * Serial UID */ private static final long serialVersionUID = 2206183202108424451L; /** * The labels representing the {@link OutputSlot} objects of the module */ private List<JLabel> outputSlotLabels = Collections.emptyList(); /** * The labels containing information about the {@link OutputSlot} objects * of the module */ private List<JLabel> outputInfoLabels = Collections.emptyList(); /** * Create a new panel for the given {@link Module} * * @param module The {@link Module} */ ModuleComponentOutputPanel(Module module) { super(new GridBagLayout()); setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.BLACK)); outputSlotLabels = new ArrayList<JLabel>(); outputInfoLabels = new ArrayList<JLabel>(); ModuleInfo moduleInfo = module.getModuleInfo(); int numOutputSlots = moduleInfo.getOutputSlotInfos().size(); for (int i=0; i<numOutputSlots; i++) { GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(0, 0, 0, 0); constraints.weighty = 1.0; constraints.gridy = i; // The outputInfoLabel will contain the // slot name and type information JLabel outputInfoLabel = new JLabel(); outputInfoLabel.setOpaque(true); outputInfoLabel.setBorder( BorderFactory.createEmptyBorder(2, 2, 2, 2)); outputInfoLabels.add(outputInfoLabel); constraints.gridx = 0; constraints.weightx = 1.0; JPanel container = new JPanel( new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0)); container.add(outputInfoLabel); add(container, constraints); // The outputSlotLabel will contain the // arrow > and allow connecting links JLabel outputSlotLabel = new JLabel(" > "); outputSlotLabel.setOpaque(true); outputSlotLabel.setBorder( BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(2, 2, 2, 2), BorderFactory.createMatteBorder( 1, 0, 1, 1, Color.BLACK))); outputSlotLabels.add(outputSlotLabel); constraints.gridx = 1; constraints.weightx = 0.0; add(outputSlotLabel, constraints); } } /** * Update the info labels that show the name and type of the * {@link InputSlot} objects and {@link OutputSlot} objects * * @param module The {@link Module} */ void updateSlotInfoLabels(Module module) { ModuleInfo moduleInfo = module.getModuleInfo(); List<SlotInfo> outputSlotInfos = moduleInfo.getOutputSlotInfos(); List<OutputSlot> outputSlots = module.getOutputSlots(); for (int i=0; i<outputSlotInfos.size(); i++) { OutputSlot slot = outputSlots.get(i); SlotInfo slotInfo = outputSlotInfos.get(i); String string = ModuleComponentUtils.createSlotString(slotInfo, slot); JLabel label = outputInfoLabels.get(i); ModuleComponentUtils.setTextAndTooltip(label, string); } } /** * Highlight the representation of the specified {@link OutputSlot} * by setting its background color to the given color. If the given * index is negative, then ALL output slots will receive * the given background. * * @param index The index of the {@link OutputSlot}, or a value &lt;0 to * set all backgrounds * @param color The background color */ void highlightOutputSlot(int index, Color color) { if (index < 0) { for (int i=0; i<outputSlotLabels.size(); i++) { JComponent component = outputSlotLabels.get(i); component.setBackground(color); } } else { JComponent component = outputSlotLabels.get(index); component.setBackground(color); } } /** * Returns the component representing the {@link OutputSlot} * with the given index * * @param index The index * @return The component representing the {@link OutputSlot} * with the given index */ JComponent getOutputSlotLabel(int index) { return outputSlotLabels.get(index); } }
34.438272
79
0.599391
d6af6ae633ccc93813ef5f6c7c8d2d05593b535e
3,305
package princess.tenergistics.modifiers; import net.minecraft.block.BlockState; import net.minecraft.block.IBucketPickupHandler; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.fluid.Fluid; import net.minecraft.fluid.FluidState; import net.minecraft.fluid.Fluids; import net.minecraft.util.ActionResultType; import net.minecraft.util.Direction; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.util.math.RayTraceContext; import net.minecraft.util.math.RayTraceResult.Type; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidAttributes; import net.minecraftforge.fluids.FluidStack; import princess.tenergistics.TEnergistics; import princess.tenergistics.tools.PoweredTool; import slimeknights.tconstruct.library.modifiers.SingleUseModifier; import slimeknights.tconstruct.library.tools.item.ToolCore; import slimeknights.tconstruct.library.tools.nbt.IModifierToolStack; public class WideFunnelModifier extends SingleUseModifier { public WideFunnelModifier() { super(0xc8bfe7); } @Override public ActionResultType onToolUse(IModifierToolStack tool, int level, World world, PlayerEntity player, Hand hand) { FluidStack fluidStack = PoweredTool.getFluidStack(tool); if (PoweredTool.getFluidCapacity(tool) - fluidStack.getAmount() < FluidAttributes.BUCKET_VOLUME) { return ActionResultType.PASS; } BlockRayTraceResult trace = ToolCore.blockRayTrace(world, player, RayTraceContext.FluidMode.SOURCE_ONLY); if (trace.getType() != Type.BLOCK) { return ActionResultType.PASS; } Direction face = trace.getFace(); BlockPos target = trace.getPos(); BlockPos offset = target.offset(face); if (!world.isBlockModifiable(player, target) || !player.canPlayerEdit(offset, face, player.getHeldItem(hand))) { return ActionResultType.PASS; } FluidState fluidState = world.getFluidState(target); Fluid currentFluid = fluidStack.getFluid(); if (fluidState.isEmpty() || !TEnergistics.exchangerModifier.get().tank .isFluidValid(tool, 0, 0, new FluidStack(fluidState.getFluid(), 1)) || (!fluidStack.isEmpty() && !currentFluid.isEquivalentTo(fluidState.getFluid()))) { return ActionResultType.PASS; } BlockState state = world.getBlockState(target); if (state.getBlock() instanceof IBucketPickupHandler) { Fluid pickedUpFluid = ((IBucketPickupHandler) state.getBlock()).pickupFluid(world, target, state); if (pickedUpFluid != Fluids.EMPTY) { player.playSound(pickedUpFluid.getAttributes().getFillSound(fluidStack), 1.0F, 1.0F); if (!world.isRemote) { if (fluidStack.isEmpty()) { PoweredTool.setFluidStack(tool, new FluidStack(pickedUpFluid, FluidAttributes.BUCKET_VOLUME)); } else if (pickedUpFluid == currentFluid) { fluidStack.grow(FluidAttributes.BUCKET_VOLUME); PoweredTool.setFluidStack(tool, fluidStack); } else { TEnergistics.log .error("Picked up a fluid {} that does not match the current fluid state {}, this should not happen", pickedUpFluid, fluidState .getFluid()); } } return ActionResultType.SUCCESS; } } return ActionResultType.PASS; } }
37.134831
136
0.751286
fcecea1b183b348b7edeb2226e7687effee97b6e
900
package top.bluesword.web.laboratory.rocket.delayed.sender; import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.support.MessageBuilder; import org.springframework.stereotype.Component; import java.util.Date; /** * @author 李林峰 */ @Component public class DelayedSender { @Autowired private RocketMQTemplate rocketTemplate; public void delayedSender(String context) { SendResult sendResult = rocketTemplate.syncSend("delay-abc", MessageBuilder.withPayload(context).build(), 1000, 2); System.out.println("queue.delay:{回调时间:"+DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.format(new Date())+'}'); } }
32.142857
122
0.744444
779dfdacafd8a892fb2a1bead1b2352fa371d87c
5,699
package org.gentar.audit.diff; import org.gentar.biology.location.Location; import org.gentar.biology.mutation.Mutation; import org.gentar.biology.mutation.sequence.MutationSequence; import org.gentar.biology.sequence.Sequence; import org.gentar.biology.sequence_location.SequenceLocation; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; // This class contains some edges cases for the detection of changes. The Mutation class is chosen // because that's one with complex cases of collections with collections inside. class ChangesDetectorComplexCasesTest { @Test void testEmptyObjects() { ChangesDetector<Mutation> testInstance = new ChangesDetector<>(Collections.emptyList(), new Mutation(), new Mutation()); List<ChangeEntry> changeEntries = testInstance.getChanges(); assertThat("No changes expected:", changeEntries.isEmpty(), is(true)); } @Test void testEqualObjects() { Mutation originalMutation = buildMutation(); Mutation newMutation = new Mutation(originalMutation); ChangesDetector<Mutation> testInstance = new ChangesDetector<>(Collections.emptyList(), originalMutation, newMutation); List<ChangeEntry> changeEntries = testInstance.getChanges(); assertThat("No changes expected:", changeEntries.isEmpty(), is(true)); } @Test void testChangeInElementCollectionInsideCollection() { Mutation originalMutation = buildMutation(); Mutation newMutation = new Mutation(originalMutation); newMutation = editMutation(newMutation); ChangesDetector<Mutation> testInstance = new ChangesDetector<>(Collections.emptyList(), originalMutation, newMutation); List<ChangeEntry> changeEntries = testInstance.getChanges(); assertThat("Changes expected:", changeEntries.isEmpty(), is(false)); } private ChangeEntry findByName(String name, List<ChangeEntry> changeEntries) { return changeEntries.stream() .filter(x -> x.getProperty().equals(name)) .findAny().orElse(null); } @Test void testChangeInElementCollectionInsideCollectionWithSequence() { Sequence originalSequence = buildSequence(); Sequence newSequence = buildSequence(); newSequence = editSequence(newSequence); ChangesDetector<Sequence> testInstance = new ChangesDetector<>(Collections.emptyList(), originalSequence, newSequence); List<ChangeEntry> changeEntries = testInstance.getChanges(); assertThat("2 changes expected:", changeEntries.size(), is(2)); ChangeEntry changeEntry1 = findByName("sequenceLocations.[1]", changeEntries); assertThat(changeEntry1.getChangeType(), is(ChangeType.CHANGED_ELEMENT)); assertThat(changeEntry1.getType(), is(SequenceLocation.class)); ChangeEntry changeEntry2 = findByName("sequenceLocations.[1].location.chr", changeEntries); assertThat(changeEntry2.getChangeType(), is(ChangeType.CHANGED_FIELD)); assertThat(changeEntry2.getType(), is(String.class)); assertThat(changeEntry2.getOldValue(), is("X")); assertThat(changeEntry2.getNewValue(), is("Y")); } private Sequence editSequence(Sequence newSequence) { for (SequenceLocation sequenceLocation : newSequence.getSequenceLocations()) { Location location = sequenceLocation.getLocation(); location.setChr("Y"); } return newSequence; } private Mutation editMutation(Mutation mutation) { for (MutationSequence mutationSequence : mutation.getMutationSequences()) { Sequence sequence = mutationSequence.getSequence(); for (SequenceLocation sequenceLocation : sequence.getSequenceLocations()) { Location location = sequenceLocation.getLocation(); location.setChr("Y"); } } return mutation; } private Mutation buildMutation() { Mutation mutation = new Mutation(); mutation.setId(1L); Set<MutationSequence> mutationSequences = new HashSet<>(); mutationSequences.add(buildMutationSequence()); mutation.setMutationSequences(mutationSequences); return mutation; } private MutationSequence buildMutationSequence() { MutationSequence mutationSequence = new MutationSequence(); mutationSequence.setId(1L); mutationSequence.setIndex(1); mutationSequence.setSequence(buildSequence()); return mutationSequence; } private Sequence buildSequence() { Sequence sequence = new Sequence(); sequence.setId(1L); sequence.setSequence("sequenceText"); List<SequenceLocation> sequenceLocations = new ArrayList<>(); sequenceLocations.add(buildSequenceLocation()); sequence.setSequenceLocations(sequenceLocations); return sequence; } private SequenceLocation buildSequenceLocation() { SequenceLocation sequenceLocation = new SequenceLocation(); sequenceLocation.setId(1L); sequenceLocation.setIndex(1); sequenceLocation.setLocation(buildLocation()); return sequenceLocation; } private Location buildLocation() { Location location = new Location(); location.setId(1L); location.setChr("X"); return location; } }
35.842767
99
0.687314
b7f3391685a32bfd26a9c2c27ee59ed73ec4355b
202
package org.marsik.bugautomation.bugzilla; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class AuthorizationCallback { String name; String password; }
16.833333
42
0.79703
517df60e7971803e3cdf50d995f7f03dbdd319e3
4,657
package tool.testForApks; import java.io.IOException; import java.util.Collections; import org.xmlpull.v1.XmlPullParserException; import soot.PackManager; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.jimple.infoflow.android.SetupApplication; import soot.jimple.infoflow.solver.cfg.InfoflowCFG; import soot.jimple.toolkits.callgraph.CHATransformer; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG; import soot.options.Options; import tool.Analy.Analysis.AnalysisRepeatLoading; public class testForApks { public static CallGraph callGraph; public static InfoflowCFG info ; public final static String androidPlatformLocation = "E:\\android SDK\\android-sdk-windows\\platforms"; public final static String apkFileLocation ="C:\\Users\\11142\\Desktop\\APKs\\Glide\\Mi-Video.apk"; public static void main(String[] args) throws IOException, XmlPullParserException { String param[] = { "-android-jars", androidPlatformLocation, "-process-dir", apkFileLocation }; initSoot(param); AnalysisRepeatLoading analysis = new AnalysisRepeatLoading(apkFileLocation, callGraph); analysis.Analyze(); } public static void initSoot(String[] param) throws IOException, XmlPullParserException { Options.v().set_src_prec(Options.src_prec_apk); Options.v().set_output_format(Options.output_format_jimple); Options.v().set_process_multiple_dex(true); Options.v().set_output_dir("JimpleOutput"); Options.v().set_keep_line_number(true); Options.v().set_prepend_classpath(true); Options.v().set_allow_phantom_refs(true); Options.v().set_android_jars(param[1]); Options.v().set_process_dir(Collections.singletonList(param[3])); Options.v().set_whole_program(true); Options.v().set_force_overwrite(true); Scene.v().loadNecessaryClasses(); // Load necessary classes CHATransformer.v().transform(); //Call graph callGraph=Scene.v().getCallGraph(); JimpleBasedInterproceduralCFG icfg = new JimpleBasedInterproceduralCFG(true,true); info = new InfoflowCFG(icfg); System.out.println("cg size:"+callGraph.size()); Scene.v().addBasicClass("java.io.BufferedReader",SootClass.HIERARCHY); Scene.v().addBasicClass("java.lang.StringBuilder",SootClass.BODIES); Scene.v().addBasicClass("java.util.HashSet",SootClass.BODIES); Scene.v().addBasicClass("android.content.Intent",SootClass.BODIES); Scene.v().addBasicClass("java.io.PrintStream",SootClass.SIGNATURES); Scene.v().addBasicClass("java.lang.System",SootClass.SIGNATURES); Scene.v().addBasicClass("com.app.test.CallBack",SootClass.BODIES); Scene.v().addBasicClass("java.io.Serializable",SootClass.SIGNATURES); Scene.v().addBasicClass("java.io.Serializable",SootClass.BODIES); Scene.v().addBasicClass("android.graphics.PointF",SootClass.SIGNATURES); Scene.v().addBasicClass("android.graphics.PointF",SootClass.BODIES); Scene.v().addBasicClass("org.reflections.Reflections",SootClass.HIERARCHY); Scene.v().addBasicClass("org.reflections.scanners.Scanner",SootClass.HIERARCHY); Scene.v().addBasicClass("org.reflections.scanners.SubTypesScanner",SootClass.HIERARCHY); Scene.v().addBasicClass("java.lang.ThreadGroup",SootClass.SIGNATURES); Scene.v().addBasicClass("com.ironsource.mobilcore.OfferwallManager",SootClass.HIERARCHY); Scene.v().addBasicClass("bolts.WebViewAppLinkResolver$2",SootClass.HIERARCHY); Scene.v().addBasicClass("com.ironsource.mobilcore.BaseFlowBasedAdUnit",SootClass.HIERARCHY); Scene.v().addBasicClass("android.annotation.TargetApi",SootClass.SIGNATURES); Scene.v().addBasicClass("com.outfit7.engine.Recorder$VideoGenerator$CacheMgr",SootClass.HIERARCHY); Scene.v().addBasicClass("com.alibaba.motu.crashreporter.handler.CrashThreadMsg$",SootClass.HIERARCHY); Scene.v().addBasicClass("java.lang.Cloneable",SootClass.HIERARCHY); Scene.v().addBasicClass("org.apache.http.util.EncodingUtils",SootClass.SIGNATURES); Scene.v().addBasicClass("org.apache.http.protocol.HttpRequestHandlerRegistry",SootClass.SIGNATURES); Scene.v().addBasicClass("org.apache.commons.logging.Log",SootClass.SIGNATURES); Scene.v().addBasicClass("org.apache.http.params.HttpProtocolParamBean",SootClass.SIGNATURES); Scene.v().addBasicClass("org.apache.http.protocol.RequestExpectContinue",SootClass.SIGNATURES); Scene.v().loadClassAndSupport("Constants"); // PackageManager } }
56.792683
111
0.7449
8a1b30f126935f0f40bf9795fcafab7f629df143
943
package com.grady.server.dto; /** * @Author Grady * @Date 2020/7/15 20:18 * @Version 1.0 */ public class SortDto { private String id; private int oldSort; private int newSort; public String getId() { return id; } public void setId(String id) { this.id = id; } public int getOldSort() { return oldSort; } public void setOldSort(int oldSort) { this.oldSort = oldSort; } public int getNewSort() { return newSort; } public void setNewSort(int newSort) { this.newSort = newSort; } @Override public String toString() { final StringBuffer sb = new StringBuffer("SortDto{"); sb.append("id='").append(id).append('\''); sb.append(", oldSort='").append(oldSort).append('\''); sb.append(", newSort='").append(newSort).append('\''); sb.append('}'); return sb.toString(); } }
19.645833
62
0.558855
f292a086ea94d9adc7f341435096ee4fe944073b
3,959
package jetbrains.mps.lang.smodel.typesystem; /*Generated by MPS */ import jetbrains.mps.lang.typesystem.runtime.AbstractInferenceRule_Runtime; import jetbrains.mps.lang.typesystem.runtime.InferenceRule_Runtime; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.typesystem.inference.TypeCheckingContext; import jetbrains.mps.lang.typesystem.runtime.IsApplicableStatus; import jetbrains.mps.typesystem.inference.EquationInfo; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations; import jetbrains.mps.lang.structure.behavior.DataTypeDeclaration__BehaviorDescriptor; import org.jetbrains.mps.openapi.language.SAbstractConcept; import jetbrains.mps.smodel.builder.SNodeBuilder; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import org.jetbrains.mps.openapi.language.SContainmentLink; import org.jetbrains.mps.openapi.language.SReferenceLink; import org.jetbrains.mps.openapi.language.SConcept; public class typeof_PropertySerializeExpression_InferenceRule extends AbstractInferenceRule_Runtime implements InferenceRule_Runtime { public typeof_PropertySerializeExpression_InferenceRule() { } public void applyRule(final SNode expr, final TypeCheckingContext typeCheckingContext, IsApplicableStatus status) { { SNode _nodeToCheck_1029348928467 = expr; EquationInfo _info_12389875345 = new EquationInfo(_nodeToCheck_1029348928467, null, "r:00000000-0000-4000-0000-011c895902fe(jetbrains.mps.lang.smodel.typesystem)", "8564914671171126329", 0, null); typeCheckingContext.createEquation((SNode) typeCheckingContext.typeOf(_nodeToCheck_1029348928467, "r:00000000-0000-4000-0000-011c895902fe(jetbrains.mps.lang.smodel.typesystem)", "8564914671171123455", true), (SNode) _quotation_createNode_uthnwl_a1a0c0a0b(), _info_12389875345); } { SNode _nodeToCheck_1029348928467 = SLinkOperations.getTarget(expr, LINKS.parameter$fgG9); EquationInfo _info_12389875345 = new EquationInfo(_nodeToCheck_1029348928467, null, "r:00000000-0000-4000-0000-011c895902fe(jetbrains.mps.lang.smodel.typesystem)", "8564914671171128412", 0, null); typeCheckingContext.createLessThanInequality((SNode) typeCheckingContext.typeOf(_nodeToCheck_1029348928467, "r:00000000-0000-4000-0000-011c895902fe(jetbrains.mps.lang.smodel.typesystem)", "8564914671171129072", true), (SNode) DataTypeDeclaration__BehaviorDescriptor.toBaseLanguageType_idhEwI9ym.invoke(SLinkOperations.getTarget(expr, LINKS.datatype$ayF6)), false, true, _info_12389875345); } } public SAbstractConcept getApplicableConcept() { return CONCEPTS.PropertySerializeExpression$ga; } public IsApplicableStatus isApplicableAndPattern(SNode argument) { return new IsApplicableStatus(argument.getConcept().isSubConceptOf(getApplicableConcept()), null); } public boolean overrides() { return false; } private static SNode _quotation_createNode_uthnwl_a1a0c0a0b() { SNode quotedNode_1 = null; SNodeBuilder nb = new SNodeBuilder(null, null).init(MetaAdapterFactory.getConcept(MetaAdapterFactory.getLanguage(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, "jetbrains.mps.baseLanguage"), 0x11d47da71ecL, "StringType")); quotedNode_1 = nb.getResult(); return quotedNode_1; } private static final class LINKS { /*package*/ static final SContainmentLink parameter$fgG9 = MetaAdapterFactory.getContainmentLink(0x7866978ea0f04cc7L, 0x81bc4d213d9375e1L, 0x76dcb083baaeddeaL, 0x76dcb083baafacd9L, "parameter"); /*package*/ static final SReferenceLink datatype$ayF6 = MetaAdapterFactory.getReferenceLink(0x7866978ea0f04cc7L, 0x81bc4d213d9375e1L, 0x76dcb083baaeddeaL, 0x7a70efbb64c05757L, "datatype"); } private static final class CONCEPTS { /*package*/ static final SConcept PropertySerializeExpression$ga = MetaAdapterFactory.getConcept(0x7866978ea0f04cc7L, 0x81bc4d213d9375e1L, 0x76dcb083baaeddeaL, "jetbrains.mps.lang.smodel.structure.PropertySerializeExpression"); } }
65.983333
395
0.824198
3845c6d12079bf3eb68b81208671c61b25949423
457
package exercicio02; public class Calculos { private Operacoes O; public void setO(Operacoes o) { O = o; } public double calculos(double x, double y){ return O.calc(x,y); } //1. fazer o functional interface //2. ter como atributo o parametro a referencia para a functional interface (linha 3) //3. fazer o set (opcional) //4. fazer um metodo para chamar a operacao contida na referencia para a func interface //5. definir o lambda }
19.041667
88
0.706783
bd64cebabf35767c79964a0969270813dd00f7b3
36,920
/******************************************************************************* * Copyright (c) 1999-2005 The Institute for Genomic Research (TIGR). * Copyright (c) 2005-2008, the Dana-Farber Cancer Institute (DFCI), * J. Craig Venter Institute (JCVI) and the University of Washington. * All rights reserved. *******************************************************************************/ /* * $RCSfile: ExperimentHeader.java,v $ * $Revision: 1.9 $ * $Date: 2006-07-13 16:08:37 $ * $Author: eleanorahowe $ * $State: Exp $ */ package org.tigr.microarray.mev.cluster.gui.impl.nmf; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.util.ArrayList; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.SwingUtilities; import org.tigr.microarray.mev.cluster.gui.Experiment; import org.tigr.microarray.mev.cluster.gui.IData; import org.tigr.microarray.mev.cluster.gui.helpers.IExperimentHeader; /** * This class is used to render header of an experiment. * * @version 1.0 * @author Aleksey D.Rezantsev */ public class NMFExperimentHeader extends JPanel implements IExperimentHeader { /** * */ private static final long serialVersionUID = 1L; private static final int RECT_HEIGHT = 15; private static final int COLOR_BAR_HEIGHT = 15; private Experiment experiment; private IData data; private int[] samplesOrder; private int[][] clusters; private ArrayList<Color> storedGeneColors; private ArrayList<Color> storedSampleColors = new ArrayList<Color>(); private ArrayList<Color> savedSampleColorOrder = new ArrayList<Color>(); private int compactedColorBarHeight = 0; private int clusterIndex; private int elementWidth; private boolean isAntiAliasing = true; private boolean isCompact = false; public boolean isShowRects = true; private boolean enableMoveable = true; private float maxValue = 3f; private float minValue = -3f; private float midValue = 0.0f; private Insets insets = new Insets(0, 10, 0, 0); private BufferedImage negColorImage; private BufferedImage posColorImage; private int activeCluster = 0; private int maxSampleLabelLength = 0; private static int[] ColorOverlaps = new int[1000000]; private boolean mouseOnMap=false; private int mouseRow = 0; private int mouseColumn = 0; private int clickedRow = 0; private int clickedColumn = 0; public boolean clickedCell = false; private boolean isDrag = false; private boolean headerDrag = false; private boolean isSampleDrag = false; private boolean isShift = false; private boolean isShiftMove = false; private int sampleDragColumn = 0; private int headerDragRow = 0; private int dragColumn = 0; private int dragRow = 0; private int startColumn = 0; private int startShift = 0; private int endShift = 0; private int startRow = 0; private int labelLength = 0; private int startShiftMove = 0; private int endShiftMove = 0; private int headerWidth = 0; public boolean clusterViewerClicked = false; public int clusterViewerClickedColumn = 0; public void setExperiment(Experiment e) { this.experiment = e; } private boolean useDoubleGradient = true; private boolean genes; public void setIData(IData d) {this.data = d;} /** * Construct an <code>ExperimentHeader</code> with specified experiment. */ public NMFExperimentHeader(Experiment experiment, int [][] clusters) { this(experiment, clusters, null); } /** * Construct an <code>ExperimentHeader</code> with specified experiment * and samples order. */ public NMFExperimentHeader(Experiment experiment, int [][] clusters, int[] samplesOrder) { this.experiment = experiment; this.clusters = clusters; this.setSamplesOrder(samplesOrder == null ? createSamplesOrder(experiment) : samplesOrder); setBackground(Color.white); Listener listener = new Listener(); addMouseListener(listener); addMouseMotionListener(listener); } public NMFExperimentHeader(Experiment experiment, int [][] clusters, int[] samplesOrder, ArrayList<Color> storedGeneColors, boolean genes) { this.genes = genes; this.experiment = experiment; this.clusters = clusters; this.storedGeneColors = storedGeneColors; this.setSamplesOrder(samplesOrder == null ? createSamplesOrder(experiment) : samplesOrder); setBackground(Color.white); Listener listener = new Listener(); addMouseListener(listener); addMouseMotionListener(listener); } public Insets getInsets(){return insets;} public Experiment getExperiment() { return experiment; } public int[][] getClusters() { return clusters; } /** * Returns a component to be inserted into scroll pane view port. */ public JComponent getContentComponent() { return this; } private static int[] createSamplesOrder(Experiment experiment) { int[] order = new int[experiment.getNumberOfSamples()]; for (int i=0; i<order.length; i++) { order[i] = i; } return order; } public int[] getSamplesOrder(){return samplesOrder;} public BufferedImage getPosColorImage(){return posColorImage;} public BufferedImage getNegColorImage(){return negColorImage;} /** * Sets data. */ public void setData(IData data) { this.data = data; } public IData getData(){return data;} /** * Sets max and min experiment values. */ public void setValues(float minValue, float midValue, float maxValue) { this.maxValue = maxValue; this.minValue = minValue; this.midValue = midValue; } /** * Sets max and min experiment values. */ public void setValues(float minValue, float maxValue) { this.maxValue = maxValue; this.minValue = minValue; } /** * Sets values when a cluster is being dragged in the experiment viewer * @param setting * @param dragColumn * @param dragRow */ public void setDrag(boolean setting, int dragColumn, int dragRow){ this.isDrag=setting; this.dragColumn = dragColumn; this.dragRow = dragRow; } /** * Sets whether the color-coded clustering display is compact */ public void setCompactClusters(boolean value){ if (value==isCompact) return; //savedGeneColorOrder is for keeping the same cluster color order when clusters are "un-compacted" if (value){ savedSampleColorOrder.clear(); for (int i=0; i<storedSampleColors.size(); i++){ savedSampleColorOrder.add((Color)storedSampleColors.get(i)); } storedSampleColors.clear(); }else{ storedSampleColors.clear(); clearColorOverlaps(); for (int i=0; i<savedSampleColorOrder.size(); i++){ storedSampleColors.add((Color)savedSampleColorOrder.get(i)); } } this.isCompact = value; } /** * clears the arraylist containing cluster color location info */ public void clearStoredSampleColors(){ storedSampleColors.clear(); } /** * clears the array that holds the compacted location of each colorbar */ private void clearColorOverlaps(){ for (int i=0; i<ColorOverlaps.length; i++){ ColorOverlaps[i] = i; } } /** * Sets positive and negative images */ public void setNegAndPosColorImages(BufferedImage neg, BufferedImage pos){ this.negColorImage = neg; this.posColorImage = pos; } /** * Sets stored Color Array List */ public void setStoredColors(ArrayList<Color> storedColors){ storedGeneColors = storedColors; } public void setClusters(int[][] mat){ clusters = new int[mat.length][mat[0].length]; for (int i=0; i<mat.length; i++){ for (int j=0; j<mat[i].length; j++){ this.clusters[i][j]=mat[i][j]; } } this.repaint(); this.updateUI(); } /** * Sets flag to use a double gradient */ public void setUseDoubleGradient(boolean useDouble) { this.useDoubleGradient = useDouble; } /** * Sets anti-aliasing property. */ public void setAntiAliasing(boolean isAntiAliasing) { this.isAntiAliasing = isAntiAliasing; } /** * Sets the left margin for the header */ public void setLeftInset(int leftMargin){ insets.left = leftMargin; } /** * Sets current cluster index */ public void setClusterIndex(int index){ clusterIndex = index; } /** * Gets current cluster */ private int [] getCluster(){ return clusters[clusterIndex]; } /** * Returns height of color bar for experiments */ private int getColorBarHeight(){ if (genes) return 0; for( int sample = 0; sample < getSamplesOrder().length ; sample++){ if(data.getExperimentColor(experiment.getSampleIndex(this.getSamplesOrder()[sample])) != null) return COLOR_BAR_HEIGHT; } return 0; } /** * Sets an element width. */ private void setElementWidth(int width) { this.elementWidth = width; if (width > 12) { width = 12; } setFont(new Font("monospaced", Font.PLAIN, width)); } /** * draws rectangle around specified sample cluster colors * @param column * @param color * @param cluster refers to whether the rectangle surrounds the cluster display */ public void drawClusterHeaderRectsAt(int column, Color color, boolean cluster){ Graphics2D g = (Graphics2D)getGraphics(); if (g == null) { return; } int side = 0; int inset = 0; if (cluster) inset = 4; g.setColor(color); if (column > (experiment.getNumberOfSamples() -1)) side = 10; if (column > (experiment.getNumberOfSamples() -1)&&isCompact) return; if (!isCompact) g.drawRect(column*elementWidth + insets.left + inset, getSize().height - (COLOR_BAR_HEIGHT*(storedSampleColors.size()) + maxSampleLabelLength + 7) , (elementWidth), (COLOR_BAR_HEIGHT)*storedSampleColors.size()+maxSampleLabelLength+4 + side); if (isCompact) g.drawRect(column*elementWidth + insets.left + inset, getSize().height - (COLOR_BAR_HEIGHT*(compactedColorBarHeight) + maxSampleLabelLength + 7), (elementWidth-1), (COLOR_BAR_HEIGHT)*compactedColorBarHeight+maxSampleLabelLength+4 + side); } /** * DS re-write */ public void updateSizes(int useless, int setElementWidth) { if(data == null) return; setElementWidth(setElementWidth); Graphics2D g = (Graphics2D)getGraphics(); if (g == null) { return; } if (isAntiAliasing) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_OFF); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } FontMetrics hfm = g.getFontMetrics(); int maxHeight = 0; String name; int contentWidth=0; final int size = this.experiment.getNumberOfSamples(); for (int feature = 0; feature < size; feature++) { if (genes) name = data.getGeneName(experiment.getSampleIndex(feature)); else name = data.getSampleName(experiment.getSampleIndex(feature)); maxHeight = Math.max(maxHeight, hfm.stringWidth(name)); } contentWidth = (experiment.getNumberOfSamples()+storedGeneColors.size())*elementWidth + insets.left + 4; maxSampleLabelLength = maxHeight; maxHeight += RECT_HEIGHT + hfm.getHeight() + 10; if (!genes){ if (!isCompact){ maxHeight += (getColorBarHeight()*storedSampleColors.size()); String sampleLabel; labelLength=0; for (int feature = 0; feature < storedSampleColors.size(); feature++) { sampleLabel = data.getClusterLabel(feature, false); if (sampleLabel != null) labelLength = Math.max(labelLength, hfm.stringWidth(sampleLabel)); } contentWidth = contentWidth + labelLength+10; if (labelLength<60) contentWidth = contentWidth + 70; } else { int maxSpacesOver=-1; for (int i=0; i<storedSampleColors.size(); i++){ if ((ColorOverlaps[i])>maxSpacesOver) maxSpacesOver=ColorOverlaps[i]; } maxHeight += getColorBarHeight()*(maxSpacesOver+1); compactedColorBarHeight= maxSpacesOver+1; } } setSize(this.headerWidth, maxHeight); setPreferredSize(new Dimension(this.headerWidth, maxHeight)); drawHeader(g); } public void setHeaderWidth(int hw){ this.headerWidth = hw; } /** * Paints the header into specified graphics. */ public void paint(Graphics g1D) { super.paint(g1D); if (data == null || (this.getCluster().length < 1)) { return; } Graphics2D g = (Graphics2D)g1D; if (isAntiAliasing) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_OFF); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } drawHeader(g); } /** * Draws the header into specified graphics. */ private void drawHeader(Graphics2D g) { final int samples = this.experiment.getNumberOfSamples(); if (samples == 0) { return; } int width = samples*elementWidth; if(useDoubleGradient) { g.drawImage(this.negColorImage, insets.left, 0, (int)(width/2f), RECT_HEIGHT, null); g.drawImage(this.posColorImage, (int)((width)/2f + insets.left), 0, (int)(width/2.0), RECT_HEIGHT, null); } else { g.drawImage(this.posColorImage, insets.left, 0, width, RECT_HEIGHT, null); } FontMetrics hfm = g.getFontMetrics(); int descent = hfm.getDescent(); int fHeight = hfm.getHeight(); g.setColor(Color.black); int textWidth; g.drawString(String.valueOf(this.minValue), insets.left, RECT_HEIGHT+fHeight); textWidth = hfm.stringWidth(String.valueOf(midValue)); if(useDoubleGradient) g.drawString(String.valueOf(midValue), (int)(width/2f)-textWidth/2 + insets.left, RECT_HEIGHT+fHeight); textWidth = hfm.stringWidth(String.valueOf(this.maxValue)); g.drawString(String.valueOf(this.maxValue), width-textWidth + insets.left, RECT_HEIGHT+fHeight); //draw possible clusters int h = -getSize().height + 5; boolean hasColorBar = false; if(this.getColorBarHeight() > 0){ if (isCompact) h += COLOR_BAR_HEIGHT*compactedColorBarHeight; if (!isCompact) h += COLOR_BAR_HEIGHT*storedSampleColors.size(); hasColorBar = true; } // draw feature names String name; g.rotate(-Math.PI/2); for (int sample = 0; sample < samples; sample++) { if (genes) name = data.getGeneName(experiment.getSampleIndex(this.getSamplesOrder()[sample])); else name = data.getSampleName(experiment.getSampleIndex(this.getSamplesOrder()[sample])); g.drawString(name, h, descent + elementWidth*sample + elementWidth/2 + insets.left); } //write the gene cluster names sideways g.rotate(Math.PI/2); int visibleClusters = 0; if (!genes){ if (storedGeneColors!=null&&!isCompact){ String clusterName; g.rotate(-Math.PI/2); int numberOfClusters = storedGeneColors.size(); for (int cluster = 0; cluster < numberOfClusters; cluster++) { int index = data.getVisibleCluster((Color)storedGeneColors.get(cluster), true); if (index==0) break; clusterName = data.getClusterLabel(index, true); g.drawString(clusterName, h, descent + elementWidth*(samples+cluster) + elementWidth/2 + insets.left+5); visibleClusters++; } g.rotate(Math.PI/2); } //write the sample cluster names if (storedSampleColors!=null&&!isCompact){ String clusterName; int numberOfClusters = storedSampleColors.size(); for (int cluster = 0; cluster < numberOfClusters; cluster++) { //if (data.getClusterLabel(cluster, false)==null) break; int index = data.getVisibleCluster((Color)storedSampleColors.get(cluster), false); if (index==-1) continue; clusterName = data.getClusterLabel(index, false); if (clusterName!=null) g.drawString(clusterName, elementWidth*(samples+visibleClusters) + insets.left+10, -h + COLOR_BAR_HEIGHT*(numberOfClusters-(cluster))); } } int spacesOver=0; if(hasColorBar){ int sscLength= storedSampleColors.size(); for(int sample = 0; sample < samples; sample++){ Color[] colors = data.getSampleColorArray(experiment.getSampleIndex(this.getSamplesOrder()[sample])); if (colors==null) { continue;} for (int clusters=0; clusters<colors.length; clusters++){ if (colors[clusters]==null) {continue;} if(storedSampleColors.contains(colors[clusters])) { activeCluster=storedSampleColors.indexOf(colors[clusters]); }else{ storedSampleColors.add(colors[clusters]); activeCluster=(storedSampleColors.size()-1); ColorOverlaps[activeCluster]= activeCluster; //compacts the cluster color display boolean compact= false; if (isCompact)compact=true; while (compact){ for (int i=0; i<storedSampleColors.size(); i++){ boolean allClear = true; for (int j=0; j<storedSampleColors.size(); j++){ if (ColorOverlaps[j]==i){ if (data.isColorOverlap(experiment.getSampleIndex(this.getSamplesOrder()[sample]), colors[clusters], (Color)storedSampleColors.get(j), false)){ allClear=false; break; } allClear=true; } } if (allClear){ ColorOverlaps[activeCluster]= i; compact=true; break; } } if (compact) break; } } spacesOver=ColorOverlaps[activeCluster]; g.setColor(colors[clusters]); if (sscLength!= storedSampleColors.size()){ g.setColor(Color.white); } g.fillRect(sample*elementWidth + insets.left, getSize().height - (COLOR_BAR_HEIGHT*(1+spacesOver)) - 2, elementWidth, COLOR_BAR_HEIGHT); } } int sizeTest = getSize().width; if (sscLength!= storedSampleColors.size()){ updateSizes(getSize().width, elementWidth); } if (sizeTest != getSize().width) repaint(); } } if (mouseOnMap&&isShowRects){ if (mouseColumn != clickedColumn) drawClusterHeaderRectsAt(mouseColumn, Color.gray, false); if (mouseRow != clickedRow) drawHorizontalRect(mouseRow, Color.gray); } mouseOnMap = false; if (clickedCell){ g.setColor(Color.red); if (!isCompact){ g.drawRect(insets.left, this.getHeight()-COLOR_BAR_HEIGHT*(storedSampleColors.size() - clickedRow)-3, elementWidth*experiment.getNumberOfSamples() + 5 + elementWidth*storedGeneColors.size() + 5 + labelLength + 2, COLOR_BAR_HEIGHT); g.drawRect(clickedColumn*elementWidth + insets.left, getSize().height - (COLOR_BAR_HEIGHT*(storedSampleColors.size()) + maxSampleLabelLength + 7) , (elementWidth), (COLOR_BAR_HEIGHT)*storedSampleColors.size()+maxSampleLabelLength+4); } } if (clusterViewerClicked&&!isCompact){ g.setColor(Color.red); g.drawRect(clusterViewerClickedColumn*elementWidth + insets.left + 4, getSize().height - (COLOR_BAR_HEIGHT*(storedSampleColors.size()) + maxSampleLabelLength + 7) , (elementWidth), (COLOR_BAR_HEIGHT)*storedSampleColors.size()+maxSampleLabelLength+4 + 10); } if (isDrag){ g.setColor(Color.blue); if (!isCompact) g.drawRect(dragColumn*elementWidth + insets.left + 4, getSize().height - (COLOR_BAR_HEIGHT*(storedSampleColors.size()) + maxSampleLabelLength + 7) , (elementWidth), (COLOR_BAR_HEIGHT)*storedSampleColors.size()+maxSampleLabelLength+4 + 10); if (isCompact) g.drawRect(dragColumn*elementWidth + insets.left + 4, getSize().height - (COLOR_BAR_HEIGHT*(compactedColorBarHeight) + maxSampleLabelLength + 7), (elementWidth), (COLOR_BAR_HEIGHT)*compactedColorBarHeight+maxSampleLabelLength+4 + 10); } if (headerDrag){ g.setColor(Color.blue); if (!isCompact) g.drawRect(insets.left, this.getHeight()-COLOR_BAR_HEIGHT*(storedSampleColors.size() - headerDragRow)-3, elementWidth*experiment.getNumberOfSamples() + 5 + elementWidth*storedGeneColors.size() + 5 + labelLength + 2, COLOR_BAR_HEIGHT); if (isCompact) g.drawRect(insets.left, this.getHeight()-COLOR_BAR_HEIGHT*(this.compactedColorBarHeight - headerDragRow)-3, elementWidth*experiment.getNumberOfSamples(), COLOR_BAR_HEIGHT); } if (isSampleDrag){ g.setColor(Color.blue); g.drawRect(this.sampleDragColumn*elementWidth + insets.left, getSize().height - (COLOR_BAR_HEIGHT*(storedSampleColors.size()) + maxSampleLabelLength + 7) , (elementWidth), (COLOR_BAR_HEIGHT)*storedSampleColors.size()+maxSampleLabelLength+4 + 10); } if (isShift){ g.setColor(new Color(175,175,175,100)); if (startShift<endShift) g.fillRect(startShift*elementWidth + insets.left, getSize().height - (COLOR_BAR_HEIGHT*(storedSampleColors.size()) + maxSampleLabelLength + 7) , (elementWidth*(endShift-startShift+1)), (COLOR_BAR_HEIGHT)*storedSampleColors.size()+maxSampleLabelLength+4 + 10); if (startShift>endShift) g.fillRect(endShift*elementWidth + insets.left, getSize().height - (COLOR_BAR_HEIGHT*(storedSampleColors.size()) + maxSampleLabelLength + 7) , (elementWidth*(startShift-endShift+1)), (COLOR_BAR_HEIGHT)*storedSampleColors.size()+maxSampleLabelLength+4 + 10); if (startShift==endShift) g.fillRect(startShift*elementWidth + insets.left, getSize().height - (COLOR_BAR_HEIGHT*(storedSampleColors.size()) + maxSampleLabelLength + 7) , (elementWidth), (COLOR_BAR_HEIGHT)*storedSampleColors.size()+maxSampleLabelLength+4 + 10); } if (isShiftMove){ g.setColor(Color.blue); int move = startShiftMove-endShiftMove; g.drawRect((Math.min(startShift, endShift)-move)*elementWidth + insets.left, getSize().height - (COLOR_BAR_HEIGHT*(storedSampleColors.size()) + maxSampleLabelLength + 7) , (elementWidth*(Math.abs(endShift-startShift)+1)), (COLOR_BAR_HEIGHT)*storedSampleColors.size()+maxSampleLabelLength+4 + 10); } } private void drawHorizontalRect(int row, Color color){ Graphics2D g = (Graphics2D)getGraphics(); if (g == null) { return; } g.setColor(color); if (!isCompact){ g.drawRect(insets.left, this.getHeight()-COLOR_BAR_HEIGHT*(storedSampleColors.size() - row)-3, elementWidth*experiment.getNumberOfSamples() + 5 + elementWidth*storedGeneColors.size() + 5 + labelLength + 2, COLOR_BAR_HEIGHT); } } private class Listener extends MouseAdapter implements MouseMotionListener { private int oldRow = -1; private int oldColumn = -1; public void mouseClicked(MouseEvent event) { int column = findColumn(event.getX()); if (SwingUtilities.isRightMouseButton(event)||column==-1) { isShiftMove=false; isSampleDrag = false; return; } int row = findRow(event.getY()); if (!isLegalPosition(row, column)) { return; } if (row==clickedRow&&column==clickedColumn){ clickedCell = false; return; } clickedRow = row; clickedColumn = column; clickedCell = true; drawClusterHeaderRectsAt(clickedColumn, Color.red, false); drawHorizontalRect(clickedRow, Color.red); } public void mouseExited(MouseEvent event){ mouseOnMap = false; repaint(); if (clickedCell&&!isCompact){ drawClusterHeaderRectsAt(clickedColumn, Color.red, false); drawHorizontalRect(clickedRow, Color.red); } } public void mouseMoved(MouseEvent event) { if (!isShowRects) return; if (experiment.getNumberOfSamples() == 0 || event.isShiftDown()) return; int column = findColumn(event.getX()); int row = findRow(event.getY()); Graphics g = null; g = getGraphics(); if (!isLegalPosition(row, column)){ repaint(); if (clickedCell&&!isCompact){ drawClusterHeaderRectsAt(clickedColumn, Color.red, false); drawHorizontalRect(clickedRow, Color.red); } return; } if (isCurrentPosition(row, column)) { if (isLegalPosition(row, column)){ drawClusterHeaderRectsAt(oldColumn, Color.gray, false); drawHorizontalRect(row, Color.gray); } if (clickedCell&&!isCompact){ drawClusterHeaderRectsAt(clickedColumn, Color.red, false); drawHorizontalRect(clickedRow, Color.red); } return; } if (!isCurrentPosition(row, column)&&isLegalPosition(row, column)){ mouseOnMap = true; mouseRow = row; mouseColumn = column; repaint(); drawClusterHeaderRectsAt(oldColumn, Color.gray, false); if (clickedCell&&!isCompact){ drawClusterHeaderRectsAt(clickedColumn, Color.red, false); drawHorizontalRect(clickedRow, Color.red); } } setOldPosition(row, column); if (g != null) { g.dispose(); } } public void mouseDragged(MouseEvent event) { repaint(); if (SwingUtilities.isRightMouseButton(event)) { isShiftMove=false; isSampleDrag = false; return; } if(event.isShiftDown()){ isSampleDrag = false; return; } int column = findColumn(event.getX()); int row = findRow(event.getY()); if (column==-1){ isShiftMove=false; isSampleDrag = false; return; } if (isShift&&enableMoveable){ isShiftMove=true; endShiftMove = column; if (startShiftMove-endShiftMove>Math.min(startShift, endShift)) endShiftMove = startShiftMove-Math.min(startShift, endShift); if (endShiftMove-startShiftMove>experiment.getNumberOfSamples()-Math.max(startShift, endShift)-1) endShiftMove = startShiftMove+experiment.getNumberOfSamples()-Math.max(startShift, endShift)-1; return; } sampleDragColumn = column; isSampleDrag = true; if (!enableMoveable){ isShiftMove=false; isSampleDrag = false; } if (!isLegalPosition(row, column)) { headerDrag = false; return; } if (!headerDrag) return; headerDragRow = row; if (column<experiment.getNumberOfSamples()){ } else{ headerDrag = false; isSampleDrag = false; } } /** Called when the mouse has been pressed. */ public void mousePressed(MouseEvent event) { startColumn = findColumn(event.getX()); if (SwingUtilities.isRightMouseButton(event)||startColumn==-1) { isShiftMove=false; isSampleDrag = false; return; } sampleDragColumn = startColumn; startRow = findRow(event.getY()); if(event.isShiftDown()){ if (!isShift) startShift = startColumn; endShift = startColumn; isShift=true; }else{ if (isShift&&(startColumn>=Math.min(startShift,endShift)&&startColumn<=Math.max(startShift,endShift))){ startShiftMove = startColumn; }else{ isShift = false; isShiftMove = false; } } if (!isLegalPosition(startRow, startColumn)) { return; } headerDrag = true; headerDragRow = startRow; } /** Called when the mouse has been released. */ public void mouseReleased(MouseEvent event) { int endColumn = findColumn(event.getX()); if (SwingUtilities.isRightMouseButton(event)||endColumn==-1) { isShiftMove=false; isSampleDrag = false; return; } if (isShiftMove){ int lowerShift=Math.min(endShift,startShift); int upperShift=Math.max(endShift,startShift);; int numMovedSamples=upperShift-lowerShift+1; int numSpacesMoved=endShiftMove-startShiftMove; int[] samplesMoved = new int[numMovedSamples]; for (int i=0; i<samplesMoved.length; i++){ samplesMoved[i]=getSamplesOrder()[lowerShift+i]; } ArrayList<Integer> tempSamplesOrder = new ArrayList<Integer>(); for (int i=0; i<getSamplesOrder().length; i++){ tempSamplesOrder.add(getSamplesOrder()[i]); } for (int i=0; i<numMovedSamples; i++){ tempSamplesOrder.remove(lowerShift); } for (int i=0; i<numMovedSamples; i++){ tempSamplesOrder.add(lowerShift+numSpacesMoved+i, samplesMoved[i]); } for (int i=0; i<getSamplesOrder().length; i++){ getSamplesOrder()[i]=tempSamplesOrder.get(i); } isShiftMove = false; isShift = false; return; } if (isSampleDrag){ if (endColumn>startColumn){ int startSample = getSamplesOrder()[startColumn]; for (int i=0; i<endColumn-startColumn; i++){ getSamplesOrder()[startColumn+i]=getSamplesOrder()[startColumn+i+1]; } getSamplesOrder()[endColumn]=startSample; repaint(); } if (endColumn<startColumn){ int startSample = getSamplesOrder()[startColumn]; for (int i=0; i<startColumn-endColumn; i++){ getSamplesOrder()[startColumn-i]=getSamplesOrder()[startColumn-(i+1)]; } getSamplesOrder()[endColumn]=startSample; repaint(); } } isSampleDrag = false; if (!headerDrag) return; headerDrag = false; int endRow = findRow(event.getY()); if (!isLegalPosition(startRow, startColumn)) { return; } if (!isCompact){ Color inter = (Color)storedSampleColors.get(storedSampleColors.size()-1-startRow); storedSampleColors.remove(storedSampleColors.size()-1-startRow); storedSampleColors.add(storedSampleColors.size()-endRow, inter); repaint(); } else{ for (int j=0; j<storedSampleColors.size(); j++){ if (ColorOverlaps[j]==compactedColorBarHeight-1-startRow) ColorOverlaps[j]=-1; if (ColorOverlaps[j]==compactedColorBarHeight-1-endRow) ColorOverlaps[j]=compactedColorBarHeight-1-startRow; if (ColorOverlaps[j]== -1) ColorOverlaps[j]=compactedColorBarHeight-1-endRow; } repaint(); } } private void setOldPosition(int row, int column) { oldColumn = column; oldRow = row; } private boolean isCurrentPosition(int row, int column) { return(row == oldRow && column == oldColumn); } } /** * Finds column for specified x coordinate. * @return -1 if column was not found. */ private int findColumn(int targetx) { int xSize = experiment.getNumberOfSamples()*elementWidth; if (targetx < insets.left) { return -1; } if (targetx > (xSize + insets.left)) return -1; return (targetx - insets.left)/elementWidth; } /** * Finds row for specified y coordinate. * @return -1 if row was not found. */ private int findRow(int targety) { int length = 0; if (!isCompact) length = (this.getSize().height-getColorBarHeight()*storedSampleColors.size()); if (isCompact) length = this.getSize().height -compactedColorBarHeight*getColorBarHeight(); if (targety >= this.getSize().height || targety < (length)) return -1; return (targety - length)/COLOR_BAR_HEIGHT; } private boolean isLegalPosition(int row, int column) { if (isLegalRow(row) && isLegalColumn(column)) return true; return false; } private boolean isLegalColumn(int column) { if (column < 0 || column > (experiment.getNumberOfSamples() -1)) return false; return true; } private boolean isLegalRow(int row) { if (row < 0 || row > storedSampleColors.size()) return false; if (isCompact){ if (row < 0 || row > compactedColorBarHeight) return false; } return true; } public void setSamplesOrder(int[] samplesOrder) { this.samplesOrder = samplesOrder; } public void setEnableMoveable(boolean enableMoveable) { this.enableMoveable = enableMoveable; } }
38.659686
306
0.5776
31346d4383205ecfe4fda33257d2ee7f5cacbaa9
1,349
/*** * Copyright (C) 2019 Verizon. All Rights Reserved Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.onap.so.db.request.data.repository; import org.onap.so.db.request.beans.InstanceNfvoMapping; import org.onap.so.db.request.beans.OperationStatus; import org.onap.so.db.request.beans.OperationStatusId; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(collectionResourceRel = "instanceNfvoMapping", path = "instanceNfvoMapping") public interface InstanceNfvoMappingRepository extends JpaRepository<InstanceNfvoMapping, String> { public InstanceNfvoMapping findOneByInstanceId(String instanceId); public InstanceNfvoMapping findOneByJobId(String jobId); }
44.966667
118
0.804299
c8f5ea9bbea10a33546f387e949c0ef7a0f1d3ed
2,799
package com.dynamsoft.demo.dynamsoftbarcodereaderdemo; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.method.ScrollingMovementMethod; import android.widget.TextView; public class ResultActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setVerticalScrollBarEnabled(true); tv.setText(""); tv.setMovementMethod(new ScrollingMovementMethod()); Intent intent = getIntent(); if (intent != null) { DriverLicense driverLicense = (DriverLicense) intent.getParcelableExtra("DriverLicense"); if (driverLicense != null) { String documentType = driverLicense.documentType; tv.append("Document Type:\n" + documentType + "\n\n"); String firstName = driverLicense.firstName; tv.append("First Name:\n" + firstName + "\n\n"); String middleName = driverLicense.middleName; tv.append("Middle Name:\n" + middleName + "\n\n"); String lastName = driverLicense.lastName; tv.append("Last Name:\n" + lastName + "\n\n"); String gender = driverLicense.gender; tv.append("Gender: \n" + gender + "\n\n"); String addressStreet = driverLicense.addressStreet; tv.append("Street:\n" + addressStreet + "\n\n"); String addressCity = driverLicense.addressCity; tv.append("City:\n" + addressCity + "\n\n"); String addressState = driverLicense.addressState; tv.append("State:\n" + addressState + "\n\n"); String addressZip = driverLicense.addressZip; tv.append("Zip:\n" + addressZip + "\n\n"); String licenseNumber = driverLicense.licenseNumber; tv.append("License Number:\n" + licenseNumber + "\n\n"); String issueDate = driverLicense.issueDate; tv.append("Issue Date:\n" + issueDate + "\n\n"); String expiryDate = driverLicense.expiryDate; tv.append("Expiry Date:\n" + expiryDate + "\n\n"); String birthDate = driverLicense.birthDate; tv.append("Birth Date:\n" + birthDate + "\n\n"); String issuingCountry = driverLicense.issuingCountry; tv.append("Issue Country:\n" + issuingCountry + "\n\n"); } } setContentView(tv); } @Override public void onBackPressed() { super.onBackPressed(); } }
45.145161
101
0.596284
7ef8a28b403ad5d4d721424c89bf89ffe74bd7e8
3,569
package com.floreerin.doit_android_sample_ui; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.Toast; import yuku.ambilwarna.AmbilWarnaDialog; public class ch12_MainActivity extends AppCompatActivity { private long backkeyClickTime = 0; int initialColor = 0; ch12_PaintView PaintView; ImageView set_color; ImageView set_stroke; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ch12_activity_main); PaintView = new ch12_PaintView(this); LinearLayout container = findViewById(R.id.container); Resources res = getResources(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT); container.addView(PaintView, params); set_color = findViewById(R.id.set_rgb); set_stroke = findViewById(R.id.set_stroke); set_color.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ChangeRGB(); // 색을 변경하는 다이얼로그 호출 } }); set_stroke.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ChangeStroke(); // 선의 굵기를 변경하는 다이얼로그 호출 } }); } private void ChangeRGB() { // github의 ambilwarna color picker 외부 라이브러리 사용 AmbilWarnaDialog dialog = new AmbilWarnaDialog(this, initialColor, new AmbilWarnaDialog.OnAmbilWarnaListener() { @Override public void onCancel(AmbilWarnaDialog dialog) { } @Override public void onOk(AmbilWarnaDialog dialog, int color) { PaintView.setColor(color); // 컬러바에서 선택 후 선의 색을 설정. } }); dialog.show(); } private void ChangeStroke() { // 굵기 설정을 하는 다이얼로그 표시 final EditText input = new EditText(this); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("원하는 굵기를 입력하세요"); builder.setView(input); builder.setPositiveButton("설정", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { PaintView.setStrokeWidth(Float.parseFloat(input.getText().toString())); // float 형 변환으로 굵기를 설정 } }); builder.setNegativeButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.show(); } @Override public void onBackPressed() { if (System.currentTimeMillis() > backkeyClickTime + 2000) { backkeyClickTime = System.currentTimeMillis(); Toast.makeText(getApplicationContext(), "뒤로 가기 버튼을 누르면 메인화면으로 이동합니다.", Toast.LENGTH_LONG).show(); } else if (System.currentTimeMillis() <= backkeyClickTime + 2000) { finish(); } } }
33.669811
152
0.660409
eb55c471fadb6a5334b0f25ec6e7a36d93bfe5c1
4,937
/* * Copyright (c) Fundacion Jala. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ package org.fundacionjala.sevenwonders.core; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Vania Catorceno */ public class CityTest { private List<Requirement> requirements; private List<Requirement> requirement; private List<Building> buildingRequirementList; private Map<ResourceType, Integer> resourcesRequirements; private Map<ResourceType, Integer> resourcesRequirementsOther; private Stage stage; private City city; private Storage storage; Building templeBuilding; Building gatesBuilding; @Before public void setUp() { requirements = new ArrayList<>(); requirement = new ArrayList<>(); templeBuilding = new Building(new ArrayList<>(), new ArrayList<>(), 4, 1, "Temple", BuildingType.CIVIC); gatesBuilding = new Building(new ArrayList<>(), new ArrayList<>(), 4, 1, "Gates of the city", BuildingType.CIVIC); buildingRequirementList = new ArrayList<>(); buildingRequirementList.add(templeBuilding); buildingRequirementList.add(gatesBuilding); resourcesRequirements = new EnumMap<>(ResourceType.class); resourcesRequirements.put(ResourceType.BRICK, 2); resourcesRequirements.put(ResourceType.GLASS, 1); resourcesRequirementsOther = new EnumMap<>(ResourceType.class); resourcesRequirementsOther.put(ResourceType.STONE, 2); resourcesRequirementsOther.put(ResourceType.WOOD, 1); requirements.add(new ResourceRequirement(resourcesRequirements)); requirements.add(new ResourceRequirement(resourcesRequirementsOther)); requirement.add(new ResourceRequirement(resourcesRequirements)); requirement.add(new BuildingRequirement(buildingRequirementList)); stage = new Stage(requirements, mock(List.class)); storage = mock(Storage.class); city = new City(mock(Wonder.class), mock(StoragePoint.class), storage); } @Test public void testCreateCity() { Wonder wonder = mock(Wonder.class); StoragePoint storagePoint = mock(StoragePoint.class); Storage storage = mock(Storage.class); City city = new City(wonder, storagePoint, storage); assertEquals(wonder, city.getWonder()); assertEquals(storagePoint, city.getStoragePoint()); assertEquals(storage, city.getStorage()); } @Test public void testBuildStageReturnTrueIfStateChangeToTrue() { when(storage.getResourceQuantity(anyObject())).thenReturn(2); assertTrue(city.buildStage(stage)); } @Test public void testBuildStageWhenTheTwoRequirementsHisValidateIsTrue() { when(storage.getResourceQuantity(anyObject())).thenReturn(2); assertTrue(city.buildStage(stage)); } @Test public void testBuildStageButNotCompliesRequirements() { when(storage.getResourceQuantity(anyObject())).thenReturn(1); assertFalse(city.buildStage(stage)); } @Test public void testBuildStageButOneRequirementHisValidateIFalseThenReturnFalse() { when(storage.getResourceQuantity(anyObject())).thenReturn(1); assertFalse(city.buildStage(stage)); } @Test(expected = NullPointerException.class) public void testBuildStageButTheListRequirementsIsNull() { List<Requirement> requirementsNull = null; stage = new Stage(requirementsNull, mock(List.class)); when(storage.getResourceQuantity(anyObject())).thenReturn(2); assertFalse(city.buildStage(stage)); } @Test(expected = NullPointerException.class) public void testBuildStageButTheStageIsNull() { stage = null; when(storage.getResourceQuantity(anyObject())).thenReturn(2); assertNull(stage); assertFalse(city.buildStage(stage)); } @Test public void testPlayCardReturnTrueIfThereAreResourcesAndRequierements() { List<Requirement> requirements = new ArrayList<>(); requirements.add(new ResourceRequirement(resourcesRequirements)); requirements.add(new BuildingRequirement(buildingRequirementList)); when(storage.getResourceQuantity(anyObject())).thenReturn(2); city.addBuilding(gatesBuilding); city.addBuilding(templeBuilding); Card card = new Card(requirements, new ArrayList<>()); assertTrue(city.playCard(card)); } }
34.524476
122
0.713591
d4766ff98b48ee2cab4f7307afd62403fc626a07
3,561
// ======================================================================== // Copyright 2010 NEXCOM Systems // ------------------------------------------------------------------------ // 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.cipango.server.ar; import static junit.framework.Assert.assertNull; import java.io.Serializable; import javax.servlet.sip.SipURI; import javax.servlet.sip.ar.SipApplicationRouterInfo; import javax.servlet.sip.ar.SipApplicationRoutingRegion; import javax.servlet.sip.ar.SipApplicationRoutingRegionType; import javax.servlet.sip.ar.SipRouteModifier; import junit.framework.Assert; import org.cipango.sip.SipURIImpl; import org.junit.Test; public class RouterInfoUtilTest { @Test public void testDecode() throws Exception { testRouterInfo(new SipApplicationRouterInfo("kaleo", SipApplicationRoutingRegion.NEUTRAL_REGION, "sip:[email protected]", new String[] { "sip:as1.cipango.voip", "sip:as2.cipango.voip" }, SipRouteModifier.ROUTE, "1")); } protected void testRouterInfo(SipApplicationRouterInfo routerInfo) throws Exception { SipURI uri = new SipURIImpl(null, "localhost", 5060); RouterInfoUtil.encode(uri, routerInfo); //System.out.println(uri); assertEquals(routerInfo, RouterInfoUtil.decode(new SipURIImpl(uri.toString()))); } public void assertEquals(SipApplicationRouterInfo orig, SipApplicationRouterInfo actual) { Assert.assertEquals(orig.getNextApplicationName(), actual.getNextApplicationName()); if (orig.getRoutingRegion() != null) { Assert.assertEquals(orig.getRoutingRegion().getType(), actual.getRoutingRegion().getType()); Assert.assertEquals(orig.getRoutingRegion().getLabel(), actual.getRoutingRegion().getLabel()); } else assertNull(actual.getRoutingRegion()); Assert.assertEquals(orig.getSubscriberURI(), actual.getSubscriberURI()); Assert.assertEquals(orig.getStateInfo(), actual.getStateInfo()); } @Test public void testDecodeNull() throws Exception { testRouterInfo(new SipApplicationRouterInfo("kaleo", null, null, null, null, null)); } @Test public void testStrangeAppName() throws Exception { testRouterInfo(new SipApplicationRouterInfo(":@1=>!;", null, null, null, null, null)); } @Test public void testCustomRegion() throws Exception { testRouterInfo(new SipApplicationRouterInfo("kaleo", new CustomRegion("custom", SipApplicationRoutingRegionType.NEUTRAL), "sip:[email protected]", new String[] { "sip:as1.cipango.voip", "sip:as2.cipango.voip" }, SipRouteModifier.ROUTE, "1")); } static class CustomRegion extends SipApplicationRoutingRegion implements Serializable { public CustomRegion(String arg0, SipApplicationRoutingRegionType arg1) { super(arg0, arg1); } @Override public String getLabel() { return super.getLabel() + " Mine"; } } }
32.972222
98
0.682112
c06ee247d6e8d476ed47973b8683b3dd7e083e87
4,760
/* * Copyright 2006-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.consol.citrus.db.driver.xml; import com.consol.citrus.db.driver.JdbcDriverException; import com.consol.citrus.db.driver.data.*; import org.w3c.dom.CharacterData; import org.w3c.dom.*; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.*; import java.io.*; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; /** * @author Christoph Deppisch */ public class XmlTableProducer implements TableProducer { /** Json data used as table source */ private final InputStream input; public XmlTableProducer(File file) { this(file.toPath()); } public XmlTableProducer(Path path) { try { this.input = new FileInputStream(path.toFile()); } catch (IOException e) { throw new JdbcDriverException(e); } } public XmlTableProducer(String jsonInput) { this.input = new ByteArrayInputStream(jsonInput.getBytes()); } public XmlTableProducer(InputStream inputStream) { this.input = inputStream; } @Override public List<Table> produce() { List<Table> tables = new ArrayList<>(); try { DOMImplementationLS domImpl = ((DOMImplementationLS) DOMImplementationRegistry.newInstance().getDOMImplementation("LS")); LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); LSInput lsInput = domImpl.createLSInput(); lsInput.setByteStream(input); Document document = parser.parse(lsInput); NodeList tableNodes = document.getDocumentElement().getChildNodes(); for (int i = 0; i < tableNodes.getLength(); i++) { Node tableNode = tableNodes.item(i); if (tableNode instanceof Element) { Table table = new Table(((Element) tableNode).getTagName()); NodeList rows = tableNode.getChildNodes(); for (int j = 0; j < rows.getLength(); j++) { Node rowNode = rows.item(j); if (rowNode instanceof Element) { Element rowElement = (Element) rowNode; Row row = new Row(); NodeList columns = rowElement.getChildNodes(); for (int k = 0; k < columns.getLength(); k++) { Node columnNode = columns.item(k); if (columnNode instanceof Element) { Element columnElement = (Element) columnNode; StringBuilder nodeValue = new StringBuilder(); NodeList textNodes = columnElement.getChildNodes(); for (int m = 0; m < textNodes.getLength(); m++) { Node item = textNodes.item(m); if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) { nodeValue.append(item.getNodeValue()); } } row.getValues().put(columnElement.getTagName(), nodeValue.toString()); } } for (int k = 0; k < rowElement.getAttributes().getLength(); k++) { Node column = rowElement.getAttributes().item(k); row.getValues().put(column.getLocalName(), column.getNodeValue()); } table.getRows().add(row); } } tables.add(table); } } } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new JdbcDriverException("Unable to read table data set from Json input", e); } return tables; } }
39.016393
143
0.54979
6ac9c427ba6f42de46fdf19eb621511db8358d97
1,342
package debug; import android.app.Application; import com.billy.cc.core.component.CC; import com.molmc.ginkgo.basic.data.NetDataSource; import com.molmc.ginkgo.basic.utils.CrashUtils; import com.molmc.ginkgo.basic.utils.DirAndFileUtils; import com.molmc.ginkgo.basic.utils.LogUtils; import com.molmc.ginkgo.scanner.BuildConfig; import com.molmc.ginkgo.scanner.R; import java.io.IOException; /** * Created by 10295 on 2018/3/9. * 二维码扫描组件DEBUG版本Application */ public class ScannerApplication extends Application { @Override public void onCreate() { super.onCreate(); // 全局捕获异常并保存异常信息 CrashUtils.getInstance().init(this); // 初始化网络库 NetDataSource.init(this, BuildConfig.DEBUG, getString(R.string.scanner_app_name)); // 初始化LOG initLog(); // 初始化CC CC.enableVerboseLog(BuildConfig.DEBUG); CC.enableDebug(BuildConfig.DEBUG); CC.enableRemoteCC(BuildConfig.DEBUG); } private void initLog() { String logDir; try { logDir = DirAndFileUtils.getLogDir().toString(); } catch (IOException e) { logDir = getCacheDir().toString(); } String logTag = getString(R.string.scanner_app_name); LogUtils.init(BuildConfig.DEBUG, true, logDir, LogUtils.FILTER_V, logTag); } }
25.807692
90
0.673621
225ac7b7d45731e4f3e9dacca5eb4224bfe4ca47
520
package org.microshed.testing.health; import java.util.ArrayList; import java.util.List; public class Health { public Status status; public List<Check> checks = new ArrayList<>(); public Check getCheck(String name) { return checks.stream() .filter(c -> c.name.equalsIgnoreCase(name)) .findAny().orElse(null); } public static class Check { public String name; public Status status; } public enum Status { UP, DOWN; } }
20
59
0.605769