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
a2539c083602cb0cfc130252a006a47e8923a1a7
2,458
package com.example.demo.service; import com.example.demo.dao.ModelContainerDao; import com.example.demo.domain.ModelContainer; import com.example.demo.utils.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.UUID; /** * Created by wang ming on 2019/5/25. */ @Service public class ModelContainerService { @Autowired ModelContainerDao modelContainerDao; @Value("${prop.upload-folder}") private String UPLOAD_FOLDER; public String findFilePathById(String id){ ModelContainer modelContainer = modelContainerDao.findById(id).orElse(null); return (modelContainer == null) ? null : modelContainer.getPath(); } public ModelContainer uploadModelContainer(MultipartFile file, String version){ //获取文件名称与后缀 String fileName = file.getOriginalFilename(); //String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/upload/" + UUID.randomUUID(); //构建文件目录及文件名 String path = UUID.randomUUID() + File.separator + fileName; String store_filePath = UPLOAD_FOLDER + path; File dest = new File(store_filePath); //检查文件目录是否存在 if(!dest.getParentFile().exists()){ dest.getParentFile().mkdirs(); } try{ file.transferTo(dest); }catch (IOException e){ throw new RuntimeException(e.getMessage()); } //数据库存储 ModelContainer modelContainer = new ModelContainer(); modelContainer.setVersion(version); modelContainer.setPath(path); modelContainer.setCreateDate(new Date()); return modelContainerDao.insert(modelContainer); } public ModelContainer getTheNewestRecord(){ List<ModelContainer> modelContainerList = modelContainerDao.findAll(); modelContainerList.sort(new Comparator<ModelContainer>() { @Override public int compare(ModelContainer o1, ModelContainer o2) { return StringUtils.compareAppVersion(o1.getVersion(), o2.getVersion()); } }.reversed()); return modelContainerList.get(0); } }
34.619718
128
0.691212
aa07b9e592e9d208ad1ca75020dc61028dc0523e
1,758
package com.artos.tests.annotation_testimportance; import com.artos.annotation.TestCase; import com.artos.annotation.TestImportance; import com.artos.annotation.TestPlan; import com.artos.annotation.Unit; import com.artos.framework.Enums.Importance; import com.artos.framework.Enums.TestStatus; import com.artos.framework.infra.TestContext; import com.artos.interfaces.TestExecutable; @TestImportance(Importance.CRITICAL) @TestPlan(preparedBy = "arpit", preparationDate = "18/02/2019", bdd = "GIVEN..WHEN..AND..THEN..") @TestCase public class Test_TestUnit_Importance implements TestExecutable { @TestImportance(Importance.CRITICAL) @Unit(sequence = 1) public void testUnit_1(TestContext context) { // -------------------------------------------------------------------------------------------- context.setTestStatus(TestStatus.FAIL, "This is CRITICAL importance test case"); // -------------------------------------------------------------------------------------------- } @TestImportance(Importance.LOW) @Unit(sequence = 2) public void testUnit_2(TestContext context) { // -------------------------------------------------------------------------------------------- context.setTestStatus(TestStatus.FAIL, "This is LOW importance test case"); // -------------------------------------------------------------------------------------------- } @TestImportance(Importance.MEDIUM) @Unit(sequence = 3) public void testUnit_3(TestContext context) { // -------------------------------------------------------------------------------------------- context.setTestStatus(TestStatus.FAIL, "This is MEDIUM importance test case"); // -------------------------------------------------------------------------------------------- } }
40.883721
97
0.526166
d0c077a2b9894e94c3f8c9742f1406692a19bbb4
8,078
package com.tang.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.lidroid.xutils.view.annotation.event.OnClick; import com.tang.blockchain.Wallet; import com.tang.blockchain.WalletBean; import com.tang.widget.ClearEditText; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.List; import com.tang.R; public class RegActivity extends AppCompatActivity { private static final String TAG = "RegActivity"; // 默认使用中国区号 // private static final String DEFAULT_COUNTRY_ID = "42"; // @ViewInject(R.id.toolbar) // private CNiaoToolBar mToolBar; @ViewInject(R.id.etxt_pn) private ClearEditText mEtxtPn; @ViewInject(R.id.etxt_pwd_3) private ClearEditText mEtxtPwd_3; @ViewInject(R.id.etxt_pwd_4) private ClearEditText mEtxtPwd_4; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); ProgressBar pgb=(ProgressBar)findViewById(R.id.progressbar); switch (msg.what) { case 0: Toast.makeText(RegActivity.this, "Wallet created successfully.", Toast.LENGTH_SHORT).show(); pgb.setVisibility(ProgressBar.GONE); Intent intent = new Intent(RegActivity.this,StartActivity.class); startActivity(intent); break; case 1: Toast.makeText(RegActivity.this, "两次输入的密码不一致,请确认!", Toast.LENGTH_SHORT).show(); pgb.setVisibility(ProgressBar.GONE); break; case 2: Toast.makeText(RegActivity.this, "该钱包名已存在!", Toast.LENGTH_SHORT).show(); pgb.setVisibility(ProgressBar.GONE); break; default: pgb.setVisibility(ProgressBar.GONE); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chain_reg_activity); ViewUtils.inject(this); // initToolBar(); /* SMSSDK.initSDK(this, ManifestUtil.getMetaDataValue(this, "mob_sms_appKey"), ManifestUtil.getMetaDataValue(this,"mob_sms_appSecrect")); evenHanlder = new SMSEvenHanlder(); SMSSDK.registerEventHandler(evenHanlder); String[] country = SMSSDK.getCountry(DEFAULT_COUNTRY_ID); if (country != null) { mTxtCountryCode.setText("+"+country[1]); mTxtCountry.setText(country[0]); } SMSSDK.getSupportedCountries();*/ } /* class SMSEvenHanlder extends EventHandler{ @Override public void afterEvent(final int event, final int result, final Object data) { runOnUiThread(new Runnable() { @Override public void run() { if (result == SMSSDK.RESULT_COMPLETE) { if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) { onCountryListGot((ArrayList<HashMap<String, Object>>) data); } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) { // 请求验证码后,跳转到验证码填写页面 afterVerificationCodeRequested((Boolean) data); } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) { } } else { // 根据服务器返回的网络错误,给toast提示 try { ((Throwable) data).printStackTrace(); Throwable throwable = (Throwable) data; JSONObject object = new JSONObject( throwable.getMessage()); String des = object.optString("detail"); if (!TextUtils.isEmpty(des)) { ToastUtils.show(RegActivity.this, des); return; } } catch (Exception e) { SMSLog.getInstance().w(e); } } } }); } } */ @OnClick(R.id.btn_login_1) public void go_login(View view){ Intent intent = new Intent(RegActivity.this,LoginActivity.class); startActivity(intent); //setResult(RESULT_OK); finish(); } // private void initToolBar() { // mToolBar.setNavigationOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // RegActivity.this.finish(); // } // }); // // } public void progressBar_Reg(View view) { //这个函数直接在XML对应的按钮点击触发 ProgressBar pgb=(ProgressBar)findViewById(R.id.progressbar); pgb.setVisibility(ProgressBar.VISIBLE); createWallet(view); } public void createWallet(View view) { List<String> names = new ArrayList<>(); List<String> passwords = new ArrayList<>(); try { new Thread(new Runnable() { @Override public void run() { String name=mEtxtPn.getText().toString(); String password1=mEtxtPwd_3.getText().toString(); String password2=mEtxtPwd_4.getText().toString(); Message msg = mHandler.obtainMessage(); if(!password1.equals(password2)){ msg.what = 1; mHandler.sendMessage(msg); //finish(); return; } Wallet wallet=Wallet.getInstance(); /*List namelist= null; namelist = wallet.getNameLists();*/ File f = new File(getFilesDir()+"/keystore"); if (!f.exists()){ f.mkdirs(); } String filepath = getFilesDir()+"/keystore"; try { List<WalletBean>lists=wallet.getWalletBeanList(filepath); for (WalletBean walletBean:lists){ String temp=walletBean.getName(); String tname=walletBean.getName(); String tpassword=walletBean.getName(); //names.add(tname); //passwords.add(tpassword); if(temp.equals(name)){ msg.what = 2; mHandler.sendMessage(msg); return; } } } catch (Exception e) { e.printStackTrace(); } /*if(namelist.contains(name)){ msg.what = 2; mHandler.sendMessage(msg); //finish(); return; }*/ wallet.createWallet(name,password1,filepath); msg.what = 0; //msg.obj = "ok";//可以是基本类型,可以是对象,可以是List、map等; mHandler.sendMessage(msg); } }).start(); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onDestroy() { super.onDestroy(); //SMSSDK.unregisterEventHandler(evenHanlder); } }
32.441767
112
0.504952
0fe643ce7e2381478cc0683861049cb1ba818c30
1,495
package com.rajendarreddyj.spring.web.hateoas.listener; import java.net.URI; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpHeaders; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.google.common.base.Preconditions; import com.rajendarreddyj.spring.web.hateoas.event.ResourceCreatedEvent; @Component class ResourceCreatedDiscoverabilityListener implements ApplicationListener<ResourceCreatedEvent> { @Override public void onApplicationEvent(final ResourceCreatedEvent resourceCreatedEvent) { Preconditions.checkNotNull(resourceCreatedEvent); final HttpServletResponse response = resourceCreatedEvent.getResponse(); final long idOfNewResource = resourceCreatedEvent.getIdOfNewResource(); this.addLinkHeaderOnResourceCreation(response, idOfNewResource); } void addLinkHeaderOnResourceCreation(final HttpServletResponse response, final long idOfNewResource) { // final String requestUrl = request.getRequestURL().toString(); // final URI uri = new UriTemplate("{requestUrl}/{idOfNewResource}").expand(requestUrl, idOfNewResource); final URI uri = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/{idOfNewResource}").buildAndExpand(idOfNewResource).toUri(); response.setHeader(HttpHeaders.LOCATION, uri.toASCIIString()); } }
41.527778
143
0.797993
080e8dd19de450411b44d35d603f3b43a3424dfb
738
package br.inatel.cdg.pilha; import br.inatel.cdg.pilha.exception.PilhaVaziaException; import java.util.ArrayList; import java.util.List; public class Pilha<T> { private List<T> elementos; private int qtdElementos; public Pilha() { elementos = new ArrayList<>(); } public boolean pilhaVazia() { return qtdElementos==0; } public void push(T elemento) { elementos.add(elemento); qtdElementos++; } public T mostraTopo() { T elemento = elementos.get(qtdElementos-1); return elemento; } public T pop(){ if(pilhaVazia()) throw new PilhaVaziaException(); T elemento = elementos.remove(qtdElementos-1); qtdElementos--; return elemento; } public int getQtdElementos() { return qtdElementos; } }
17.571429
57
0.707317
d7540c54236f4065df4f475ab24c56998b1f5c9a
3,568
/* * Copyright 2015. AppDynamics LLC and its affiliates. * All Rights Reserved. * This is unpublished proprietary source code of AppDynamics LLC and its affiliates. * The copyright notice above does not evidence any actual or intended publication of such source code. * */ package com.appdynamics.extensions.docker; import com.appdynamics.extensions.logging.ExtensionsLoggerFactory; import com.fasterxml.jackson.databind.JsonNode; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import java.io.File; import java.io.IOException; import java.io.InputStream; /** * Created by abey.tom on 4/3/15. */ public class UnixSocketDataFetcherTest { public static final Logger logger = ExtensionsLoggerFactory.getLogger(UnixSocketDataFetcherTest.class); @Test public void multilineResponseTest() throws IOException { if (isUnix()) { File file = copyAndGetPath("/raw/multiline.sh"); UnixSocketDataFetcher fetcher = new UnixSocketDataFetcher(file.getAbsolutePath()); JsonNode jsonNode = fetcher.fetchData("/info", JsonNode.class, true); Assert.assertEquals(4,jsonNode.get("Containers").asInt()); } else { logger.warn("Unsupported OS for this test case"); } } @Test public void singleLineResponseTest() throws IOException { if (isUnix()) { File file = copyAndGetPath("/raw/singleline.sh"); UnixSocketDataFetcher fetcher = new UnixSocketDataFetcher(file.getAbsolutePath()); JsonNode jsonNode = fetcher.fetchData("/info", JsonNode.class, false); Assert.assertEquals(4,jsonNode.get("Containers").asInt()); } else { logger.warn("Unsupported OS for this test case"); } } @Test public void errorResponseTest() throws IOException { if (isUnix()) { File file = copyAndGetPath("/raw/error.sh"); UnixSocketDataFetcher fetcher = new UnixSocketDataFetcher(file.getAbsolutePath()); JsonNode jsonNode = fetcher.fetchData("/info", JsonNode.class, false); Assert.assertNull(jsonNode); } else { logger.warn("Unsupported OS for this test case"); } } @Test public void invalidResponseTest() throws IOException { if (isUnix()) { File file = copyAndGetPath("/raw/invalid.sh"); UnixSocketDataFetcher fetcher = new UnixSocketDataFetcher(file.getAbsolutePath()); JsonNode jsonNode = fetcher.fetchData("/info", JsonNode.class, false); Assert.assertNull(jsonNode); } else { logger.warn("Unsupported OS for this test case"); } } private File copyAndGetPath(String path) throws IOException { InputStream in = getClass().getResourceAsStream(path); File file = new File(System.getProperty("java.io.tmpdir"), path); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } if (file.exists()) { FileUtils.deleteQuietly(file); } FileUtils.copyInputStreamToFile(in, file); Runtime.getRuntime().exec(new String[]{"chmod", "+x", file.getAbsolutePath()}); return file; } private boolean isUnix() { String property = System.getProperty("os.name"); return property != null && (property.toLowerCase().contains("mac") || property.toLowerCase().contains("nix")); } }
36.040404
107
0.644339
0fda7d52b0dbe42c14cbc78ba6d12ab6f957a855
4,295
/** * 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.pulsar.client.impl.schema; import static java.nio.charset.StandardCharsets.UTF_8; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.pulsar.client.api.schema.FieldSchemaBuilder; import org.apache.pulsar.client.api.schema.GenericSchema; import org.apache.pulsar.client.api.schema.RecordSchemaBuilder; import org.apache.pulsar.common.schema.SchemaInfo; import org.apache.pulsar.common.schema.SchemaType; /** * The default implementation of {@link RecordSchemaBuilder}. */ public class RecordSchemaBuilderImpl implements RecordSchemaBuilder { public static final String NAMESPACE = "org.apache.pulsar.schema.record"; public static final String DEFAULT_SCHEMA_NAME = "PulsarDefault"; private final String name; private final Map<String, String> properties; private final List<FieldSchemaBuilderImpl> fields = new ArrayList<>(); private String doc; public RecordSchemaBuilderImpl(String name) { this.name = name; this.properties = new HashMap<>(); } @Override public RecordSchemaBuilder property(String name, String val) { this.properties.put(name, val); return this; } @Override public FieldSchemaBuilder field(String fieldName) { FieldSchemaBuilderImpl field = new FieldSchemaBuilderImpl(fieldName); fields.add(field); return field; } @Override public FieldSchemaBuilder field(String fieldName, GenericSchema genericSchema) { FieldSchemaBuilderImpl field = new FieldSchemaBuilderImpl(fieldName, genericSchema); fields.add(field); return field; } @Override public RecordSchemaBuilder doc(String doc) { this.doc = doc; return this; } @Override public SchemaInfo build(SchemaType schemaType) { switch (schemaType) { case JSON: case AVRO: break; default: throw new RuntimeException("Currently only AVRO and JSON record schema is supported"); } String schemaNs = NAMESPACE; String schemaName = DEFAULT_SCHEMA_NAME; if (name != null) { String[] split = splitName(name); schemaNs = split[0]; schemaName = split[1]; } org.apache.avro.Schema baseSchema = org.apache.avro.Schema.createRecord( schemaName != null ? schemaName : DEFAULT_SCHEMA_NAME, doc, schemaNs, false ); List<org.apache.avro.Schema.Field> avroFields = new ArrayList<>(); for (FieldSchemaBuilderImpl field : fields) { avroFields.add(field.build()); } baseSchema.setFields(avroFields); return new SchemaInfoImpl( name, baseSchema.toString().getBytes(UTF_8), schemaType, properties ); } /** * Split a full dotted-syntax name into a namespace and a single-component name. */ private static String[] splitName(String fullName) { String[] result = new String[2]; int indexLastDot = fullName.lastIndexOf('.'); if (indexLastDot >= 0) { result[0] = fullName.substring(0, indexLastDot); result[1] = fullName.substring(indexLastDot + 1); } else { result[0] = null; result[1] = fullName; } return result; } }
32.293233
102
0.659837
138afd9db3d0132f9efb48a8041840ce9d2aae6e
4,224
/** * Copyright 2010-2012 by PHP-maven.org * * 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.phpmaven.phpdoc.impl; import org.apache.maven.execution.MavenSession; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.phpmaven.core.BuildPluginConfiguration; import org.phpmaven.core.ConfigurationParameter; import org.phpmaven.core.IComponentFactory; import org.phpmaven.phpdoc.IPhpdocConfiguration; import org.phpmaven.phpdoc.IPhpdocService; import org.phpmaven.phpdoc.IPhpdocSupport; /** * Configuration impl. * * @author <a href="mailto:Martin.Eisengardt@googlemail.com">Martin Eisengardt</a> * @since 2.0.0 */ @Component(role = IPhpdocConfiguration.class, instantiationStrategy = "per-lookup") @BuildPluginConfiguration(groupId = "de.slothsoft.phpmaven", artifactId = "maven-php-phpdoc", filter = { "executableConfig", "phpdocVersion", "installPhpdoc", "installFolder", "arguments" }) public class PhpdocConfiguration implements IPhpdocConfiguration { /** * The component factory. */ @Requirement private IComponentFactory factory; /** * The maven session. */ @ConfigurationParameter(name = "session", expression = "${session}") private MavenSession session; /** * The service name. */ @Configuration(name = "phpdocService", value = "PEAR") private String phpdocService; /** * {@inheritDoc} */ @Override public String getPhpdocService() { return this.phpdocService; } /** * {@inheritDoc} */ @Override public void setPhpdocService(String service) { this.phpdocService = service; } /** * {@inheritDoc} */ @Override public IPhpdocSupport getPhpdocSupport() throws PlexusConfigurationException, ComponentLookupException { for (final IPhpdocService service : this.factory.getServiceImplementations(IPhpdocService.class, session)) { if (this.phpdocService.equals(service.getServiceName())) { return service.createDefault(this.session); } } return null; } /** * {@inheritDoc} */ @Override public IPhpdocSupport getPhpdocSupport(String phpdocVersion) throws PlexusConfigurationException, ComponentLookupException { for (final IPhpdocService service : this.factory.getServiceImplementations(IPhpdocService.class, session)) { if (this.phpdocService.equals(service.getServiceName())) { return service.createForPhpdocVersion(phpdocVersion, session); } } return null; } /** * {@inheritDoc} */ @Override public IPhpdocSupport getPhpdocSupport(MavenProject project) throws PlexusConfigurationException, ComponentLookupException { final MavenSession inherited = this.session.clone(); inherited.setCurrentProject(project); for (final IPhpdocService service : this.factory.getServiceImplementations(IPhpdocService.class, inherited)) { if (this.phpdocService.equals(service.getServiceName())) { return service.createDefault(inherited); } } return null; } }
34.064516
119
0.67661
740e1c8ff7b420470534fe77dfa6896e9bd2af22
704
package com.gao.yingjian.mobiledevelopmentassignmentone.Models; import java.util.ArrayList; public class SurveyDetailGroup { private String groupName; private String groupDescription; private ArrayList<SurveyDetailItem> items; public SurveyDetailGroup(String groupName, String groupDescription, ArrayList<SurveyDetailItem> items) { this.groupName = groupName; this.groupDescription = groupDescription; this.items = items; } public String getGroupName() { return groupName; } public String getGroupDescription() { return groupDescription; } public ArrayList<SurveyDetailItem> getItems() { return items; } }
25.142857
108
0.710227
bad12684edf32396297f170de6a87d4325a72870
3,195
/* * 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.accumulo.core.constraints; import java.util.List; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.dataImpl.KeyExtent; import org.apache.accumulo.core.security.AuthorizationContainer; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * This class is replaced by {@link org.apache.accumulo.core.data.constraints.Constraint} * * @deprecated since 2.1.0 Use {@link org.apache.accumulo.core.data.constraints.Constraint} */ @Deprecated(since = "2.1.0") @SuppressFBWarnings(value = "NM_SAME_SIMPLE_NAME_AS_INTERFACE", justification = "Same name used for compatibility during deprecation cycle") public interface Constraint extends org.apache.accumulo.core.data.constraints.Constraint { /** * The environment within which a constraint exists. */ interface Environment extends org.apache.accumulo.core.data.constraints.Constraint.Environment { /** * Gets the key extent of the environment. * * @return key extent */ KeyExtent getExtent(); /** * Gets the user within the environment. * * @return user */ @Override String getUser(); /** * Gets the authorizations in the environment. * * @return authorizations */ @Override AuthorizationContainer getAuthorizationsContainer(); } /** * Gets a short, one-sentence description of what a given violation code means. * * @param violationCode * numeric violation code * @return matching violation description */ @Override String getViolationDescription(short violationCode); /** * Checks a mutation for constraint violations. If the mutation contains no violations, returns * null. Otherwise, returns a list of violation codes. * * Violation codes must be non-negative. Negative violation codes are reserved for system use. * * @param env * constraint environment * @param mutation * mutation to check * @return list of violation codes, or null if none */ List<Short> check(Environment env, Mutation mutation); /** * Implemented for backwards compatibility. * * @since 2.1.0 */ @Override default List<Short> check(org.apache.accumulo.core.data.constraints.Constraint.Environment env, Mutation mutation) { return check((Environment) env, mutation); } }
31.323529
98
0.714241
ec904280a303dddebda4804dd6d593e56df4f894
730
package <%= appPackage %>.<%= packageName %>; import com.joxad.easydatabinding.bottomsheet.DialogBottomSheetBaseVM; import <%= appPackage %>.R; import <%= appPackage %>.BR; import <%= appPackage %>.databinding.<%= name %>Binding; import <%= appPackage %>.<%= packageName %>.<%= name %>; /** * Generated by generator-android-template */ public class <%= name %>VM extends DialogBottomSheetBaseVM<<%= name %>, <%= name %>Binding> { private static final String TAG = <%= name %>VM.class.getSimpleName(); /*** * @param fragment * @param binding */ public <%= name %>VM(<%= name %> fragment, <%= name %>Binding binding) { super(fragment, binding); } @Override public void onCreate() { } }
25.172414
93
0.624658
ea4103c37610409e8f2a952dc281b4392a8be8ec
332
package io.kurumi.ntt.td.client; import io.kurumi.ntt.td.TdApi; public class TdException extends RuntimeException { private TdApi.Error error; public TdException(TdApi.Error error) { super(error.message); this.error = error; } public TdApi.Error getError() { return error; } }
13.833333
51
0.64759
a4333dc34f15d4e4de36e3f1191bf5b2859a2ca9
3,424
package cn.bgenius.jf_android_java_demos; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * Created by jinfei on 20/02/2017. */ public class AsyncTaskDemoActivity extends Activity { private Button btnSubmit; private EditText edtUrl; private TextView tvShowHtml; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_asynctaskdemo); btnSubmit = (Button)findViewById(R.id.btnSubmit); edtUrl = (EditText) findViewById(R.id.edtUrl); tvShowHtml = (TextView) findViewById(R.id.tvShowHtml); btnSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ReadUrl("http://www.163.com"); } }); } public void ReadUrl(String url){ new AsyncTask<String, Float, String>(){ @Override protected String doInBackground(String... params) { try { URL url = new URL(params[0]); URLConnection conn = url.openConnection(); long totalLength = conn.getContentLength(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null){ sb.append(line); publishProgress((float)(sb.toString().length() / totalLength)); } br.close(); isr.close(); is.close(); return sb.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPreExecute() { Toast.makeText(AsyncTaskDemoActivity.this, "开始读取...", Toast.LENGTH_SHORT).show(); super.onPreExecute(); } @Override protected void onPostExecute(String s) { tvShowHtml.setText(s); Log.d("debuginfo", s); super.onPostExecute(s); } @Override protected void onProgressUpdate(Float... values) { Log.d("debuginfo", String.valueOf(values[0])); super.onProgressUpdate(values); } @Override protected void onCancelled(String s) { super.onCancelled(s); } @Override protected void onCancelled() { super.onCancelled(); } }.execute(url); } }
32
97
0.551402
9f43366806d57deefeed0c1ff09aacc70be22a29
4,610
// Generated from io\onedev\server\search\entity\build\BuildQuery.g4 by ANTLR 4.7.2 package io.onedev.server.search.entity.build; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.TerminalNode; /** * This class provides an empty implementation of {@link BuildQueryListener}, * which can be extended to create a listener which only needs to handle a subset * of the available methods. */ public class BuildQueryBaseListener implements BuildQueryListener { /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterQuery(BuildQueryParser.QueryContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitQuery(BuildQueryParser.QueryContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterOperatorCriteria(BuildQueryParser.OperatorCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitOperatorCriteria(BuildQueryParser.OperatorCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterParensCriteria(BuildQueryParser.ParensCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitParensCriteria(BuildQueryParser.ParensCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterOrCriteria(BuildQueryParser.OrCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitOrCriteria(BuildQueryParser.OrCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterFieldOperatorValueCriteria(BuildQueryParser.FieldOperatorValueCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitFieldOperatorValueCriteria(BuildQueryParser.FieldOperatorValueCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterFieldOperatorCriteria(BuildQueryParser.FieldOperatorCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitFieldOperatorCriteria(BuildQueryParser.FieldOperatorCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterAndCriteria(BuildQueryParser.AndCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitAndCriteria(BuildQueryParser.AndCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterOperatorValueCriteria(BuildQueryParser.OperatorValueCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitOperatorValueCriteria(BuildQueryParser.OperatorValueCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterNotCriteria(BuildQueryParser.NotCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitNotCriteria(BuildQueryParser.NotCriteriaContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterOrder(BuildQueryParser.OrderContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitOrder(BuildQueryParser.OrderContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) { } }
28.993711
114
0.711497
1ade1c3643b39d6092f3d6ec8e7e0b459069a7b3
1,927
import java.util.*; import javafx.collections.*; import javafx.scene.control.*; import javafx.scene.control.cell.*; public class ProspettoModelliSalvati extends TableView<ModelloSalvato> { private final ObservableList<ModelloSalvato> ol; public void aggiornaListaModelli(List<ModelloSalvato> modelli) { ol.clear(); ol.addAll(modelli); } public String restituisciModelloSelezionato() throws NessunModelloSelezionatoException{ if (getSelectionModel().isEmpty()) //(01) throw new NessunModelloSelezionatoException( "Devi prima selezionare un modello da recuperare!\n" + "Puoi farlo selezionando una riga della tabella"); return getSelectionModel().getSelectedItem().getNomeModello(); //(01) } public ProspettoModelliSalvati() { setColumnResizePolicy(CONSTRAINED_RESIZE_POLICY); TableColumn colonnaNome = new TableColumn("Modello"); colonnaNome.setCellValueFactory(new PropertyValueFactory<>("nomeModello")); TableColumn colonnaAutore = new TableColumn("Autore"); colonnaAutore.setCellValueFactory(new PropertyValueFactory<>("nomeAutore")); TableColumn colonnaData = new TableColumn("Data"); colonnaData.setCellValueFactory(new PropertyValueFactory<>("dataSalvataggio")); colonnaData.setMinWidth(60); ol = FXCollections.observableArrayList(); setItems(ol); getColumns().addAll(colonnaNome, colonnaAutore, colonnaData); setLayoutX(270); setLayoutY(430); setMaxHeight(150); setMinWidth(300); } } /* (01) Il metodo getSelectionModel() di TableView permette di recuperare le informazioni associate alla riga selezionata nella tabella. https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TableView.html#getSelectionModel-- */
41
100
0.687078
4f4aab93a2ef1328987f595eec919a7f44dca23a
3,777
/* * 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 freemarker.core; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.IOException; import org.junit.Test; import com.google.common.collect.ImmutableSet; import freemarker.template.Configuration; import freemarker.template.DefaultIterableAdapter; import freemarker.template.DefaultNonListCollectionAdapter; import freemarker.template.TemplateCollectionModelEx; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import freemarker.template.TemplateSequenceModel; import freemarker.template.utility.ObjectWrapperWithAPISupport; import freemarker.test.TemplateTest; public class SequenceBuiltInTest extends TemplateTest { @Test public void testWithCollection() throws TemplateException, IOException { ObjectWrapperWithAPISupport ow = (ObjectWrapperWithAPISupport) getConfiguration().getObjectWrapper(); TemplateModel xs = DefaultIterableAdapter.adapt(ImmutableSet.of("a", "b"), ow); assertThat(xs, not(instanceOf(TemplateCollectionModelEx.class))); assertThat(xs, not(instanceOf(TemplateSequenceModel.class))); addToDataModel("xs", xs); try { assertOutput("${xs[1]}", "b"); fail(); } catch (TemplateException e) { assertThat(e.getMessage(), containsString("?sequence")); // Contains tip to use ?sequence } assertOutput("${xs?sequence[1]}", "b"); try { assertOutput("${xs?size}", "2"); fail(); } catch (TemplateException e) { assertThat(e.getMessage(), containsString("?sequence")); // Contains tip to use ?sequence } assertOutput("${xs?sequence?size}", "2"); } @Test public void testWithCollectionEx() throws TemplateException, IOException { ObjectWrapperWithAPISupport ow = (ObjectWrapperWithAPISupport) getConfiguration().getObjectWrapper(); TemplateModel xs = DefaultNonListCollectionAdapter.adapt(ImmutableSet.of("a", "b"), ow); assertThat(xs, not(instanceOf(TemplateSequenceModel.class))); assertThat(xs, instanceOf(TemplateCollectionModelEx.class)); addToDataModel("xs", xs); try { assertOutput("${xs[1]}", "b"); fail(); } catch (TemplateException e) { assertThat(e.getMessage(), containsString("?sequence")); // Contains tip to use ?sequence } assertOutput("${xs?sequence[1]}", "b"); assertOutput("${xs?size}", "2"); // No need for ?sequence } @Test public void testWithSequence() throws TemplateException, IOException { assertOutput("${[11, 12]?sequence[1]}", "12"); getConfiguration().setIncompatibleImprovements(Configuration.VERSION_2_3_23); // As it returns the sequence as is, it works with an infinite sequence: assertOutput("${(11..)?sequence[1]}", "12"); } }
38.151515
109
0.686524
165eaa1109ddaf7d6a3d94bba41e7a8b83d327df
2,823
package org.openvasp.client.crypto; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; /** * @author Olexandr_Bilovol@epam.com */ class ECDHKeyPairTests { /* * CSHARP_ keys generated by OpenVASP.CSharpClient.Cryptography.ECDH_Key */ private static final String CSHARP_PRIVATE_KEY_1 = "0x1a25586d9f2ae0e0a129f23a58cb82d29b31978473e09c4eac59ecc41f18acf5"; private static final String CSHARP_PUBLIC_KEY_1 = "0x04fba7640d73126ac06647901dada168762049ec7f3fc869454d4a0194d64f683ec1565a66fa4208aaf07a3ac6deeff0fb60274dfc53d4d823fe625e4c605e40fa"; private static final String CSHARP_PRIVATE_KEY_2 = "0x5f4476f3053bbe449d5af2238a49eead9d2507c57a4d0d3b60b45ab82642f1c3"; private static final String CSHARP_PUBLIC_KEY_2 = "0x04c044b13614142bcedcf7f38ee7e58cc3529f4aa570a567c0c6f98850ffb4cc9b00707e6545c2a98e60d445f173d65bea78543f810b9a14745ed214d771358e64"; private static final String CSHARP_SHARED_SECRET = "0x24146426385d76262122a7e0f7b23679f2da341612b0175999de97efbb5ad99c"; @Test void checkCSharpCompliance() { var ecdh1 = ECDHKeyPair.importPrivateKey(CSHARP_PRIVATE_KEY_1); assertThat(ecdh1.getPrivateKey()).isEqualTo(CSHARP_PRIVATE_KEY_1); assertThat(ecdh1.getPublicKey()).isEqualTo(CSHARP_PUBLIC_KEY_1); var ecdh2 = ECDHKeyPair.importPrivateKey(CSHARP_PRIVATE_KEY_2); assertThat(ecdh2.getPrivateKey()).isEqualTo(CSHARP_PRIVATE_KEY_2); assertThat(ecdh2.getPublicKey()).isEqualTo(CSHARP_PUBLIC_KEY_2); var sharedSecret = ecdh1.generateSharedSecretHex(ecdh2.getPublicKey()); assertThat(sharedSecret).isEqualTo(CSHARP_SHARED_SECRET); } @Test void checkSharedSecret() { var key1 = ECDHKeyPair.generateKeyPair(); var key2 = ECDHKeyPair.generateKeyPair(); var sharedSecret12 = key1.generateSharedSecretHex(key2.getPublicKey()); var sharedSecret21 = key2.generateSharedSecretHex(key1.getPublicKey()); assertThat(sharedSecret12).isEqualTo(sharedSecret21); } @Test void checkSessionPublicKey() { var privateKey = "0x502eb0b1a40d5b788b2395394bc6ae47adae61e9f0a9584c4700132914a8ed04"; // public key is "0x04" + ecdhpk where ecdhpk is taken from the JSON sample // at // https://github.com/LykkeBusiness/openvasp-message-samples/blob/master/session-request.txt var publicKey = "0x04ac7c9764497e5e5d3c42a4cc0b1425fda9f7564e49f288994fdbbb42e5731bb0f30f82e1890459cb40325989a6a872a963d40efdbc88d66e427da1ecded0e4c2"; var keyPair = ECDHKeyPair.importPrivateKey(privateKey); var sharedSecret = keyPair.generateSharedSecretHex(publicKey); assertThat(sharedSecret).isEqualTo("0x182fef693d3c2289d101bf708049abb2099540bafe7b0e05ffbb40c1fb3eccce"); } }
45.532258
189
0.784626
ee113036ecabe283c6f16c7a3b15465cd656d0a5
3,620
package nc.unc.application.data.service; import com.vaadin.flow.server.VaadinSession; import nc.unc.application.data.entity.LogEnregistrement; import nc.unc.application.data.entity.User; import nc.unc.application.data.enums.TypeCrud; import nc.unc.application.data.repository.LogEnregistrementRepository; import org.springframework.stereotype.Service; import nc.unc.application.security.AuthenticatedUser; import java.util.List; import java.util.Optional; @Service public class LogEnregistrmentService { private final LogEnregistrementRepository logEnregistrementRepository; private final AuthenticatedUser authenticatedUser; public LogEnregistrmentService(LogEnregistrementRepository logEnregistrementRepository, AuthenticatedUser authenticatedUser) { this.logEnregistrementRepository = logEnregistrementRepository; this.authenticatedUser = authenticatedUser; } public List<LogEnregistrement> findAllLogs(String stringFilter) { if (stringFilter == null || stringFilter.isEmpty()) { return logEnregistrementRepository.findAllByOrderByCreatedAtDesc(); } else { return logEnregistrementRepository.search(stringFilter); } } public long countLogs() { return logEnregistrementRepository.count(); } public void deleteLog(LogEnregistrement logEnregistrement) { logEnregistrementRepository.delete(logEnregistrement); } /** * Définition d'un log de sauvegarde d'un élément * @param description_log la description du log, correspondant aux information de l'élément ajouté (son toString) */ public void saveLogAjoutString(String description_log) { LogEnregistrement logEnregistrement = new LogEnregistrement(); logEnregistrement.setDescription_log(description_log); logEnregistrement.setTypeCrud(TypeCrud.AJOUT); setExecutant(logEnregistrement); saveLog(logEnregistrement); } /** * définition d'un log dans le cas d'une modification d'élément * @param oldValues anciennes valeurs de l'élément * @param newValues nouvelles valeurs de l'élément */ public void saveLogEditString(String oldValues, String newValues) { LogEnregistrement logEnregistrement = new LogEnregistrement(); logEnregistrement.setDescription_log( "ANCIENNES VALEURS : \n" + oldValues + "\n\uD83C\uDD95 REMPLACÉES PAR : \n" + newValues ); logEnregistrement.setTypeCrud(TypeCrud.MODIFICATION); setExecutant(logEnregistrement); saveLog(logEnregistrement); } /** * Définition d'un log dans le cas de la suppression d'un élément * @param description_log */ public void saveLogDeleteString(String description_log) { LogEnregistrement logEnregistrement = new LogEnregistrement(); logEnregistrement.setDescription_log(description_log); logEnregistrement.setTypeCrud(TypeCrud.SUPPRESSION); setExecutant(logEnregistrement); saveLog(logEnregistrement); } /** * Sauvegarde d'un log * @param logEnregistrement */ public void saveLog(LogEnregistrement logEnregistrement) { if (logEnregistrement == null) { System.err.println("L'enregistrement est nul..."); return; } logEnregistrementRepository.save(logEnregistrement); } /** * Défini qui est la personne qui a effectuée l'action provoquant l'enregistrement d'un log * @param logEnregistrement */ public void setExecutant(LogEnregistrement logEnregistrement) { Optional<User> maybeUser = authenticatedUser.get(); if (maybeUser.isPresent()) { User user = maybeUser.get(); logEnregistrement.setExecutant(user.getNom() + " " + user.getPrenom()); } } }
33.831776
128
0.75884
272564ab7b1d5ec06bc678e8a40ef04c0e3e3f85
4,515
package com.painless.pc.folder; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; import android.widget.TabHost.TabContentFactory; import com.painless.pc.R; import com.painless.pc.nav.CFolderFrag; import com.painless.pc.nav.FolderFrag; import com.painless.pc.picker.IconPicker; import com.painless.pc.picker.IconPicker.Callback; import com.painless.pc.util.CallerActivity; public class FolderPick extends CallerActivity implements TabContentFactory, OnTabChangeListener, OnClickListener, Callback { private CFolderFrag mNewFolderFrag; private Fragment mExistingFolderFragmet; private ImageView mIconSelect; private Bitmap mIcon; private IconPicker mIconPicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setResult(RESULT_CANCELED); setContentView(R.layout.folder_picker); TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost); tabHost.setup(); tabHost.addTab(tabHost.newTabSpec("t1").setIndicator(getString(R.string.folder_new)).setContent(this)); tabHost.addTab(tabHost.newTabSpec("t2").setIndicator(getString(R.string.folder_existing)).setContent(this)); tabHost.setCurrentTab(0); tabHost.setOnTabChangedListener(this); onTabChanged(null); mIconPicker = new IconPicker(this, true); mIconSelect = (ImageView) findViewById(R.id.folder_icon); mIconSelect.setOnClickListener(this); } @Override public void onTabChanged(String tabId) { Fragment currentFrag; if ("t2".equals(tabId)) { mExistingFolderFragmet = getIfNull(FolderFrag.class, mExistingFolderFragmet); currentFrag = mExistingFolderFragmet; } else { mNewFolderFrag = (CFolderFrag) getIfNull(CFolderFrag.class, mNewFolderFrag); currentFrag = mNewFolderFrag; } FragmentTransaction transaction = getFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack transaction.replace(android.R.id.tabcontent, currentFrag); // Commit the transaction transaction.commit(); } private Fragment getIfNull(Class<?> fragClass, Fragment toCheck) { return (toCheck == null) ? Fragment.instantiate(this, fragClass.getName()) : toCheck; } @Override public View createTabContent(String tag) { return new View(this); } private void returnFolder(String dbName, String shrtName, String settings) { int icon = R.drawable.folder_icon; // The result we are passing back from this activity setResult(RESULT_OK, new Intent() .putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this, FolderActivity.class).setAction(FolderUtils.ACTION).setData(Uri.parse("folder/?" + dbName))) .putExtra(Intent.EXTRA_SHORTCUT_NAME, shrtName) .putExtra(Intent.EXTRA_SHORTCUT_ICON, mIcon) .putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, icon))); finish(); } public void returnFolder(String dbName, String shrtName) { FolderDb db = new FolderDb(this, dbName); String settings = db.getSettings(); db.close(); returnFolder(dbName, shrtName, settings); } public void returnNew(String settings, String shrtName, byte[] background) { String dbName = FolderUtils.newDbName(this); // create a database file FolderDb db = new FolderDb(this, dbName); db.saveSettigns(settings, background); db.close(); shrtName = TextUtils.isEmpty(shrtName) ? getString(R.string.folder_name) : shrtName; FolderUtils.setName(shrtName, dbName, this); returnFolder(dbName, shrtName, settings); } @Override public void onDoneClicked() { } @Override public void onClick(View v) { if (mNewFolderFrag != null) { mIconPicker.icon3dColors = mNewFolderFrag.getCurrentColors(); } mIconPicker.pickIcon(this, Color.WHITE); } @Override public void onIconReceived(Bitmap icon) { mIcon = icon; if (icon == null) { mIconSelect.setImageResource(R.drawable.folder_icon); } else { mIconSelect.setImageBitmap(icon); } } }
33.198529
155
0.743743
6b7fb809e776b5ce5f2e86ec80c5a105b3a3e5b8
920
package snake; /** * @author Giulio Jiang * time scheduler thread */ public class TimerRunnable implements Runnable { private long start; private long next; private Board board; private long delay; public TimerRunnable(Board board) { this.board = board; this.start = System.currentTimeMillis(); this.delay = 2; this.next = this.start + delay; } @Override public void run() { start = System.currentTimeMillis(); next = start + delay; while (true) { if (Thread.currentThread().isInterrupted()) { return; } if (System.currentTimeMillis() > next) { next += delay; board.actionPerformed(null); } } } public void setDelay(long delay) { this.delay = delay; } }
18.77551
55
0.517391
269d264324fe5cb75afd629633ca3da069b43f37
1,867
package org.tiscs.reststack.core; import ch.qos.logback.ext.spring.web.LogbackConfigListener; import ch.qos.logback.ext.spring.web.WebLogbackConfigurer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import org.tiscs.reststack.core.contexts.AppContext; import org.tiscs.reststack.core.contexts.WebContext; public class AppEntry { public static void main(String[] args) throws Exception { org.apache.ibatis.logging.LogFactory.useSlf4jLogging(); Server server = new Server(8080); ServletContextHandler servletContext = new ServletContextHandler(ServletContextHandler.SESSIONS); servletContext.setContextPath("/"); AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext(); appContext.register(AppContext.class); servletContext.setInitParameter(WebLogbackConfigurer.EXPOSE_WEB_APP_ROOT_PARAM, "false"); servletContext.addEventListener(new ContextLoaderListener(appContext)); servletContext.addEventListener(new LogbackConfigListener()); AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext(); webContext.register(WebContext.class); ServletHolder apiServlet = new ServletHolder("rest-api", new DispatcherServlet(webContext)); servletContext.addServlet(apiServlet, "/api/*"); apiServlet.getRegistration().setLoadOnStartup(1); apiServlet.setAsyncSupported(true); server.setHandler(servletContext); server.start(); server.join(); } }
44.452381
105
0.778254
da9f0d83e0b9e60387310060039841fd8bb66ef0
2,922
package com.mexus.homeleisure.security.controller; import com.mexus.homeleisure.security.request.RefreshRequest; import com.mexus.homeleisure.security.request.SignInRequest; import com.mexus.homeleisure.security.request.SignUpRequest; import com.mexus.homeleisure.security.response.RefreshResponse; import com.mexus.homeleisure.security.response.SignInResponse; import com.mexus.homeleisure.security.service.AuthService; import lombok.RequiredArgsConstructor; import org.springframework.hateoas.MediaTypes; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * 회원 인증 컨트롤러 * * @author always0ne * @version 1.0 */ @RestController @RequiredArgsConstructor @RequestMapping(value = "/auth", produces = MediaTypes.HAL_JSON_VALUE) public class AuthController { private final AuthService authService; /** * 토큰 발급받기 * * @param signInRequest 사용자 ID, 비밀번호 * @return accessToken */ @PostMapping("/signin") @ResponseStatus(HttpStatus.OK) public SignInResponse signIn( @RequestBody SignInRequest signInRequest ) { return this.authService.signIn(signInRequest.getId(), signInRequest.getPassword()); } /** * 회원 가입하기 * * @param signUpRequest 사용자 ID, 비밀번호, 이름 * @return accessToken */ @PostMapping("/signup") @ResponseStatus(HttpStatus.OK) public SignInResponse signUp( @RequestBody SignUpRequest signUpRequest ) { return this.authService .signUp(signUpRequest.getId(), signUpRequest.getPassword(), signUpRequest.getNickName(), signUpRequest.getEmail()); } /** * 아이디 중복 체크하기 * * @param userId 중복확인할 ID * @return 사용가능 여부 */ @GetMapping("/checkid/{userId}") @ResponseStatus(HttpStatus.OK) public String idCheck( @PathVariable String userId ) { this.authService.idCheck(userId); return "사용가능한 아이디입니다."; } /** * 닉네임 중복 체크하기 * * @param nickName 중복확인할 닉네임 * @return 사용가능 여부 */ @GetMapping("/checkNickName/{nickName}") @ResponseStatus(HttpStatus.OK) public String nickNameCheck( @PathVariable String nickName ) { this.authService.nickNameCheck(nickName); return "사용가능한 닉네임입니다."; } /** * RefreshToken 으로 AccessToken 재발급 받기 * * @param refreshRequest 토큰 갱신 요청 * @return AccessToken */ @PostMapping("/refresh") @ResponseStatus(HttpStatus.OK) public RefreshResponse getNewAccessToken( @RequestBody RefreshRequest refreshRequest ) { return this.authService.refreshAccessToken(refreshRequest); } }
27.055556
96
0.738535
fb488808badcf27ab9798ef54881af68c37bea59
3,543
package io.github.fablabsmc.fablabs.api.fiber.v1.schema.type; import java.math.BigDecimal; import java.util.Objects; import java.util.StringJoiner; import javax.annotation.Nullable; import io.github.fablabsmc.fablabs.api.fiber.v1.exception.ValueDeserializationException; import io.github.fablabsmc.fablabs.api.fiber.v1.serialization.TypeSerializer; import io.github.fablabsmc.fablabs.api.fiber.v1.serialization.ValueSerializer; import io.github.fablabsmc.fablabs.impl.fiber.constraint.DecimalConstraintChecker; /** * The {@link SerializableType} for numeric ranges. This type handles integral as well as real * and fractional ranges using Java's {@link BigDecimal} type. */ public final class DecimalSerializableType extends PlainSerializableType<BigDecimal> { /** * Specifies a numerical lower bound. * * <p>Values must be equal to or greater than the constraint's value to satisfy the constraint. */ @Nullable private final BigDecimal minimum; /** * Specifies a numerical upper bound. * * <p>Values must be equal to or lesser than the constraint's value to satisfy the constraint. */ @Nullable private final BigDecimal maximum; @Nullable private final BigDecimal increment; public DecimalSerializableType(@Nullable BigDecimal min, @Nullable BigDecimal max, @Nullable BigDecimal increment) { super(BigDecimal.class, DecimalConstraintChecker.instance()); if (min != null && max != null) { if (min.compareTo(max) > 0) { throw new IllegalArgumentException("Provided minimum " + min + " is greater than provided maximum " + max); } if (increment != null && max.subtract(min).compareTo(increment) < 0) { throw new IllegalArgumentException("Provided step " + increment + " is bigger than range [" + min + ", " + max + "]"); } } if (increment != null) { if (min == null) throw new IllegalStateException("A nonnull increment requires a minimum value"); if (increment.compareTo(BigDecimal.ZERO) <= 0) { throw new IllegalArgumentException("Increment cannot be negative (" + increment + ")"); } } this.minimum = min; this.maximum = max; this.increment = increment; } @Nullable public BigDecimal getMinimum() { return this.minimum; } @Nullable public BigDecimal getMaximum() { return this.maximum; } @Nullable public BigDecimal getIncrement() { return this.increment; } @Override public <S> void serialize(TypeSerializer<S> serializer, S target) { serializer.serialize(this, target); } @Override public <S> S serializeValue(BigDecimal value, ValueSerializer<S, ?> serializer) { return serializer.serializeNumber(value, this); } @Override public <S> BigDecimal deserializeValue(S elem, ValueSerializer<S, ?> serializer) throws ValueDeserializationException { return serializer.deserializeNumber(elem, this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; DecimalSerializableType that = (DecimalSerializableType) o; return Objects.equals(this.minimum, that.minimum) && Objects.equals(this.maximum, that.maximum) && Objects.equals(this.increment, that.increment); } @Override public int hashCode() { return Objects.hash(this.minimum, this.maximum, this.increment); } @Override public String toString() { return new StringJoiner(", ", DecimalSerializableType.class.getSimpleName() + "[", "]") .add("minimum=" + minimum) .add("maximum=" + maximum) .add("increment=" + increment) .toString(); } }
30.543103
122
0.726785
5f69a9cce035bee41fed5851d6933b7dea10c77d
8,913
/** * HpcCatalogDAOImpl.java * * <p> * Copyright SVG, Inc. Copyright Leidos Biomedical Research, Inc * * <p> * Distributed under the OSI-approved BSD 3-Clause License. See * http://ncip.github.com/HPC/LICENSE.txt for details. */ package gov.nih.nci.hpc.dao.oracle.impl; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.SingleColumnRowMapper; import org.springframework.util.StringUtils; import gov.nih.nci.hpc.dao.HpcReviewDAO; import gov.nih.nci.hpc.domain.error.HpcErrorType; import gov.nih.nci.hpc.domain.notification.HpcNotificationReview; import gov.nih.nci.hpc.domain.review.HpcReviewEntry; import gov.nih.nci.hpc.domain.user.HpcIntegratedSystem; import gov.nih.nci.hpc.exception.HpcException; /** * HPC Review DAO Implementation. * * @author <a href="mailto:yuri.dinh@nih.gov">Yuri Dinh</a> */ public class HpcReviewDAOImpl implements HpcReviewDAO { // ---------------------------------------------------------------------// // Constants // ---------------------------------------------------------------------// // SQL Queries. private static final String GET_REVIEW_CURATOR_EQUAL_SQL = " data_curator = ?"; private static final String GET_REVIEW_STATUS_EQUAL_SQL = " project_status = ?"; private static final String GET_REVIEW_END_SQL = " order by project_status, last_reviewed desc"; private static final String GET_REVIEW_SQL = "select id, path, project_title, project_description, " + "project_start_date, data_owner, data_curator, data_curator_name, project_status, publications, " + "deposition, sunset_date, retention_years, project_completed_date, last_reviewed " + ",review_sent ,reminder_sent " + "from r_review_meta_main "; private static final String GET_REVIEW_COUNT_SQL = "select count(id) from r_review_meta_main "; private static final String INSERT_REVIEW_NOTIFICATION_SQL = "insert into HPC_NOTIFICATION_REVIEW ( " + "USER_ID, EVENT_TYPE, DELIVERED) values (?, ?, ?)"; private static final String GET_CURATORS_FOR_REVIEW_SQL = "select distinct review.data_curator from R_REVIEW_META_MAIN review " + "left outer join HPC_NOTIFICATION_REVIEW notification " + "on review.data_curator=notification.USER_ID " + "where (review.project_status='Active' or review.project_status is null) " + "and (notification.EVENT_TYPE is null or notification.EVENT_TYPE='REVIEW_SENT') " + "group by review.data_curator " + "having trunc(max(notification.DELIVERED)) < add_months(sysdate,-12) or max(notification.DELIVERED) is null"; private static final String GET_CURATORS_FOR_REMINDER_SQL = "select distinct review.data_curator " + "from R_REVIEW_META_MAIN review left outer join HPC_NOTIFICATION_REVIEW notification " + "on review.data_curator=notification.USER_ID " + "where (review.project_status='Active' or review.project_status is null) " + "and notification.EVENT_TYPE='REVIEW_SENT' " + "group by review.data_curator, last_reviewed " + "having last_reviewed is null or max(notification.DELIVERED) > to_date(last_reviewed, 'YYYY-MM-DD')"; // ---------------------------------------------------------------------// // Instance members // ---------------------------------------------------------------------// // The Spring JDBC Template instance. @Autowired private JdbcTemplate jdbcTemplate = null; // Row mappers. private SingleColumnRowMapper<String> curatorRowMapper = new SingleColumnRowMapper<>(); private RowMapper<HpcReviewEntry> reviewEntryRowMapper = (rs, rowNum) -> { HpcReviewEntry reviewEntry = new HpcReviewEntry(); reviewEntry.setId(rs.getInt(1)); reviewEntry.setPath(rs.getString(2)); reviewEntry.setProjectTitle(rs.getString(3)); reviewEntry.setProjectDescription(rs.getString(4)); reviewEntry.setProjectStartDate(rs.getString(5)); reviewEntry.setDataOwner(rs.getString(6)); reviewEntry.setDataCurator(rs.getString(7)); reviewEntry.setDataCuratorName(rs.getString(8)); reviewEntry.setProjectStatus(rs.getString(9)); reviewEntry.setPublications(rs.getString(10)); reviewEntry.setDeposition(rs.getString(11)); reviewEntry.setSunsetDate(rs.getString(12)); reviewEntry.setRetentionYears(rs.getString(13)); reviewEntry.setProjectCompletedDate(rs.getString(14)); reviewEntry.setLastReviewed(rs.getString(15)); reviewEntry.setReviewSent(rs.getString(16)); reviewEntry.setReminderSent(rs.getString(17)); return reviewEntry; }; // ---------------------------------------------------------------------// // Constructors // ---------------------------------------------------------------------// /** Constructor for Spring Dependency Injection. */ private HpcReviewDAOImpl() { } // ---------------------------------------------------------------------// // Methods // ---------------------------------------------------------------------// // ---------------------------------------------------------------------// // HpcCatalogDAO Interface Implementation // ---------------------------------------------------------------------// @Override public List<HpcReviewEntry> getReview(String projectStatus, String dataCurator) throws HpcException { // Build the query based on provided search criteria. StringBuilder sqlQueryBuilder = new StringBuilder(); List<Object> args = new ArrayList<>(); sqlQueryBuilder.append(GET_REVIEW_SQL); if (!StringUtils.isEmpty(projectStatus)) { sqlQueryBuilder.append(" where "); sqlQueryBuilder.append(GET_REVIEW_STATUS_EQUAL_SQL); args.add(projectStatus); } if (!StringUtils.isEmpty(dataCurator)) { if (StringUtils.isEmpty(projectStatus)) sqlQueryBuilder.append(" where "); else sqlQueryBuilder.append(" and "); sqlQueryBuilder.append(GET_REVIEW_CURATOR_EQUAL_SQL); args.add(dataCurator); } sqlQueryBuilder.append(GET_REVIEW_END_SQL); try { return jdbcTemplate.query(sqlQueryBuilder.toString(), reviewEntryRowMapper, args.toArray()); } catch (IncorrectResultSizeDataAccessException irse) { return Collections.emptyList(); } catch (DataAccessException e) { throw new HpcException("Failed to get projects for review: " + e.getMessage(), HpcErrorType.DATABASE_ERROR, HpcIntegratedSystem.ORACLE, e); } } @Override public int getReviewCount(String projectStatus, String dataCurator) throws HpcException { // Build the query based on provided search criteria. StringBuilder sqlQueryBuilder = new StringBuilder(); List<Object> args = new ArrayList<>(); sqlQueryBuilder.append(GET_REVIEW_COUNT_SQL); sqlQueryBuilder.append(GET_REVIEW_SQL); if (!StringUtils.isEmpty(projectStatus)) { sqlQueryBuilder.append(" where "); sqlQueryBuilder.append(GET_REVIEW_STATUS_EQUAL_SQL); args.add(projectStatus); } if (!StringUtils.isEmpty(dataCurator)) { if (StringUtils.isEmpty(projectStatus)) sqlQueryBuilder.append(" where "); else sqlQueryBuilder.append(" and "); sqlQueryBuilder.append(GET_REVIEW_CURATOR_EQUAL_SQL); args.add(dataCurator); } try { return jdbcTemplate.queryForObject(sqlQueryBuilder.toString(), Integer.class, args.toArray()); } catch (DataAccessException e) { throw new HpcException("Failed to get count of projects for review: " + e.getMessage(), HpcErrorType.DATABASE_ERROR, HpcIntegratedSystem.ORACLE, e); } } @Override public void addReviewNotification(HpcNotificationReview reviewNotification) throws HpcException { try { jdbcTemplate.update(INSERT_REVIEW_NOTIFICATION_SQL, reviewNotification.getUserId(), reviewNotification.getEventType().value(), reviewNotification.getDelivered()); } catch (DataAccessException e) { throw new HpcException("Failed to add a review notification record: " + e.getMessage(), HpcErrorType.DATABASE_ERROR, HpcIntegratedSystem.ORACLE, e); } } @Override public List<String> getCuratorsForAnnualReview() throws HpcException { try { return jdbcTemplate.query(GET_CURATORS_FOR_REVIEW_SQL, curatorRowMapper); } catch (DataAccessException e) { throw new HpcException("Failed to get a list of curators to send annual review email: " + e.getMessage(), HpcErrorType.DATABASE_ERROR, HpcIntegratedSystem.ORACLE, e); } } @Override public List<String> getCuratorsForAnnualReviewReminder() throws HpcException { try { return jdbcTemplate.query(GET_CURATORS_FOR_REMINDER_SQL, curatorRowMapper); } catch (DataAccessException e) { throw new HpcException("Failed to get a list of curators to send annual review reminder email: " + e.getMessage(), HpcErrorType.DATABASE_ERROR, HpcIntegratedSystem.ORACLE, e); } } }
38.921397
129
0.703242
1374a0a68033b0d7eeb93f62ca2e54e3009086ca
276
package com.bit.juniornaver.model.dao; import java.util.List; import com.bit.juniornaver.model.vo.CharacterBean; public interface CharacterMapper { public List<CharacterBean> listCharacter(int menuId); public CharacterBean getCharacter(int characterId); }
21.230769
55
0.771739
e2b20f8d43d03d6e2da90d5fed905d6278707c59
1,229
package com.quanlt.vietcomicclean.domain.interactor; import com.quanlt.vietcomicclean.domain.executor.PostExecutionThread; import com.quanlt.vietcomicclean.domain.executor.ThreadExecutor; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.schedulers.Schedulers; import rx.subscriptions.Subscriptions; public abstract class UseCase { private final ThreadExecutor threadExecutor; private final PostExecutionThread postExecutionThread; private Subscription subscription = Subscriptions.empty(); public UseCase(ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread) { this.threadExecutor = threadExecutor; this.postExecutionThread = postExecutionThread; } protected abstract Observable buildUseCaseObservable(); public void execute(Subscriber useCaseSubscriber) { this.subscription = this.buildUseCaseObservable() .subscribeOn(Schedulers.from(threadExecutor)) .observeOn(postExecutionThread.getScheduler()) .subscribe(useCaseSubscriber); } public void unsubscribe() { if (!subscription.isUnsubscribed()) { subscription.unsubscribe(); } } }
31.512821
92
0.74288
6d3827f3a636574769b9e4278990cb28887d1c00
4,710
package com.vimukti.accounter.web.client.ui.vat; import java.util.ArrayList; import java.util.List; import com.vimukti.accounter.web.client.AccounterAsyncCallback; import com.vimukti.accounter.web.client.core.ClientFinanceDate; import com.vimukti.accounter.web.client.core.ClientTDSChalanDetail; import com.vimukti.accounter.web.client.core.IAccounterCore; import com.vimukti.accounter.web.client.exception.AccounterException; import com.vimukti.accounter.web.client.ui.Accounter; import com.vimukti.accounter.web.client.ui.StyledPanel; import com.vimukti.accounter.web.client.ui.UIUtils; import com.vimukti.accounter.web.client.ui.core.BaseView; import com.vimukti.accounter.web.client.ui.core.ButtonBar; import com.vimukti.accounter.web.client.ui.core.CancelButton; import com.vimukti.accounter.web.client.ui.forms.DynamicForm; import com.vimukti.accounter.web.client.ui.forms.LabelItem; public class TDSFiledDetailsView extends BaseView { int formType; String ackNo; int financialYearStart; int financialYearEnd; int quater; long dateOfFiled; LabelItem formNoLabel; LabelItem ackNoLabel; LabelItem dateOfFiledLabel; LabelItem financialYearLabel; LabelItem assesmentYearLabel; LabelItem quaterLabel; StyledPanel mainPanel = new StyledPanel("mainPanel"); public TDSFiledDetailsView(int formType, String ackNo, int financialYearStart, int financialYearEnd, int quater, long dateOfFiled) { super(); this.formType = formType; this.ackNo = ackNo; this.financialYearStart = financialYearStart; this.financialYearEnd = financialYearEnd; this.quater = quater; this.dateOfFiled = dateOfFiled; } @Override public void init() { super.init(); this.getElement().setId("TDSFiledDetailsView"); createControls(); // setSize("100%", "100%"); } @Override public void initData() { Accounter.createHomeService().getTDSChallansForAckNo(ackNo, new AccounterAsyncCallback<ArrayList<ClientTDSChalanDetail>>() { @Override public void onException(AccounterException exception) { // TODO Auto-generated method stub } @Override public void onResultSuccess( ArrayList<ClientTDSChalanDetail> result) { if (result != null) { showItems(result); } } }); } protected void showItems(ArrayList<ClientTDSChalanDetail> challans) { for (ClientTDSChalanDetail challan : challans) { StyledPanel panel = new StyledPanel("panel"); panel.add(new TDSChallanItem(challan)); mainPanel.add(panel); } } private void createControls() { formNoLabel = new LabelItem(getFormTypes().get(formType - 1), "formnolabel"); ackNoLabel = new LabelItem(messages.acknowledgmentNo(), "ackNoLabel"); ackNoLabel.setValue(ackNo); dateOfFiledLabel = new LabelItem(messages.dateOfFiled(), "dateOfFiledLabel"); dateOfFiledLabel.setValue(UIUtils .getDateByCompanyType(new ClientFinanceDate(dateOfFiled))); financialYearLabel = new LabelItem(messages.financialYear(), "financialYearLabel"); financialYearLabel.setValue(Integer.toString(financialYearStart) + "-" + Integer.toString(financialYearEnd)); assesmentYearLabel = new LabelItem(messages.assessmentYear(), "assesmentYearLabel"); assesmentYearLabel.setValue(Integer.toString(financialYearStart + 1) + "-" + Integer.toString(financialYearEnd + 1)); quaterLabel = new LabelItem(messages.period(), "quaterLabel"); quaterLabel .setValue((String) getFinancialQuatersList().get(quater - 1)); DynamicForm filedForm = new DynamicForm("filedForm"); filedForm.add(ackNoLabel, dateOfFiledLabel, financialYearLabel, assesmentYearLabel, quaterLabel); mainPanel.add(formNoLabel.getMainWidget()); mainPanel.add(filedForm); this.add(mainPanel); } private List<String> getFormTypes() { ArrayList<String> list = new ArrayList<String>(); list.add(messages.form26Q()); list.add(messages.form27Q()); list.add(messages.form27EQ()); return list; } @Override public void deleteFailed(AccounterException caught) { // TODO Auto-generated method stub } @Override public void deleteSuccess(IAccounterCore result) { // TODO Auto-generated method stub } @Override protected String getViewTitle() { return messages.tdsFiledDetails(); } @Override public List getForms() { // TODO Auto-generated method stub return null; } @Override public void setFocus() { // TODO Auto-generated method stub } @Override protected void createButtons() { this.cancelButton = new CancelButton(this); addButton(cancelButton); } }
28.545455
73
0.728025
9fdcbc6ebf6baec6223f06b98388656bd039900e
27,632
package fi.nls.oskari.work; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.pojo.*; import fi.nls.oskari.wfs.WFSImage; import fi.nls.oskari.wfs.pojo.WFSLayerStore; import fi.nls.oskari.worker.AbstractJob; import org.geotools.feature.FeatureCollection; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.operation.MathTransform; import java.awt.image.BufferedImage; import java.util.*; /** * Job for WFS Map Layer */ public abstract class OWSMapLayerJob extends AbstractJob<String> { public static final String STATUS_CANCELED = "canceled"; protected static final Logger log = LogFactory .getLogger(OWSMapLayerJob.class); protected static Set<String> excludedProperties = new HashSet<String>(); static { excludedProperties.add("metaDataProperty"); excludedProperties.add("description"); excludedProperties.add("name"); excludedProperties.add("boundedBy"); excludedProperties.add("location"); } public static final String OUTPUT_LAYER_ID = "layerId"; public static final String OUTPUT_ONCE = "once"; public static final String OUTPUT_MESSAGE = "message"; public static final String OUTPUT_FEATURES = "features"; public static final String OUTPUT_GEOMETRIES = "geometries"; public static final String OUTPUT_FEATURE = "feature"; public static final String OUTPUT_FIELDS = "fields"; public static final String OUTPUT_LOCALES = "locales"; public static final String OUTPUT_KEEP_PREVIOUS = "keepPrevious"; public static final String OUTPUT_STYLE = "style"; public static final String OUTPUT_IMAGE_SRS = "srs"; public static final String OUTPUT_IMAGE_BBOX = "bbox"; public static final String OUTPUT_IMAGE_ZOOM = "zoom"; public static final String OUTPUT_IMAGE_TYPE = "type"; public static final String OUTPUT_IMAGE_WIDTH = "width"; public static final String OUTPUT_IMAGE_HEIGHT = "height"; public static final String OUTPUT_IMAGE_URL = "url"; public static final String OUTPUT_IMAGE_DATA = "data"; public static final String OUTPUT_BOUNDARY_TILE = "boundaryTile"; public static final String BROWSER_MSIE = "msie"; public static final String PROCESS_STARTED = "Started"; public static final String PROCESS_ENDED = "Ended"; public static final String DEFAULT_FE_SLD_STYLE_PATH ="/fi/nls/oskari/fe/output/style/default/default_fe_sld_"; // process information protected ResultProcessor service; protected SessionStore session; protected Layer sessionLayer; protected WFSLayerPermissionsStore permissions; protected String layerId; protected WFSLayerStore layer; protected boolean layerPermission; protected boolean reqSendFeatures; protected boolean reqSendImage; protected boolean reqSendHighlight; protected boolean sendFeatures; protected boolean sendImage; protected boolean sendHighlight; protected MathTransform transformService; protected MathTransform transformClient; protected JobType type; protected FeatureCollection<SimpleFeatureType, SimpleFeature> features; protected List<String> processedFIDs = new ArrayList<String>(); protected List<List<Object>> featureValuesList; protected List<List<Object>> geomValuesList; protected WFSImage image = null; protected static final List<List<Object>> EMPTY_LIST = new ArrayList(); /** * Creates a new runnable job with own Jedis instance * * Parameters define client's service (communication channel), session and * layer's id. Sends all resources that the layer configuration allows. * * @param service * @param store * @param layer */ public OWSMapLayerJob(ResultProcessor service, JobType type, SessionStore store, WFSLayerStore layer) { this(service, type, store, layer, true, true, true); } /** * Creates a new runnable job with own Jedis instance * * Parameters define client's service (communication channel), session and * layer's id. Also sets resources that will be sent if the layer * configuration allows. * * @param service * @param store * @param reqSendFeatures * @param reqSendImage * @param reqSendHighlight */ public OWSMapLayerJob(ResultProcessor service, JobType type, SessionStore store, WFSLayerStore layer, boolean reqSendFeatures, boolean reqSendImage, boolean reqSendHighlight) { this.service = service; this.type = type; this.session = store; this.layer = layer; this.layerId = layer.getLayerId(); this.sessionLayer = this.session.getLayers().get(this.layerId); this.permissions = null; this.layerPermission = false; this.reqSendFeatures = reqSendFeatures; this.reqSendImage = reqSendImage; this.reqSendHighlight = reqSendHighlight; this.transformService = null; this.transformClient = null; } public String getSessionId() { return this.session.getSession(); } public String getRoute() { return this.session.getRoute(); } public JobType getType() { return type; } public String getLayerId() { return layerId; } /** * Releases all when removed */ @Override protected void finalize() throws Throwable { super.finalize(); } /** * Unique key definition */ @Override public String getKey() { return this.getClass().getSimpleName() + "_" + this.session.getClient() + "_" + this.layerId + "_" + this.type; } /** * Process of the job * * Worker calls this when starts the job. * */ public String run() { log.debug(PROCESS_STARTED + " " + getKey()); setResourceSending(); // if different SRS, create transforms for geometries if(!this.session.getLocation().getSrs().equals(this.layer.getSRSName())) { this.transformService = this.session.getLocation().getTransformForService(this.layer.getCrs(), true); this.transformClient = this.session.getLocation().getTransformForClient(this.layer.getCrs(), true); } // check that the job isn't canceled if (!goNext()) { log.debug("[fe] Cancelled"); return STATUS_CANCELED; } // run job specific tasks boolean completed = runRequestedJob(); if(!completed) { log.debug("[fe] Cancelled"); return STATUS_CANCELED; } log.debug("[fe] " + PROCESS_ENDED + " " + getKey()); return "success"; } private boolean runRequestedJob() { // tiles for grid if (this.type == JobType.NORMAL) { return runNormalJob(); } else if (this.type == JobType.HIGHLIGHT) { return runHighlightJob(); } else if (this.type == JobType.MAP_CLICK) { return runMapClickJob(); } else if (this.type == JobType.GEOJSON) { return runGeoJSONJob(); } else if (this.type == JobType.PROPERTY_FILTER) { return runPropertyFilterJob(); } return runUnknownJob(); } public boolean runNormalJob() { // make single request if (!this.layer.isTileRequest()) { log.debug("single request"); if (!this.normalHandlers(null, true)) { log.debug("!normalHandlers leaving"); return false; } else { log.debug("single request - continue"); } } else { log.debug("MAKING TILED REQUESTS"); } log.debug("normal tile images handling"); // init enlarged envelope List<List<Double>> grid = this.session.getGrid().getBounds(); if (grid.size() > 0) { this.session.getLocation().setEnlargedEnvelope(grid.get(0)); } boolean first = true; int index = 0; for(List<Double> bounds : grid) { if (!goNext()) { return false; } log.debug("Tile bounds:", bounds); // make a request per tile if(this.layer.isTileRequest()) { if(!this.normalHandlers(bounds, first)) { continue; } } if(!goNext()) { return false; } boolean isThisTileNeeded = true; if (!this.sendImage) { log.debug("[fe] !sendImage - not sending PNG"); isThisTileNeeded = false; } if (!this.sessionLayer.isTile(bounds)) { log.debug("[fe] !layer.isTile - not sending PNG"); isThisTileNeeded = false; } if (isThisTileNeeded) { Double[] bbox = bounds.toArray(new Double[4]); // get from cache BufferedImage bufferedImage = getImageCache(bbox); boolean isboundaryTile = this.session.getGrid().isBoundsOnBoundary2(this.session.getLocation(), bbox); if(bufferedImage == null) { if(this.image == null) { this.image = createResponseImage(); } bufferedImage = this.image.draw(this.session.getTileSize(), this.session.getLocation(), bounds, this.features); if(bufferedImage == null) { this.imageParsingFailed(); throw new RuntimeException("Image parsing failed!"); } // setup cachekey String cacheStyleName = this.session.getLayers().get(this.layerId).getStyleName(); if (cacheStyleName.startsWith(WFSImage.PREFIX_CUSTOM_STYLE)) { cacheStyleName += "_" + this.session.getSession(); } // save to cache setImageCache(bufferedImage, cacheStyleName, bbox, !isboundaryTile); } String url = createImageURL(this.session.getLayers().get(this.layerId).getStyleName(), bbox); this.sendWFSImage(url, bufferedImage, bbox, true, isboundaryTile); } else { log.debug("Tile not needed?", bounds); } if (first) { first = false; // keep the next tiles this.session.setKeepPrevious(true); } index++; } return true; } public boolean runHighlightJob() { if(!this.sendHighlight) { // highlight job with a flag for not sending images, what is going on in here? return true; } if(!this.requestHandler(null)) { return false; } this.featuresHandler(); if (!goNext()) { return false; } // Send geometries, if requested as well if(this.session.isGeomRequest()){ this.sendWFSFeatureGeometries(this.geomValuesList, ResultProcessor.CHANNEL_FEATURE_GEOMETRIES); } log.debug("highlight image handling", this.features.size()); // IMAGE HANDLING log.debug("sending"); Location location = this.session.getLocation(); if(this.image == null) { this.image = new WFSImage(this.layer, this.session.getClient(), this.session.getLayers().get(this.layerId).getStyleName(), JobType.HIGHLIGHT.toString()); } BufferedImage bufferedImage = this.image.draw(this.session.getMapSize(), location, this.features); if(bufferedImage == null) { this.imageParsingFailed(); throw new RuntimeException("Image parsing failed!"); } Double[] bbox = location.getBboxArray(); // cache (non-persistant) setImageCache(bufferedImage, JobType.HIGHLIGHT.toString() + "_" + this.session.getSession(), bbox, false); String url = createImageURL(JobType.HIGHLIGHT.toString(), bbox); this.sendWFSImage(url, bufferedImage, bbox, false, false); return true; } public boolean runMapClickJob() { if (!this.requestHandler(null)) { // success, just no hits this.sendWFSFeatures(EMPTY_LIST, ResultProcessor.CHANNEL_MAP_CLICK); return true; } this.featuresHandler(); if (!goNext()) { return false; } // features if (this.sendFeatures) { log.debug("Feature values list", this.featureValuesList); this.sendWFSFeatures(this.featureValuesList, ResultProcessor.CHANNEL_MAP_CLICK); } else { log.debug("No feature data!"); this.sendWFSFeatures(EMPTY_LIST, ResultProcessor.CHANNEL_MAP_CLICK); } return true; } public boolean runGeoJSONJob() { if (!this.requestHandler(null)) { return false; } this.featuresHandler(); if (!goNext()) { return false; } if (this.sendFeatures) { this.sendWFSFeatures(this.featureValuesList, ResultProcessor.CHANNEL_FILTER); } return true; } public boolean runPropertyFilterJob() { // should be same functionality return runGeoJSONJob(); } public boolean runUnknownJob() { log.debug("Type is not handled " + this.type); return true; } /** * Wrapper for normal type job's handlers */ protected boolean normalHandlers(List<Double> bounds, boolean first) { if(!this.requestHandler(bounds)) { log.debug("Cancelled by request handler"); return false; } if(first) { propertiesHandler(); if(!goNext()) { return false; } } if(!goNext()) { return false; } this.featuresHandler(); if(!goNext()) { return false; } return true; } /** * Makes request and parses response to features * * @param bounds * @return <code>true</code> if thread should continue; <code>false</code> * otherwise. */ /** * Makes request and parses response to features * * @param bounds * @return <code>true</code> if thread should continue; <code>false</code> * otherwise. */ protected abstract boolean requestHandler(List<Double> bounds) ; /** * Parses features properties and sends to appropriate channels */ protected abstract void propertiesHandler() ; /** * Parses features values */ protected abstract void featuresHandler() ; /** * Send image parsing error */ protected void imageParsingFailed() { imageParsingFailed(ResultProcessor.ERROR_WFS_IMAGE_PARSING); } /** * Send image parsing error */ protected void imageParsingFailed(final String message) { log.debug("Image parsing failed"); Map<String, Object> output = new HashMap<String, Object>(); output.put(OUTPUT_LAYER_ID, this.layerId); output.put(OUTPUT_ONCE, true); output.put(OUTPUT_MESSAGE, message); this.service.addResults(session.getClient(), ResultProcessor.CHANNEL_ERROR, output); } /** * Sets which resources will be sent (features, image) */ protected void setResourceSending() { // layer configuration is the default this.sendFeatures = layer.isGetFeatureInfo(); this.sendImage = layer.isGetMapTiles(); this.sendHighlight = layer.isGetHighlightImage(); // if request defines false and layer configuration allows if(!this.reqSendFeatures && this.sendFeatures) this.sendFeatures = false; if(!this.reqSendImage && this.sendImage) this.sendImage = false; if(!this.reqSendHighlight && this.sendHighlight) this.sendHighlight = false; log.debug("send - features:", this.sendFeatures, "image:", this.sendImage, "highlight:", this.sendHighlight); } /** * Checks if the map scale is valid * * @return <code>true</code> if map scale is valid; * <code>false</code> otherwise. */ protected boolean validateMapScales() { return JobHelper.isRequestScalesInRange( this.session.getMapScales(), (int) this.session.getLocation().getZoom(), layer, session.getLocation().getSrs()); } /** * Checks if enough information for running the task type * * @return <code>true</code> if enough information for type; * <code>false</code> otherwise. */ public boolean hasValidParams() { if(this.type == JobType.HIGHLIGHT) { if(this.sessionLayer.getHighlightedFeatureIds() != null && this.sessionLayer.getHighlightedFeatureIds().size() > 0) { return true; } } else if(this.type == JobType.MAP_CLICK) { if(session.getMapClick() != null) { return true; } } else if(this.type == JobType.GEOJSON) { if(session.getFilter() != null) { return true; } } else if(this.type == JobType.PROPERTY_FILTER) { if(session.getPropertyFilter() != null) { return true; } } else if(this.type == JobType.NORMAL) { return true; } return false; } /** * Creates image url * * @param style * @param bbox */ protected String createImageURL(final String style, Double[] bbox) { return "/image" + "?" + OUTPUT_LAYER_ID + "=" + this.layerId + "&" + OUTPUT_STYLE + "=" + style + "&" + OUTPUT_IMAGE_SRS + "=" + this.session.getLocation().getSrs() + "&" + OUTPUT_IMAGE_BBOX + "=" + bbox[0] + "," + bbox[1] + "," + bbox[2] + "," + bbox[3] + "&" + OUTPUT_IMAGE_ZOOM + "=" + this.session.getLocation().getZoom(); } /** * Sends properties (fields and locales) * * @param fields * @param locales */ protected void sendWFSProperties(List<String> fields, List<String> locales) { if(fields == null || fields.size() == 0) { log.warn("Failed to send properties"); return; } if(!fields.contains("__fid")) fields.add(0, "__fid"); if(!fields.contains("__centerX"))fields.add("__centerX"); if(!fields.contains("__centerY"))fields.add("__centerY"); if(locales != null && !locales.isEmpty()) { locales.add(0, "ID"); locales.add("x"); locales.add("y"); } else { locales = new ArrayList<String>(); } Map<String, Object> output = new HashMap<String, Object>(); output.put(OUTPUT_LAYER_ID, this.layerId); output.put(OUTPUT_FIELDS, fields); output.put(OUTPUT_LOCALES, locales); this.service.addResults(this.session.getClient(), ResultProcessor.CHANNEL_PROPERTIES, output); } /** * Sends one feature * * @param values */ protected void sendWFSFeature(List<Object> values) { if(values == null || values.size() == 0) { log.warn("Failed to send feature"); return; } Map<String, Object> output = new HashMap<String, Object>(); output.put(OUTPUT_LAYER_ID, this.layerId); output.put(OUTPUT_FEATURE, values); this.service.addResults(this.session.getClient(), ResultProcessor.CHANNEL_FEATURE, output); } /** * Sends list of features * * @param features * @param channel */ protected void sendWFSFeatures(List<List<Object>> features, String channel) { if (features == null || features.size() == 0) { log.debug("No features to Send"); return; } log.debug("#### Sending " + features.size() + " FEATURES"); Map<String, Object> output = new HashMap<String, Object>(); output.put(OUTPUT_LAYER_ID, this.layerId); output.put(OUTPUT_FEATURES, features); if (channel.equals(ResultProcessor.CHANNEL_MAP_CLICK) || channel.equals(ResultProcessor.CHANNEL_FILTER)) { output.put(OUTPUT_KEEP_PREVIOUS, this.session.isKeepPrevious()); } log.debug("Sending", features.size(), "features"); this.service.addResults(this.session.getClient(), channel, output); } /** * Sends image as an URL to IE 8 & 9, base64 data for others * * @param url * @param bufferedImage * @param bbox * @param isTiled */ protected void sendWFSImage(String url, BufferedImage bufferedImage, Double[] bbox, boolean isTiled, boolean isboundaryTile) { if(bufferedImage == null) { log.warn("Failed to send image"); return; } Map<String, Object> output = new HashMap<String, Object>(); output.put(OUTPUT_LAYER_ID, this.layerId); Location location = this.session.getLocation(); Tile tileSize = null; if(isTiled) { tileSize = this.session.getTileSize(); } else { tileSize = this.session.getMapSize(); } output.put(OUTPUT_IMAGE_SRS, location.getSrs()); output.put(OUTPUT_IMAGE_BBOX, bbox); output.put(OUTPUT_IMAGE_ZOOM, location.getZoom()); output.put(OUTPUT_IMAGE_TYPE, this.type.toString()); // "normal" | "highlight" output.put(OUTPUT_KEEP_PREVIOUS, this.session.isKeepPrevious()); output.put(OUTPUT_BOUNDARY_TILE, isboundaryTile); output.put(OUTPUT_IMAGE_WIDTH, tileSize.getWidth()); output.put(OUTPUT_IMAGE_HEIGHT, tileSize.getHeight()); output.put(OUTPUT_IMAGE_URL, url); byte[] byteImage = WFSImage.imageToBytes(bufferedImage); String base64Image = WFSImage.bytesToBase64(byteImage); int base64Size = (base64Image.length()*2)/1024; // IE6 & IE7 doesn't support base64, max size in base64 for IE8 is 32KB if(!(this.session.getBrowser().equals(BROWSER_MSIE) && this.session.getBrowserVersion() < 8 || this.session.getBrowser().equals(BROWSER_MSIE) && this.session.getBrowserVersion() == 8 && base64Size >= 32)) { output.put(OUTPUT_IMAGE_DATA, base64Image); } this.service.addResults(this.session.getClient(), ResultProcessor.CHANNEL_IMAGE, output); } /** * Sends list of feature geometries * * @param geometries * @param channel */ protected void sendWFSFeatureGeometries(List<List<Object>> geometries, String channel) { if(geometries == null || geometries.size() == 0) { log.warn("Failed to send feature geometries"); return; } Map<String, Object> output = new HashMap<String, Object>(); output.put(OUTPUT_LAYER_ID, this.layerId); output.put(OUTPUT_GEOMETRIES, geometries); output.put(OUTPUT_KEEP_PREVIOUS, this.session.isKeepPrevious()); log.debug("Sending", geometries.size(), "geometries"); this.service.addResults(this.session.getClient(), channel, output); } public abstract RequestResponse request(JobType type, WFSLayerStore layer, SessionStore session, List<Double> bounds, MathTransform transformService); public abstract FeatureCollection<SimpleFeatureType, SimpleFeature> response( WFSLayerStore layer, RequestResponse response); /** * Gets image from cache * * @param bbox */ protected BufferedImage getImageCache(Double[] bbox) { return WFSImage.getCache( this.layerId, this.session.getLayers().get(this.layerId).getStyleName(), this.session.getLocation().getSrs(), bbox, this.session.getLocation().getZoom() ); } /** * Sets image to cache * * @param bufferedImage * @param style * @param bbox * @param persistent */ protected void setImageCache(BufferedImage bufferedImage, final String style, Double[] bbox, boolean persistent) { WFSImage.setCache(bufferedImage, this.layerId, style, this.session .getLocation().getSrs(), bbox, this.session.getLocation() .getZoom(), persistent); } protected WFSImage createResponseImage() { return new WFSImage(this.layer, this.session.getClient(), this.session .getLayers().get(this.layerId).getStyleName(), null); } protected WFSImage createHighlightImage() { return new WFSImage(this.layer, this.session.getClient(), this.session .getLayers().get(this.layerId).getStyleName(), JobType.HIGHLIGHT.toString()); } public void sendCommonErrorResponse(final String message, final boolean once) { Map<String, Object> output = createCommonResponse(message); if(once) { output.put(OUTPUT_ONCE, once); } this.service.addResults(session.getClient(), ResultProcessor.CHANNEL_ERROR, output); } public Map<String, Object> createCommonResponse(final String message) { Map<String, Object> output = createCommonResponse(); output.put(OUTPUT_MESSAGE, message); return output; } public Map<String, Object> createCommonResponse() { Map<String, Object> output = new HashMap<String, Object>(); output.put(OUTPUT_LAYER_ID, this.layerId); return output; } public void notifyError() { notifyError(null); } public void notifyError(String error) { if (error == null) { error = "Something went wrong"; } log.error("On Error - layer:", layerId, "type:", type, "msg:", error); Map<String, Object> output = createCommonResponse(error); output.put("type", type.toString()); this.service.addResults(session.getClient(), ResultProcessor.CHANNEL_ERROR, output); } public void notifyStart() { log.info("On start - layer:", layerId, "type:", type); this.service.addResults(session.getClient(), ResultProcessor.CHANNEL_STATUS, createCommonResponse("started")); } public void notifyCompleted(final boolean success) { log.info("Completed - layer:", layerId, "type:", type, "success:", success); Map<String, Object> output = createCommonResponse("completed"); output.put("success", success); output.put("type", type.toString()); this.service.addResults(session.getClient(), ResultProcessor.CHANNEL_STATUS, output); } }
34.19802
130
0.592248
4c93d83d13c5ba11d577abea11da2b911eeba374
3,433
/** * Copyright (C) 2006-2021 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.talend.sdk.component.singer.kitap; import static java.util.Collections.emptyMap; import static java.util.Collections.singleton; import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.charset.StandardCharsets; import java.time.ZoneId; import java.time.ZonedDateTime; import javax.json.Json; import javax.json.JsonObject; import org.junit.jupiter.api.Test; import org.talend.sdk.component.api.record.Schema; import org.talend.sdk.component.api.service.record.RecordBuilderFactory; import org.talend.sdk.component.runtime.record.RecordBuilderFactoryImpl; import org.talend.sdk.component.singer.java.IO; import org.talend.sdk.component.singer.java.Singer; class RecordJsonMapperTest { private final RecordBuilderFactory factory = new RecordBuilderFactoryImpl(null); @Test void map() { final JsonObject object = new RecordJsonMapper(Json.createBuilderFactory(emptyMap()), new Singer(new IO(), ZonedDateTime::now)) .apply(factory .newRecordBuilder() .withString("name", "hello") .withInt("age", 1) .withBoolean("toggle", true) .withDateTime("date", ZonedDateTime.of(2019, 8, 23, 16, 31, 0, 0, ZoneId.of("UTC"))) .withLong("lg", 2L) .withBytes("bytes", "test".getBytes(StandardCharsets.UTF_8)) .withRecord("nested", factory .newRecordBuilder() .withString("value", "set") .withRecord("nested2", factory.newRecordBuilder().withInt("l2", 2).build()) .build()) .withArray(factory .newEntryBuilder() .withType(Schema.Type.ARRAY) .withName("array") .withElementSchema(factory.newSchemaBuilder(Schema.Type.STRING).build()) .build(), singleton("value-from-array")) .build()); assertEquals("{" + "\"name\":\"hello\"," + "\"age\":1," + "\"toggle\":true," + "\"date\":\"2019-08-23T16:31:00.000Z\"," + "\"lg\":2," + "\"bytes\":\"dGVzdA==\"," + "\"array\":[\"value-from-array\"]," + "\"nested\":{\"value\":\"set\",\"nested2\":{\"l2\":2}}}", object.toString()); } }
47.680556
117
0.535683
55ce3b4bb5620e4d969a9a410405216d805b3cf7
311
package ec.edu.ups.dao; import java.util.List; public interface GenericDAO<T, ID> { public void create(T entity); public T read(ID id); public void update(T entity); public void delete(T entity); public void deleteByID(ID id); public List<T> findAll(); }
15.55
37
0.610932
107eb08c0e480c21ef8e03ce0e30809bb7c26221
1,261
package com.openwebserver.core.Connection; import ByteReader.ByteReader; import java.io.IOException; import java.net.Socket; public class Connection extends ByteReader implements ConnectionWriter { protected Thread handler; private final Socket socket; public Connection(Socket socket) throws IOException { super(socket.getInputStream()); this.socket = socket; ConnectionManager.register(this); } public void close(){ if(!socket.isClosed()){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } ConnectionManager.close(this); } public boolean isConnected() { return socket.isConnected(); } public Socket getSocket() { return socket; } public String getAddress(){ return getSocket().getInetAddress().toString(); } public int getPort(){ return getSocket().getPort(); } public int getLocalPort(){ return getSocket().getLocalPort(); } public String getConnectionString() { return getAddress() + ":"+ getPort(); } @Override public Connection getConnection() { return this; } }
21.372881
72
0.602696
9055ca8c59bdf8931be9b32b4dfdcf4f44e664f9
1,160
/* * */ package com.synectiks.process.common.plugins.pipelineprocessor.processors.listeners; import com.synectiks.process.common.plugins.pipelineprocessor.ast.Pipeline; import com.synectiks.process.common.plugins.pipelineprocessor.ast.Rule; import com.synectiks.process.common.plugins.pipelineprocessor.ast.Stage; import com.synectiks.process.server.plugin.Message; import java.util.Set; public interface InterpreterListener { void startProcessing(); void finishProcessing(); void processStreams(Message message, Set<Pipeline> pipelines, Set<String> streams); void enterStage(Stage stage); void exitStage(Stage stage); void evaluateRule(Rule rule, Pipeline pipeline); void failEvaluateRule(Rule rule, Pipeline pipeline); void satisfyRule(Rule rule, Pipeline pipeline); void dissatisfyRule(Rule rule, Pipeline pipeline); void executeRule(Rule rule, Pipeline pipeline); void finishExecuteRule(Rule rule, Pipeline pipeline); void failExecuteRule(Rule rule, Pipeline pipeline); void continuePipelineExecution(Pipeline pipeline, Stage stage); void stopPipelineExecution(Pipeline pipeline, Stage stage); }
41.428571
87
0.787069
2c3f3baed4d959430e4b433312362f352e8987e4
47
private long nl() { return in.nextLong(); }
15.666667
25
0.617021
95fd731cb22453ba09f233e4061865cb46c3c499
1,256
package com.senla.autoservice.repository; import java.util.Arrays; import com.senla.autoservice.bean.Work; import com.senla.autoservice.utills.ArrayChecker; public class WorkList { private Work[] serviceList; static private int lastID; public WorkList(int size) { serviceList = new Work[size]; } public WorkList(Work[] list) { serviceList = list; } public Work[] getListOfServices() { return serviceList; } static public int getLastID() { return lastID; } public Work getService(int id) { for (int i = 0; i < serviceList.length; i++) { if (serviceList[i].getId() == id) { return serviceList[i]; } } return null; } public Work findById(Integer id) { for (Work entity : serviceList) { if (entity == null) { break; } if (entity.getId() == id) { return entity; } } return null; } public Boolean add(Work obj) { if (!ArrayChecker.isFreeId(obj.getId(), serviceList)) { return false; } if (!ArrayChecker.isEnoughtSpace(serviceList)) { serviceList = Arrays.copyOf(ArrayChecker.resize(serviceList), serviceList.length * 2, Work[].class); } Integer position = ArrayChecker.getFreePosition(serviceList); lastID = position; serviceList[position] = obj; return true; } }
20.258065
103
0.67914
5abafcc46d0b11c53c06a0bc0fffb6cbdde5f8fc
941
package com.bapplications.maplemobile.utils; public class Color { public static final int RED = android.graphics.Color.argb(255, 255, 0, 0); public static final int GREEN = android.graphics.Color.argb(255, 0, 255, 0); public static final int BLUE = android.graphics.Color.argb(255, 0, 0, 255); private final float a; private final float r; private final float g; private final float b; private int color; public Color(float R, float G, float B, float A){ color = android.graphics.Color.argb(A, R, G, B); r = R; g = G; b = B; a = A; } public static int alpha(int color) { return android.graphics.Color.alpha(color); } public int getEnc(){ return color; } public int alpha() { return (color >> 24) & 0xff; } public Color mul(Color o) { return new Color(r * o.r, g * o.g, b * o.b, a * o.a); } }
26.138889
80
0.587673
a060c0daebaf85af41bb6e618b44eec0d4e98043
12,697
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.hdinsight.v2018_06_01_preview; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * The details of metric specifications. */ public class MetricSpecifications { /** * The name of the metric specification. */ @JsonProperty(value = "name") private String name; /** * The display name of the metric specification. */ @JsonProperty(value = "displayName") private String displayName; /** * The display description of the metric specification. */ @JsonProperty(value = "displayDescription") private String displayDescription; /** * The unit of the metric specification. */ @JsonProperty(value = "unit") private String unit; /** * The aggregation type of the metric specification. */ @JsonProperty(value = "aggregationType") private String aggregationType; /** * The supported aggregation types of the metric specification. */ @JsonProperty(value = "supportedAggregationTypes") private List<String> supportedAggregationTypes; /** * The supported time grain types of the metric specification. */ @JsonProperty(value = "supportedTimeGrainTypes") private List<String> supportedTimeGrainTypes; /** * The flag indicates whether enable regional mdm account or not. */ @JsonProperty(value = "enableRegionalMdmAccount") private Boolean enableRegionalMdmAccount; /** * The source mdm account. */ @JsonProperty(value = "sourceMdmAccount") private String sourceMdmAccount; /** * The source mdm namespace. */ @JsonProperty(value = "sourceMdmNamespace") private String sourceMdmNamespace; /** * The metric filter pattern. */ @JsonProperty(value = "metricFilterPattern") private String metricFilterPattern; /** * The flag indicates whether filling gap with zero. */ @JsonProperty(value = "fillGapWithZero") private Boolean fillGapWithZero; /** * The category of the metric. */ @JsonProperty(value = "category") private String category; /** * The override name of resource id dimension name. */ @JsonProperty(value = "resourceIdDimensionNameOverride") private String resourceIdDimensionNameOverride; /** * The flag indicates whether the metric is internal or not. */ @JsonProperty(value = "isInternal") private Boolean isInternal; /** * The override name of delegate metric. */ @JsonProperty(value = "delegateMetricNameOverride") private String delegateMetricNameOverride; /** * The dimensions of the metric specification. */ @JsonProperty(value = "dimensions") private List<Dimension> dimensions; /** * Get the name of the metric specification. * * @return the name value */ public String name() { return this.name; } /** * Set the name of the metric specification. * * @param name the name value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withName(String name) { this.name = name; return this; } /** * Get the display name of the metric specification. * * @return the displayName value */ public String displayName() { return this.displayName; } /** * Set the display name of the metric specification. * * @param displayName the displayName value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withDisplayName(String displayName) { this.displayName = displayName; return this; } /** * Get the display description of the metric specification. * * @return the displayDescription value */ public String displayDescription() { return this.displayDescription; } /** * Set the display description of the metric specification. * * @param displayDescription the displayDescription value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withDisplayDescription(String displayDescription) { this.displayDescription = displayDescription; return this; } /** * Get the unit of the metric specification. * * @return the unit value */ public String unit() { return this.unit; } /** * Set the unit of the metric specification. * * @param unit the unit value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withUnit(String unit) { this.unit = unit; return this; } /** * Get the aggregation type of the metric specification. * * @return the aggregationType value */ public String aggregationType() { return this.aggregationType; } /** * Set the aggregation type of the metric specification. * * @param aggregationType the aggregationType value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withAggregationType(String aggregationType) { this.aggregationType = aggregationType; return this; } /** * Get the supported aggregation types of the metric specification. * * @return the supportedAggregationTypes value */ public List<String> supportedAggregationTypes() { return this.supportedAggregationTypes; } /** * Set the supported aggregation types of the metric specification. * * @param supportedAggregationTypes the supportedAggregationTypes value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withSupportedAggregationTypes(List<String> supportedAggregationTypes) { this.supportedAggregationTypes = supportedAggregationTypes; return this; } /** * Get the supported time grain types of the metric specification. * * @return the supportedTimeGrainTypes value */ public List<String> supportedTimeGrainTypes() { return this.supportedTimeGrainTypes; } /** * Set the supported time grain types of the metric specification. * * @param supportedTimeGrainTypes the supportedTimeGrainTypes value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withSupportedTimeGrainTypes(List<String> supportedTimeGrainTypes) { this.supportedTimeGrainTypes = supportedTimeGrainTypes; return this; } /** * Get the flag indicates whether enable regional mdm account or not. * * @return the enableRegionalMdmAccount value */ public Boolean enableRegionalMdmAccount() { return this.enableRegionalMdmAccount; } /** * Set the flag indicates whether enable regional mdm account or not. * * @param enableRegionalMdmAccount the enableRegionalMdmAccount value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withEnableRegionalMdmAccount(Boolean enableRegionalMdmAccount) { this.enableRegionalMdmAccount = enableRegionalMdmAccount; return this; } /** * Get the source mdm account. * * @return the sourceMdmAccount value */ public String sourceMdmAccount() { return this.sourceMdmAccount; } /** * Set the source mdm account. * * @param sourceMdmAccount the sourceMdmAccount value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withSourceMdmAccount(String sourceMdmAccount) { this.sourceMdmAccount = sourceMdmAccount; return this; } /** * Get the source mdm namespace. * * @return the sourceMdmNamespace value */ public String sourceMdmNamespace() { return this.sourceMdmNamespace; } /** * Set the source mdm namespace. * * @param sourceMdmNamespace the sourceMdmNamespace value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withSourceMdmNamespace(String sourceMdmNamespace) { this.sourceMdmNamespace = sourceMdmNamespace; return this; } /** * Get the metric filter pattern. * * @return the metricFilterPattern value */ public String metricFilterPattern() { return this.metricFilterPattern; } /** * Set the metric filter pattern. * * @param metricFilterPattern the metricFilterPattern value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withMetricFilterPattern(String metricFilterPattern) { this.metricFilterPattern = metricFilterPattern; return this; } /** * Get the flag indicates whether filling gap with zero. * * @return the fillGapWithZero value */ public Boolean fillGapWithZero() { return this.fillGapWithZero; } /** * Set the flag indicates whether filling gap with zero. * * @param fillGapWithZero the fillGapWithZero value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withFillGapWithZero(Boolean fillGapWithZero) { this.fillGapWithZero = fillGapWithZero; return this; } /** * Get the category of the metric. * * @return the category value */ public String category() { return this.category; } /** * Set the category of the metric. * * @param category the category value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withCategory(String category) { this.category = category; return this; } /** * Get the override name of resource id dimension name. * * @return the resourceIdDimensionNameOverride value */ public String resourceIdDimensionNameOverride() { return this.resourceIdDimensionNameOverride; } /** * Set the override name of resource id dimension name. * * @param resourceIdDimensionNameOverride the resourceIdDimensionNameOverride value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withResourceIdDimensionNameOverride(String resourceIdDimensionNameOverride) { this.resourceIdDimensionNameOverride = resourceIdDimensionNameOverride; return this; } /** * Get the flag indicates whether the metric is internal or not. * * @return the isInternal value */ public Boolean isInternal() { return this.isInternal; } /** * Set the flag indicates whether the metric is internal or not. * * @param isInternal the isInternal value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withIsInternal(Boolean isInternal) { this.isInternal = isInternal; return this; } /** * Get the override name of delegate metric. * * @return the delegateMetricNameOverride value */ public String delegateMetricNameOverride() { return this.delegateMetricNameOverride; } /** * Set the override name of delegate metric. * * @param delegateMetricNameOverride the delegateMetricNameOverride value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withDelegateMetricNameOverride(String delegateMetricNameOverride) { this.delegateMetricNameOverride = delegateMetricNameOverride; return this; } /** * Get the dimensions of the metric specification. * * @return the dimensions value */ public List<Dimension> dimensions() { return this.dimensions; } /** * Set the dimensions of the metric specification. * * @param dimensions the dimensions value to set * @return the MetricSpecifications object itself. */ public MetricSpecifications withDimensions(List<Dimension> dimensions) { this.dimensions = dimensions; return this; } }
27.542299
109
0.661574
c5214606ea4f6d1442eeb7f719644449d7fccaa5
1,483
package com.github.joonasvali.naturalmouse.support; import com.github.joonasvali.naturalmouse.api.SystemCalls; import java.awt.*; public class DefaultSystemCalls implements SystemCalls { private final Robot robot; public DefaultSystemCalls(Robot robot) { this.robot = robot; } @Override public long currentTimeMillis() { return System.currentTimeMillis(); } @Override public void sleep(long time) throws InterruptedException { Thread.sleep(time); } @Override public Dimension getScreenSize() { return Toolkit.getDefaultToolkit().getScreenSize(); } /** * <p>Moves the mouse to specified pixel using the provided Robot.</p> * * <p>It seems there is a certain delay, measurable in less than milliseconds, * before the mouse actually ends up on the requested pixel when using a Robot class. * this usually isn't a problem, but when we ask the mouse position right after this call, * there's extremely low but real chance we get wrong information back. I didn't add sleep * here as it would cause overhead to sleep always, even when we don't instantly use * the mouse position, but just acknowledged the issue with this warning. * (Use fast unrestricted loop of Robot movement and checking the position after every move to invoke the issue.)</p> * * @param x the x-coordinate * @param y the y-coordinate */ @Override public void setMousePosition(int x, int y) { robot.mouseMove(x, y); } }
30.895833
119
0.724208
ed4be6334d42e85cec1708960b535c5af5460d2e
171
/** * Fixtures for testing {@link org.anchoranalysis.image.io.bean.stack.writer.StackWriter} and related classes. */ package org.anchoranalysis.test.image.rasterwriter;
34.2
110
0.783626
bf764d2fb0302b5612bb383abc13fc9e722366be
6,734
package com.tecmanic.gogrocer.Fragments; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.cooltechworks.views.shimmer.ShimmerRecyclerView; import com.tecmanic.gogrocer.Activity.ViewAll_TopDeals; import com.tecmanic.gogrocer.Adapters.CartAdapter; import com.tecmanic.gogrocer.ModelClass.CartModel; import com.tecmanic.gogrocer.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.tecmanic.gogrocer.Config.BaseURL.HomeRecent; import static com.tecmanic.gogrocer.Config.BaseURL.whatsnew; /** * A simple {@link Fragment} subclass. */ public class Whats_New_Fragment extends Fragment { ShimmerRecyclerView recyclerWhatNew; CartAdapter recentAdapter; ProgressDialog progressDialog; TextView viewall; private List<CartModel> recentList = new ArrayList<>(); private LinearLayout mm; private RelativeLayout no_data; public Whats_New_Fragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_whats__new_, container, false); viewall =view.findViewById(R.id.viewall); mm =view.findViewById(R.id.mm); no_data =view.findViewById(R.id.no_data); viewall.setOnClickListener(v -> { Intent intent = new Intent(v.getContext(), ViewAll_TopDeals.class); intent.putExtra("action_name","Whats_New_Fragment"); startActivity(intent); }); recyclerWhatNew=view.findViewById(R.id.recyclerWhatNew); progressDialog=new ProgressDialog(getContext()); progressDialog.setMessage("Loading..."); progressDialog.setCancelable(false); recentUrl(); return view; } private void recentUrl() { mm.setVisibility(View.VISIBLE); viewall.setVisibility(View.VISIBLE); no_data.setVisibility(View.GONE); StringRequest stringRequest = new StringRequest(Request.Method.GET, whatsnew, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("homeRecent",response); progressDialog.dismiss(); try { JSONObject jsonObject = new JSONObject(response); String status = jsonObject.getString("status"); String message = jsonObject.getString("message"); if (status.equals("1")){ recentList.clear(); JSONArray jsonArray = jsonObject.getJSONArray("data"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject1 = jsonArray.getJSONObject(i); String product_id = jsonObject1.getString("product_id"); String product_name = jsonObject1.getString("product_name"); String varient_id = jsonObject1.getString("varient_id"); String description= jsonObject1.getString("description"); String pprice= jsonObject1.getString("price"); String quantity = jsonObject1.getString("quantity"); String product_image = jsonObject1.getString("varient_image"); String mmrp = jsonObject1.getString("mrp"); String unit = jsonObject1.getString("unit"); // String count = jsonObject1.getString("count"); String totalOff= String.valueOf(Integer.parseInt(String.valueOf(mmrp))-Integer.parseInt(String.valueOf(pprice))); CartModel recentData= new CartModel(product_id,product_name,description,pprice,quantity+" "+unit,product_image,getResources().getString(R.string.currency)+totalOff+" "+"Off",mmrp,"",unit); recentData.setVarient_id(varient_id); recentList.add(recentData); } recentAdapter = new CartAdapter(recentList,getActivity()); recyclerWhatNew.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerWhatNew.setAdapter(recentAdapter); recentAdapter.notifyDataSetChanged(); }else { mm.setVisibility(View.GONE); viewall.setVisibility(View.GONE); no_data.setVisibility(View.VISIBLE); // JSONObject resultObj = jsonObject.getJSONObject("results"); // String msg = resultObj.getString("message"); Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); } catch (JSONException e) { e.printStackTrace(); } progressDialog.dismiss(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mm.setVisibility(View.GONE); viewall.setVisibility(View.GONE); no_data.setVisibility(View.VISIBLE); progressDialog.dismiss(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String,String> params = new HashMap<>(); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); requestQueue.getCache().clear(); requestQueue.add(stringRequest); } }
39.846154
216
0.619543
a5464fac1859f4c6e85aac0ef749a63e86aeeaf5
6,124
package com.worldql.mammoth.worldql_serialization; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.nio.ByteBuffer; import java.util.List; import java.util.UUID; import static com.worldql.mammoth.worldql_serialization.Codec.copyByteBuffer; import static com.worldql.mammoth.worldql_serialization.Codec.copyList; public record Message( Instruction instruction, @NotNull UUID senderUuid, @NotNull String worldName, Replication replication, @Nullable Vec3D position, @Nullable List<Record> records, @Nullable List<Entity> entities, @Nullable String parameter, @Nullable ByteBuffer flex ) { // region: Constructors public Message(Instruction instruction, @NotNull UUID senderUuid, @NotNull String worldName) { this(instruction, senderUuid, worldName, Replication.ExceptSelf, null, null, null, null, null); } public Message(Instruction instruction, @NotNull UUID senderUuid, @NotNull String worldName, @Nullable Vec3D position) { this(instruction, senderUuid, worldName, Replication.ExceptSelf, position, null, null, null, null); } public Message(Instruction instruction, @NotNull UUID senderUuid, @NotNull String worldName, Replication replication) { this(instruction, senderUuid, worldName, replication, null, null, null, null, null); } public Message(Instruction instruction, @NotNull UUID senderUuid, @NotNull String worldName, Replication replication, @Nullable Vec3D position) { this(instruction, senderUuid, worldName, replication, position, null, null, null, null); } // endregion // region: Wither Functions public Message copy() { return new Message( instruction(), senderUuid(), worldName(), replication(), position(), copyList(records(), Record::copy), copyList(entities(), Entity::copy), parameter(), copyByteBuffer(flex()) ); } public Message withInstruction(Instruction instruction) { return new Message( instruction, senderUuid(), worldName(), replication(), position(), copyList(records(), Record::copy), copyList(entities(), Entity::copy), parameter(), copyByteBuffer(flex()) ); } public Message withSenderUuid(@NotNull UUID senderUuid) { return new Message( instruction(), senderUuid, worldName(), replication(), position(), copyList(records(), Record::copy), copyList(entities(), Entity::copy), parameter(), copyByteBuffer(flex()) ); } public Message withWorldName(@NotNull String worldName) { return new Message( instruction(), senderUuid(), worldName, replication(), position(), copyList(records(), Record::copy), copyList(entities(), Entity::copy), parameter(), copyByteBuffer(flex()) ); } public Message withReplication(Replication replication) { return new Message( instruction(), senderUuid(), worldName(), replication, position(), copyList(records(), Record::copy), copyList(entities(), Entity::copy), parameter(), copyByteBuffer(flex()) ); } public Message withPosition(@Nullable Vec3D position) { return new Message( instruction(), senderUuid(), worldName(), replication(), position, copyList(records(), Record::copy), copyList(entities(), Entity::copy), parameter(), copyByteBuffer(flex()) ); } public Message withRecords(@Nullable List<Record> records) { return new Message( instruction(), senderUuid(), worldName(), replication(), position(), records, copyList(entities(), Entity::copy), parameter(), copyByteBuffer(flex()) ); } public Message withEntities(@Nullable List<Entity> entities) { return new Message( instruction(), senderUuid(), worldName(), replication(), position(), copyList(records(), Record::copy), entities, parameter(), copyByteBuffer(flex()) ); } public Message withParameter(@Nullable String parameter) { return new Message( instruction(), senderUuid(), worldName(), replication(), position(), copyList(records(), Record::copy), copyList(entities(), Entity::copy), parameter, copyByteBuffer(flex()) ); } public Message withFlex(@Nullable ByteBuffer flex) { return new Message( instruction(), senderUuid(), worldName(), replication(), position(), copyList(records(), Record::copy), copyList(entities(), Entity::copy), parameter(), flex ); } // endregion // region: Codec public byte[] encode() { return Codec.encodeMessage(this); } public static Message decode(@NotNull ByteBuffer buf) { return Codec.decodeMessage(buf); } // endregion }
31.56701
149
0.529393
9585672dd47fe956ee50f498bcc7b330036968cf
1,912
package me.etki.grac.infrastructure.dto.github; /** * @author Etki {@literal <etki@etki.name>} * @version %I%, %G% * @since 0.1.0 */ public class RateLimit { private ResourceSection resources; private ResourceLimit rate; public ResourceSection getResources() { return resources; } public RateLimit setResources(ResourceSection resources) { this.resources = resources; return this; } public ResourceLimit getRate() { return rate; } public RateLimit setRate(ResourceLimit rate) { this.rate = rate; return this; } public static class ResourceLimit { private Integer limit; private Integer remaining; private Integer reset; public Integer getLimit() { return limit; } public ResourceLimit setLimit(Integer limit) { this.limit = limit; return this; } public Integer getRemaining() { return remaining; } public ResourceLimit setRemaining(Integer remaining) { this.remaining = remaining; return this; } public Integer getReset() { return reset; } public ResourceLimit setReset(Integer reset) { this.reset = reset; return this; } } public static class ResourceSection { private ResourceLimit core; private ResourceLimit search; public ResourceLimit getCore() { return core; } public ResourceSection setCore(ResourceLimit core) { this.core = core; return this; } public ResourceLimit getSearch() { return search; } public ResourceSection setSearch(ResourceLimit search) { this.search = search; return this; } } }
21.483146
64
0.569561
067a6a04b1ba4174ed37cbf9a43a539ddefd8f01
3,528
package com.larksuite.oapi.core.utils; import com.larksuite.oapi.core.model.OapiHeader; import com.larksuite.oapi.core.model.OapiRequest; import com.larksuite.oapi.core.model.OapiResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors; public class Servlets { public static OapiRequest toRequest(HttpServletRequest req) throws IOException { String uri = req.getRequestURI(); OapiHeader header = new OapiHeader(toHeaderMap(req)); Map<String, List<String>> query = toQueryMap(req.getQueryString()); String body = req.getReader().lines().collect(Collectors.joining(System.lineSeparator())); String remoteAddress = req.getRemoteAddr(); return new OapiRequest(uri, header, query, body, remoteAddress); } public static Map<String, List<String>> toHeaderMap(HttpServletRequest req) { Map<String, List<String>> headers = new HashMap<>(); Enumeration<String> names = req.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); List<String> values = Collections.list(req.getHeaders(name)); headers.put(name, values); } return headers; } public static void writeResponse(OapiResponse oapiResponse, HttpServletResponse resp) throws IOException { resp.setStatus(oapiResponse.getStatusCode()); for (Map.Entry<String, List<String>> header : oapiResponse.getHeaders().entrySet()) { String name = header.getKey(); for (String value : header.getValue()) { resp.addHeader(name, value); } } if (oapiResponse.getBody() != null) { resp.setContentType(oapiResponse.getContentType()); resp.setCharacterEncoding(StandardCharsets.UTF_8.name()); resp.getWriter().write(oapiResponse.getBody()); resp.getWriter().flush(); } } public static Map<String, List<String>> toQueryMap(String query) { if (query == null) { return null; } Map<String, List<String>> queryParams = new LinkedHashMap<>(); String[] pairs = query.split("&"); for (String pair : pairs) { int idx = pair.indexOf("="); try { if (pair.trim().isEmpty()) { continue; } String key = URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.name()); String value = URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name()); List<String> values = queryParams.get(key); if (values == null) { values = new ArrayList<>(); } values.add(value); queryParams.put(key, values); } catch (UnsupportedEncodingException e) { String key = pair.substring(0, idx); String value = pair.substring(idx + 1); List<String> values = queryParams.get(key); if (values == null) { values = new ArrayList<>(); } values.add(value); queryParams.put(key, values); } } return queryParams; } }
40.090909
110
0.601474
26fde4fceba086fb36bba9aa992fafad9bb44fd2
1,202
package rocks.cleanstone.game.command.cleanstone; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import rocks.cleanstone.game.command.CommandMessage; import rocks.cleanstone.game.command.SimpleCommand; import rocks.cleanstone.player.Player; import rocks.cleanstone.player.PlayerManager; import java.util.Arrays; @Component public class AlertCommand extends SimpleCommand { private final PlayerManager playerManager; @Autowired public AlertCommand(PlayerManager playerManager) { super("alert", Arrays.asList("say", "broadcast"), String.class); this.playerManager = playerManager; } @Override public void execute(CommandMessage message) { if (message.getCommandSender() instanceof Player) { if (!((Player) message.getCommandSender()).isOp()) { message.getCommandSender().sendRawMessage("No permission"); return; } } String inputMessage = message.requireStringMessage(); playerManager.getOnlinePlayers().forEach(player -> player.sendMessage("game.command.cleanstone.alert-format", inputMessage)); } }
33.388889
133
0.72213
93fabfb8a011cbab9550145f482ed44f16600cb6
1,413
package com.maven.dao; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.maven.base.dao.BaseDao; import com.maven.entity.ExchangeRate; @Repository public interface ExchangeRateDao extends BaseDao<ExchangeRate> { /** * 查询所有汇率 * @return List<ExchangeRate> */ List<ExchangeRate> getAllExchangeRate(); /** * 根据货币ID查询该货币对人民币汇率 * @param id * @return ExchangeRate */ ExchangeRate getExchangeRateByID(Integer id); /** * 根据货币名称查询该货币对人民币汇率 * @param String 货币名称 * @return ExchangeRate */ ExchangeRate getExchangeRateByCurrencyName(String currencyName); /** * 根据货币的英文代码查询该货币对人民币汇率 * @param CurrencyName * @return ExchangeRate */ ExchangeRate getExchangeRateByCurrencyCode(String currencyCode); /** * 根据条件模糊查询 * @param currencyName * @param currencyCode * @return */ List<ExchangeRate> getExchangeRateByCondition(Map<String,Object> condition); /** * 查询数据大小 * @param currencyName * @param currencyCode * @return */ int getQueryCount(Map<String,Object> condition); /** * 保存汇率 * @param exchangeRate */ int saveExchangeRate(ExchangeRate exchangeRate); /** * 跟新汇率 * @param exchangeRate */ int updateExchangeRate(ExchangeRate exchangeRate); /** * 删除汇率 * @param id 货币ID */ int deleteExchangeRate(Integer id); /** * 批量删除 * @param ids * @return */ int batchDelete(String[] ids); }
20.185714
77
0.71196
1e6c103270e6a7e626f384bfd9aac5d0b8231793
3,479
package com.github.kklisura.cdt.examples; import com.github.kklisura.cdt.launch.ChromeLauncher; import com.github.kklisura.cdt.protocol.commands.*; import com.github.kklisura.cdt.protocol.types.dom.RGBA; import com.github.kklisura.cdt.protocol.types.overlay.HighlightConfig; import com.github.kklisura.cdt.services.ChromeDevToolsService; import com.github.kklisura.cdt.services.ChromeService; import com.github.kklisura.cdt.services.types.ChromeTab; /** * Highlights an elements same way the Chrome inspector does. * * @author Kenan Klisura */ public class HighlightElementExample { private static void highlightNode( ChromeDevToolsService devToolsService, HighlightConfig highlightConfig, String selector) { final DOM dom = devToolsService.getDOM(); final Overlay overlay = devToolsService.getOverlay(); final Integer nodeId = dom.querySelector(devToolsService.getDOM().getDocument().getNodeId(), selector); overlay.highlightNode(highlightConfig, nodeId, null, null, null); } public static void main(String[] args) { // Create chrome launcher. final ChromeLauncher launcher = new ChromeLauncher(); // Launch chrome either as headless (true) or regular (false). final ChromeService chromeService = launcher.launch(false); // Create empty tab ie about:blank. final ChromeTab tab = chromeService.createTab(); // Get DevTools service to this tab final ChromeDevToolsService devToolsService = chromeService.createDevToolsService(tab); // Get individual commands final Page page = devToolsService.getPage(); final Network network = devToolsService.getNetwork(); final Performance performance = devToolsService.getPerformance(); devToolsService.getDOM().enable(); devToolsService.getOverlay().enable(); performance.enable(); network.onLoadingFinished( event -> { HighlightConfig highlightConfig = new HighlightConfig(); highlightConfig.setBorderColor(rgba(255, 229, 153, 0.66)); highlightConfig.setContentColor(rgba(111, 168, 220, 0.66)); highlightConfig.setCssGridColor(rgb(75, 0, 130)); highlightConfig.setEventTargetColor(rgba(255, 196, 196, 0.66)); highlightConfig.setMarginColor(rgba(246, 178, 107, 0.66)); highlightConfig.setPaddingColor(rgba(147, 196, 125, 0.55)); highlightConfig.setShapeColor(rgba(96, 82, 117, 0.8)); highlightConfig.setShapeMarginColor(rgba(96, 82, 127, 0.6)); highlightConfig.setShowExtensionLines(true); highlightConfig.setShowInfo(true); highlightConfig.setShowRulers(true); highlightConfig.setShowStyles(false); highlightNode(devToolsService, highlightConfig, "h1.h000-mktg"); sleep(); }); // Enable network events. network.enable(); // Navigate to github.com. page.navigate("https://www.github.com"); devToolsService.waitUntilClosed(); } private static void sleep() { try { Thread.sleep(100000); } catch (InterruptedException e) { e.printStackTrace(); } } private static RGBA rgba(int r, int g, int b, double a) { RGBA result = new RGBA(); result.setR(r); result.setG(g); result.setB(b); result.setA(a); return result; } private static RGBA rgb(int r, int g, int b) { RGBA result = new RGBA(); result.setR(r); result.setG(g); result.setB(b); return result; } }
32.820755
96
0.696752
086812449814ad2a0921e432808a93ab9a80f110
2,822
package br.com.sailboat.canoe.dialog.selectable; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.FragmentManager; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import java.util.List; import br.com.sailboat.canoe.R; import br.com.sailboat.canoe.base.BaseDialogFragment; import br.com.sailboat.canoe.helper.StringHelper; public class SelectItemDialog extends BaseDialogFragment implements SelectableItemAdapter.Callback { private TextView tvTitle; private RecyclerView recycler; private List<SelectableItem> items; private SelectableItem selectedItem; private String title; private SelectItemDialog.Callback callback; public static void show(FragmentManager manager, String title, List<SelectableItem> items, SelectableItem selectedItem, SelectItemDialog.Callback callback) { SelectItemDialog dialog = new SelectItemDialog(); dialog.callback = callback; dialog.items = items; dialog.selectedItem = selectedItem; dialog.title = title; dialog.show(manager, SelectItemDialog.class.getName()); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View view = View.inflate(getActivity(), R.layout.dlg_reycler, null); initViews(view); updateViews(); return buildDialog(view); } @Override public void onClickItem(int position) { callback.onClickItem(getItems().get(position)); dismiss(); } private void initViews(View view) { tvTitle = (TextView) view.findViewById(R.id.dlg_recycler__tv__title); recycler = (RecyclerView) view.findViewById(R.id.recycler); recycler.setLayoutManager(new LinearLayoutManager(getActivity())); recycler.setAdapter(new SelectableItemAdapter(this)); } private void updateViews() { if (StringHelper.isNotEmpty(title)) { tvTitle.setText(title); tvTitle.setVisibility(View.VISIBLE); } else { tvTitle.setVisibility(View.GONE); } recycler.getAdapter().notifyDataSetChanged(); } private Dialog buildDialog(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(view); return builder.create(); } @Override public SelectableItem getSelectedItem() { return selectedItem; } @Override public List<SelectableItem> getItems() { return this.items; } public interface Callback { void onClickItem(SelectableItem item); } }
29.092784
100
0.700921
1a50309228ae68f8543a826c60e48b7a56c96352
8,354
/* Copyright (c) 2014-2016 Boundless and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/edl-v10.html * * Contributors: * Johnathan Garrett (LMN Solutions) - initial implementation */ package org.locationtech.geogig.test.integration; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.locationtech.geogig.model.RevCommit; import org.locationtech.geogig.plumbing.CheckSparsePath; import org.locationtech.geogig.porcelain.BranchCreateOp; import org.locationtech.geogig.porcelain.CheckoutOp; import org.locationtech.geogig.porcelain.CommitOp; import org.locationtech.geogig.porcelain.ConfigOp; import org.locationtech.geogig.porcelain.ConfigOp.ConfigAction; import org.locationtech.geogig.porcelain.MergeOp; import org.locationtech.geogig.storage.GraphDatabase; public class CheckSparsePathTest extends RepositoryTestCase { @Rule public ExpectedException exception = ExpectedException.none(); @Override protected void setUpInternal() throws Exception { // These values should be used during a commit to set author/committer // TODO: author/committer roles need to be defined better, but for // now they are the same thing. repo.command(ConfigOp.class).setAction(ConfigAction.CONFIG_SET).setName("user.name") .setValue("groldan").call(); repo.command(ConfigOp.class).setAction(ConfigAction.CONFIG_SET).setName("user.email") .setValue("groldan@boundlessgeo.com").call(); } @Test public void testCheckSparsePath() throws Exception { // Create the following revision graph // o - commit1 // |\ // | o - commit2 // | | // | o - commit3 // | |\ // | | o - commit4 // | | |\ // | | | o - commit5 (sparse) // | | | | // | | o | - commit6 // | | |/ // | | o - commit7 // | | // o | - commit8 // | | // | o - commit9 // |/ // o - commit10 insertAndAdd(points1); RevCommit commit1 = geogig.command(CommitOp.class).setMessage("commit1").call(); // create branch1 and checkout geogig.command(BranchCreateOp.class).setAutoCheckout(true).setName("branch1").call(); insertAndAdd(points2); RevCommit commit2 = geogig.command(CommitOp.class).setMessage("commit2").call(); insertAndAdd(points3); RevCommit commit3 = geogig.command(CommitOp.class).setMessage("commit3").call(); geogig.command(BranchCreateOp.class).setAutoCheckout(true).setName("branch2").call(); insertAndAdd(lines1); RevCommit commit4 = geogig.command(CommitOp.class).setMessage("commit4").call(); geogig.command(BranchCreateOp.class).setAutoCheckout(true).setName("branch3").call(); insertAndAdd(poly1); RevCommit commit5 = geogig.command(CommitOp.class).setMessage("commit5").call(); geogig.getRepository().graphDatabase().setProperty(commit5.getId(), GraphDatabase.SPARSE_FLAG, "true"); geogig.command(CheckoutOp.class).setSource("branch2").call(); insertAndAdd(poly2); RevCommit commit6 = geogig.command(CommitOp.class).setMessage("commit6").call(); RevCommit commit7 = geogig.command(MergeOp.class).setMessage("commit7") .addCommit(commit5.getId()).call().getMergeCommit(); geogig.command(CheckoutOp.class).setSource("branch1").call(); insertAndAdd(lines3); RevCommit commit9 = geogig.command(CommitOp.class).setMessage("commit9").call(); // checkout master geogig.command(CheckoutOp.class).setSource("master").call(); insertAndAdd(lines2); RevCommit commit8 = geogig.command(CommitOp.class).setMessage("commit8").call(); RevCommit commit10 = geogig.command(MergeOp.class).setMessage("commit10") .addCommit(commit9.getId()).call().getMergeCommit(); CheckSparsePath command = geogig.command(CheckSparsePath.class); assertTrue(command.setStart(commit7.getId()).setEnd(commit1.getId()).call()); assertFalse(command.setStart(commit6.getId()).setEnd(commit1.getId()).call()); assertTrue(command.setStart(commit5.getId()).setEnd(commit2.getId()).call()); assertFalse(command.setStart(commit10.getId()).setEnd(commit1.getId()).call()); assertFalse(command.setStart(commit10.getId()).setEnd(commit3.getId()).call()); assertFalse(command.setStart(commit8.getId()).setEnd(commit1.getId()).call()); assertFalse(command.setStart(commit4.getId()).setEnd(commit2.getId()).call()); assertFalse(command.setStart(commit7.getId()).setEnd(commit5.getId()).call()); } @Test public void testCheckSparsePath2() throws Exception { // Create the following revision graph // o - commit1 // |\ // | o - commit2 (sparse) // | | // | o - commit3 // | |\ // | | o - commit4 // | | |\ // | | | o - commit5 (sparse) // | | | | // | | o | - commit6 // | | |/ // | | o - commit7 // | | // o | - commit8 // | | // | o - commit9 // |/ // o - commit10 insertAndAdd(points1); RevCommit commit1 = geogig.command(CommitOp.class).setMessage("commit1").call(); // create branch1 and checkout geogig.command(BranchCreateOp.class).setAutoCheckout(true).setName("branch1").call(); insertAndAdd(points2); RevCommit commit2 = geogig.command(CommitOp.class).setMessage("commit2").call(); geogig.getRepository().graphDatabase().setProperty(commit2.getId(), GraphDatabase.SPARSE_FLAG, "true"); insertAndAdd(points3); RevCommit commit3 = geogig.command(CommitOp.class).setMessage("commit3").call(); geogig.command(BranchCreateOp.class).setAutoCheckout(true).setName("branch2").call(); insertAndAdd(lines1); RevCommit commit4 = geogig.command(CommitOp.class).setMessage("commit4").call(); geogig.command(BranchCreateOp.class).setAutoCheckout(true).setName("branch3").call(); insertAndAdd(poly1); RevCommit commit5 = geogig.command(CommitOp.class).setMessage("commit5").call(); geogig.getRepository().graphDatabase().setProperty(commit5.getId(), GraphDatabase.SPARSE_FLAG, "true"); geogig.command(CheckoutOp.class).setSource("branch2").call(); insertAndAdd(poly2); RevCommit commit6 = geogig.command(CommitOp.class).setMessage("commit6").call(); RevCommit commit7 = geogig.command(MergeOp.class).setMessage("commit7") .addCommit(commit5.getId()).call().getMergeCommit(); geogig.command(CheckoutOp.class).setSource("branch1").call(); insertAndAdd(lines3); RevCommit commit9 = geogig.command(CommitOp.class).setMessage("commit9").call(); // checkout master geogig.command(CheckoutOp.class).setSource("master").call(); insertAndAdd(lines2); RevCommit commit8 = geogig.command(CommitOp.class).setMessage("commit8").call(); RevCommit commit10 = geogig.command(MergeOp.class).setMessage("commit10") .addCommit(commit9.getId()).call().getMergeCommit(); CheckSparsePath command = geogig.command(CheckSparsePath.class); assertTrue(command.setStart(commit7.getId()).setEnd(commit1.getId()).call()); assertTrue(command.setStart(commit6.getId()).setEnd(commit1.getId()).call()); assertTrue(command.setStart(commit5.getId()).setEnd(commit2.getId()).call()); assertTrue(command.setStart(commit10.getId()).setEnd(commit1.getId()).call()); assertFalse(command.setStart(commit10.getId()).setEnd(commit3.getId()).call()); assertFalse(command.setStart(commit8.getId()).setEnd(commit1.getId()).call()); assertFalse(command.setStart(commit4.getId()).setEnd(commit2.getId()).call()); assertFalse(command.setStart(commit7.getId()).setEnd(commit5.getId()).call()); } }
46.154696
93
0.651784
3435782757ffe6d21287d7f8e95eb7e3aa21716e
2,364
import java.util.*; class point { int x, y; point(int x, int y) { this.x = x; this.y = y; } } public class ClosestPair { static Scanner scan = new Scanner(System.in); static double dist(int x1, int y1, int x2, int y2) { return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); } static double bruteFind(point[] points, int lb, int ub) { double min = Double.MAX_VALUE; for (int i = lb; i <= ub; i++) { for (int j = i + 1; j <= ub; j++) { double curr = dist(points[i].x, points[i].y, points[j].x, points[j].y); if (curr < min) { min = curr; } } } return min; } static double findStripMin(point[] strip, double min) { for (int i = 0; i < strip.length; i++) { for (int j = i + 1; j < strip.length && (strip[j].y - strip[i].y) < min; j++) { double t = dist(strip[i].x, strip[i].y, strip[j].x, strip[j].y); if (t < min) min = t; } } return min; } static double findClosest(point[] points, int lb, int ub) { if ((ub - lb) <= 3) { return bruteFind(points, lb, ub); } else { int mid = (lb + ub) / 2; point midPoint = points[mid]; double lh = findClosest(points, lb, mid); double uh = findClosest(points, mid + 1, ub); double min = lh < uh ? lh : uh; ArrayList<point> strip = new ArrayList<point>(); for (int i = lb; i <= ub; i++) { if (Math.abs(midPoint.x - points[i].x) < min) { strip.add(points[i]); } } point[] stripArr = new point[strip.size()]; strip.toArray(stripArr); Arrays.sort(stripArr, new Comparator<point>() { public int compare(point a, point b) { return a.y - b.y; } }); double stripMin = findStripMin(stripArr, min); return stripMin < min ? stripMin : min; } } public static void main(String[] args) { System.out.println("Enter the number of points:"); int count = scan.nextInt(); point[] points = new point[count]; for (int i = 0; i < count; i++) { System.out.println("Enter the x&y co-ordinate for " + (i + 1) + "th point:"); int x = scan.nextInt(); int y = scan.nextInt(); points[i] = new point(x, y); } Arrays.sort(points, new Comparator<point>() { public int compare(point a, point b) { return a.x - b.x; } }); double min = findClosest(points, 0, points.length - 1); System.out.println("The minimum distance between two points is:" + min); } }
26.266667
82
0.579526
89d2040fe2b82e7acb5eef54a2f87558cd22eaf3
673
/* * Copyright 2012-09-12 the original author or authors. */ package pl.com.softproject.springtestaltkom.springaspect; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; /** * * @author Adrian Lapierre <adrian@softproject.com.pl> */ @ContextConfiguration("/spring-context.xml") public class TestAspect extends AbstractJUnit4SpringContextTests { @Autowired NewInterface bean; @Test public void test() { bean.someMethod(1); bean.method2(); } }
24.925926
80
0.745914
639398e77b268ff0e571e0fce612fb99ac949814
15,263
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.HC4.nio.client.methods; import java.io.File; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.net.URI; import org.apache.http.HC4.HttpEntityEnclosingRequest; import org.apache.http.HC4.HttpHost; import org.apache.http.HC4.HttpRequest; import org.apache.http.HC4.HttpResponse; import org.apache.http.HC4.entity.ContentType; import org.apache.http.HC4.nio.entity.HttpAsyncContentProducer; import org.apache.http.HC4.nio.entity.NByteArrayEntity; import org.apache.http.HC4.nio.entity.NStringEntity; import org.apache.http.HC4.nio.protocol.BasicAsyncRequestProducer; import org.apache.http.HC4.nio.protocol.BasicAsyncResponseConsumer; import org.apache.http.HC4.nio.protocol.HttpAsyncRequestProducer; import org.apache.http.HC4.nio.protocol.HttpAsyncResponseConsumer; import org.apache.http.HC4.util.Args; import org.apache.http.HC4.client.methods.HttpDelete; import org.apache.http.HC4.client.methods.HttpGet; import org.apache.http.HC4.client.methods.HttpOptions; import org.apache.http.HC4.client.methods.HttpPost; import org.apache.http.HC4.client.methods.HttpPut; import org.apache.http.HC4.client.methods.HttpTrace; import org.apache.http.HC4.client.methods.HttpUriRequest; import org.apache.http.HC4.client.utils.URIUtils; /** * Factory methods for asynchronous request producers and response consumers. * * @since 4.0 */ public final class HttpAsyncMethods { /** * Creates asynchronous request generator for the given request message. * * @param target request target. * @param request request message. * @return asynchronous request generator */ public static HttpAsyncRequestProducer create(final HttpHost target, final HttpRequest request) { Args.notNull(target, "HTTP host"); Args.notNull(request, "HTTP request"); return new RequestProducerImpl(target, request); } /** * Creates asynchronous request generator for the given request message. * * @param request request message. * @return asynchronous request generator */ public static HttpAsyncRequestProducer create(final HttpUriRequest request) { Args.notNull(request, "HTTP request"); final HttpHost target = URIUtils.extractHost(request.getURI()); return new RequestProducerImpl(target, request); } /** * Creates asynchronous {@code GET} request generator. * * @param requestURI request URI. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createGet(final URI requestURI) { return create(new HttpGet(requestURI)); } /** * Creates asynchronous {@code GET} request generator. * * @param requestURI request URI. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createGet(final String requestURI) { return create(new HttpGet(URI.create(requestURI))); } /** * Creates asynchronous {@code HEAD} request generator. * * @param requestURI request URI. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createHead(final URI requestURI) { return create(new HttpGet(requestURI)); } /** * Creates asynchronous {@code HEAD} request generator. * * @param requestURI request URI. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createHead(final String requestURI) { return create(new HttpGet(URI.create(requestURI))); } /** * Creates asynchronous {@code DELETE} request generator. * * @param requestURI request URI. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createDelete(final URI requestURI) { return create(new HttpDelete(requestURI)); } /** * Creates asynchronous {@code DELETE} request generator. * * @param requestURI request URI. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createDelete(final String requestURI) { return create(new HttpDelete(URI.create(requestURI))); } /** * Creates asynchronous {@code OPTIONS} request generator. * * @param requestURI request URI. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createOptions(final URI requestURI) { return create(new HttpOptions(requestURI)); } /** * Creates asynchronous {@code OPTIONS} request generator. * * @param requestURI request URI. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createOptions(final String requestURI) { return create(new HttpOptions(URI.create(requestURI))); } /** * Creates asynchronous {@code TRACE} request generator. * * @param requestURI request URI. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createTrace(final URI requestURI) { return create(new HttpTrace(requestURI)); } /** * Creates asynchronous {@code TRACE} request generator. * * @param requestURI request URI. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createTrace(final String requestURI) { return create(new HttpTrace(URI.create(requestURI))); } /** * Creates asynchronous {@code POST} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createPost( final URI requestURI, final String content, final ContentType contentType) throws UnsupportedEncodingException { final HttpPost httppost = new HttpPost(requestURI); final NStringEntity entity = new NStringEntity(content, contentType); httppost.setEntity(entity); final HttpHost target = URIUtils.extractHost(requestURI); return new RequestProducerImpl(target, httppost, entity); } /** * Creates asynchronous {@code POST} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createPost( final String requestURI, final String content, final ContentType contentType) throws UnsupportedEncodingException { return createPost(URI.create(requestURI), content, contentType); } /** * Creates asynchronous {@code POST} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createPost( final URI requestURI, final byte[] content, final ContentType contentType) { final HttpPost httppost = new HttpPost(requestURI); final NByteArrayEntity entity = new NByteArrayEntity(content, contentType); final HttpHost target = URIUtils.extractHost(requestURI); return new RequestProducerImpl(target, httppost, entity); } /** * Creates asynchronous {@code POST} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createPost( final String requestURI, final byte[] content, final ContentType contentType) { return createPost(URI.create(requestURI), content, contentType); } /** * Creates asynchronous {@code PUT} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createPut( final URI requestURI, final String content, final ContentType contentType) throws UnsupportedEncodingException { final HttpPut httpput = new HttpPut(requestURI); final NStringEntity entity = new NStringEntity(content, contentType); httpput.setEntity(entity); final HttpHost target = URIUtils.extractHost(requestURI); return new RequestProducerImpl(target, httpput, entity); } /** * Creates asynchronous {@code PUT} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createPut( final String requestURI, final String content, final ContentType contentType) throws UnsupportedEncodingException { return createPut(URI.create(requestURI), content, contentType); } /** * Creates asynchronous {@code PUT} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createPut( final URI requestURI, final byte[] content, final ContentType contentType) { final HttpPut httpput = new HttpPut(requestURI); final NByteArrayEntity entity = new NByteArrayEntity(content, contentType); final HttpHost target = URIUtils.extractHost(requestURI); return new RequestProducerImpl(target, httpput, entity); } /** * Creates asynchronous {@code PUT} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createPut( final String requestURI, final byte[] content, final ContentType contentType) { return createPut(URI.create(requestURI), content, contentType); } /** * Creates asynchronous zero-copy {@code POST} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createZeroCopyPost( final URI requestURI, final File content, final ContentType contentType) throws FileNotFoundException { return new ZeroCopyPost(requestURI, content, contentType); } /** * Creates asynchronous zero-copy {@code POST} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createZeroCopyPost( final String requestURI, final File content, final ContentType contentType) throws FileNotFoundException { return new ZeroCopyPost(URI.create(requestURI), content, contentType); } /** * Creates asynchronous zero-copy {@code PUT} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createZeroCopyPut( final URI requestURI, final File content, final ContentType contentType) throws FileNotFoundException { return new ZeroCopyPut(requestURI, content, contentType); } /** * Creates asynchronous zero-copy {@code PUT} request generator. * * @param requestURI request URI. * @param content request content. * @param contentType request contentType. * @return asynchronous request generator */ public static HttpAsyncRequestProducer createZeroCopyPut( final String requestURI, final File content, final ContentType contentType) throws FileNotFoundException { return new ZeroCopyPut(URI.create(requestURI), content, contentType); } /** * Creates basic response consumer that will buffer response content in memory. * @return asynchronous response consumer. */ public static HttpAsyncResponseConsumer<HttpResponse> createConsumer() { return new BasicAsyncResponseConsumer(); } /** * Creates zero-copy response consumer that will stream response content * directly to the given file. * @return asynchronous response consumer. */ public static HttpAsyncResponseConsumer<HttpResponse> createZeroCopyConsumer( final File file) throws FileNotFoundException { return new ZeroCopyConsumer<HttpResponse>(file) { @Override protected HttpResponse process( final HttpResponse response, final File file, final ContentType contentType) { return response; } }; } static class RequestProducerImpl extends BasicAsyncRequestProducer { protected RequestProducerImpl( final HttpHost target, final HttpEntityEnclosingRequest request, final HttpAsyncContentProducer producer) { super(target, request, producer); } public RequestProducerImpl(final HttpHost target, final HttpRequest request) { super(target, request); } } }
35.828638
101
0.678962
21d5db674c25c45aa99b840c052abc4b3598b795
2,393
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.12 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package org.libTAU4j.swig; public class pause_flags_t { private transient long swigCPtr; protected transient boolean swigCMemOwn; protected pause_flags_t(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(pause_flags_t obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; libTAU_jni.delete_pause_flags_t(swigCPtr); } swigCPtr = 0; } } public pause_flags_t() { this(libTAU_jni.new_pause_flags_t(), true); } public static pause_flags_t all() { return new pause_flags_t(libTAU_jni.pause_flags_t_all(), true); } public boolean non_zero() { return libTAU_jni.pause_flags_t_non_zero(swigCPtr, this); } public boolean eq(pause_flags_t f) { return libTAU_jni.pause_flags_t_eq(swigCPtr, this, pause_flags_t.getCPtr(f), f); } public boolean ne(pause_flags_t f) { return libTAU_jni.pause_flags_t_ne(swigCPtr, this, pause_flags_t.getCPtr(f), f); } public pause_flags_t or_(pause_flags_t other) { return new pause_flags_t(libTAU_jni.pause_flags_t_or_(swigCPtr, this, pause_flags_t.getCPtr(other), other), true); } public pause_flags_t and_(pause_flags_t other) { return new pause_flags_t(libTAU_jni.pause_flags_t_and_(swigCPtr, this, pause_flags_t.getCPtr(other), other), true); } public pause_flags_t xor(pause_flags_t other) { return new pause_flags_t(libTAU_jni.pause_flags_t_xor(swigCPtr, this, pause_flags_t.getCPtr(other), other), true); } public pause_flags_t inv() { return new pause_flags_t(libTAU_jni.pause_flags_t_inv(swigCPtr, this), true); } public int to_int() { return libTAU_jni.pause_flags_t_to_int(swigCPtr, this); } public static pause_flags_t from_int(int val) { return new pause_flags_t(libTAU_jni.pause_flags_t_from_int(val), true); } }
28.831325
119
0.66987
fce0fa175aab69fcb96cdff6ebae77deb06121fb
522
package com.donaldwu.main.responsebody; import java.util.List; import java.util.Map; public class GetAllUserResponseBody { private String message; private List<Map<String, Object>> users; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<Map<String, Object>> getUsers() { return users; } public void setUsers(List<Map<String, Object>> users) { this.users = users; } }
20.076923
59
0.649425
8208a56a41c8e605552e9824496b2565e46f32ed
1,470
/* * Copyright 2022 Starwhale, Inc. 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 ai.starwhale.mlops.domain.swds.bo; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * Star Whale Data Set */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class SWDataSet { /** * unique id of the swds */ Long id; /** * The total amount data pairs of the DS * One data pair contains a piece of Raw Data and a piece of Label Data */ Integer size; /** * The storage path of the DS, it could be a directory or a single file */ String path; /** * The storage path of the DS index, it could be a directory or a single file */ String indexPath; /** * the name for the data set */ String name; /** * the version for the data set */ String version; }
22.96875
81
0.672789
212bb7807832fc220eea641bf3d08f6aa3b1b4ab
2,713
package org.platformlayer.client.cli.output; import java.io.Closeable; import java.io.IOException; import java.io.OutputStream; import java.io.StringWriter; import java.io.Writer; import org.platformlayer.metrics.model.MetricDataStream; import org.platformlayer.metrics.model.MetricDataVisitor; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; public class MetricToJsonVisitor implements MetricDataVisitor, Closeable { final JsonGenerator jsonGenerator; public MetricToJsonVisitor(OutputStream os) throws IOException { JsonFactory jsonFactory = buildJsonFactory(); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(os); this.jsonGenerator = jsonGenerator; } public MetricToJsonVisitor(Writer writer) throws IOException { JsonFactory jsonFactory = buildJsonFactory(); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer); jsonGenerator.useDefaultPrettyPrinter(); this.jsonGenerator = jsonGenerator; } private JsonFactory buildJsonFactory() { return new JsonFactory(); } public static String toString(MetricDataStream s) throws IOException { // TODO: This is not very efficient; we deserialize a JSON stream and reserialize it StringWriter writer = new StringWriter(); MetricToJsonVisitor visitor = new MetricToJsonVisitor(writer); s.accept(visitor); visitor.close(); return writer.toString(); } @Override public void startObject() throws IOException { jsonGenerator.writeStartObject(); } @Override public void endObject() throws IOException { jsonGenerator.writeEndObject(); } @Override public void gotValueString(String s) throws IOException { jsonGenerator.writeString(s); } @Override public void gotKey(String key) throws IOException { jsonGenerator.writeFieldName(key); } @Override public void startArray() throws IOException { jsonGenerator.writeStartArray(); } @Override public void endArray() throws IOException { jsonGenerator.writeEndArray(); } @Override public void gotValueBoolean(boolean v) throws IOException { jsonGenerator.writeBoolean(v); } @Override public void gotValueNull() throws IOException { jsonGenerator.writeNull(); } @Override public void gotValueInt(int v) throws IOException { jsonGenerator.writeNumber(v); } @Override public void gotValueFloat(float v) throws IOException { jsonGenerator.writeNumber(v); } @Override public void gotValueDouble(double v) throws IOException { jsonGenerator.writeNumber(v); } @Override public void gotValueLong(long v) throws IOException { jsonGenerator.writeNumber(v); } @Override public void close() throws IOException { jsonGenerator.close(); } }
23.798246
86
0.77958
7b49509cfed62f6789a9510efeb71e5b97599fab
623
package com.gaofengze.demo.data; /** * Created by gaofengze on 2018/11/26 */ public class NetWorkData { public static final String success = "200"; public static final String codeError = "201"; public static final String logout = "300"; public static final String serverError = "500"; // 60.251.145.1 public static final String baseUrl="https://nginx.laviewine.com.tw/lavie/"; public static final String baseUrl_test = "http://10.10.113.35:32002/"; public static final String TOKEN = "Bearer "; public static String H5 = "https://nginx.laviewine.com.tw/LaVie/index.html?type="; }
34.611111
86
0.691814
a4878b4ffad852bc04e743afa435efd43a6518cf
935
package com.stemcell.android.exception; import java.util.Arrays; /** * */ public class BusinessException extends RuntimeException { private static final long serialVersionUID = -6578431977912288874L; private Object[] params; public BusinessException(String message, Throwable cause, Object... messageParams) { super(message, cause); this.params = messageParams; } public BusinessException(String message, Object... messageParams) { super(message); this.params = messageParams; } public Object[] getMessageParams() { Object[] copyParams = null; if (this.params != null) { copyParams = Arrays.copyOf(this.params, params.length); } return copyParams; } public void setMessageParams(Object[] params) { if (params != null) { this.params = Arrays.copyOf(params, params.length); } } }
22.804878
88
0.636364
a9652cd3af57cb9bfe4fa03e3050015e04e11c3c
269
package name.anonymous.heros.api.web.pagination.query.builder.jpa.criteria.parser; import name.anonymous.heros.api.web.pagination.query.builder.jpa.criteria.model.IGroup; public interface IGroupParser { Object parse(IGroup group, JsonRuleParser parser); }
33.625
88
0.791822
a676c0f0be4946973ce64d10d5e1442bcd224dc9
3,085
package org.fugerit.java.core.web.navmap.model; import java.io.Serializable; import java.util.Iterator; import org.fugerit.java.core.util.collection.KeyObject; import org.fugerit.java.core.util.collection.ListMapStringKey; /** * NavEntry wrapper * * Version 1.0 (2016-12-02) * * @author Fugerit <m@fugerit.org> * * @see org.fugerit.java.core.web.navmap.model.NavMap * */ public class NavEntry implements Serializable, KeyObject<String> { public static final String SESSION_ATT_NAME = "org.fugerit.java.mod.web.navmap.model.NavEntry#AttName"; /** * */ private static final long serialVersionUID = 3238506516488055084L; private String url; private String label; private String menu1; private String menu2; private String menu3; private String auth; public NavEntry(String url, String label, String menu1, String menu2, String menu3, String auth) { super(); this.url = url; this.label = label; this.menu1 = menu1; this.menu2 = menu2; this.menu3 = menu3; this.auth = auth; this.kids = new ListMapStringKey<NavEntry>(); this.alias = new ListMapStringKey<NavEntry>(); } public String getUrl() { return url; } public String getMenu1() { return menu1; } public String getMenu2() { return menu2; } public String getMenu3() { return menu3; } public String getAuth() { return auth; } @Override public String getKey() { return this.getUrl(); } public String getLabel() { return label; } @Override public String toString() { return this.getClass().getName()+"[url:"+this.getUrl()+"]"; } private NavEntry parent; private NavEntry aliasFor; public NavEntry getAliasFor() { return aliasFor; } public void setAliasFor(NavEntry aliasFor) { this.aliasFor = aliasFor; } private ListMapStringKey<NavEntry> kids; private ListMapStringKey<NavEntry> alias; public NavEntry getParent() { return parent; } public void setParent(NavEntry parent) { this.parent = parent; } public ListMapStringKey<NavEntry> getKids() { return kids; } public ListMapStringKey<NavEntry> getAlias() { return alias; } public boolean isLeaf() { return this.getKids() == null || this.getKids().isEmpty(); } public boolean isRoot() { return this.getParent() == null; } public boolean isAlias() { return this.getAliasFor() != null; } public boolean isCurrentBranch( NavEntry entry ) { boolean check = entry.getUrl().equals( this.getUrl() ); if ( !check ) { if ( this.isAlias() ) { check = entry.getAliasFor().isCurrentBranch( entry ); } Iterator<NavEntry> it = this.getKids().iterator(); while ( it.hasNext() && !check ) { NavEntry current = it.next(); check = current.isCurrentBranch( entry ); } it = this.getAlias().iterator(); while ( it.hasNext() && !check ) { NavEntry current = it.next(); check = current.isCurrentBranch( entry ); } } return check; } }
20.163399
105
0.647326
73a74e8dc58590d36d8d0dce1a1e87b9cc7abea0
557
package com.gnd.calificaprofesores.NetworkProfOpinion; public class Materia { private String nombre; private String facultad; public Materia(String nombre, String facultad) { this.nombre = nombre; this.facultad = facultad; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getFacultad() { return facultad; } public void setFacultad(String facultad) { this.facultad = facultad; } }
19.892857
54
0.635548
f7bfac398fddc46e62498cf698a4a48cfbe0a2af
2,236
/* * 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.axis2.description; import org.apache.axiom.om.util.UUIDGenerator; import org.apache.axis2.AxisFault; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.OperationContext; import org.apache.axis2.i18n.Messages; import javax.xml.namespace.QName; import java.util.HashMap; public class InOutAxisOperation extends TwoChannelAxisOperation { public InOutAxisOperation() { super(); //setup a temporary name QName tmpName = new QName(this.getClass().getName() + "_" + UUIDGenerator.getUUID()); this.setName(tmpName); } public InOutAxisOperation(QName name) { super(name); } public void addMessageContext(MessageContext msgContext, OperationContext opContext) throws AxisFault { HashMap mep = opContext.getMessageContexts(); MessageContext inMsgContext = (MessageContext) mep.get(MESSAGE_LABEL_IN_VALUE); MessageContext outmsgContext = (MessageContext) mep.get(MESSAGE_LABEL_OUT_VALUE); if ((inMsgContext != null) && (outmsgContext != null)) { throw new AxisFault(Messages.getMessage("mepcompleted")); } if (inMsgContext == null) { mep.put(MESSAGE_LABEL_IN_VALUE, msgContext); } else { mep.put(MESSAGE_LABEL_OUT_VALUE, msgContext); opContext.setComplete(true); opContext.cleanup(); } } }
36.064516
93
0.709302
c2eb9a30c67bd42eae4854c0dff73d8c5b7638f1
1,723
/* * Copyright 2017 MovingBlocks * * 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.terasology.scenario.components; import org.terasology.entitySystem.Component; import org.terasology.network.FieldReplicateType; import org.terasology.network.Replicate; import org.terasology.scenario.internal.utilities.ArgumentParser; /** * Text component that is attached to a Scenario logic entity, the text included is parsed to determine the text that is * displayed in the logic editor and what parameters are needed to satisfy the arguments * * The text should follow a pattern based on the below example: * text = "give [player1:Player] [amount:Integer] of [blocktype:Block]" * * Parameters follow the pattern of [key:type] where key is the string name of the variable, each key must be unique to the rest of the keys in the entity * * the type is the Type of the parameter, this type must be accounted for in {@link ArgumentParser} * * Scenario logic entities detailed in {@link ScenarioComponent} */ public class ScenarioLogicTextComponent implements Component { @Replicate(FieldReplicateType.SERVER_TO_CLIENT) public String text; }
45.342105
162
0.745792
42def3e5cfe4b9bc2e5820b1ff09ec5e389611ea
2,830
/* * Copyright 2006-2016 Edward Smith * * 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 root.xml; import java.math.BigDecimal; import root.annotation.Todo; import root.lang.Extractable; import root.lang.StringExtractor; import root.time.Calendar; /** * https://www.w3schools.com/xml/schema_simple.asp * * @author Edward Smith * @version 0.5 * @since 0.5 */ @Todo("Does Extractable play any role here at all, whether for names and/or values? Maybe make everything FastString so they all fly when extracted...maybe the names should be FastString and the values should be Extractable so that I can support FastString, FastInteger, FastWhatever, etc") public final class XMLBroker implements Extractable { public static void main(final String[] args) { final XMLBroker xmlBroker = new XMLBroker("bookstore"); final ParentElement bookstore = xmlBroker.getRootElement(); final ParentElement book = bookstore.addParentElement("book"); book.addAttribute("category", "cooking"); final ChildElement child = book.addChildElement("title", "Everyday Italian"); child.addAttribute("lang", "en"); book.addChildElement("author", "Giada De Laurentiis"); book.addChildElement("year", 2005); book.addChildElement("price", new BigDecimal(30).setScale(2)); book.addChildElement("onSale", false); book.addChildElement("publishDate", Calendar.getDate()); book.addChildElement("currentTime", Calendar.getTime()); book.addChildElement("timestamp", Calendar.getDateTime()); System.out.println(xmlBroker); System.exit(0); } // <><><><><><><><><><><><><><><> Attributes <><><><><><><><><><><><><><><> private final ParentElement rootElement; // <><><><><><><><><><><><><><>< Constructors ><><><><><><><><><><><><><><> public XMLBroker(final String elementName) { this.rootElement = new ParentElement(elementName); } // <><><><><><><><><><><><><><> Public Methods <><><><><><><><><><><><><><> @Override public final void extract(final StringExtractor extractor) { this.rootElement.extract(extractor); } public final ParentElement getRootElement() { return this.rootElement; } @Override public final String toString() { final StringExtractor extractor = new StringExtractor(1024); this.extract(extractor); return extractor.toString(); } } // End XMLBroker
32.159091
290
0.70212
2b31e4fb248eb50ca06ffdf8f9f6441ba1c83b3c
418
package com.omisoft.vitafu.themoviedbapi.model.changes; import com.fasterxml.jackson.annotation.JsonProperty; import com.omisoft.vitafu.themoviedbapi.model.core.IdElement; public class ChangedMovie extends IdElement { @JsonProperty("adult") private boolean adult; public boolean isAdult() { return adult; } public void setAdult(boolean adult) { this.adult = adult; } }
18.173913
61
0.712919
4b616483d2dfa50445df0e31b789258146277625
1,539
/** ISOQuant, isoquant.plugins.processing.fractions, 07.05.2012 */ package isoquant.plugins.processing.fractions; import isoquant.app.Defaults; import isoquant.interfaces.iMainApp; import isoquant.kernel.db.DBProject; import isoquant.kernel.plugin.SingleActionPlugin4DB; import de.mz.jk.jsix.mysql.MySQL; import de.mz.jk.jsix.utilities.Settings; /** * <h3>{@link LCFractionsTimeUnshifter}</h3> * @author kuharev * @version 07.05.2012 11:43:13 */ public class LCFractionsTimeUnshifter extends SingleActionPlugin4DB { public LCFractionsTimeUnshifter(iMainApp app) { super(app); } private boolean fractionShiftingEnabled = false; @Override public void loadSettings(Settings cfg) { fractionShiftingEnabled = cfg.getBooleanValue("process.emrt.rt.shiftByFraction", fractionShiftingEnabled, !Defaults.DEBUG); } @Override public void runPluginAction(DBProject p) throws Exception { if (!fractionShiftingEnabled) return; MySQL db = p.mysql; // skip actions if column oldRT in table mass_spectrum does not exist! if (!db.columnExists("mass_spectrum", "oldRT")) { System.out.println("Fraction times are not shifted!"); System.out.println("skipping unshifting fraction times ..."); return; } db.executeSQLFile(getPackageResource("unshift.sql")); } @Override public String getPluginName() { return "Gel Fraction Unshifter"; } @Override public String getMenuItemText() { return "unshift Gel Fractions Times"; } @Override public String getMenuItemIconName() { return "fraction_unshift"; } }
26.534483
125
0.758285
b86c215c4e6815bd56e71c2c041a2d7b511a2bd9
4,473
package com.muxistudio.jobs.ui.forum; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.muxistudio.jobs.R; import com.muxistudio.jobs.bean.PostDetailResult; import com.muxistudio.jobs.bean.ReplyData; import com.muxistudio.jobs.util.CircleTransformation; import com.muxistudio.jobs.util.TimeUtil; import com.squareup.picasso.Picasso; import com.squareup.picasso.Transformation; import java.util.Date; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by ybao (ybaovv@gmail.com) * Date: 17/3/13 */ public class PostDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context mContext; private PostDetailResult.DataBean mPostDetailData; private Transformation circleTransformation = new CircleTransformation(); public static final int ITEM_TYPE_TOPIC = 0; public static final int ITEM_TYPE_REPLY = 1; public PostDetailAdapter(PostDetailResult.DataBean postDetailData) { mPostDetailData = postDetailData; } @Override public int getItemViewType(int position) { if (position == 0) { return ITEM_TYPE_TOPIC; } return ITEM_TYPE_REPLY; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { mContext = parent.getContext(); switch (viewType) { case ITEM_TYPE_TOPIC: return new TopicViewHolder( LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_topic, parent, false)); case ITEM_TYPE_REPLY: default: return new ReplyViewHolder( LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_reply, parent, false)); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (position == 0) { TopicViewHolder topicViewHolder = (TopicViewHolder) holder; Picasso.with(mContext).load(mPostDetailData.topic.avator).transform( circleTransformation).into(topicViewHolder.mIvAvatar); topicViewHolder.mTvTitle.setText(mPostDetailData.topic.title); topicViewHolder.mTvContent.setText(mPostDetailData.topic.content); topicViewHolder.mTvAuthor.setText(mPostDetailData.topic.name); topicViewHolder.mTvTime.setText(TimeUtil.toTimeInPost(new Date(mPostDetailData.topic.time))); }else { ReplyViewHolder replyViewHolder = (ReplyViewHolder) holder; ReplyData replyData = mPostDetailData.replys.get(position - 1); Picasso.with(mContext).load(mPostDetailData.replys.get(position - 1).avator).transform( circleTransformation).into(replyViewHolder.mIvAvatar); replyViewHolder.mTvAuthor.setText(replyData.name); replyViewHolder.mTvContent.setText(replyData.content); replyViewHolder.mTvTime.setText(TimeUtil.toTimeInPost(new Date(replyData.time))); } } @Override public int getItemCount() { if (mPostDetailData.replys != null) { return mPostDetailData.replys.size() + 1; } return 0; } public static class TopicViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.tv_title) TextView mTvTitle; @BindView(R.id.iv_avatar) ImageView mIvAvatar; @BindView(R.id.tv_author) TextView mTvAuthor; @BindView(R.id.tv_content) TextView mTvContent; @BindView(R.id.tv_time) TextView mTvTime; public TopicViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } public static class ReplyViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.iv_avatar) ImageView mIvAvatar; @BindView(R.id.tv_author) TextView mTvAuthor; @BindView(R.id.tv_content) TextView mTvContent; @BindView(R.id.tv_time) TextView mTvTime; public ReplyViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
33.631579
105
0.667337
a4d33e2d4b5584115648296f3bce92c932d56a81
2,605
/* * Copyright 2015-2017 Alexandr Evstigneev * * 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.perl5.lang.perl.psi; import com.perl5.lang.perl.psi.mro.PerlMro; import com.perl5.lang.perl.psi.mro.PerlMroC3; import com.perl5.lang.perl.psi.mro.PerlMroDfs; import com.perl5.lang.perl.psi.mro.PerlMroType; import com.perl5.lang.perl.psi.utils.PerlNamespaceAnnotations; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; /** * Describes api for perl namespace definition; Should be used only for inheritance */ public interface PerlNamespaceDefinition extends PerlDeprecatable { /** * Returns package name * * @return canonical package name */ @Nullable String getNamespaceName(); /** * Get mro type for current package * * @return mro type */ @NotNull PerlMroType getMroType(); /** * Returns MRO instance for current package * * @return mro class instance */ @NotNull default PerlMro getMro() { return getMroType() == PerlMroType.C3 ? PerlMroC3.INSTANCE : PerlMroDfs.INSTANCE; } /** * Returns list of parent namespace names from stub or psi * * @return list of names */ @NotNull List<String> getParentNamespacesNames(); /** * Returns stubbed, local or external namespace annotations * * @return annotations or null */ @Nullable PerlNamespaceAnnotations getAnnotations(); /** * Retuns list of exports from this module * * @return list of @EXPORTs */ @NotNull List<String> getEXPORT(); /** * . * Returns list of optional exports from this module * * @return list of @EXPORT_OKs */ @NotNull List<String> getEXPORT_OK(); /** * Returns map of exported tags * * @return map of %EXPORT_TAGS */ @NotNull Map<String, List<String>> getEXPORT_TAGS(); @Override default boolean isDeprecated() { PerlNamespaceAnnotations namespaceAnnotations = getAnnotations(); return namespaceAnnotations != null && namespaceAnnotations.isDeprecated(); } }
24.345794
85
0.706334
1e56a77f427e113a38e78e84b3a25db6e66bd025
524
/* * Copyright (c) 2017 Hiylo Org. All rights reserved * Project: framework * File: CartException.java * Data: 11/27/17 7:54 AM * Author: hiylo */ package org.hiylo.components.exceptions; import java.io.Serializable; /** * @author hiylo * @date 2017年10月19日 08:09:34 */ public class CartException extends BaseException implements Serializable { private static final long serialVersionUID = 6192360479862525938L; public CartException(String code, String message) { super(code, message); } }
20.96
74
0.715649
ea3d5c43c981fbde2c11bee020d9387cbff65586
3,401
package uk.org.retep.util; import java.awt.*; import javax.swing.*; import java.awt.event.*; /** * Display an Exception to the user * @author * @version 1.0 */ public class ExceptionDialog extends JDialog { // This is used to store the parent frame. // Classes like StandaloneApp set's this so that the // displayException() method can work without knowing/finding out // the parent Frame/JFrame. private static Frame globalFrame; private static ExceptionDialog globalDialog; JPanel panel1 = new JPanel(); BorderLayout borderLayout1 = new BorderLayout(); JTextArea message = new JTextArea(); JPanel jPanel1 = new JPanel(); JButton jButton1 = new JButton(); GridLayout gridLayout1 = new GridLayout(); JButton jButton2 = new JButton(); JLabel jLabel1 = new JLabel(); public ExceptionDialog(Frame frame, String title, boolean modal) { super(frame, title, modal); try { jbInit(); pack(); } catch(Exception ex) { ex.printStackTrace(); } } public ExceptionDialog() { this(null, "", false); } void jbInit() throws Exception { panel1.setLayout(borderLayout1); message.setBorder(BorderFactory.createLoweredBevelBorder()); message.setText("jTextArea1"); message.setBackground(Color.lightGray); message.setEditable(false); jButton1.setText("Close"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { jButton1_actionPerformed(e); } }); jPanel1.setLayout(gridLayout1); jButton2.setEnabled(false); jButton2.setText("Stack Trace"); jLabel1.setEnabled(false); getContentPane().add(panel1); panel1.add(message, BorderLayout.CENTER); this.getContentPane().add(jPanel1, BorderLayout.SOUTH); jPanel1.add(jButton2, null); jPanel1.add(jLabel1, null); jPanel1.add(jButton1, null); } /** * Sets the Frame used to display all dialog boxes. */ public static void setFrame(Frame aFrame) { globalFrame = aFrame; } /** * Displays a dialog based on the exception * @param ex Exception that was thrown */ public static void displayException(Exception ex) { displayException(ex,null); } /** * Displays a dialog based on the exception * @param ex Exception that was thrown */ public static void displayException(Exception ex,String msg) { String cname = ex.getClass().getName(); int i=cname.lastIndexOf("."); displayException(cname.substring(i+1),ex,msg); } public static void displayException(String title,Exception ex) { displayException(title,ex,null); } public static void displayException(String title,Exception ex,String msg) { Logger.log(Logger.ERROR,title,ex.getMessage()); // Default to a stack trace if no frame set if(globalFrame==null) { ex.printStackTrace(); return; } if(globalDialog==null) { globalDialog=new ExceptionDialog(globalFrame,title,true); globalDialog.pack(); } globalDialog.setTitle(title); if(msg!=null) { globalDialog.message.setText(msg); globalDialog.message.append(":\n"); } globalDialog.message.append(ex.getMessage()); globalDialog.pack(); globalDialog.setVisible(true); } void jButton1_actionPerformed(ActionEvent e) { setVisible(false); } }
24.120567
75
0.676566
aa5616f18734c220f0d4443f1174394e30d7468b
617
package io.cryptolens.models; public class DeactivateModel extends RequestModel { public int ProductId; public String Key; public String MachineCode; public boolean Floating; public DeactivateModel() { } public DeactivateModel(int productId, String key, String machineCode) { ProductId = productId; Key = key; MachineCode = machineCode; } public DeactivateModel(int productId, String key, String machineCode, boolean floating) { ProductId = productId; Key = key; MachineCode = machineCode; Floating = floating; } }
22.851852
93
0.662885
cd2cb2c96eccae2deb98a3910dc30952b7aa053d
946
/* * Copyright (C) 2014 Michell Bak * * 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.miz.functions; /** * Simple class to hold keys for Intent keys. This should * always be used when dealing with Intents. Scattered keys * across the app? No thank you. * @author Michell * */ public class IntentKeys { private IntentKeys() {} // No instantiation public static final String TOOLBAR_COLOR = "toolbarColor"; }
28.666667
75
0.72833
27b15b782c0765805dbe57e8f979675f802f0b52
348
import java.io.*; public class exceptions_tryCatch { public static void main(String args[]) { try { int a[] = new int[3]; System.out.println("element four: " + a[4]); }catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown: " + e); } } }
26.769231
58
0.525862
6d65e6099cc01b65a3b3207ed3187ab20a94671c
321
package us.dot.its.jpo.ode.model; public class OdeBsmData extends OdeData { private static final long serialVersionUID = 4944935387116447760L; public OdeBsmData() { super(); } public OdeBsmData(OdeMsgMetadata metadata, OdeMsgPayload payload) { super(metadata, payload); } }
20.0625
71
0.679128
ec5fb85bc7f59d46c7f59faac6d2ff67bed8b895
1,103
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; /** * BQServiceSchedulingRetrieveInputModelServiceSchedulingInstanceAnalysis */ public class BQServiceSchedulingRetrieveInputModelServiceSchedulingInstanceAnalysis { private String serviceSchedulingInstanceAnalysisReference = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the control record instance analysis view * @return serviceSchedulingInstanceAnalysisReference **/ public String getServiceSchedulingInstanceAnalysisReference() { return serviceSchedulingInstanceAnalysisReference; } public void setServiceSchedulingInstanceAnalysisReference(String serviceSchedulingInstanceAnalysisReference) { this.serviceSchedulingInstanceAnalysisReference = serviceSchedulingInstanceAnalysisReference; } }
33.424242
194
0.835902
27d82144663f19716c1b83ec758dadde097650f4
4,744
package stego.main; import com.google.common.base.Throwables; import org.apache.sanselan.ImageFormat; import org.apache.sanselan.ImageReadException; import org.apache.sanselan.ImageWriteException; import org.apache.sanselan.Sanselan; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import stego.StegoTool; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Base64; import static stego.StegoTool.getLSB; import static stego.StegoTool.replaceLSB; @Controller public class MainController { @RequestMapping(value = "/", method = RequestMethod.GET) public String stego(){ return "stego-boot"; } @RequestMapping(value = "/encode", method = RequestMethod.POST) public ModelAndView encode(@RequestParam("cover") MultipartFile cover, @RequestParam("message") MultipartFile message, @RequestParam("name") String name) throws IOException, ImageReadException, ImageWriteException { final ModelAndView imageOutput = new ModelAndView("imageOutput"); BufferedImage messageImg = Sanselan.getBufferedImage(message.getInputStream()); int[] msgPixelArray = new int[messageImg.getWidth() * messageImg.getHeight()]; messageImg.getRGB(0, 0, messageImg.getWidth(), messageImg.getHeight(), msgPixelArray, 0, messageImg.getWidth()); BufferedImage coverImg = Sanselan.getBufferedImage(cover.getInputStream()); int[] coverPixelArray = new int[messageImg.getWidth() * messageImg.getHeight()]; coverImg.getRGB(0, 0, messageImg.getWidth(), messageImg.getHeight(), coverPixelArray, 0, messageImg.getWidth()); for(int index = 0; index < msgPixelArray.length; index++ ){ final Color coverColor = new Color(coverPixelArray[index]); int msgRGB = msgPixelArray[index]; coverPixelArray[index] = new Color(replaceLSB(coverColor.getRed(), StegoTool.getBit(msgRGB, 24)), replaceLSB(coverColor.getGreen(), StegoTool.getBit(msgRGB, 16)), replaceLSB(coverColor.getBlue(), StegoTool.getBit(msgRGB, 8))).getRGB(); } coverImg.setRGB(0, 0, messageImg.getWidth(), messageImg.getHeight(), coverPixelArray, 0, messageImg.getWidth()); imageOutput.addObject("image64", Base64.getEncoder().encodeToString(getBytesFromBufferedImage(coverImg))); imageOutput.addObject("name", name); return imageOutput; } @RequestMapping(value = "/decode", method = RequestMethod.POST) public ModelAndView decode(@RequestParam("stego-object") MultipartFile stegoObject) throws IOException, ImageReadException, ImageWriteException { final ModelAndView imageOutput = new ModelAndView("imageOutput"); final BufferedImage image = Sanselan.getBufferedImage(stegoObject.getInputStream()); int[] msgPixelArray = new int[image.getWidth() * image.getHeight()]; image.getRGB(0, 0, image.getWidth(), image.getHeight(), msgPixelArray, 0, image.getWidth()); for(int index = 0; index < msgPixelArray.length; index++ ) { final Color color = new Color(msgPixelArray[index]); final Color lsbColor = new Color(255 * getLSB(color.getRed()), 255 * getLSB(color.getGreen()), 255 * getLSB(color.getBlue())); msgPixelArray[index] = lsbColor.getRGB(); } image.setRGB(0, 0, image.getWidth(), image.getHeight(), msgPixelArray, 0, image.getWidth()); imageOutput.addObject("image64", Base64.getEncoder().encodeToString(getBytesFromBufferedImage(image))); return imageOutput; } @RequestMapping(value = "/output", method = RequestMethod.GET) public ModelAndView imageOutput(){ return new ModelAndView("imageOutput"); } @ExceptionHandler({IOException.class, ImageReadException.class, ImageWriteException.class}) private ModelAndView handleException(Exception e){ ModelAndView error = new ModelAndView("errorPage"); error.addObject("errorName", e.getMessage()); error.addObject("stackTrace", Throwables.getStackTraceAsString(e)); return error; } private static byte[] getBytesFromBufferedImage(BufferedImage image) throws IOException, ImageWriteException { return Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_PNG, null); } }
47.919192
247
0.733769
80e8759d9580e80ba8fa9599280bb5ae0e318a39
1,770
package seedu.revision.logic.commands; import static seedu.revision.logic.commands.CommandTestUtil.assertCommandFailure; import static seedu.revision.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.revision.testutil.TypicalMcqs.getTypicalMcqs; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import seedu.revision.logic.commands.main.AddCommand; import seedu.revision.logic.parser.exceptions.ParseException; import seedu.revision.model.History; import seedu.revision.model.Model; import seedu.revision.model.ModelManager; import seedu.revision.model.UserPrefs; import seedu.revision.model.answerable.Answerable; import seedu.revision.testutil.McqBuilder; /** * Contains integration tests (interaction with the Model) for {@code AddCommand}. */ public class AddCommandIntegrationTest { private Model model; @BeforeEach public void setUp() { model = new ModelManager(getTypicalMcqs(), new UserPrefs(), new History()); } @Test public void execute_newAnswerable_success() throws ParseException { Answerable validAnswerable = new McqBuilder().build(); Model expectedModel = new ModelManager(model.getRevisionTool(), new UserPrefs(), new History()); expectedModel.addAnswerable(validAnswerable); assertCommandSuccess(new AddCommand(validAnswerable), model, String.format(AddCommand.MESSAGE_SUCCESS, validAnswerable), expectedModel); } @Test public void execute_duplicateAnswerable_throwsCommandException() { Answerable answerableInList = model.getRevisionTool().getAnswerableList().get(0); assertCommandFailure(new AddCommand(answerableInList), model, AddCommand.MESSAGE_DUPLICATE_ANSWERABLE); } }
36.122449
111
0.774011
c91a8c6dad08262a819b0ecf1e4107c4f6b0a917
945
package frc.robot.utils; import org.montclairrobotics.sprocket.drive.DTStep; import org.montclairrobotics.sprocket.drive.DTTarget; import org.montclairrobotics.sprocket.drive.steps.GyroCorrection; import org.montclairrobotics.sprocket.geometry.Degrees; import org.montclairrobotics.sprocket.utils.Togglable; public class FieldCentric implements DTStep, Togglable { GyroCorrection correction; boolean enabled = false; public FieldCentric(GyroCorrection correction){ this.correction = correction; } @Override public DTTarget get(DTTarget dtTarget) { if(enabled) { return new DTTarget(dtTarget.getDirection().rotate(correction.getCurrentAngleReset().times(-1)), dtTarget.getTurn()); }else{ return dtTarget; } } @Override public void enable() { enabled = true; } @Override public void disable() { enabled = false; } }
25.540541
129
0.696296
7059ccc27c4621d20cfab627f31de7cd6c229134
351
package com.tvycas.countyinfo.network; import com.tvycas.countyinfo.model.BoundingBox; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface CountryBoundingBoxApiService { @GET("search?format=json&limit=1") Call<List<BoundingBox>> getPosts(@Query("country") String name); }
23.4
68
0.780627
4c818a4064de9e166f2495c6fdf27ebc59458ec0
2,098
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.ltk.core.refactoring; import org.eclipse.core.runtime.Assert; /** * A group category is used to annotate change groups so that * they can be identified and filtered. * <p> * Note: this class is not intended to be subclassed * </p> * * @since 3.2 * * @noextend This class is not intended to be subclassed by clients. */ public class GroupCategory { private String fId; private String fName; private String fDescription; /** * Creates a new group category with the given name and * description. * * @param id a unique identifier * @param name the name * @param description the description */ public GroupCategory(String id, String name, String description) { Assert.isNotNull(id); Assert.isNotNull(name); Assert.isNotNull(description); fId = id; fName = name; fDescription = description; } /** * Returns the name of the group category. * * @return the name */ public String getName() { return fName; } /** * Returns the description of the group category. * * @return the description */ public String getDescription() { return fDescription; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || !getClass().equals(obj.getClass())) return false; return fId.equals(((GroupCategory) obj).fId); } @Override public int hashCode() { return fId.hashCode(); } }
25.277108
81
0.594852
e06c61e910e4b108794e73750ad480919d15815c
2,995
package com.haxademic.sketch.volume; import java.io.PrintWriter; import java.util.ArrayList; import com.haxademic.core.app.AppSettings; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.draw.shapes.MarchingCubes; import com.haxademic.core.hardware.kinect.KinectSize; import processing.core.PImage; import processing.core.PVector; import toxi.geom.Vec3D; public class CubeMarchTest extends PAppletHax { public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } // from: http://iwearshorts.com/blog/bubble-boy2/ MarchingCubes mc; Vec3D rotationAxis; Boolean bUseFill; // kinect float a = 0; float deg = 8; // Start at 15 degrees PImage depthImg; int minDepth = 40; int maxDepth = 1860; // set initial record to false boolean record = false; int counter = 0; // print custom file boolean printFile = false; ArrayList points; PrintWriter output; protected void overridePropsFile() { p.appConfig.setProperty( AppSettings.RENDERING_MOVIE, "false" ); p.appConfig.setProperty( AppSettings.KINECT_ACTIVE, "true" ); p.appConfig.setProperty( AppSettings.WIDTH, "1024" ); p.appConfig.setProperty( AppSettings.HEIGHT, "768" ); } public void setup() { super.setup(); Vec3D aabbMin = new Vec3D(-width*2, -height*2, -1500); Vec3D aabbMax = new Vec3D(width*2, height*2, 1500); Vec3D numPoints = new Vec3D(50,50,50); float isoLevel = 2; mc = new MarchingCubes(this, aabbMin, aabbMax, numPoints, isoLevel); rotationAxis = new Vec3D(); bUseFill = false; points = new ArrayList(); } public void drawApp() { p.background(0); int skip = 20; float pixelDepth = 0; //translate(width/750,height/750,-50); mc.reset(); // original for loop // println("entering loop"); int nBalls = 0; for ( int x = 0; x < KinectSize.WIDTH; x += skip ) { for ( int y = 0; y < KinectSize.HEIGHT; y += skip ) { pixelDepth = p.kinectWrapper.getMillimetersDepthForKinectPixel( x, y ); if( pixelDepth != 0 && pixelDepth > minDepth && pixelDepth < maxDepth ) { PVector v = new PVector(x,y,pixelDepth); Vec3D metaBallPos = new Vec3D(v.x, v.y, -v.z); mc.addMetaBall(metaBallPos, 30, 3); nBalls++; } } } // println("done with loop, " + nBalls + " balls"); // end original for loop mc.createMesh(); if(bUseFill){ fill(0,255,0); noStroke(); } else { noFill(); stroke(127); } pushMatrix(); // translate(width/2, height/2, -500); rotateX(rotationAxis.x); rotateY(rotationAxis.y); mc.renderMesh(); popMatrix(); } public void keyPressed(){ if(key == CODED){ if(keyCode == LEFT) rotationAxis.y += 0.05; if(keyCode == RIGHT) rotationAxis.y -= 0.05; if(keyCode == UP) rotationAxis.x -= 0.05; if(keyCode == DOWN) rotationAxis.x += 0.05; } else { if(key == ' '){ bUseFill = !bUseFill; } if(key == 'r' || key == 'R'){ mc.reset(); rotationAxis.set(0,0,0); } } } }
23.217054
118
0.66177
37189235a320cc58810637f6452fb4746beec3e5
327
package com.ceiba.tipo.comando; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class ComandoTipoGlamping { private Long id; private String definicion; private Long cantPersonasMax; }
15.571429
34
0.795107
1689b45e0103042638a10f49dc6ab931696b1e3e
123
package ch.itenengineering.naming.ejb; public interface AnnotationNamingRemote { public String echo(String message); }
15.375
41
0.804878
b1caac42df11c4c08ac4bff3cad37ee36a2330a5
6,282
package com.borzaindustries.dumbwiki; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import java.net.URLEncoder; import java.util.Stack; public class mainActivity extends Activity { final int DIALOG_CREATE = 1; public final int REQUEST_EDIT = 0; public final static String NAME = "NAME"; public static final String TEXT = "TEXT"; public final static String OLDNAME = "OLDNAME"; private Database db; private WikiPage page; java.util.Stack<String> history; private String currentPage; private WebView webView; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); history = new Stack<String>(); webView = (WebView) findViewById(R.id.webview); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("wiki://")) { loadWikiUrl(url); return true; } // push current page? return false; } }); db = new Database(this); db.loadPages(); db.initializeIfFirstRun(); goHome(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { goBack(); return true; } return super.onKeyDown(keyCode, event); } private void goBack() { // pop page from history and go there if (history.isEmpty()) return; String pageName = history.pop(); navigate(pageName, false); } private void goHome() { loadWikiUrl("wiki://home"); } public void loadWikiUrl(String url) { String pageName = url.substring("wiki://".length()).toLowerCase(); navigate(pageName, true); } private void navigate(String pageName, boolean push) { page = db.getPage(pageName); if (page == null) { openInEdit(pageName, ""); return; } setTitle(pageName + " - " + getString(R.string.app_name)); String data = page.RenderToHTML(db); WebView webView = (WebView) findViewById(R.id.webview); webView.loadData(URLEncoder.encode(data).replaceAll("\\+", "%20"), "text/html", "utf-8"); // push page to stack, only if it's not already at the top of the stack if (currentPage != null && push) { pushPage(currentPage); } currentPage = pageName; } private void pushPage(String current) { // if the page at top of the stack is current page, don't do anything if (!history.empty() && history.peek().equals(currentPage)) return; history.push(current); } private void openInEdit(String name, String text) { Intent intent = new Intent(getBaseContext(), EditActivity.class); intent.putExtra(NAME, name); intent.putExtra(TEXT, text); startActivityForResult(intent, REQUEST_EDIT); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_EDIT) { if (resultCode != RESULT_OK) { // cancel pressed return; } // navigate to new page // save current edited page String name = data.getExtras().getString(NAME); String text = data.getExtras().getString(TEXT); String oldname = data.getExtras().getString(OLDNAME); // delete oldname if (!oldname.equals(name)) db.deletePage(oldname); // boolean deleted = db.setPage(name, text); db.setPage(name, text); saveAll(); /* * if (deleted) goBack(); else */ navigate(name, true); } } private void saveAll() { db.savePages(); Toast.makeText(this, "Saved.", Toast.LENGTH_SHORT).show(); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_CREATE: // create a dialog that asks if crearea a new page in edit return null; } return super.onCreateDialog(id); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_edit: openInEdit(page.Name, page.Text); return true; case R.id.menu_home: goHome(); return true; case R.id.menu_back: goBack(); return true; case R.id.menu_backup: Toast.makeText(this, "Saving backup to /sdcard/dumbwiki.bak", Toast.LENGTH_SHORT).show(); db.backup(); // TODO backup() should return bool Toast.makeText(this, "Backup saved to /sdcard/dumbwiki.bak", Toast.LENGTH_SHORT).show(); // db.zap(); return true; case R.id.menu_restore: Toast.makeText(this, "Restoring from /sdcard/dumbwiki.bak", Toast.LENGTH_SHORT).show(); db.restore(); // TODO restore() should return bool Toast.makeText(this, "Restored from /sdcard/dumbwiki.bak", Toast.LENGTH_SHORT).show(); goHome(); return true; default: return super.onOptionsItemSelected(item); } } }
32.381443
83
0.566062
e518a3c6608f9465c0dea4425154d34ae7d9a281
1,643
package android.support.p001v7.app; import android.content.res.Resources.NotFoundException; import java.lang.Thread.UncaughtExceptionHandler; /* renamed from: android.support.v7.app.q */ /* compiled from: AppCompatDelegateImplBase */ class C0777q implements UncaughtExceptionHandler { /* renamed from: a */ final /* synthetic */ UncaughtExceptionHandler f2343a; C0777q(UncaughtExceptionHandler uncaughtExceptionHandler) { this.f2343a = uncaughtExceptionHandler; } public void uncaughtException(Thread thread, Throwable thowable) { if (m3662a(thowable)) { StringBuilder sb = new StringBuilder(); sb.append(thowable.getMessage()); sb.append(". If the resource you are trying to use is a vector resource, you may be referencing it in an unsupported way. See AppCompatDelegate.setCompatVectorFromResourcesEnabled() for more info."); Throwable wrapped = new NotFoundException(sb.toString()); wrapped.initCause(thowable.getCause()); wrapped.setStackTrace(thowable.getStackTrace()); this.f2343a.uncaughtException(thread, wrapped); return; } this.f2343a.uncaughtException(thread, thowable); } /* renamed from: a */ private boolean m3662a(Throwable throwable) { boolean z = false; if (!(throwable instanceof NotFoundException)) { return false; } String message = throwable.getMessage(); if (message != null && (message.contains("drawable") || message.contains("Drawable"))) { z = true; } return z; } }
37.340909
211
0.663421
14518f5183c4a17eb78b6e6bc2fb28403d67d1f8
1,160
package com.example.android.sunshine.app.watchview; import android.graphics.Bitmap; import android.graphics.Canvas; /** * Created by AArifi on 9/10/2016 * Project:Unsplash * Email "adonisarifi@gmail.com" */ public interface UnsplashContract { interface View extends BaseView<UnsplashContract.SunshinePresenter> { void setupView(android.view.View v); void initializeControls(android.view.View view); void connectToWearableApiGoogleApi(); Bitmap getImageForLevelOfBattery(String levelOfBattery); void updateTimer(); void setDateAndTime(); void requestWeatherInfoFromPhone(); void updateLayoutOnAmbientMode(Canvas canvas); void setBackground(); void setWeatherData(String highTem, String lowTem); void setLocationName(String locationName); void setSteps(); void setBateryPercentage(); void remindmetobringumbrell(); void showNearbyWatch(); void registerReceiver(); void unregisterReceiver(); } interface SunshinePresenter extends BasePresenter { void updateBackground(); } }
20.350877
73
0.687069
de7090f74fa2e8828dba3bf6ea88f4989e93e3e9
215
package designpattern.adapterpattern; /** * 适配器模式,将类的接口转换成想要的接口,来实现不同 的接口 * 真实的适配器,有的改变插座形状来匹配不同的插头。 * 有的会改变交流电为直流电这样执行复杂的操作。 * <p> * OO适配器:将现有的系统 和新增加的厂商类搭配使用是,写一个中间类。进行数据转换。 */ public class AdapterTest { }
17.916667
44
0.753488
922b3a49651ce2df09606fe46316fed5e44a4669
3,471
/** */ package org.talend.repository.generic.model.genericMetadata.impl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.talend.repository.generic.model.genericMetadata.*; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class GenericMetadataFactoryImpl extends EFactoryImpl implements GenericMetadataFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static GenericMetadataFactory init() { try { GenericMetadataFactory theGenericMetadataFactory = (GenericMetadataFactory)EPackage.Registry.INSTANCE.getEFactory(GenericMetadataPackage.eNS_URI); if (theGenericMetadataFactory != null) { return theGenericMetadataFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new GenericMetadataFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public GenericMetadataFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case GenericMetadataPackage.GENERIC_CONNECTION: return createGenericConnection(); case GenericMetadataPackage.GENERIC_CONNECTION_ITEM: return createGenericConnectionItem(); case GenericMetadataPackage.SUB_CONTAINER: return createSubContainer(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public GenericConnection createGenericConnection() { GenericConnectionImpl genericConnection = new GenericConnectionImpl(); return genericConnection; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public GenericConnectionItem createGenericConnectionItem() { GenericConnectionItemImpl genericConnectionItem = new GenericConnectionItemImpl(); return genericConnectionItem; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SubContainer createSubContainer() { SubContainerImpl subContainer = new SubContainerImpl(); return subContainer; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public GenericMetadataPackage getGenericMetadataPackage() { return (GenericMetadataPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static GenericMetadataPackage getPackage() { return GenericMetadataPackage.eINSTANCE; } } //GenericMetadataFactoryImpl
29.415254
159
0.600691
f6eb3e1b5233f9eda170d2dc30f615206218537a
254
package net.accela.prismatic.annotation; /** * Anything with a back and front buffer that can be refreshed. */ public interface BufferRefreshable { /** * Refreshes the contents of this {@link BufferRefreshable}. */ void refresh(); }
21.166667
64
0.685039
40831a5ca454c93486d2c264ec8027e0c5993f6a
1,076
package com.veadan.recManage.recController; import com.veadan.config.resultFormat.JsonResult; import com.veadan.recManage.recModel.PrintDetail; import com.veadan.recManage.recService.PrintDetailService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by Veadan on 2017/6/19. */ @RestController @RequestMapping("/api/v1/rec") @Api(value ="打印详细",description = "打印详情或列表") public class PrintDetailController { @Autowired private PrintDetailService printDetailService; @ApiOperation(value = "打印详细/列表", notes = "跟踪物资是列表,非跟踪物资是详细,recId;barcode") @PostMapping(value = "/PrintDetail",produces = "application/json") public JsonResult PrintDetailByBarcodeOrRecId(PrintDetail printDetail) { return printDetailService.printDetailFindBy(printDetail); } }
32.606061
78
0.795539
05c35751df8026121d7ad4a64c8d2f0650fc63c8
585
package Demo01File; import java.io.File; public class Demo03GetMethod { public static void main(String[] args) { File f1 = new File("F:\\wenjian"); System.out.println(f1.getAbsoluteFile()); System.out.println(f1.getName()); System.out.println(f1.toString()); System.out.println(f1.getPath()); System.out.println("=========="); File f2 = new File("C:\\Users\\wenmingbin\\Pictures\\Camera Roll"); System.out.println(f2.length()); //System.out.println("C:\\Users\\wenmingbin\\Pictures\\Camera Roll"); } }
30.789474
77
0.608547
81197bafc5d8f49ac44abd53f1d7ccadef13824a
12,093
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.governanceservers.openlineage.admin; import org.janusgraph.core.JanusGraph; import org.odpi.openmetadata.adminservices.configuration.properties.OpenLineageConfig; import org.odpi.openmetadata.adminservices.ffdc.exception.OMAGConfigurationErrorException; import org.odpi.openmetadata.frameworks.connectors.ConnectorBroker; import org.odpi.openmetadata.frameworks.connectors.ffdc.ConnectorCheckedException; import org.odpi.openmetadata.frameworks.connectors.properties.beans.Connection; import org.odpi.openmetadata.frameworks.connectors.properties.beans.Endpoint; import org.odpi.openmetadata.governanceservers.openlineage.auditlog.OpenLineageAuditCode; import org.odpi.openmetadata.governanceservers.openlineage.eventprocessors.GraphBuilder; import org.odpi.openmetadata.governanceservers.openlineage.services.GraphFactory; import org.odpi.openmetadata.governanceservers.openlineage.services.GraphServices; import org.odpi.openmetadata.governanceservers.openlineage.listeners.InTopicListener; import org.odpi.openmetadata.governanceservers.openlineage.mockdata.MockGraphGenerator; import org.odpi.openmetadata.governanceservers.openlineage.server.OpenLineageServicesInstance; import org.odpi.openmetadata.repositoryservices.auditlog.OMRSAuditLog; import org.odpi.openmetadata.repositoryservices.auditlog.OMRSAuditingComponent; import org.odpi.openmetadata.repositoryservices.connectors.openmetadatatopic.OpenMetadataTopicConnector; import org.odpi.openmetadata.repositoryservices.connectors.openmetadatatopic.OpenMetadataTopicListener; import org.odpi.openmetadata.repositoryservices.ffdc.OMRSErrorCode; import org.odpi.openmetadata.repositoryservices.ffdc.exception.OMRSConfigErrorException; import org.odpi.openmetadata.repositoryservices.ffdc.exception.RepositoryErrorException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * OpenLineageOperationalServices is responsible for controlling the startup and shutdown of * of the open lineage services. */ public class OpenLineageOperationalServices { private static final Logger log = LoggerFactory.getLogger(OpenLineageOperationalServices.class); private String localServerName; private String localServerType; private String localMetadataCollectionName; private String localOrganizationName; private String localServerUserId; private String localServerURL; private int maxPageSize; private OMRSAuditLog auditLog; private OpenMetadataTopicConnector inTopicConnector; private GraphBuilder graphBuilder; private OpenLineageServicesInstance instance; public static JanusGraph mainGraph; public static JanusGraph bufferGraph; public static JanusGraph historyGraph; public static JanusGraph mockGraph; /** * Constructor used at server startup. * * @param localServerName name of the local server * @param localServerType type of the local server * @param localOrganizationName name of the organization that owns the local server * @param localServerUserId user id for this server to use if processing inbound messages. * @param localServerURL URL root for this server. * @param maxPageSize maximum number of records that can be requested on the pageSize parameter */ public OpenLineageOperationalServices(String localServerName, String localServerType, String localOrganizationName, String localServerUserId, String localServerURL, int maxPageSize) { this.localServerName = localServerName; this.localServerType = localServerType; this.localOrganizationName = localOrganizationName; this.localServerUserId = localServerUserId; this.localServerURL = localServerURL; this.maxPageSize = maxPageSize; } public void initialize(OpenLineageConfig openLineageConfig, OMRSAuditLog auditLog) throws OMAGConfigurationErrorException { if (openLineageConfig != null) { final String actionDescription = "initialize"; OpenLineageAuditCode auditCode; auditCode = OpenLineageAuditCode.SERVICE_INITIALIZING; auditLog.logRecord(actionDescription, auditCode.getLogMessageId(), auditCode.getSeverity(), auditCode.getFormattedLogMessage(), null, auditCode.getSystemAction(), auditCode.getUserAction()); this.auditLog = auditLog; try { this.mainGraph = GraphFactory.openMainGraph(); this.bufferGraph = GraphFactory.openBufferGraph(); this.historyGraph = GraphFactory.openHistoryGraph(); this.mockGraph = GraphFactory.openMockGraph(); this.graphBuilder = new GraphBuilder(); MockGraphGenerator mockGraphGenerator = new MockGraphGenerator(); GraphServices graphServices = new GraphServices(); this.instance = new OpenLineageServicesInstance(mockGraphGenerator, graphServices, localServerName); } catch (RepositoryErrorException e) { log.error("{} Could not open graph database", "GraphBuilder constructor"); //TODO elaborate error } Connection inTopicConnection = openLineageConfig.getInTopicConnection(); String inTopicName = getTopicName(inTopicConnection); inTopicConnector = initializeOpenLineageTopicConnector(inTopicConnection); if (inTopicConnector != null) { OpenMetadataTopicListener ALOutTopicListener = new InTopicListener(graphBuilder, auditLog); this.inTopicConnector.registerListener(ALOutTopicListener); startConnector(OpenLineageAuditCode.SERVICE_REGISTERED_WITH_AL_OUT_TOPIC, actionDescription, inTopicName, inTopicConnector); } auditCode = OpenLineageAuditCode.SERVICE_INITIALIZED; auditLog.logRecord(actionDescription, auditCode.getLogMessageId(), auditCode.getSeverity(), auditCode.getFormattedLogMessage(localServerName), null, auditCode.getSystemAction(), auditCode.getUserAction()); } //TODO Error handling and logging } private String getTopicName(Connection connection) { String topicName = null; if (connection != null) { Endpoint topicEndpoint = connection.getEndpoint(); if (topicEndpoint != null) { topicName = topicEndpoint.getAddress(); } } return topicName; } /** * Returns the topic created based on connection properties * * @param topicConnection properties of the topic * @return the topic created based on the connection properties */ private OpenMetadataTopicConnector initializeOpenLineageTopicConnector(Connection topicConnection) { final String actionDescription = "initialize"; if (topicConnection != null) { try { return getTopicConnector(topicConnection); } catch (Exception e) { OpenLineageAuditCode auditCode = OpenLineageAuditCode.ERROR_INITIALIZING_CONNECTION; auditLog.logRecord(actionDescription, auditCode.getLogMessageId(), auditCode.getSeverity(), auditCode.getFormattedLogMessage(topicConnection.toString(), localServerName, e.getMessage()), null, auditCode.getSystemAction(), auditCode.getUserAction()); throw e; } } return null; } /** * Returns the connector created from topic connection properties * * @param topicConnection properties of the topic connection * @return the connector created based on the topic connection properties */ private OpenMetadataTopicConnector getTopicConnector(Connection topicConnection) { try { ConnectorBroker connectorBroker = new ConnectorBroker(); OpenMetadataTopicConnector topicConnector = (OpenMetadataTopicConnector) connectorBroker.getConnector(topicConnection); topicConnector.setAuditLog(auditLog.createNewAuditLog(OMRSAuditingComponent.OPEN_METADATA_TOPIC_CONNECTOR)); return topicConnector; } catch (Throwable error) { String methodName = "getTopicConnector"; if (log.isDebugEnabled()) { log.debug("Unable to create topic connector: " + error.toString()); } OMRSErrorCode errorCode = OMRSErrorCode.NULL_TOPIC_CONNECTOR; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage("getTopicConnector"); throw new OMRSConfigErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction(), error); } } private void startConnector(OpenLineageAuditCode auditCode, String actionDescription, String topicName, OpenMetadataTopicConnector topicConnector) throws OMAGConfigurationErrorException { auditLog.logRecord(actionDescription, auditCode.getLogMessageId(), auditCode.getSeverity(), auditCode.getFormattedLogMessage(topicName), null, auditCode.getSystemAction(), auditCode.getUserAction()); try { topicConnector.start(); } catch (ConnectorCheckedException e) { auditCode = OpenLineageAuditCode.ERROR_INITIALIZING_OPEN_LINEAGE_TOPIC_CONNECTION; auditLog.logRecord(actionDescription, auditCode.getLogMessageId(), auditCode.getSeverity(), auditCode.getFormattedLogMessage(topicName, localServerName), null, auditCode.getSystemAction(), auditCode.getUserAction()); throw new OMAGConfigurationErrorException(400, OpenLineageOperationalServices.class.getSimpleName(), actionDescription, auditCode.getFormattedLogMessage(), auditCode.getSystemAction(), auditCode.getUserAction() ); } } /** * Shutdown the Open Lineage Services. * * @param permanent boolean flag indicating whether this server permanently shutting down or not * @return boolean indicated whether the disconnect was successful. */ public boolean disconnect(boolean permanent) { try { inTopicConnector.disconnect(); } catch (ConnectorCheckedException e) { log.error("Error disconnecting Asset Lineage Out Topic Connector"); return false; } if (instance != null) { instance.shutdown(); } final String actionDescription = "shutdown"; OpenLineageAuditCode auditCode; auditCode = OpenLineageAuditCode.SERVICE_SHUTDOWN; auditLog.logRecord(actionDescription, auditCode.getLogMessageId(), auditCode.getSeverity(), auditCode.getFormattedLogMessage(localServerName), null, auditCode.getSystemAction(), auditCode.getUserAction()); return true; } }
43.974545
191
0.667494
6b007c15d404b6d45917feadb9d0b2425bda7904
9,564
package uk.gov.hmcts.reform.hmc.helper; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import uk.gov.hmcts.reform.hmc.data.ActualAttendeeIndividualDetailEntity; import uk.gov.hmcts.reform.hmc.data.ActualHearingDayEntity; import uk.gov.hmcts.reform.hmc.data.ActualHearingDayPausesEntity; import uk.gov.hmcts.reform.hmc.data.ActualHearingEntity; import uk.gov.hmcts.reform.hmc.data.ActualHearingPartyEntity; import uk.gov.hmcts.reform.hmc.data.ActualPartyRelationshipDetailEntity; import uk.gov.hmcts.reform.hmc.exceptions.BadRequestException; import uk.gov.hmcts.reform.hmc.model.ActualHearingDay; import uk.gov.hmcts.reform.hmc.model.ActualHearingDayParties; import uk.gov.hmcts.reform.hmc.model.ActualHearingDayPartyDetail; import uk.gov.hmcts.reform.hmc.model.ActualHearingDayPauseDayTime; import uk.gov.hmcts.reform.hmc.model.ActualHearingOrganisationDetail; import uk.gov.hmcts.reform.hmc.model.HearingActual; import uk.gov.hmcts.reform.hmc.model.HearingResultType; import java.util.List; import java.util.stream.Collectors; @Component public class HearingActualsMapper { public ActualHearingEntity toActualHearingEntity(HearingActual request) { ActualHearingEntity actualHearing = new ActualHearingEntity(); actualHearing.setActualHearingType(request.getHearingOutcome().getHearingType()); actualHearing.setActualHearingIsFinalFlag(request.getHearingOutcome().getHearingFinalFlag()); actualHearing.setHearingResultType(HearingResultType.getByLabel( request.getHearingOutcome().getHearingResult())); actualHearing.setHearingResultReasonType(request.getHearingOutcome().getHearingResultReasonType()); actualHearing.setHearingResultDate(request.getHearingOutcome().getHearingResultDate()); actualHearing.setActualHearingDay(toActualHearingDayEntities(request.getActualHearingDays(), actualHearing)); return actualHearing; } private List<ActualHearingDayEntity> toActualHearingDayEntities(List<ActualHearingDay> actualHearingDay, ActualHearingEntity actualHearing) { return actualHearingDay.stream() .map((ActualHearingDay day) -> toActualHearingDayEntity(day, actualHearing)) .collect(Collectors.toList()); } private ActualHearingDayEntity toActualHearingDayEntity(ActualHearingDay actualHearingDay, ActualHearingEntity actualHearing) { ActualHearingDayEntity actualHearingDayEntity = new ActualHearingDayEntity(); actualHearingDayEntity.setHearingDate(actualHearingDay.getHearingDate()); actualHearingDayEntity.setStartDateTime(actualHearingDay.getHearingStartTime()); actualHearingDayEntity.setEndDateTime(actualHearingDay.getHearingEndTime()); actualHearingDayEntity.setActualHearingDayPauses( toActualHearingDayPausesEntities(actualHearingDay.getPauseDateTimes(), actualHearingDayEntity)); actualHearingDayEntity.setActualHearingParty( toActualHearingPartyEntities(actualHearingDay.getActualDayParties(), actualHearingDayEntity)); actualHearingDayEntity.setActualHearing(actualHearing); return actualHearingDayEntity; } private List<ActualHearingDayPausesEntity> toActualHearingDayPausesEntities( List<ActualHearingDayPauseDayTime> dayPauseDayTimes, ActualHearingDayEntity dayEntity) { if (CollectionUtils.isEmpty(dayPauseDayTimes)) { return List.of(); } return dayPauseDayTimes.stream() .map(dayPauseDayTime -> toActualHearingDayPausesEntity(dayPauseDayTime, dayEntity)) .collect(Collectors.toList()); } private ActualHearingDayPausesEntity toActualHearingDayPausesEntity(ActualHearingDayPauseDayTime dayPauseDayTime, ActualHearingDayEntity dayEntity) { ActualHearingDayPausesEntity dayPausesEntity = new ActualHearingDayPausesEntity(); dayPausesEntity.setPauseDateTime(dayPauseDayTime.getPauseStartTime()); dayPausesEntity.setResumeDateTime(dayPauseDayTime.getPauseEndTime()); dayPausesEntity.setActualHearingDay(dayEntity); return dayPausesEntity; } private List<ActualHearingPartyEntity> toActualHearingPartyEntities( List<ActualHearingDayParties> actualDayParties, ActualHearingDayEntity dayEntity) { if (CollectionUtils.isEmpty(actualDayParties)) { return List.of(); } List<ActualHearingPartyEntity> actualHearingPartyEntities = actualDayParties.stream() .map(actualHearingDayParty -> toActualHearingPartyEntity( actualHearingDayParty, dayEntity )) .collect(Collectors.toList()); createActualPartyRelationshipDetailEntity(actualHearingPartyEntities, actualDayParties); return actualHearingPartyEntities; } private ActualHearingPartyEntity toActualHearingPartyEntity(ActualHearingDayParties actualHearingDayParty, ActualHearingDayEntity dayEntity) { ActualHearingPartyEntity partyEntity = new ActualHearingPartyEntity(); setOrGeneratePartyId(actualHearingDayParty, partyEntity); partyEntity.setActualPartyRoleType(actualHearingDayParty.getPartyRole()); partyEntity.setDidNotAttendFlag(actualHearingDayParty.getDidNotAttendFlag() != null ? actualHearingDayParty.getDidNotAttendFlag() : false); partyEntity.setActualAttendeeIndividualDetail(createIndividualDetail(actualHearingDayParty, partyEntity)); partyEntity.setActualHearingDay(dayEntity); return partyEntity; } private void setOrGeneratePartyId(ActualHearingDayParties actualHearingDayParty, ActualHearingPartyEntity partyEntity) { if (actualHearingDayParty.getActualPartyId() == null) { if (actualHearingDayParty.getIndividualDetails() != null) { partyEntity.setPartyId(String.valueOf(actualHearingDayParty.getIndividualDetails().hashCode())); } else if (actualHearingDayParty.getOrganisationDetails() != null) { partyEntity.setPartyId(String.valueOf(actualHearingDayParty.getOrganisationDetails().hashCode())); } } else { partyEntity.setPartyId(actualHearingDayParty.getActualPartyId()); } } private List<ActualHearingPartyEntity> createActualPartyRelationshipDetailEntity( List<ActualHearingPartyEntity> hearingPartyEntities, List<ActualHearingDayParties> actualDayParties) { for (ActualHearingDayParties actualHearingDayParty : actualDayParties) { String representedPartyId = actualHearingDayParty.getRepresentedParty(); if (representedPartyId != null) { ActualHearingPartyEntity matchingHearingPartyEntity = getHearingPartyEntityByReference(representedPartyId, hearingPartyEntities); ActualHearingPartyEntity sourceEntity = getHearingPartyEntityByReference(actualHearingDayParty.getActualPartyId(), hearingPartyEntities); ActualPartyRelationshipDetailEntity partyRelationshipDetail = ActualPartyRelationshipDetailEntity .builder() .targetActualParty(matchingHearingPartyEntity) .sourceActualParty(sourceEntity) .build(); sourceEntity.setActualPartyRelationshipDetail(List.of(partyRelationshipDetail)); } } return hearingPartyEntities; } private ActualHearingPartyEntity getHearingPartyEntityByReference( String partyId, List<ActualHearingPartyEntity> hearingPartyEntities) { final List<ActualHearingPartyEntity> matchingHearingPartyEntities = hearingPartyEntities.stream() .filter(hearingPartyEntity -> partyId.equals(hearingPartyEntity.getPartyId())) .collect(Collectors.toList()); if (matchingHearingPartyEntities.size() != 1) { throw new BadRequestException( String.format("Cannot find unique PartyID with value %s", partyId)); } return matchingHearingPartyEntities.get(0); } private ActualAttendeeIndividualDetailEntity createIndividualDetail( ActualHearingDayParties actualHearingDayParty, ActualHearingPartyEntity partyEntity) { ActualAttendeeIndividualDetailEntity individualDetailEntity = new ActualAttendeeIndividualDetailEntity(); ActualHearingDayPartyDetail individualDetails = actualHearingDayParty.getIndividualDetails(); if (individualDetails != null) { individualDetailEntity.setFirstName(individualDetails.getFirstName()); individualDetailEntity.setLastName(individualDetails.getLastName()); } ActualHearingOrganisationDetail organisationDetails = actualHearingDayParty.getOrganisationDetails(); if (organisationDetails != null) { individualDetailEntity.setPartyOrganisationName(organisationDetails.getName()); } individualDetailEntity.setPartyActualSubChannelType(actualHearingDayParty.getPartyChannelSubType()); individualDetailEntity.setActualHearingParty(partyEntity); return individualDetailEntity; } }
53.730337
117
0.732016
d9e9b2e5c207fbb285efaae3d89ff98e7b5bf883
165
package com.github.romankh3.templaterepository.springboot.dto; import lombok.Data; @Data public class LectureDTO { private Long id; private String name; }
16.5
62
0.763636
73d39d6cef4f9b29b0cba35d3e68df63e3b141cf
1,819
package com.wis.view; /** * Created by ybbz on 16/7/28. */ import java.io.IOException; import android.content.Context; import android.hardware.Camera; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder mHolder; private Camera mCamera; public static float mWidth; public static float mHeight; @SuppressWarnings("deprecation") public CameraPreview(Context context, Camera camera) { super(context); mCamera = camera; mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(SurfaceHolder holder) { try { mCamera.setPreviewDisplay(holder); mCamera.setDisplayOrientation(90); mCamera.startPreview(); } catch (IOException e) { e.printStackTrace(); } } public void surfaceDestroyed(SurfaceHolder holder) { mCamera.release(); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { mWidth = width; mHeight = height; mCamera.setDisplayOrientation(90); if (mHolder.getSurface() == null) { return; } try { mCamera.stopPreview(); } catch (Exception e) { e.printStackTrace(); } try { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (Exception e) { e.printStackTrace(); } } }
23.320513
89
0.636064
000ba14d30e8f1f02b149e9d37b90731bec7fbff
5,400
/******************************************************************************* * Copyright (c) 2012 IBM Corporation. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompanies this distribution. * * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * * Steve Pitschke - initial API and implementation *******************************************************************************/ package org.eclipse.lyo.oslc4j.bugzilla.utils; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.params.ClientPNames; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SchemeSocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.eclipse.lyo.oslc4j.bugzilla.Credentials; /** * Utility for doing HTTP GET's against Bugzilla server. */ public class BugzillaHttpClient { public BugzillaHttpClient( String rootURL, Credentials credentials ) throws UnsupportedEncodingException { this.rootURL = rootURL; authorization = "&Bugzilla_login=" + URLEncoder.encode(credentials.getUsername(), "UTF-8") + "&Bugzilla_password=" + URLEncoder.encode(credentials.getPassword(), "UTF-8"); httpClient = getHttpClient(); cntxt = new BasicHttpContext(); } public InputStream httpGet(String path) throws IOException { HttpGet get = new HttpGet(rootURL + "/" + path + authorization); get.addHeader("Referer", rootURL); HttpResponse response = httpClient.execute(get, cntxt); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { throw new IOException(status.getReasonPhrase()); } return response.getEntity().getContent(); } private static HttpClient getHttpClient() { SSLContext sc = getTrustingSSLContext(); SchemeSocketFactory sf = new SSLSocketFactory(sc); Scheme scheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(scheme); sf = PlainSocketFactory.getSocketFactory(); scheme = new Scheme("http", 80, sf); schemeRegistry.register(scheme); ClientConnectionManager clientConnectionManager = new PoolingClientConnectionManager(schemeRegistry); HttpParams clientParams = new BasicHttpParams(); clientParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT); clientParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT); clientParams.setParameter(ClientPNames.HANDLE_REDIRECTS, true); return new DefaultHttpClient(clientConnectionManager, clientParams); } private static SSLContext getTrustingSSLContext() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); return sc; } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } private final String rootURL; private final String authorization; private final HttpClient httpClient; private final HttpContext cntxt; private static final int TIMEOUT = 30000; // 30 seconds }
35.761589
105
0.671852
03c857f5f11f0133fed6ccfc5759d1c0bfd456cc
309
package io.renren.modules.app.dto; import java.util.ArrayList; import java.util.List; import lombok.Data; @Data public class TreeNode { protected int id; protected int parentId; protected List<TreeNode> children = new ArrayList<TreeNode>(); public void add(TreeNode node) { children.add(node); } }
17.166667
63
0.747573
0a61208011416362a4034e249224bf5ec1e43a50
23,600
/* * Copyright 2013-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.rules; import static com.facebook.buck.rules.TestCellBuilder.createCellRoots; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.parser.NoSuchBuildTargetException; import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory; import com.facebook.buck.testutil.FakeProjectFilesystem; import com.facebook.buck.util.ObjectMappers; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Throwables; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.junit.Before; import org.junit.Test; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; @SuppressWarnings("unused") // Many unused fields in sample DTO objects. public class ConstructorArgMarshallerTest { private Path basePath; private ConstructorArgMarshaller marshaller; private BuildRuleResolver ruleResolver; private ProjectFilesystem filesystem; @Before public void setUpInspector() { basePath = Paths.get("example", "path"); marshaller = new ConstructorArgMarshaller(new DefaultTypeCoercerFactory( ObjectMappers.newDefaultInstance())); ruleResolver = new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); filesystem = new FakeProjectFilesystem(); } @Test public void shouldNotPopulateAnEmptyArg() throws NoSuchBuildTargetException { class Dto { } Dto dto = new Dto(); try { marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of()); } catch (RuntimeException | ConstructorArgMarshalException e) { fail("Did not expect an exception to be thrown:\n" + Throwables.getStackTraceAsString(e)); } } @Test public void shouldPopulateAStringValue() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public String name; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("name", "cheese")); assertEquals("cheese", dto.name); } @Test public void shouldPopulateABooleanValue() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public boolean value; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("value", true)); assertTrue(dto.value); } @Test public void shouldPopulateBuildTargetValues() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public BuildTarget target; public BuildTarget local; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of( "target", "//cake:walk", "local", ":fish" )); assertEquals(BuildTargetFactory.newInstance(filesystem, "//cake:walk"), dto.target); assertEquals(BuildTargetFactory.newInstance(filesystem, "//example/path:fish"), dto.local); } @Test public void shouldPopulateANumericValue() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public long number; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("number", 42L)); assertEquals(42, dto.number); } @Test public void shouldPopulateAPathValue() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { @Hint(name = "some_path") public Path somePath; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("somePath", "Fish.java")); assertEquals(Paths.get("example/path", "Fish.java"), dto.somePath); } @Test public void shouldPopulateSourcePaths() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public SourcePath filePath; public SourcePath targetPath; } ProjectFilesystem projectFilesystem = new FakeProjectFilesystem(); BuildTarget target = BuildTargetFactory.newInstance("//example/path:peas"); SourcePathResolver resolver = new SourcePathResolver( new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()) ); FakeBuildRule rule = new FakeBuildRule(target, resolver); ruleResolver.addToIndex(rule); Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of( "filePath", "cheese.txt", "targetPath", ":peas" )); assertEquals( new PathSourcePath(projectFilesystem, Paths.get("example/path/cheese.txt")), dto.filePath); assertEquals( new BuildTargetSourcePath(rule.getBuildTarget()), dto.targetPath); } @Test public void shouldPopulateAnImmutableSortedSet() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public ImmutableSortedSet<BuildTarget> deps; } BuildTarget t1 = BuildTargetFactory.newInstance("//please/go:here"); BuildTarget t2 = BuildTargetFactory.newInstance("//example/path:there"); Dto dto = new Dto(); // Note: the ordering is reversed from the natural ordering marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("deps", ImmutableList.of("//please/go:here", ":there"))); assertEquals(ImmutableSortedSet.of(t2, t1), dto.deps); } @Test public void shouldPopulateSets() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public Set<Path> paths; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("paths", ImmutableList.of("one", "two"))); assertEquals( ImmutableSet.of(Paths.get("example/path/one"), Paths.get("example/path/two")), dto.paths); } @Test public void shouldPopulateLists() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public List<String> list; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("list", ImmutableList.of("alpha", "beta"))); assertEquals(ImmutableList.of("alpha", "beta"), dto.list); } @Test public void collectionsCanBeOptionalAndWillBeSetToAnOptionalEmptyCollectionIfMissing() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public Optional<Set<BuildTarget>> targets; } Dto dto = new Dto(); Map<String, Object> args = Maps.newHashMap(); args.put("targets", Lists.newArrayList()); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), args); assertEquals(Optional.of((Set<BuildTarget>) Sets.<BuildTarget>newHashSet()), dto.targets); } @Test public void onlyFieldNamedDepsAreConsideredDeclaredDeps() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public Optional<Set<BuildTarget>> deps; public Optional<Set<BuildTarget>> notdeps; } final String dep = "//is/a/declared:dep"; final String notDep = "//is/not/a/declared:dep"; BuildTarget declaredDep = BuildTargetFactory.newInstance(dep); Dto dto = new Dto(); Map<String, Object> args = Maps.newHashMap(); args.put("deps", ImmutableList.of(dep)); args.put("notdeps", ImmutableList.of(notDep)); ImmutableSet.Builder<BuildTarget> declaredDeps = ImmutableSet.builder(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, declaredDeps, ImmutableSet.<VisibilityPattern>builder(), args); assertEquals(ImmutableSet.of(declaredDep), declaredDeps.build()); } @Test public void fieldsWithIsDepEqualsFalseHintAreNotTreatedAsDeps() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { @Hint(isDep = false) public Optional<Set<BuildTarget>> deps; } final String dep = "//should/be:ignored"; Dto dto = new Dto(); Map<String, Object> args = Maps.newHashMap(); args.put("deps", ImmutableList.of(dep)); ImmutableSet.Builder<BuildTarget> declaredDeps = ImmutableSet.builder(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, declaredDeps, ImmutableSet.<VisibilityPattern>builder(), args); assertEquals(ImmutableSet.of(), declaredDeps.build()); } @Test public void optionalCollectionsWithoutAValueWillBeSetToAnEmptyOptionalCollection() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public Optional<Set<String>> strings; } Dto dto = new Dto(); Map<String, Object> args = Maps.newHashMap(); // Deliberately not populating args marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), args); assertEquals(Optional.of((Set<String>) Sets.<String>newHashSet()), dto.strings); } @Test(expected = ConstructorArgMarshalException.class) public void shouldBeAnErrorToAttemptToSetASingleValueToACollection() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public String file; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("file", ImmutableList.of("a", "b"))); } @Test(expected = ConstructorArgMarshalException.class) public void shouldBeAnErrorToAttemptToSetACollectionToASingleValue() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public Set<String> strings; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("strings", "isn't going to happen")); } @Test(expected = ConstructorArgMarshalException.class) public void shouldBeAnErrorToSetTheWrongTypeOfValueInACollection() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public Set<String> strings; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("strings", ImmutableSet.of(true, false))); } @Test public void shouldNormalizePaths() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public Path path; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("path", "./bar/././fish.txt")); assertEquals(basePath.resolve("bar/fish.txt").normalize(), dto.path); } @Test(expected = RuntimeException.class) public void lowerBoundGenericTypesCauseAnException() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public List<? super BuildTarget> nope; } marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), new Dto(), ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("nope", ImmutableList.of("//will/not:happen"))); } public void shouldSetBuildTargetParameters() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public BuildTarget single; public BuildTarget sameBuildFileTarget; public List<BuildTarget> targets; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of( "single", "//com/example:cheese", "sameBuildFileTarget", ":cake", "targets", ImmutableList.of(":cake", "//com/example:cheese") )); BuildTarget cheese = BuildTargetFactory.newInstance("//com/example:cheese"); BuildTarget cake = BuildTargetFactory.newInstance("//example/path:cake"); assertEquals(cheese, dto.single); assertEquals(cake, dto.sameBuildFileTarget); assertEquals(ImmutableList.of(cake, cheese), dto.targets); } @Test public void upperBoundGenericTypesCauseValuesToBeSetToTheUpperBound() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public List<? extends SourcePath> yup; } SourcePathResolver pathResolver = new SourcePathResolver( new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()) ); BuildRule rule = new FakeBuildRule( BuildTargetFactory.newInstance("//will:happen"), pathResolver); ruleResolver.addToIndex(rule); Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of( "yup", ImmutableList.of(rule.getBuildTarget().getFullyQualifiedName()))); BuildTargetSourcePath path = new BuildTargetSourcePath(rule.getBuildTarget()); assertEquals(ImmutableList.of(path), dto.yup); } @Test public void specifyingZeroIsNotConsideredOptional() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public Optional<Integer> number; } Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of("number", 0)); assertTrue(dto.number.isPresent()); assertEquals(Optional.of(0), dto.number); } @Test public void canPopulateSimpleConstructorArgFromBuildFactoryParams() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public String required; public Optional<String> notRequired; public int num; // Turns out there no optional number params //public Optional<Long> optionalLong; public boolean needed; public Optional<Boolean> notNeeded; public SourcePath aSrcPath; public Optional<SourcePath> notASrcPath; public Path aPath; public Optional<Path> notAPath; } SourcePathResolver resolver = new SourcePathResolver( new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()) ); FakeBuildRule expectedRule = new FakeBuildRule( BuildTargetFactory.newInstance("//example/path:path"), resolver); ruleResolver.addToIndex(expectedRule); ImmutableMap<String, Object> args = ImmutableMap.<String, Object>builder() .put("required", "cheese") .put("notRequired", "cake") // Long because that's what comes from python. .put("num", 42L) // Skipping optional Long. .put("needed", true) // Skipping optional boolean. .put("aSrcPath", ":path") .put("aPath", "./File.java") .put("notAPath", "./NotFile.java") .build(); Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), args); assertEquals("cheese", dto.required); assertEquals("cake", dto.notRequired.get()); assertEquals(42, dto.num); assertTrue(dto.needed); assertEquals(Optional.<Boolean>absent(), dto.notNeeded); BuildTargetSourcePath expected = new BuildTargetSourcePath(expectedRule.getBuildTarget()); assertEquals(expected, dto.aSrcPath); assertEquals(Paths.get("example/path/NotFile.java"), dto.notAPath.get()); } @Test /** * Since we populated the params from the python script, and the python script inserts default * values instead of nulls it's never possible for someone to see "Optional.absent()", but that's * what we want as authors of buildables. Handle that case. */ public void shouldPopulateDefaultValuesAsBeingAbsent() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public Optional<String> noString; public Optional<String> defaultString; public Optional<SourcePath> noSourcePath; public Optional<SourcePath> defaultSourcePath; public int primitiveNum; public Integer wrapperObjectNum; public boolean primitiveBoolean; public Boolean wrapperObjectBoolean; } // This is not an ImmutableMap so we can test null values. Map<String, Object> args = Maps.newHashMap(); args.put("defaultString", null); args.put("defaultSourcePath", null); Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), args); assertEquals(Optional.<String>absent(), dto.noString); assertEquals(Optional.<String>absent(), dto.defaultString); assertEquals(Optional.<SourcePath>absent(), dto.noSourcePath); assertEquals(Optional.<SourcePath>absent(), dto.defaultSourcePath); assertEquals(0, dto.primitiveNum); assertEquals(Integer.valueOf(0), dto.wrapperObjectNum); } @Test public void shouldResolveCollectionOfSourcePaths() throws ConstructorArgMarshalException, NoSuchBuildTargetException { class Dto { public ImmutableSortedSet<SourcePath> srcs; } BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); BuildTarget target = BuildTargetFactory.newInstance("//example/path:manifest"); BuildRule rule = new FakeBuildRule(target, new SourcePathResolver(resolver)); resolver.addToIndex(rule); Dto dto = new Dto(); marshaller.populate( createCellRoots(filesystem), filesystem, buildRuleFactoryParams(), dto, ImmutableSet.<BuildTarget>builder(), ImmutableSet.<VisibilityPattern>builder(), ImmutableMap.<String, Object>of( "srcs", ImmutableList.of("main.py", "lib/__init__.py", "lib/manifest.py"))); ImmutableSet<String> observedValues = FluentIterable.from(dto.srcs) .transform( new Function<SourcePath, String>() { @Nullable @Override public String apply(SourcePath input) { return ((PathSourcePath) input).getRelativePath().toString(); } }) .toSet(); assertEquals( ImmutableSet.of( Paths.get("example/path/main.py").toString(), Paths.get("example/path/lib/__init__.py").toString(), Paths.get("example/path/lib/manifest.py").toString()), observedValues); } public BuildRuleFactoryParams buildRuleFactoryParams() { BuildTarget target = BuildTargetFactory.newInstance("//example/path:three"); return new BuildRuleFactoryParams(new FakeProjectFilesystem(), target); } }
31.891892
99
0.685254
1d26096c1837a7e327e6a768d357af7b106a5d09
3,250
package com.wildsmith.material.playground; import android.content.Context; import android.util.Log; import android.view.View; import android.view.ViewGroup; import com.wildsmith.material.list.ListRow; import com.wildsmith.material.list.ListRowAdapter; import com.wildsmith.material.playground.rows.PlaygroundActionBarCardRow; import com.wildsmith.material.playground.rows.PlaygroundActionCardRow; import com.wildsmith.material.playground.rows.PlaygroundElevationCardRow; import com.wildsmith.material.playground.rows.PlaygroundNavigationCardRow; public class PlaygroundListRowAdapter extends ListRowAdapter { private static final String TAG = PlaygroundListRowAdapter.class.getSimpleName(); // private int mPosition; public PlaygroundListRowAdapter(Context pContext, int pViewResourceId) { super(pContext, pViewResourceId); } @Override public View getView(int position, View convertView, ViewGroup parent) { ListRow mRow = getRow(position); if (mRow == null) { return null; } try { View view = mRow.getView(mInflater, convertView, mContext, position); // if (mPosition > position) { // animateViewDown(view); // } else if (mPosition < position) { // animateViewUp(view); // } // mPosition = position; return view; } catch (Exception e) { Log.e(TAG, "Could not create the given row for position: " + position + "." + e.getMessage()); } return null; } // private void animateViewUp(View view) { // // get the center for the clipping circle // int cx = (view.getLeft() + view.getRight()) / 2; // // // get the final radius for the clipping circle // int finalRadius = view.getWidth(); // // // create and start the animator for this view // // (the start radius is zero) // ValueAnimator anim = ViewAnimationUtils.createCircularReveal(view, cx, view.getBottom(), 0, // finalRadius); // anim.start(); // } // // private void animateViewDown(View view) { // // get the center for the clipping circle // int cx = (view.getLeft() + view.getRight()) / 2; // // // get the final radius for the clipping circle // int finalRadius = view.getWidth(); // // // create and start the animator for this view // // (the start radius is zero) // ValueAnimator anim = ViewAnimationUtils.createCircularReveal(view, cx, view.getTop(), 0, // finalRadius); // anim.start(); // } @Override public int getViewTypeCount() { return 4; } @Override public int getItemViewType(int position) { if (mRows == null || mRows.isEmpty() || mRows.size() < position) { return -1; } ListRow row = mRows.get(position); if (row instanceof PlaygroundActionBarCardRow) { return 0; } else if (row instanceof PlaygroundActionCardRow) { return 1; } else if (row instanceof PlaygroundNavigationCardRow) { return 2; } else if (row instanceof PlaygroundElevationCardRow) { return 3; } return -1; } }
31.553398
106
0.630154
aceffce511f9603b6f14ead8e38d9abb39509f5d
3,372
package CommandTree; import Errors.InvalidCommandException; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.regex.Pattern; /** * This class takes in a command from a user as a string and then converts that string into usable information for other * classes to create the command nodes. The StringParser is created by the controller class. * * @author Duc Tran * @author Robert Duval */ public class StringParser { private static String WHITESPACE_TRIM = "\\s+"; private List<Entry<String, Pattern>> mySymbols; private List<String> myFilter = new ArrayList<>(); /** * The constructor reads in a list of strings that should be dealt with differently if encountered. Also sets * the initial language to English. */ public StringParser(){ mySymbols = new ArrayList<>(); var filterList = ResourceBundle.getBundle("languages/Filter"); for (var key : Collections.list(filterList.getKeys())){ myFilter.add(key); } setLanguage("English"); } /** * Adds the given resource file to this language's recognized types */ private void addPatterns (String syntax) { var resources = ResourceBundle.getBundle(syntax); for (var key : Collections.list(resources.getKeys())) { var regex = resources.getString(key); mySymbols.add(0, new SimpleEntry<>(key, Pattern.compile(regex, Pattern.CASE_INSENSITIVE))); } } /** * Takes in a language and sets the StringParser's understood language to the new language. * * @param language The language that the StringParser will be set too. */ public void setLanguage(String language){ mySymbols.clear(); addPatterns("languages/Syntax"); addPatterns("languages/" + language); } /** * Takes in the user's command and then using the set language, translates the command into an array of string that * the command tree class can use. * * @param command The command that the user inputs. * * @return An array of strings with that the command tree class will use. Throws an error if a command is not correct. */ public String[] parseCommand(String command){ if(command.indexOf("#")!=-1) { command = command.substring(0, command.indexOf("#")); } var commandWords = command.split(WHITESPACE_TRIM); var parsedCommand = new String[commandWords.length]; for(int i = 0; i < commandWords.length; i++){ if(!myFilter.contains(getSymbol(commandWords[i]))){ parsedCommand[i] = getSymbol(commandWords[i]).toLowerCase(); }else { parsedCommand[i] = commandWords[i]; } } return parsedCommand; } /** * Returns language's type associated with the given text if one exists */ private String getSymbol (String text) { for (var e : mySymbols) { if (match(text, e.getValue())) { return e.getKey(); } } throw new InvalidCommandException(); } /** * Returns true if the given text matches the given regular expression pattern */ private boolean match (String text, Pattern regex) { return regex.matcher(text).matches(); } }
32.114286
121
0.662515
8d68943bbfb4757a36baeb7d2099ecfd0545416b
29,758
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package etrt.system; import etrt.database.My_CNX; import java.awt.Color; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.border.Border; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingConstants; /** * * @author leduy */ public class Visit_Form extends javax.swing.JFrame { String visit_id; String visit_date; String visit_number; String patient_name; String thc; /** * Creates new form Visit_Form */ public Visit_Form() { initComponents(); this.setLocationRelativeTo(null); } public Visit_Form(int thc_int){ initComponents(); this.setLocationRelativeTo(null); thc = String.valueOf(thc_int); jTextField_THC.setText(thc); PreparedStatement st; ResultSet rs; // SELECT * FROM visit NATURAL JOIN patient WHERE visit_number = (SELECT MAX(visit_number) FROM visit WHERE thc = 120) AND thc =120; String query = "SELECT * FROM `visit` NATURAL JOIN `patient` WHERE `visit_number` = (SELECT MAX(`visit_number`) FROM `visit` WHERE `thc` = ?) AND `thc` =?"; try { st = My_CNX.getConnection().prepareStatement(query); st.setInt(1, thc_int); st.setInt(2, thc_int); rs = st.executeQuery(); if(rs.next()) { visit_id = rs.getString("visit_id"); visit_date = rs.getString("visit_date"); visit_number = String.valueOf(rs.getInt("visit_number")); patient_name = rs.getString("first_name")+ " " +rs.getString("last_name"); jTextField_Visit_ID.setText(visit_id); jTextField_Date.setText(visit_date); jTextField_VisitNo.setText(visit_number); jTextField_Patient_Name.setText(patient_name); } }catch (SQLException ex) { Logger.getLogger(Visit_Form.class.getName()).log(Level.SEVERE, null, ex); } } public Visit_Form(int thc_int, int visit_id_int){ initComponents(); this.setLocationRelativeTo(null); thc = String.valueOf(thc_int); jTextField_THC.setText(thc); visit_id = String.valueOf(visit_id_int); PreparedStatement st; ResultSet rs; String query = "SELECT * FROM `visit` NATURAL JOIN `patient` WHERE `thc` = ? AND visit_id = ?"; String query1 = "SELECT * FROM `visit` WHERE `thc` = ? AND `visit_id` = ?"; try { st = My_CNX.getConnection().prepareStatement(query); st.setInt(1, thc_int); st.setInt(2, visit_id_int); rs = st.executeQuery(); if(rs.next()) { visit_id = rs.getString("visit_id"); visit_date = rs.getString("visit_date"); visit_number = String.valueOf(rs.getInt("visit_number")); patient_name = rs.getString("first_name")+ " " +rs.getString("last_name"); jTextField_Visit_ID.setText(visit_id); jTextField_Date.setText(visit_date); jTextField_VisitNo.setText(visit_number); jTextField_Patient_Name.setText(patient_name); } }catch (SQLException ex) { Logger.getLogger(Visit_Form.class.getName()).log(Level.SEVERE, null, ex); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jButton_Initial = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jTextField_Visit_ID = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jTextField_Patient_Name = new javax.swing.JTextField(); jTextField_Date = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jTextField_THC = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jTextField_VisitNo = new javax.swing.JTextField(); jButton_Initial1 = new javax.swing.JButton(); jButton_Initial2 = new javax.swing.JButton(); jButton_Initial3 = new javax.swing.JButton(); jLabel_minimize = new javax.swing.JLabel(); jLabel_close = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); jPanel1.setBackground(new java.awt.Color(204, 204, 204)); jPanel2.setBackground(new java.awt.Color(102, 102, 102)); jButton_Initial.setBackground(new java.awt.Color(0, 84, 140)); jButton_Initial.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 14)); // NOI18N jButton_Initial.setForeground(new java.awt.Color(255, 255, 255)); jButton_Initial.setText("<html><center>Audiology </center></html>"); jButton_Initial.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton_Initial.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { jButton_InitialMouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jButton_InitialMouseEntered(evt); } }); jButton_Initial.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_InitialActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setText("Visit ID :"); jTextField_Visit_ID.setEditable(false); jTextField_Visit_ID.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField_Visit_IDActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel4.setText("Patient : "); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setText("Date:"); jTextField_Patient_Name.setEditable(false); jTextField_Date.setEditable(false); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel5.setText("THC#: "); jTextField_THC.setEditable(false); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel6.setText("Visit no."); jTextField_VisitNo.setEditable(false); jButton_Initial1.setBackground(new java.awt.Color(0, 84, 140)); jButton_Initial1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 14)); // NOI18N jButton_Initial1.setForeground(new java.awt.Color(255, 255, 255)); jButton_Initial1.setText("<html><center>Interview </center></html>"); jButton_Initial1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton_Initial1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { jButton_Initial1MouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jButton_Initial1MouseEntered(evt); } }); jButton_Initial1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_Initial1ActionPerformed(evt); } }); jButton_Initial2.setBackground(new java.awt.Color(0, 84, 140)); jButton_Initial2.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 14)); // NOI18N jButton_Initial2.setForeground(new java.awt.Color(255, 255, 255)); jButton_Initial2.setText("<html><center>Medical other </center></html>"); jButton_Initial2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton_Initial2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { jButton_Initial2MouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jButton_Initial2MouseEntered(evt); } }); jButton_Initial2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_Initial2ActionPerformed(evt); } }); jButton_Initial3.setBackground(new java.awt.Color(0, 84, 140)); jButton_Initial3.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 14)); // NOI18N jButton_Initial3.setForeground(new java.awt.Color(255, 255, 255)); jButton_Initial3.setText("<html><center>Diagnose </center></html>"); jButton_Initial3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton_Initial3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { jButton_Initial3MouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jButton_Initial3MouseEntered(evt); } }); jButton_Initial3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_Initial3ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(45, 45, 45) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_Patient_Name, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_THC, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_VisitNo, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField_Visit_ID, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(15, 15, 15) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_Date, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(39, 39, 39) .addComponent(jButton_Initial1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton_Initial, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton_Initial2, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton_Initial3, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(47, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField_Visit_ID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(jTextField_Date, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextField_THC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(jTextField_VisitNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTextField_Patient_Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(34, 34, 34) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_Initial1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton_Initial, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton_Initial2, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton_Initial3, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(44, Short.MAX_VALUE)) ); jLabel_minimize.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel_minimize.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel_minimize.setText("-"); jLabel_minimize.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabel_minimize.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel_minimizeMouseClicked(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jLabel_minimizeMouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jLabel_minimizeMouseEntered(evt); } }); jLabel_close.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N jLabel_close.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel_close.setText("X"); jLabel_close.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabel_close.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel_closeMouseClicked(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jLabel_closeMouseExited(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jLabel_closeMouseEntered(evt); } }); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Visits"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel_minimize, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel_close, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(9, 9, 9)) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel_close) .addComponent(jLabel_minimize) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton_InitialMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton_InitialMouseExited // TODO add your handling code here: }//GEN-LAST:event_jButton_InitialMouseExited private void jButton_InitialMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton_InitialMouseEntered // TODO add your handling code here: }//GEN-LAST:event_jButton_InitialMouseEntered private void jButton_InitialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_InitialActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton_InitialActionPerformed private void jLabel_minimizeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_minimizeMouseClicked this.setState(JFrame.ICONIFIED); }//GEN-LAST:event_jLabel_minimizeMouseClicked private void jLabel_minimizeMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_minimizeMouseExited Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black); jLabel_minimize.setBorder(label_border); jLabel_minimize.setForeground(Color.black); }//GEN-LAST:event_jLabel_minimizeMouseExited private void jLabel_minimizeMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_minimizeMouseEntered Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.white); jLabel_minimize.setBorder(label_border); jLabel_minimize.setForeground(Color.white); }//GEN-LAST:event_jLabel_minimizeMouseEntered private void jLabel_closeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_closeMouseClicked System.exit(0); }//GEN-LAST:event_jLabel_closeMouseClicked private void jLabel_closeMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_closeMouseExited Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black); jLabel_close.setBorder(label_border); jLabel_close.setForeground(Color.black); }//GEN-LAST:event_jLabel_closeMouseExited private void jLabel_closeMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_closeMouseEntered Border label_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.white); jLabel_close.setBorder(label_border); jLabel_close.setForeground(Color.white); }//GEN-LAST:event_jLabel_closeMouseEntered private void jButton_Initial1MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton_Initial1MouseExited // TODO add your handling code here: }//GEN-LAST:event_jButton_Initial1MouseExited private void jButton_Initial1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton_Initial1MouseEntered // TODO add your handling code here: }//GEN-LAST:event_jButton_Initial1MouseEntered private void jButton_Initial1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Initial1ActionPerformed // TODO add your handling code here: Interview_form form = new Interview_form(visit_id, visit_date,visit_number,thc,patient_name); form.setVisible(true); form.pack(); form.setLocationRelativeTo(null); this.dispose(); }//GEN-LAST:event_jButton_Initial1ActionPerformed private void jButton_Initial2MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton_Initial2MouseExited // TODO add your handling code here: }//GEN-LAST:event_jButton_Initial2MouseExited private void jButton_Initial2MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton_Initial2MouseEntered // TODO add your handling code here: }//GEN-LAST:event_jButton_Initial2MouseEntered private void jButton_Initial2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Initial2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton_Initial2ActionPerformed private void jButton_Initial3MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton_Initial3MouseExited // TODO add your handling code here: }//GEN-LAST:event_jButton_Initial3MouseExited private void jButton_Initial3MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton_Initial3MouseEntered // TODO add your handling code here: }//GEN-LAST:event_jButton_Initial3MouseEntered private void jButton_Initial3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Initial3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton_Initial3ActionPerformed private void jTextField_Visit_IDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_Visit_IDActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField_Visit_IDActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Visit_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Visit_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Visit_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Visit_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Visit_Form().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_Initial; private javax.swing.JButton jButton_Initial1; private javax.swing.JButton jButton_Initial2; private javax.swing.JButton jButton_Initial3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel_close; private javax.swing.JLabel jLabel_minimize; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JTextField jTextField_Date; private javax.swing.JTextField jTextField_Patient_Name; private javax.swing.JTextField jTextField_THC; private javax.swing.JTextField jTextField_VisitNo; private javax.swing.JTextField jTextField_Visit_ID; // End of variables declaration//GEN-END:variables }
52.950178
182
0.668459
aa43fc0803c8f225a1927b9866572cef2217ece4
1,922
package com.quasar.sika.design.server.business.role.controller; import java.util.List; import com.sika.code.result.Result; import com.sika.code.standard.base.controller.BaseStandardController; import com.quasar.sika.design.server.business.role.service.RoleService; import com.quasar.sika.design.server.business.role.pojo.dto.RoleDTO; import com.quasar.sika.design.server.business.role.pojo.query.RoleQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <p> * 角色信息表 前端控制器 * </p> * * @author daiqi * @since 2021-01-07 23:35:59 */ @RestController(value = "roleController") @RequestMapping("role") public class RoleController extends BaseStandardController { @Autowired private RoleService roleService; @RequestMapping(value = "save") public Result save(@RequestBody RoleDTO roleDto) { return super.success(roleService.save(roleDto)); } @RequestMapping(value = "save_batch") public Result saveBatch(@RequestBody List<RoleDTO> roleDtos) { return super.success(roleService.saveForBatch(roleDtos)); } @RequestMapping(value = "update_by_id") public Result updateById(@RequestBody RoleDTO roleDto) { return super.success(roleService.updateById(roleDto)); } @RequestMapping(value = "page") public Result page(@RequestBody RoleQuery roleQuery) { return super.success(roleService.page(roleQuery)); } @RequestMapping(value = "find") public Result find(@RequestBody RoleQuery roleQuery) { return super.success(roleService.find(roleQuery)); } @RequestMapping(value = "list") public Result list(@RequestBody RoleQuery roleQuery) { return super.success(roleService.list(roleQuery)); } }
33.137931
72
0.744017