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
|
---|---|---|---|---|---|
5772b2a52f9d105178604cf1021d6d180a2d98fa | 493 | package org.endeavourhealth.transform.tpp.xml.transforms;
import org.endeavourhealth.transform.tpp.xml.schema.Event;
import org.endeavourhealth.transform.tpp.xml.schema.Relationship;
import org.hl7.fhir.instance.model.Encounter;
import org.hl7.fhir.instance.model.Resource;
import java.util.List;
public class RelationshipTransformer {
public static void transform(List<Relationship> tppRelationships, Event tppEvent, Encounter fhirEncounter, List<Resource> fhirResources) {
}
}
| 29 | 142 | 0.813387 |
2e689814a2f8d6a96526b779c08365ce24bb8d7a | 1,511 | package br.gov.sp.fatec.saloon.model.repository.regi;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import br.gov.sp.fatec.saloon.model.entity.regi.Usuario;
/**
* @apiNote Dao da entidade Usuario
*
* I Spring fornece um Query Method Meu resultado pode voltar uma lista
* ou somente um O nome do método tem que começar com "findBy" +
* atributo Ex. para o atributo "nome" findByNome (Que seria o mesmo
* que findByNomeEquals) Ex. para usar o like findByNomeContains(String
* nome); findByNomeContainsIgnoreCase(String nome);
*
*/
@Repository
public interface UsuarioRepository extends JpaRepository<Usuario, Long>{
@Query("select u from Usuario u inner join u.usuarioNivel n where n.key = 'ROLE_PROPRIETARIO'")
public List<Usuario> buscarUsuariosProprietarios();
@Query("select u from Usuario u where u.id = ?1")
public Usuario buscarPorId(Long id);
@Query("select n.key from Usuario u inner join u.usuarioNivel n where u.id = ?1")
public String[] niveis(Long id);
public Optional<Usuario> findById(Long id);
public Usuario findByApelido(String apelido);
public List<Usuario> findByNomeContainsIgnoreCase(String nome);
public List<Usuario> findByCpfContainsIgnoreCase(String cpf);
public boolean existsByApelido(String descr);
}
| 33.577778 | 99 | 0.735936 |
2163bb7570d8adc7cf5be86c1c8e77fe5e1761c6 | 2,246 | package com.avaje.ebeaninternal.server.deploy;
import java.lang.reflect.Method;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import com.avaje.ebeaninternal.server.reflect.BeanReflectGetter;
/**
* For abstract classes that hold the id property we need to
* use reflection to get the id values some times.
* <p>
* This provides the BeanReflectGetter objects to do that.
* </p>
* @author rbygrave
*/
public class ReflectGetter {
/**
* Create a reflection based BeanReflectGetter for getting the
* id from abstract inheritance hierarchy object.
*/
public static BeanReflectGetter create(DeployBeanProperty prop) {
if (!prop.isId()){
// not expecting this to ever be used/called
return new NonIdGetter(prop.getFullBeanName());
} else {
String property = prop.getFullBeanName();
Method readMethod = prop.getReadMethod();
if (readMethod == null){
String m = "Abstract class with no readMethod for "+property;
throw new RuntimeException(m);
}
return new IdGetter(property, readMethod);
}
}
public static class IdGetter implements BeanReflectGetter {
public static final Object[] NO_ARGS = new Object[0];
private final Method readMethod;
private final String property;
public IdGetter(String property, Method readMethod) {
this.property = property;
this.readMethod = readMethod;
}
public Object get(Object bean) {
try {
return readMethod.invoke(bean, NO_ARGS);
} catch (Exception e) {
String m = "Error on ["+property+"] using readMethod "+readMethod;
throw new RuntimeException(m, e);
}
}
public Object getIntercept(Object bean) {
return get(bean);
}
}
public static class NonIdGetter implements BeanReflectGetter {
private final String property;
public NonIdGetter(String property) {
this.property = property;
}
public Object get(Object bean) {
String m = "Not expecting this method to be called on ["+property
+"] as it is a NON ID property on an abstract class";
throw new RuntimeException(m);
}
public Object getIntercept(Object bean) {
return get(bean);
}
}
}
| 26.116279 | 71 | 0.679875 |
01d938318869c680d96b2cc8aba9bafb641b1cbd | 3,897 | /**
*
*/
package br.com.swconsultoria.efd.icms.registros.blocoB;
import java.util.ArrayList;
import java.util.List;
/**
* @author Sidnei Klein
*/
public class RegistroB001 {
private final String reg = "B001";
private String ind_dad;
private RegistroB020 registroB020;
private List<RegistroB030> registroB030;
private List<RegistroB350> registroB350;
private List<RegistroB420> registroB420;
private List<RegistroB440> registroB440;
private List<RegistroB460> registroB460;
private RegistroB470 registroB470;
private RegistroB500 registroB500;
/**
* @return the reg
*/
public String getReg() {
return reg;
}
/**
* @return the ind_dad
*/
public String getInd_dad() {
return ind_dad;
}
/**
* @param ind_dad the ind_dad to set
*/
public void setInd_dad(String ind_dad) {
this.ind_dad = ind_dad;
}
/**
* @return the registroB020
*/
public RegistroB020 getRegistroB020() {
return registroB020;
}
/**
* @param registroB020 the registroB020 to set
*/
public void setRegistroB020(RegistroB020 registroB020) {
this.registroB020 = registroB020;
}
/**
* @return the registroB030
*/
public List<RegistroB030> getRegistroB030() {
return registroB030;
}
/**
* @param registroB030 the registroB030 to set
*/
public void setRegistroB030(List<RegistroB030> registroB030) {
if (registroB030 == null) {
registroB030 = new ArrayList<>();
}
this.registroB030 = registroB030;
}
/**
* @return the registroB350
*/
public List<RegistroB350> getRegistroB350() {
return registroB350;
}
/**
* @param registroB350 the registroB350 to set
*/
public void setRegistroB350(List<RegistroB350> registroB350) {
if (registroB350 == null) {
registroB350 = new ArrayList<>();
}
this.registroB350 = registroB350;
}
/**
* @return the registroB420
*/
public List<RegistroB420> getRegistroB420() {
return registroB420;
}
/**
* @param registroB420 the registroB420 to set
*/
public void setRegistroB420(List<RegistroB420> registroB420) {
if (registroB420 == null) {
registroB420 = new ArrayList<>();
}
this.registroB420 = registroB420;
}
/**
* @return the registroB440
*/
public List<RegistroB440> getRegistroB440() {
return registroB440;
}
/**
* @param registroB440 the registroB440 to set
*/
public void setRegistroB440(List<RegistroB440> registroB440) {
if (registroB440 == null) {
registroB440 = new ArrayList<>();
}
this.registroB440 = registroB440;
}
/**
* @return the registroB460
*/
public List<RegistroB460> getRegistroB460() {
return registroB460;
}
/**
* @param registroB460 the registroB460 to set
*/
public void setRegistroB460(List<RegistroB460> registroB460) {
if (registroB460 == null) {
registroB460 = new ArrayList<>();
}
this.registroB460 = registroB460;
}
/**
* @return the registroB470
*/
public RegistroB470 getRegistroB470() {
return registroB470;
}
/**
* @param registroB470 the registroB470 to set
*/
public void setRegistroB470(RegistroB470 registroB470) {
this.registroB470 = registroB470;
}
/**
* @return the registroB500
*/
public RegistroB500 getRegistroB500() {
return registroB500;
}
/**
* @param registroB500 the registroB500 to set
*/
public void setRegistroB500(RegistroB500 registroB500) {
this.registroB500 = registroB500;
}
}
| 22.268571 | 66 | 0.602258 |
39963a55945184b089e630a9d16b31b09d0c98ca | 1,496 | package com.github.frimtec.android.pikettassist.ui.alerts;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.github.frimtec.android.pikettassist.R;
import com.github.frimtec.android.pikettassist.domain.Alert;
import java.util.List;
import java.util.Objects;
class AlertArrayAdapter extends ArrayAdapter<Alert> {
AlertArrayAdapter(Context context, List<Alert> alerts) {
super(context, 0, alerts);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Alert alert = getItem(position);
Objects.requireNonNull(alert);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.alert_log_item, parent, false);
}
ImageView playIcon = convertView.findViewById(R.id.alert_log_item_image_play);
playIcon.setVisibility(alert.isClosed() ? View.INVISIBLE : View.VISIBLE);
TextView timeWindow = convertView.findViewById(R.id.alert_log_item_time_window);
TextView durations = convertView.findViewById(R.id.alert_log_item_durations);
timeWindow.setText(AlertViewHelper.getTimeWindow(alert));
durations.setText(AlertViewHelper.getDurations(getContext(), alert));
return convertView;
}
}
| 34 | 102 | 0.782086 |
58425ee6af1877a070c78aefd4334f257f130664 | 2,812 |
package com.linkb.jstx.component;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import com.linkb.jstx.network.model.SNSMomentVideo;
import com.linkb.jstx.app.LvxinApplication;
import com.linkb.jstx.bean.User;
import com.linkb.jstx.listener.OnCommentSelectedListener;
import com.linkb.jstx.model.Moment;
import com.linkb.R;
import com.linkb.jstx.util.FileURLBuilder;
import com.google.gson.Gson;
import java.io.File;
public class TimelineMomentVideoView extends TimelineMomentView {
private WebImageView thumbnailView;
private SNSMomentVideo video;
public TimelineMomentVideoView(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
}
@Override
public void onFinishInflate() {
super.onFinishInflate();
thumbnailView = findViewById(R.id.thumbnailView);
((ViewGroup) thumbnailView.getParent()).setOnClickListener(this);
}
@Override
public void displayMoment(Moment moment, User self, OnCommentSelectedListener commentSelectedListener) {
super.displayMoment(moment, self, commentSelectedListener);
Log.d("TEST_KK","content=="+moment.content+",\nextra=="+moment.extra);
try{
video = new Gson().fromJson(moment.content, SNSMomentVideo.class);
}catch (Exception e){
e.printStackTrace();
video=null;
}
if(video==null){
return;
}
if (video.mode == SNSMomentVideo.HORIZONTAL) {
thumbnailView.getLayoutParams().width = getContext().getResources().getDimensionPixelOffset(R.dimen.sns_video_height);
thumbnailView.getLayoutParams().height = getContext().getResources().getDimensionPixelOffset(R.dimen.sns_video_width);
} else {
thumbnailView.getLayoutParams().width = getContext().getResources().getDimensionPixelOffset(R.dimen.sns_video_width);
thumbnailView.getLayoutParams().height = getContext().getResources().getDimensionPixelOffset(R.dimen.sns_video_height);
}
File thumbnailFile = new File(LvxinApplication.CACHE_DIR_VIDEO, video.image);
if (thumbnailFile.exists()) {
thumbnailView.load(thumbnailFile, R.color.video_background);
} else {
String url = FileURLBuilder.getMomentFileUrl(video.image);
thumbnailView.load(url, R.color.video_background);
}
}
@Override
public void onClick(View view) {
if (view == thumbnailView.getParent()) {
LvxinApplication.getInstance().startVideoActivity(getContext(), false, video, (View) thumbnailView.getParent());
return;
}
super.onClick(view);
}
}
| 36.519481 | 131 | 0.696657 |
bf64b9fc3edf1af7efaef2afb95c2e98da0a247c | 2,059 | package enginecrafter77.survivalinc.stats;
import java.io.Serializable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
/**
* StatProvider serves as a descriptor of a stat.
* StatProvider's main job is providing the stat's
* ID, creating new {@link StatRecord}, and updating
* the record each tick.
* @author Enginecrafter77
*/
public interface StatProvider<RECORD extends StatRecord> extends Serializable {
/**
* Called by the stat {@link StatTracker#update(EntityPlayer) tracker}
* to update the value of this stat. This method basically calculates
* the change to the stat value based on the player the update was
* called for. The general principle is to take the <i>current</i>
* parameter, calculate the new value for the target <i>player</i>,
* and return the new value from this method.
* @param target The player this update was called for
* @param current The current value of the stat
* @return The new value of the stat
*/
public void update(EntityPlayer target, RECORD record);
/**
* Returns a {@link ResourceLocation} based
* stat identifier. This is used to avoid stat
* name conflicts among different mods.
* @return A ResourceLocation-based stat ID
*/
public ResourceLocation getStatID();
/**
* Creates a new record for the stat provider.
* This method is used to create a new record
* about the stat this interface tries to describe.
* This method allows for custom implementations
* to specify their own StatRecords that will be
* used to store their stats. This method replaces
* the legacy method <tt>getDefault</tt>, as this
* method can be used for the same purpose of setting
* default values when new record is created.
* @return A new instance of stat record.
*/
public RECORD createNewRecord();
/**
* Returns the formal type representation
* of the {@link StatRecord} used by this
* provider.
* @return The type of object returned by {@link createNewRecord}
*/
public Class<RECORD> getRecordClass();
}
| 34.898305 | 79 | 0.73628 |
98a155f473c8978fd1fc87d5dca162c7fc60516f | 810 | package Predicates;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person("lola", 10));
persons.add(new Person("olga", 20));
persons.add(new Person("oleg", 100));
// persons.stream().forEach( p -> System.out.println(p) );
persons.stream().filter(p -> p.getAge() >= 18).
sorted((p1, p2) -> p1.getName().compareTo(p2.getName())).
map(p -> p.getName()).
forEach(System.out::println);
double average = persons.stream().filter(p -> p.getAge() >= 18).
mapToInt(p -> p.getAge()).
average().getAsDouble();
System.out.println(average);
}
}
| 31.153846 | 73 | 0.550617 |
2659e5325b719ea722787fe2e95b23054c5dbe30 | 1,638 | package org.apache.zeppelin.interpreter.recovery;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.interpreter.InterpreterSettingManager;
import org.apache.zeppelin.interpreter.launcher.InterpreterClient;
import org.apache.zeppelin.util.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Map;
/**
* Utility class for stopping interpreter in the case that you want to stop all the
* interpreter process even when you enable recovery, or you want to kill interpreter process
* to avoid orphan process.
*/
public class StopInterpreter {
private static final Logger LOGGER = LoggerFactory.getLogger(StopInterpreter.class);
public static void main(String[] args) throws IOException {
ZeppelinConfiguration zConf = ZeppelinConfiguration.create();
InterpreterSettingManager interpreterSettingManager =
new InterpreterSettingManager(zConf, null, null, null);
RecoveryStorage recoveryStorage = ReflectionUtils.createClazzInstance(zConf.getRecoveryStorageClass(),
new Class[] {ZeppelinConfiguration.class, InterpreterSettingManager.class},
new Object[] {zConf, interpreterSettingManager});
LOGGER.info("Using RecoveryStorage: {}", recoveryStorage.getClass().getName());
Map<String, InterpreterClient> restoredClients = recoveryStorage.restore();
if (restoredClients != null) {
for (InterpreterClient client : restoredClients.values()) {
LOGGER.info("Stop Interpreter Process: {}:{}", client.getHost(), client.getPort());
client.stop();
}
}
}
}
| 39 | 107 | 0.761294 |
52a2c2be5f905c23df70119fdfa893d97d1e06af | 479 | package com.supanadit.restsuite.model;
public class BodyTypeModel {
protected String name;
public BodyTypeModel(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static BodyTypeModel RAW() {
return new BodyTypeModel("RAW");
}
public static BodyTypeModel FORM() {
return new BodyTypeModel("FORM");
}
}
| 18.423077 | 41 | 0.611691 |
1e812a575f69da9e629a5f489f9e3288b0b75cf2 | 466 | package com.manywho.sdk.services.controllers;
import com.manywho.sdk.api.run.elements.type.ObjectDataRequest;
import com.manywho.sdk.api.run.elements.type.ObjectDataResponse;
public interface DataController {
ObjectDataResponse delete(ObjectDataRequest objectDataRequest) throws Exception;
ObjectDataResponse load(ObjectDataRequest objectDataRequest) throws Exception;
ObjectDataResponse save(ObjectDataRequest objectDataRequest) throws Exception;
}
| 35.846154 | 84 | 0.841202 |
9db291ded146fa7f097aea446c08d89d1e60e999 | 2,885 | package com.yxf.bookshop.model;
/**
* 订单详情实体类
* @author 余晓枫,0410190109
*
* */
public class Orderitems {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column orderitems.order_id
*
* @mbg.generated Mon May 24 18:37:14 CST 2021
*/
private Integer orderId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column orderitems.product_id
*
* @mbg.generated Mon May 24 18:37:14 CST 2021
*/
private Integer productId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column orderitems.buy_num
*
* @mbg.generated Mon May 24 18:37:14 CST 2021
*/
private Integer buyNum;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column orderitems.order_id
*
* @return the value of orderitems.order_id
*
* @mbg.generated Mon May 24 18:37:14 CST 2021
*/
public Integer getOrderId() {
return orderId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column orderitems.order_id
*
* @param orderId the value for orderitems.order_id
*
* @mbg.generated Mon May 24 18:37:14 CST 2021
*/
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column orderitems.product_id
*
* @return the value of orderitems.product_id
*
* @mbg.generated Mon May 24 18:37:14 CST 2021
*/
public Integer getProductId() {
return productId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column orderitems.product_id
*
* @param productId the value for orderitems.product_id
*
* @mbg.generated Mon May 24 18:37:14 CST 2021
*/
public void setProductId(Integer productId) {
this.productId = productId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column orderitems.buy_num
*
* @return the value of orderitems.buy_num
*
* @mbg.generated Mon May 24 18:37:14 CST 2021
*/
public Integer getBuyNum() {
return buyNum;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column orderitems.buy_num
*
* @param buyNum the value for orderitems.buy_num
*
* @mbg.generated Mon May 24 18:37:14 CST 2021
*/
public void setBuyNum(Integer buyNum) {
this.buyNum = buyNum;
}
} | 27.216981 | 81 | 0.632929 |
100a17a09e15db8d75b7016bfce1198202f42349 | 979 | package org.unclesky4.webflux.demo_2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
/**
*
* @ClassName: WebRoutes
* @Description: 创建Route
* @author: unclesky4
* @date: May 28, 2018 9:40:14 PM
*/
@Configuration
public class WebRoutes {
TestHandler handler = new TestHandler();
@Bean
public RouterFunction<ServerResponse> route() {
return RouterFunctions.route(RequestPredicates.GET("/getName"),
request -> ServerResponse.ok().body(BodyInserters.fromObject("aaa")))
.andRoute(RequestPredicates.GET("/info"), handler::info);
}
}
| 31.580645 | 74 | 0.787538 |
f04136e22eba8904c6179394a3163b5dc2585d33 | 1,871 | package org.frekele.fiscal.focus.nfe.client.enumeration;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import java.util.Arrays;
import java.util.List;
/**
* Restrição do veículo.
*
* @author frekele - Leandro Kersting de Freitas
*/
@XmlType
@XmlEnum(String.class)
public enum NFeVeiculoRestricaoEnum {
/**
* 0 - Não há.
*/
NAO_HA("0", "Não há"),
/**
* 1 - Alienação fiduciária.
*/
ALIENACAO_FIDUCIARIA("1", "Alienação fiduciária"),
/**
* 2 - Arrendamento mercantil.
*/
ARRENDAMENTO_MERCANTIL("2", "Arrendamento mercantil"),
/**
* 3 - Reserva de domínio.
*/
RESERVA_DE_DOMINIO("3", "Reserva de domínio"),
/**
* 4 - Penhor de veículos.
*/
PENHOR_DE_VEICULOS("4", "Penhor de veículos"),
/**
* 9 - Outras.
*/
OUTRAS("9", "Outras");
private String code;
private String description;
private NFeVeiculoRestricaoEnum(String code, String description) {
this.code = code;
this.description = description;
}
@JsonValue
@XmlValue
public String getCode() {
return this.code;
}
@JsonCreator
public static NFeVeiculoRestricaoEnum fromCode(String value) {
if (value != null && value.length() != 0) {
for (NFeVeiculoRestricaoEnum obj : getAll()) {
if (obj.code.equals(value)) {
return obj;
}
}
}
return null;
}
public static List<NFeVeiculoRestricaoEnum> getAll() {
return Arrays.asList(NFeVeiculoRestricaoEnum.values());
}
public String getDescription() {
return description;
}
}
| 23.098765 | 70 | 0.612507 |
a0bf61985a75dce30c3abd024268fd14a5cf1181 | 672 | package akkaTipsAndTricks;
import java.io.File;
import akka.NotUsed;
import akka.stream.javadsl.FileIO;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Framing;
import akka.util.ByteString;
public class FlatmapExample {
static int maxLineSize = 1024;
static final ByteString delim = ByteString.fromString("\r\n");
static final Flow<String, String, NotUsed> pathsToContents =
Flow.of(String.class)
.flatMapConcat(path -> FileIO.fromFile(new File(path))
.via(Framing.delimiter(delim, maxLineSize))
.map(byteStr -> byteStr.utf8String()));
}
| 11.016393 | 73 | 0.645833 |
ca00ebe87f1f9e14e8ba92672aa1c128d5877dd0 | 3,550 | /*
* 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 userinterface.SystemAdminWorkArea;
import java.awt.CardLayout;
import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
/**
*
* @author chand
*/
public class PatientsPanel extends javax.swing.JPanel {
/**
* Creates new form PatientsPanel
*/
JPanel userProcessContainer;
ChartPanel chPanel;
public PatientsPanel(JPanel userProcessContainer,ChartPanel chPanel) {
initComponents();
this.userProcessContainer=userProcessContainer;
this.chPanel=chPanel;
targetPanel.add(chPanel);
}
/**
* 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() {
targetPanel = new javax.swing.JPanel();
backBtn = new javax.swing.JButton();
targetPanel.setBackground(new java.awt.Color(255, 153, 153));
targetPanel.setLayout(new java.awt.BorderLayout());
backBtn.setText("<<Back");
backBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addComponent(targetPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 828, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(415, 415, 415)
.addComponent(backBtn)))
.addContainerGap(58, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(backBtn)
.addGap(18, 18, 18)
.addComponent(targetPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 597, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(56, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backBtnActionPerformed
// TODO add your handling code here:
userProcessContainer.remove(this);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.previous(userProcessContainer);
}//GEN-LAST:event_backBtnActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backBtn;
private javax.swing.JPanel targetPanel;
// End of variables declaration//GEN-END:variables
}
| 39.010989 | 136 | 0.661972 |
933f86b8b212f6ec48900be79803b319a09b4a63 | 1,651 | package ice.ui;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class CodeDialog extends Reader{
private String bufferString = null;
private int pos = 0;
public int read(char[] cbuf, int off, int len) throws IOException{
if(bufferString==null) {
String in = showDialog();
if(in==null) {
return -1;
}
else {
print(in);
bufferString = in+"\n";
pos = 0;
}
}
int size = 0;
int length = bufferString.length();
while(pos<length&& size<len) {
cbuf[off+size++] = bufferString.charAt(pos++);
}
if(pos==length) {
bufferString = null;
}
return size;
}
protected void print(String s) {
System.out.println(s);
}
public void close() throws IOException{
}
protected String showDialog() {
JTextArea area = new JTextArea(20,40);
JScrollPane pane = new JScrollPane(area);
int result = JOptionPane.showOptionDialog(null, pane, "Input",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
null, null, null);
if(result==JOptionPane.OK_OPTION) {
return area.getText();
}
else {
return null;
}
}
public static Reader file() throws FileNotFoundException{
JFileChooser chooser = new JFileChooser();
if(chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION) {
return new BufferedReader(new FileReader(chooser.getSelectedFile()));
}
else {
throw new FileNotFoundException("no file spcified");
}
}
}
| 21.723684 | 72 | 0.69473 |
2921d17160e8681a7a608bbd875a89ac9e3122a0 | 227 | package com.comandulli.data.file;
public class DataFileException extends RuntimeException {
private static final long serialVersionUID = -687274114294508334L;
public DataFileException(String error) {
super(error);
}
}
| 18.916667 | 67 | 0.792952 |
41573ae5c4d3de823a9023b80ce5cc44cb46e494 | 6,814 | import java.sql.*;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main
{
private final static String url ="jdbc:postgresql://localhost:5432/mini-project";
private final static String user="student";
private final static String password="C0d3Cr3w";
//function to make connection to database
public static java.sql.Connection connect() {
Scanner read= new Scanner(System.in);
int choose;
java.sql.Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = java.sql.DriverManager.getConnection(url, user, password);
System.out.println("Connected to the PostgreSQL server successfully.\n");
System.out.println("Welcome to the football channel");
while (true) //never-ending while loop
{
System.out.println("Press 1 to a list of all the matches.");
System.out.println("Press 2 to add a goal.");
try { //tries to read an integer from nextInt()
choose = read.nextInt();
if (choose==1) {allMatches(conn);choose=0;} //if the user selects 1, it will call the function allMatches to list all the matches
else if(choose==2){addGoals(conn); choose=0;} // if the user selects 2, it will call a function to add goals
else{System.out.println("Please enter 1 or 2.");} // if a user enters an integer that is neither 1 nor 2,
}
catch(InputMismatchException e){System.out.println("Invalid input");read.nextLine();} //this catch the error if the user does not input an integer
}
} catch (java.sql.SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
public static void allMatches(Connection conn) { //returns all matches
String SQL="Select * from game";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL);
ResultSet rs=pstmt.executeQuery();
while (rs.next()) { System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3)+","+rs.getString(4)+","+rs.getString(5));}
System.out.println("\n");
}
catch(SQLException e) {System.out.println(e.getMessage());}
}
public static void addGoals(Connection conn) {
Scanner scan= new Scanner(System.in);
//flags to run an loop until a valid input
boolean idFlag=true,teamFlag=true,scoreFlag=true,nameFlag=true;
int matchid = 0, gametime = 0;
String teamid="",player="";
//test if user enters a valid game id
while (idFlag) {
System.out.println("Enter match id");
if (scan.hasNextInt()) {
matchid = scan.nextInt();
if (matchid >= 1001 && matchid <= 1031) {System.out.println("Valid id");break; }
else {System.out.println("Invalid id. The game ids range from 1001 to 1031");scan.nextLine();}
}
else {System.out.println("Invalid id. The game ids range from 1001 to 1031");scan.nextLine(); }
}
//test if user enters a valid team id that represent the teams that played in that match
while(teamFlag)
{
System.out.println(matchid);
System.out.println("Enter the team id of the team that scored");
if (scan.hasNext()) {
teamid = scan.next().toUpperCase();
//runs a query search to ensure the game exist with that particular team
String verifyteam = "select * from game where id=? and (team1=? or team2=?)";
try {
PreparedStatement pstmt = conn.prepareStatement(verifyteam);
pstmt.setInt(1,matchid);
pstmt.setString(2,teamid);
pstmt.setString(3,teamid);
ResultSet rs = pstmt.executeQuery();
// if there is an entry for that game id with that team, it breaks out of the loop
if(rs.next()) {System.out.println(teamid+" is a valid input");break;}
else{System.out.println(teamid+" did not play in this game");}
}
catch (SQLException e) {System.out.println(e.getMessage());}
}
else{System.out.println("Invalid input for team id"); scan.nextLine();};
}
//Checks for a valid entry for a goal
while(scoreFlag)
{
System.out.println("Enter the time goal was scored");
if (scan.hasNextInt()) { // looks for an integer input
gametime = scan.nextInt();
String verifytime = "select * from goal where matchid=? and gtime=?";
try {
PreparedStatement pstmt = conn.prepareStatement(verifytime);
pstmt.setInt(1, matchid);
pstmt.setInt(2, gametime);
ResultSet rs = pstmt.executeQuery();
//Only 1 goal can be scored each minute. So if there is a match for that particular goal at that time, the loop continues.
if (rs.next()) {System.out.println("A goal has already been scored at gtime: " + gametime);}
//if no goal was scored at that time, the entry is valid
else {System.out.println(gametime + " is a valid game time.");break;}
}
catch(SQLException e){ System.out.println(e.getMessage());}
}
else {System.out.println("Invalid input");scan.nextLine();}
}
while (nameFlag)//enters a name for the user who scored the goal
{
System.out.println("Enter the name of the player who scored");
try
{
scan.nextLine();
player=scan.nextLine();
System.out.println(player);
break;
}
catch(InputMismatchException e)
{
System.out.println("Invalid input");
}
}
//Once all the flags have been passed, the goal can be added into the table
String update="Insert Into goal values(?,?,?,? )";
try
{
PreparedStatement pstmt= conn.prepareStatement(update);
pstmt.setInt(1,matchid);
pstmt.setString(2,teamid);
pstmt.setString(3,player);
pstmt.setInt(4,gametime);
pstmt.executeUpdate();
}
catch (SQLException e){System.out.println(e.getMessage());}
}
public static void main(String[] args) {
// while(true)
connect();
System.out.println("Hello World!");
}
}
| 42.322981 | 162 | 0.570296 |
a664b9f8ffd467d47576b99bf998e768ee24ef0a | 1,946 | /* detect-lines, extract lines and their width from images.
Copyright (C) 1996-1998 Carsten Steger
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
/* Changes Made by R. Balasubramanian for incorporating the the detect lines code to incorporate
within GRASP (May 10th 1999) */
/* Port to ImageJ plugin Eugene Katrukha August 2015 */
package fiji.plugin.CurveTrace.stegers;
/** This data structure facilitates the quick search for the next possible
starting point of a line. An array of crossrefs will be accumulated and
sorted according to its value. x and y are the coordinates of a point in
the image. When this point has been processed it will be marked as done. **/
public class crossref implements Comparable <crossref>{
public short x;
public short y;
public double value;
public boolean done;
public crossref()
{
super();
}
public crossref(short nx, short ny, double nvalue, boolean ndone)
{
x = nx;
y = ny;
value = nvalue;
done = ndone;
}
/** This function compares two crossrefs according to their value. It is called
by qsort. **/
public int compareTo(crossref otherref) {
// TODO Auto-generated method stub
if (this.value>otherref.value)
return -1;
if (this.value<otherref.value)
return 1;
return 0;
}
} ;
| 34.75 | 97 | 0.720452 |
2d8a235febbd274f3e331cbcc903efb357f84416 | 1,801 | package com.enderio.core.client;
import java.lang.reflect.Field;
import com.enderio.core.common.util.Log;
import net.minecraft.client.particle.Particle;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
public class ClientUtil {
private static final Field MOTION_X;
private static final Field MOTION_Y;
private static final Field MOTION_Z;
static {
Field motionX = null;
Field motionY = null;
Field motionZ = null;
try {
motionX = ObfuscationReflectionHelper.findField(Particle.class, "field_187129_i");
motionY = ObfuscationReflectionHelper.findField(Particle.class, "field_187130_j");
motionZ = ObfuscationReflectionHelper.findField(Particle.class, "field_187131_k");
} catch (Exception e) {
Log.error("ClientUtil: Could not find motion fields for class Particle: " + e.getMessage());
} finally {
MOTION_X = motionX;
MOTION_Y = motionY;
MOTION_Z = motionZ;
}
}
public static void setParticleVelocity(Particle p, double x, double y, double z) {
if (p == null) {
return;
}
try {
MOTION_X.set(p, x);
MOTION_Y.set(p, y);
MOTION_Z.set(p, z);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setParticleVelocityY(Particle p, double y) {
if (p == null) {
return;
}
try {
MOTION_Y.set(p, y);
} catch (Exception e) {
e.printStackTrace();
}
}
public static double getParticleVelocityY(Particle p) {
if (p == null) {
return 0;
}
try {
Object val = MOTION_Y.get(p);
return ((Double) val).doubleValue();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
| 25.013889 | 99 | 0.618545 |
1c4ebdeb821332626edf0718f9fb365dfac15a4e | 13,251 | package omicsdatalab.bioliner.utils;
import omicsdatalab.bioliner.Module;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class contains exclusively static methods that parse various element values
* from an input or modules XML file.
* @author Joshua Hazlewood
*/
public class XmlParser {
private static final Logger LOGGER = Logger.getLogger( XmlParser.class.getName() );
/**
* Accepts a input xml file and parses out the contents of any workflow elements.
* @param inputFile the file to be parsed.
* @return An ArrayList<String> containing any sequences found in the file,
* or an empty ArrayList if none are found.
*/
public static ArrayList<String> parseWorkflowFromInputFile(File inputFile) {
try {
String workflowString;
ArrayList<String> workflow = new ArrayList<>();
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document inputFileAsDoc = dBuilder.parse(inputFile);
inputFileAsDoc.getDocumentElement().normalize();
NodeList workflowList = inputFileAsDoc.getElementsByTagName("workflow");
workflowString = workflowList.item(0).getTextContent();
String[] workflowArray = workflowString.split(",");
for (int i = 0; i < workflowArray.length; i ++) {
workflow.add(workflowArray[i]);
}
LOGGER.log(Level.INFO, "Workflow correctly parsed from input XML file.");
return workflow;
} catch (ParserConfigurationException | SAXException | IOException ex) {
LOGGER.log(Level.SEVERE, "Error parsing workflows from input XML File!", ex);
return new ArrayList<>();
}
}
/**
* Accepts a input xml file and parses out the contents of any Module elements.
* @param inputFile the file to be parsed
* @return An ArrayList<Modules> containing any modules found in the file,
* or an empty ArrayList if none are found.
*/
public static ArrayList<Module> parseModulesFromInputFile(File inputFile) {
try {
ArrayList<Module> modules = new ArrayList<>();
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document inputFileAsDoc = dBuilder.parse(inputFile);
inputFileAsDoc.getDocumentElement().normalize();
NodeList modulesList = inputFileAsDoc.getElementsByTagName("module");
for ( int i = 0; i < modulesList.getLength(); i++) {
Node moduleNode = modulesList.item(i);
if (moduleNode.getNodeType() == Node.ELEMENT_NODE) {
Element moduleElement = (Element) moduleNode;
moduleElement.normalize();
String moduleName = moduleElement.getElementsByTagName("name").item(0).getTextContent();
String input = moduleElement.getElementsByTagName("input").item(0).getTextContent();
String[] inputs = parseInputsString(input);
String inputFilePath = parseFilePath(inputs[0]);
String outputFilePath = parseFilePath(inputs[1]);
String[] params = parseParams(inputs[2]);
modules.add(new Module(moduleName, inputFilePath, outputFilePath, params));
}
}
LOGGER.log(Level.INFO, "Modules correctly parsed from input XML file.");
return modules;
} catch (ParserConfigurationException | SAXException | IOException ex) {
LOGGER.log(Level.SEVERE, "Error parsing modules from input XML File!", ex);
return new ArrayList<>();
}
}
/**
* Accepts a input xml file and parses out the contents of a outputFolderPath element.
* @param inputFile the file to input
* @return A String containing the contents of the <outputFolder> element from an input xml file.
*/
public static String parseOutputFolderPath(File inputFile) {
String outputFolderPath = "";
try {
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document inputFileAsDoc = dBuilder.parse(inputFile);
inputFileAsDoc.getDocumentElement().normalize();
NodeList outputFolderList = inputFileAsDoc.getElementsByTagName("outputFolder");
outputFolderPath = outputFolderList.item(0).getTextContent();
LOGGER.log(Level.INFO, "Output Folder correctly parsed from input XML file.");
return outputFolderPath;
} catch (ParserConfigurationException | SAXException | IOException ex) {
LOGGER.log(Level.SEVERE, "Error parsing workflows from input XML File!", ex);
return outputFolderPath;
}
}
/**
* Accepts a input xml file and parses out the contents of a uniqueId element.
* @param inputFile
* @return A String containing the contents of the <uniqueId> element from an input xml file.
*/
public static String parseUniqueId(File inputFile) {
String uniqueId = "";
try {
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document inputFileAsDoc = dBuilder.parse(inputFile);
inputFileAsDoc.getDocumentElement().normalize();
NodeList uniqueList = inputFileAsDoc.getElementsByTagName("uniqueId");
uniqueId = uniqueList.item(0).getTextContent();
LOGGER.log(Level.INFO, "UniqueId correctly parsed from input XML file.");
return uniqueId;
} catch (ParserConfigurationException | SAXException | IOException ex) {
LOGGER.log(Level.SEVERE, "Error parsing UniqueId from input XML File!", ex);
return uniqueId;
}
}
/**
* Accepts a path to a input xml file and parses out the contents of any Module elements.
* @param input the file path of the resource file to be parsed
* @return An ArrayList<DefinedModule> containing any modules found in the file,
* or an empty ArrayList if none are found.
*/
public static ArrayList<Module> parseModulesFromConfigFile(File input) {
try {
ArrayList<Module> modules = new ArrayList<>();
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document inputFileAsDoc = dBuilder.parse(input);
inputFileAsDoc.getDocumentElement().normalize();
NodeList modulesList = inputFileAsDoc.getElementsByTagName("module");
for ( int i = 0; i < modulesList.getLength(); i++) {
Node moduleNode = modulesList.item(i);
if (moduleNode.getNodeType() == Node.ELEMENT_NODE) {
Element moduleElement = (Element) moduleNode;
moduleElement.normalize();
String name = moduleElement.getElementsByTagName("name").item(0).getTextContent();
String description = moduleElement.getElementsByTagName("description").item(0).getTextContent();
String inputFile = moduleElement.getElementsByTagName("inputFile").item(0).getTextContent();
String inputParamStr = moduleElement.getElementsByTagName("inputParam").item(0).getTextContent();
Boolean inputParam = Boolean.parseBoolean(inputParamStr);
String outputFileRequiredStr = moduleElement.getElementsByTagName("outputFile_required")
.item(0).getTextContent();
boolean outputFileRequired = Boolean.parseBoolean(outputFileRequiredStr);
boolean outputFileExists = moduleElement.getElementsByTagName("outputFile").getLength() > 0;
String outputFile;
String outputParamStr;
Boolean outputParam;
if (outputFileExists) {
outputFile = moduleElement.getElementsByTagName("outputFile").item(0).getTextContent();
outputParamStr = moduleElement.getElementsByTagName("outputParam").item(0).getTextContent();
outputParam = Boolean.parseBoolean(outputParamStr);
} else {
outputFile = null;
outputParam = false;
}
String rawParams = moduleElement.getElementsByTagName("params").item(0).getTextContent();
String[] parsedParams = parseParams(rawParams);
String command = moduleElement.getElementsByTagName("command").item(0).getTextContent();
if (outputFile == null) {
modules.add(new Module(name, description, inputFile, inputParam, outputFileRequired,
parsedParams, command));
} else {
modules.add(new Module(name, description, inputFile, inputParam, outputFileRequired,
outputFile, outputParam, parsedParams, command));
}
}
}
LOGGER.log(Level.INFO, "Defined Modules correctly parsed from input XML file.");
return modules;
} catch (ParserConfigurationException | SAXException | IOException ex) {
LOGGER.log(Level.SEVERE, "Error parsing modules from input XML File!", ex);
return new ArrayList<>();
}
}
/**
* Accepts a path to a module to tool mapping xml file and parses out the contents of any Module elements.
* @param mappingFile the file path of the mapping file to be parsed
* @return A HashMap<String, String> containing module names and tool subdirectory names found in the file,
* or an empty HashMap if none are found.
*/
public static HashMap<String, String> parseModuleToolMappingFile(File mappingFile) {
try {
HashMap<String, String> modulesMap = new HashMap<>();
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document mappingFileAsDoc = dBuilder.parse(mappingFile);
mappingFileAsDoc.getDocumentElement().normalize();
NodeList modulesList = mappingFileAsDoc.getElementsByTagName("module");
for ( int i = 0; i < modulesList.getLength(); i++) {
Node moduleNode = modulesList.item(i);
if (moduleNode.getNodeType() == Node.ELEMENT_NODE) {
Element moduleElement = (Element) moduleNode;
moduleElement.normalize();
String moduleName = moduleElement.getElementsByTagName("name").item(0).getTextContent();
String toolSubFolder = moduleElement.getElementsByTagName("tool_subfolder").item(0).getTextContent();
modulesMap.put(moduleName, toolSubFolder);
}
}
LOGGER.log(Level.INFO, "Modules correctly parsed from module_tool_mapping XML file.");
return modulesMap;
} catch (ParserConfigurationException | SAXException | IOException ex) {
LOGGER.log(Level.SEVERE, "Error parsing modules from module_tool_mapping XML File!", ex);
return new HashMap<>();
}
}
/**
* This method parses individual parameter/value pairs from the string contained in
* <input> elements of the input.xml file
* @param input
* @return
*/
public static String[] parseInputsString(String input) {
input = input.trim();
String trimmedInput = input.substring(1, input.length() - 1);
String[] inputs = trimmedInput.split(",");
for (int i = 0; i < inputs.length; i++) {
inputs[i] = inputs[i].substring(1, inputs[i].length() - 1);
}
return inputs;
}
/**
* Parses a file path from a string found in the <input> element of a input xml file.
* String is in the format "Inputfile:<name>"
* @param input string to parse.
* @return input file path from the whole string.
*/
private static String parseFilePath(String input) {
String[] parts = input.split(":", 2);
String inputFilePath;
try {
inputFilePath = parts[1];
} catch (Exception e) {
inputFilePath = "";
}
return inputFilePath;
}
/**
* Parses the parameters from the <input> element in an input xml file.
* @param paramString string containing all the parameters to parse out.
* @return the parameters in a String[].
*/
private static String[] parseParams(String paramString) {
String[] params = paramString.split(" ");
return params;
}
}
| 45.380137 | 121 | 0.625538 |
2efe8f48bc64f934e32b91874a28c8583109ee8e | 1,345 | package com.yeskery.filter;
/**
* 和值过滤器
*
* @author yeskery
* @date 2018-07-26 12:23
*/
public class SumFilter extends AbstractFilter {
private int[] all;
private int[] data;
/**
* 和值过滤器
* @param star 星级
* @param retain true 代表保留,false 代表删除
* @param data 需要过滤的数据数组
*/
public SumFilter(int star, boolean retain, int... data) {
super(data.length, retain);
if (star < Node.MIN_STAR || star > Node.MAX_STAR) {
throw new RuntimeException("star out of bounds");
}
this.data = data;
all = new int[star * 9 + 1];
for (int i = 0;i < all.length;i++) {
all[i] = i;
}
}
/**
*
* @see SumFilter#SumFilter(int, boolean, int...)
*/
public SumFilter(int star, boolean retain, char... data) {
super(data.length, retain);
if (star < 2 || star > 5) {
throw new RuntimeException("star out of bounds");
}
this.data = parse(data);
all = new int[star * 9 + 1];
for (int i = 0;i < all.length;i++) {
all[i] = i;
}
}
@Override
protected int getAllDataCount() {
return all.length;
}
@Override
protected boolean judge(Node node) {
return contain(data, node.getSum());
}
@Override
protected boolean judgeReverse(Node node) {
int[] reverse = getReverseArray(all, data);
return contain(reverse, node.getSum());
}
}
| 20.378788 | 60 | 0.594052 |
fd5b0279a9c8f639780fd0a5cdc6c681423fe4de | 1,124 | package jmx;
import javax.management.*;
import java.lang.management.ManagementFactory;
/**
* @author vision8
*/
public class AppStart {
/**
* Startup of the class and JMX setup.
* @param args Command line startup arguments.
*/
public static void main(String... args) {
// ------- initing the App -------
System.out.println(">>> App is starting up ...");
AppMBean app = new App();
// ------- JMX setup -------
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try {
ObjectName motd = new ObjectName("MOTD:name=Motd");
mbs.registerMBean(app, motd);
} catch (Exception e) {
System.err.println(">>> JMX init error: " + e.getMessage());
}
// ------- starting the App -------
try {
Thread appThread = new Thread((Runnable) app);
appThread.start();
// main thread is waiting for the app thread to stop
appThread.join();
} catch (InterruptedException e) {
// nothing to do but exit
}
}
}
| 24.434783 | 72 | 0.535587 |
0ba53ea0d2efc57b4b3b20350350268628cc7376 | 10,791 | /*
* Copyright 2020 The FATE Authors. 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 com.webank.ai.fatecloud.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.corba.se.spi.orbutil.fsm.FSMImpl;
import com.webank.ai.fatecloud.common.util.PageBean;
import com.webank.ai.fatecloud.system.dao.entity.FederatedGroupSetDo;
import com.webank.ai.fatecloud.system.dao.entity.FederatedSiteManagerDo;
import com.webank.ai.fatecloud.system.dao.entity.FederatedSiteModelDo;
import com.webank.ai.fatecloud.system.dao.mapper.FederatedGroupSetMapper;
import com.webank.ai.fatecloud.system.dao.mapper.FederatedModelMapper;
import com.webank.ai.fatecloud.system.dao.mapper.FederatedSiteManagerMapper;
import com.webank.ai.fatecloud.system.pojo.qo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class FederatedModelService {
@Autowired
FederatedModelMapper federatedModelMapper;
@Autowired
FederatedSiteManagerMapper federatedSiteManagerMapper;
@Transactional
public void addModelNew(List<ModelAddQo> modelAddQos) {
//update status of old models
QueryWrapper<FederatedSiteModelDo> federatedSiteModelDoQueryWrapperForOldModel = new QueryWrapper<>();
federatedSiteModelDoQueryWrapperForOldModel.eq("id", modelAddQos.get(0).getId()).eq("status", 1);
List<FederatedSiteModelDo> federatedSiteModelDosForOldModel = federatedModelMapper.selectList(federatedSiteModelDoQueryWrapperForOldModel);
ArrayList<String> oldModels = new ArrayList<>();
for (FederatedSiteModelDo federatedSiteModelDo : federatedSiteModelDosForOldModel) {
oldModels.add(federatedSiteModelDo.getInstallItems());
}
ArrayList<String> newModels = new ArrayList<>();
for (ModelAddQo modelAddQo : modelAddQos) {
newModels.add(modelAddQo.getInstallItems());
}
for (String oldModel : oldModels) {
if (!newModels.contains(oldModel)) {
QueryWrapper<FederatedSiteModelDo> federatedSiteModelDoQueryWrapperForModelNotExistInNewVersion = new QueryWrapper<>();
federatedSiteModelDoQueryWrapperForModelNotExistInNewVersion.eq("id", modelAddQos.get(0).getId()).eq("status", 1).eq("install_items", oldModel);
FederatedSiteModelDo modelDo = new FederatedSiteModelDo();
modelDo.setStatus(2);
federatedModelMapper.update(modelDo, federatedSiteModelDoQueryWrapperForModelNotExistInNewVersion);
}
}
int detectiveStatus = 2;
for (ModelAddQo modelAddQo : modelAddQos) {
FederatedSiteModelDo modelDo = new FederatedSiteModelDo(modelAddQo);
//update model status of site existed in databases
QueryWrapper<FederatedSiteModelDo> federatedSiteModelDoQueryWrapper = new QueryWrapper<>();
federatedSiteModelDoQueryWrapper.eq("id", modelAddQo.getId()).eq("install_items", modelAddQo.getInstallItems()).eq("status", 1);
List<FederatedSiteModelDo> federatedSiteModelDos = federatedModelMapper.selectList(federatedSiteModelDoQueryWrapper);
if (federatedSiteModelDos.size() > 0) {
for (FederatedSiteModelDo federatedSiteModelDo : federatedSiteModelDos) {
federatedSiteModelDo.setStatus(2);
federatedModelMapper.updateById(federatedSiteModelDo);
}
modelDo.setInstallTime(federatedSiteModelDos.get(0).getInstallTime());
} else {
modelDo.setInstallTime(modelAddQo.getUpdateTime());
}
modelDo.setUpdateTime(modelAddQo.getUpdateTime());
modelDo.setLastDetectiveTime(new Date());
federatedModelMapper.insert(modelDo);
if (modelAddQo.getDetectiveStatus() == 1) {
detectiveStatus = 1;
}
}
//update site detective status
FederatedSiteManagerDo federatedSiteManagerDo = new FederatedSiteManagerDo();
federatedSiteManagerDo.setId(modelAddQos.get(0).getId());
federatedSiteManagerDo.setLastDetectiveTime(new Date());
federatedSiteManagerDo.setDetectiveStatus(detectiveStatus);
federatedSiteManagerMapper.updateById(federatedSiteManagerDo);
}
@Transactional
public void modelHeart(ArrayList<ModelHeartQo> modelHeartQos) {
Date date = new Date();
int detectiveStatus = 2;
for (ModelHeartQo modelHeartQo : modelHeartQos) {
QueryWrapper<FederatedSiteModelDo> federatedSiteModelDoQueryWrapperForModelNotExistInNewVersion = new QueryWrapper<>();
federatedSiteModelDoQueryWrapperForModelNotExistInNewVersion.eq("id", modelHeartQo.getId()).eq("status", 1).eq("install_items", modelHeartQo.getInstallItems()).eq("version", modelHeartQo.getVersion());
FederatedSiteModelDo modelDo = new FederatedSiteModelDo();
modelDo.setDetectiveStatus(modelHeartQo.getDetectiveStatus());
modelDo.setLastDetectiveTime(date);
federatedModelMapper.update(modelDo, federatedSiteModelDoQueryWrapperForModelNotExistInNewVersion);
if (modelHeartQo.getDetectiveStatus() == 1) {
detectiveStatus = 1;
}
}
//update site detective status
FederatedSiteManagerDo federatedSiteManagerDo = new FederatedSiteManagerDo();
federatedSiteManagerDo.setId(modelHeartQos.get(0).getId());
federatedSiteManagerDo.setLastDetectiveTime(date);
federatedSiteManagerDo.setDetectiveStatus(detectiveStatus);
federatedSiteManagerMapper.updateById(federatedSiteManagerDo);
}
public PageBean<FederatedSiteManagerDo> findPagedSitesWithModel(SiteListWithModelsQo siteListWithModelsQo) {
int sum = federatedModelMapper.selectCount(siteListWithModelsQo);
PageBean<FederatedSiteManagerDo> federatedSiteManagerDoPageBean = new PageBean<>(siteListWithModelsQo.getPageNum(), siteListWithModelsQo.getPageSize(), sum);
List<FederatedSiteManagerDo> pagedRegionInfo = federatedModelMapper.findPage(siteListWithModelsQo, federatedSiteManagerDoPageBean.getStartIndex());
federatedSiteManagerDoPageBean.setList(pagedRegionInfo);
return federatedSiteManagerDoPageBean;
}
public List<FederatedSiteModelDo> findModelHistory(ModelHistoryQo modelHistoryQo) {
QueryWrapper<FederatedSiteModelDo> federatedSiteModelDoQueryWrapper = new QueryWrapper<>();
federatedSiteModelDoQueryWrapper.eq(modelHistoryQo.getId() != null, "id", modelHistoryQo.getId()).eq(modelHistoryQo.getInstallItems() != null, "install_items", modelHistoryQo.getInstallItems());
List<FederatedSiteModelDo> federatedSiteModelDos = federatedModelMapper.selectList(federatedSiteModelDoQueryWrapper);
return federatedSiteModelDos;
}
public List<FederatedSiteModelDo> findSitesWithModel(OneSiteQo oneSiteQo) {
QueryWrapper<FederatedSiteModelDo> federatedSiteModelDoQueryWrapper = new QueryWrapper<>();
federatedSiteModelDoQueryWrapper.eq(oneSiteQo.getId() != null, "id", oneSiteQo.getId()).eq("status", 1);
List<FederatedSiteModelDo> federatedSiteModelDos = federatedModelMapper.selectList(federatedSiteModelDoQueryWrapper);
return federatedSiteModelDos;
}
//update model status and site status
@Scheduled(cron = "0 */2 * * * ?")
public void updateModelAndSiteStatus() {
log.info("start detective");
long time = new Date().getTime();
QueryWrapper<FederatedSiteModelDo> federatedSiteModelDoQueryWrapper = new QueryWrapper<>();
federatedSiteModelDoQueryWrapper.eq("status", 2).eq("detective_status", 2);
List<FederatedSiteModelDo> federatedSiteModelDos = federatedModelMapper.selectList(federatedSiteModelDoQueryWrapper);
for (FederatedSiteModelDo federatedSiteModelDo : federatedSiteModelDos) {
if (time - federatedSiteModelDo.getLastDetectiveTime().getTime() > 3000) {
//update model status
federatedSiteModelDo.setDetectiveStatus(1);
federatedModelMapper.updateById(federatedSiteModelDo);
//update site status
FederatedSiteManagerDo federatedSiteManagerDo = federatedSiteManagerMapper.selectById(federatedSiteModelDo.getId());
if (federatedSiteManagerDo.getDetectiveStatus() == 2) {
federatedSiteManagerDo.setDetectiveStatus(1);
federatedSiteManagerMapper.updateById(federatedSiteManagerDo);
}
log.info("model:{} failed", federatedSiteModelDo);
log.info("site:{} failed", federatedSiteManagerDo);
}
}
QueryWrapper<FederatedSiteManagerDo> ew = new QueryWrapper<>();
ew.select("id", "last_detective_time");
ew.eq("status", 2).eq("detective_status", 2);
List<FederatedSiteManagerDo> federatedSiteManagerDos = federatedSiteManagerMapper.selectList(ew);
for (FederatedSiteManagerDo federatedSiteManagerDo : federatedSiteManagerDos) {
Date lastDetectiveTime = federatedSiteManagerDo.getLastDetectiveTime();
if (lastDetectiveTime == null) {
continue;
}
if (time - lastDetectiveTime.getTime() > 3000) {
FederatedSiteManagerDo federatedSiteManagerDoToUpdate = new FederatedSiteManagerDo();
federatedSiteManagerDoToUpdate.setDetectiveStatus(1);
QueryWrapper<FederatedSiteManagerDo> federatedSiteManagerDoQueryWrapper = new QueryWrapper<>();
federatedSiteManagerDoQueryWrapper.eq("id", federatedSiteManagerDo.getId());
federatedSiteManagerMapper.update(federatedSiteManagerDoToUpdate, ew);
}
log.info("site:{} failed", federatedSiteManagerDo);
}
}
}
| 53.157635 | 213 | 0.720322 |
c0ed4c3d281935337b077e480c3a4f671bec3d7c | 511 | /**
* Copyright (C) 2018 WeBank, Inc. All Rights Reserved.
*/
package com.webank.webasebee.parser.generated.bo.method;
import com.webank.webasebee.common.bo.data.MethodBO;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper=true)
public class BAC003SafeBatchTransferFromBO extends MethodBO {
private String _from;
private String _to;
private String _ids;
private String _values;
private String _data;
}
| 24.333333 | 61 | 0.794521 |
eccbbb606608e3924c5d78e19981b47287d5f848 | 239 | package org.apache.hadoop.hive.ql.exec.tez.monitoring;
import org.apache.hadoop.hive.common.log.InPlaceUpdate;
public interface Constants {
String SEPARATOR = new String(new char[InPlaceUpdate.MIN_TERMINAL_WIDTH]).replace("\0", "-");
} | 34.142857 | 95 | 0.778243 |
2cb062851ddac66f6fa3bcc47b80c52d261f357b | 2,241 | package com.o3dr.services.android.lib.drone.companion.solo.tlv;
import android.os.Parcel;
import com.o3dr.services.android.lib.coordinate.LatLongAlt;
import java.nio.ByteBuffer;
/**
* Send the app our cable cam waypoint when it’s recorded.
* Deprecated since shotmanager 2.0
*/
public class SoloCableCamWaypoint extends TLVPacket {
private LatLongAlt coordinate;
/**
* Yaw in degrees
*/
private float degreesYaw;
/**
* Camera pitch in degrees
*/
private float pitch;
public SoloCableCamWaypoint(double latitude, double longitude, float altitude, float degreesYaw, float pitch) {
super(TLVMessageTypes.TYPE_SOLO_CABLE_CAM_WAYPOINT, 28);
this.coordinate = new LatLongAlt(latitude, longitude, altitude);
this.degreesYaw = degreesYaw;
this.pitch = pitch;
}
public LatLongAlt getCoordinate() {
return coordinate;
}
public float getDegreesYaw() {
return degreesYaw;
}
public float getPitch() {
return pitch;
}
@Override
protected void getMessageValue(ByteBuffer valueCarrier) {
valueCarrier.putDouble(coordinate.getLatitude());
valueCarrier.putDouble(coordinate.getLongitude());
valueCarrier.putFloat((float) coordinate.getAltitude());
valueCarrier.putFloat(degreesYaw);
valueCarrier.putFloat(pitch);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeParcelable(this.coordinate, 0);
dest.writeFloat(this.degreesYaw);
dest.writeFloat(this.pitch);
}
protected SoloCableCamWaypoint(Parcel in) {
super(in);
this.coordinate = in.readParcelable(LatLongAlt.class.getClassLoader());
this.degreesYaw = in.readFloat();
this.pitch = in.readFloat();
}
public static final Creator<SoloCableCamWaypoint> CREATOR = new Creator<SoloCableCamWaypoint>() {
public SoloCableCamWaypoint createFromParcel(Parcel source) {
return new SoloCableCamWaypoint(source);
}
public SoloCableCamWaypoint[] newArray(int size) {
return new SoloCableCamWaypoint[size];
}
};
}
| 28.0125 | 115 | 0.673806 |
c0da65fb1c52a0dfc419130e3b0f6506c3caf689 | 3,556 | /*
Part of the Androrat project - https://github.com/RobinDavid/androrat
Copyright (c) 2012 Robin David
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, version 3.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package server;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import gui.GUI;
import inout.Protocol;
import Packet.CommandPacket;
import Packet.Packet;
import in.Demux;
import in.Receiver;
import out.Mux;
public class ClientHandler extends Thread {
private String imei;
private Socket clientSocket;
private Receiver receiver;
private Server server;
private Demux demux;
private Mux mux;
private ByteBuffer buffer;
private boolean connected;
private GUI mainGUI;
public ClientHandler(Socket your_socket, String id, Server s, GUI mainGUI)
throws IOException {
this.mainGUI = mainGUI;
server = s;
imei = id;
clientSocket = your_socket;
receiver = new Receiver(clientSocket);
demux = new Demux(server, imei);
mux = new Mux(new DataOutputStream(clientSocket.getOutputStream()));
connected = true;
buffer = ByteBuffer.allocate(Protocol.MAX_PACKET_SIZE);
buffer.clear();
}
// attend des donn�es du Receiver et les transmet au Demultiplexeur
public void run() {
while (connected) {
try {
//System.out.println("");
//buffer = receiver.read();
buffer = receiver.read(buffer);
try {
if (demux.receive(buffer)) {
//System.out.println("Restant: "+buffer.remaining()+" Position: "+buffer.position()+" Limit: "+buffer.limit());
buffer.compact();
}
} catch (Exception e) {
connected = false;
/*
connected = false;
try {
clientSocket.close();
mainGUI.deleteUser(imei);
} catch (IOException e1) {
}*/
server.getGui().logErrTxt("ERROR: while deconding received stream (Demux) : "+e.getCause());
}
}
catch (IOException e) {
connected = false;
try {
clientSocket.close();
mainGUI.deleteUser(imei);
} catch (IOException e1) {
server.getGui().logErrTxt("ERROR: while reading from a socket(Receiver)");
}
}
catch(IndexOutOfBoundsException e) {
server.getGui().logErrTxt("Client ended gently !");
connected = false;
try {
clientSocket.close();
mainGUI.deleteUser(imei);
} catch (IOException e1) {
server.getGui().logErrTxt("Cannot close socket when socket client closed it before");
}
}
}
server.DeleteClientHandler(imei);
}
// transmet les donn�es � envoyer au Multiplexeur
public void toMux(short command, int channel, byte[] args) {
Packet packet = new CommandPacket(command, channel, args);
mux.send(0, packet.build());
//server.getGui().logTxt("Request sent :" + command + ",on the channel "+ channel);
}
public void updateIMEI(String i) {
imei = i;
demux.setImei(imei);
}
}
| 26.537313 | 117 | 0.691507 |
3dce1a17c0d68677ffe9dd8ebe5a908f85bace55 | 1,063 | import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Menu extends JFrame{
//Attributes
private static final long serialVersionUID = 9221558304803846443L;
private BufferedImage title, btnPlay, btnScore, btnQuit, scoreTable, instructions;
//Render Method
public void render (Graphics g) {
try {
ImageLoader loader = new ImageLoader();
title = loader.loadImage("/res/title.png");
btnPlay = loader.loadImage("/res/playbutton.png");
btnScore = loader.loadImage("/res/scorebutton.png");
btnQuit = loader.loadImage("/res/quitbutton.png");
scoreTable = loader.loadImage("/res/scoretable.png");
instructions = loader.loadImage("/res/instructions.png");
g.drawImage(title, 110, 115, null);
g.drawImage(scoreTable, 150, 265,null);
g.drawImage(btnPlay, 500, 250, null);
g.drawImage(btnScore, 500, 325, null);
g.drawImage(btnQuit, 500, 400, null);
g.drawImage(instructions, 107, 500, null);
g.dispose();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 28.72973 | 83 | 0.706491 |
7b98e2cef8dc33b7b3414965a73edc04ef07ea03 | 1,494 | package today.flux.utility;
public class AnimationTimer {
private final int delay;
private int bottom;
private int top;
private int timer;
private boolean wasRising;
private DelayTimer helpertimer = new DelayTimer();
public AnimationTimer(int delay) {
this.delay = delay;
this.top = delay;
this.bottom = 0;
}
public void update(boolean increment) {
if (helpertimer.hasPassed(10f)) {
if (increment) {
if (this.timer < this.delay) {
if (!this.wasRising) {
this.bottom = this.timer;
}
++this.timer;
}
this.wasRising = true;
} else {
if (this.timer > 0) {
if (this.wasRising) {
this.top = this.timer;
}
--this.timer;
}
this.wasRising = false;
}
helpertimer.reset();
}
}
public void reset() {
this.timer = 0;
this.wasRising = false;
this.helpertimer.reset();
this.top = delay;
this.bottom = 0;
}
public double getValue() {
return this.wasRising ? Math.sin((double) (this.timer - this.bottom) / (double) (this.delay - this.bottom) * Math.PI / 2.00D) : 1.00D - Math.cos((double) this.timer / (double) this.top * Math.PI / 2.00D);
}
}
| 25.758621 | 212 | 0.481928 |
c96b23289bbb1dd47ca12a8dc880aef75e954153 | 3,719 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.trevni.avro;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.avro.reflect.ReflectData;
import org.apache.avro.mapred.AvroJob;
import org.apache.avro.mapred.AvroWrapper;
/**
* An {@link org.apache.hadoop.mapred.InputFormat} for Trevni files.
*
* <p>
* A subset schema to be read may be specified with
* {@link AvroJob#setInputSchema(JobConf,Schema)}.
*/
public class AvroTrevniInputFormat<T> extends FileInputFormat<AvroWrapper<T>, NullWritable> {
@Override
protected boolean isSplitable(FileSystem fs, Path filename) {
return false;
}
@Override
protected FileStatus[] listStatus(JobConf job) throws IOException {
List<FileStatus> result = new ArrayList<>();
job.setBoolean("mapred.input.dir.recursive", true);
for (FileStatus file : super.listStatus(job))
if (file.getPath().getName().endsWith(AvroTrevniOutputFormat.EXT))
result.add(file);
return result.toArray(new FileStatus[0]);
}
@Override
public RecordReader<AvroWrapper<T>, NullWritable> getRecordReader(InputSplit split, final JobConf job,
Reporter reporter) throws IOException {
final FileSplit file = (FileSplit) split;
reporter.setStatus(file.toString());
final AvroColumnReader.Params params = new AvroColumnReader.Params(new HadoopInput(file.getPath(), job));
params.setModel(ReflectData.get());
if (job.get(AvroJob.INPUT_SCHEMA) != null)
params.setSchema(AvroJob.getInputSchema(job));
return new RecordReader<AvroWrapper<T>, NullWritable>() {
private AvroColumnReader<T> reader = new AvroColumnReader<>(params);
private float rows = reader.getRowCount();
private long row;
@Override
public AvroWrapper<T> createKey() {
return new AvroWrapper<>(null);
}
@Override
public NullWritable createValue() {
return NullWritable.get();
}
@Override
public boolean next(AvroWrapper<T> wrapper, NullWritable ignore) throws IOException {
if (!reader.hasNext())
return false;
wrapper.datum(reader.next());
row++;
return true;
}
@Override
public float getProgress() throws IOException {
return row / rows;
}
@Override
public long getPos() throws IOException {
return row;
}
@Override
public void close() throws IOException {
reader.close();
}
};
}
}
| 31.252101 | 109 | 0.710137 |
bbf0df19e78a8ce0051617be8c20f953ea730566 | 15,229 | package noear.weed;
import noear.weed.cache.CacheUsing;
import noear.weed.cache.ICacheService;
import noear.weed.ext.Act1;
import noear.weed.ext.Act2;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yuety on 14/11/12.
*
* # //不加表空间(table(xxx) : 默认加表空间)
* $. //当前表空间
* $NOW() //说明这里是一个sql 函数
* ?... //说明这里是一个数组或查询结果
*/
public class DbTableQueryBase<T extends DbTableQueryBase> {
String _table;
DbContext _context;
SQLBuilder _builder;
boolean _isLog = false;
public DbTableQueryBase(DbContext context) {
_context = context;
_builder = new SQLBuilder();
}
public T log(Boolean isLog){
_isLog = isLog;
return (T)this;
}
public T expre(Act1<T> action){
action.run((T)this);
return (T)this;
}
protected T table(String table) { //相当于 from
if(table.startsWith("#")){
_table = table.replace("#","");
}else {
if (table.indexOf('.') > 0)
_table = table;
else
_table = "$." + table;
}
return (T) this;
}
//使用 ?... 支持数组参数
public T where(String where, Object... args) {
_builder.append(" WHERE ").append(where, args);
return (T)this;
}
public T where() {
_builder.append(" WHERE ");
return (T)this;
}
public T and(String and, Object... args) {
_builder.append(" AND ").append(and, args);
return (T)this;
}
public T and() {
_builder.append(" AND ");
return (T)this;
}
public T or(String or, Object... args) {
_builder.append(" OR ").append(or, args);
return (T)this;
}
public T or() {
_builder.append(" OR ");
return (T)this;
}
public T begin() {
_builder.append(" ( ");
return (T)this;
}
public T begin(String and, Object... args) {
_builder.append(" ( ").append(and, args);
return (T)this;
}
public T end() {
_builder.append(" ) ");
return (T)this;
}
public T from(String table){
_builder.append(" FROM ").append(table);
return (T)this;
}
public long insert(IDataItem data) throws SQLException {
if (data == null || data.count() == 0)
return 0;
List<Object> args = new ArrayList<Object>();
StringBuilder sb = new StringBuilder();
sb.append(" INSERT INTO ").append(_table).append(" (");
data.forEach((key, value) -> {
// if(value==null) //支持null插入
// return;
sb.append(_context.field(key)).append(",");
});
sb.deleteCharAt(sb.length() - 1);
sb.append(") ");
sb.append("VALUES");
sb.append("(");
data.forEach((key, value) -> {
if (value == null) {
sb.append("null,"); //充许插入null
} else {
if (value instanceof String) {
String val2 = (String) value;
if (isSqlExpr(val2)) { //说明是SQL函数
sb.append(val2.substring(1)).append(",");
} else {
sb.append("?,");
args.add(value);
}
} else {
sb.append("?,");
args.add(value);
}
}
});
sb.deleteCharAt(sb.length() - 1);
sb.append(");");
_builder.clear();
_builder.append(sb.toString(), args.toArray());
return compile().insert();
}
public <T> boolean insertList(List<T> valuesList, Act2<T,DataItem> hander) throws SQLException {
List<DataItem> list2 = new ArrayList<>();
for (T values : valuesList) {
DataItem item = new DataItem();
hander.run(values, item);
list2.add(item);
}
if (list2.size() > 0) {
return insertList(list2.get(0), list2);
}else{
return false;
}
}
public boolean insertList(List<DataItem> valuesList) throws SQLException {
if (valuesList == null || valuesList.size() == 0)
return false;
return insertList(valuesList.get(0), valuesList);
}
protected <T extends GetHandler> boolean insertList(IDataItem cols, List<T> valuesList)throws SQLException {
if (valuesList == null || valuesList.size() == 0)
return false;
if (cols == null || cols.count() == 0)
return false;
List<Object> args = new ArrayList<Object>();
StringBuilder sb = new StringBuilder();
sb.append(" INSERT INTO ").append(_table).append(" (");
for (String key : cols.keys()) {
sb.append(_context.field(key)).append(",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(") ");
sb.append("VALUES");
for (GetHandler item : valuesList) {
sb.append("(");
for (String key : cols.keys()) {
Object val = item.get(key);
if (val == null) {
sb.append("null,");
} else {
if (val instanceof String) {
String val2 = (String) val;
if (isSqlExpr(val2)) { //说明是SQL函数
sb.append(val2.substring(1)).append(",");
} else {
sb.append("?,");
args.add(val);
}
} else {
sb.append("?,");
args.add(val);
}
}
}
sb.deleteCharAt(sb.length() - 1);
sb.append("),");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(";");
_builder.append(sb.toString(), args.toArray());
return compile().execute() > 0;
}
public long insert(Act1<IDataItem> fun) throws SQLException
{
DataItem item = new DataItem();
fun.run(item);
return insert(item);
}
public void updateExt(IDataItem data, String constraints) throws SQLException {
String[] ff = constraints.split(",");
this.where("1=1");
for (String f : ff) {
this.and(f + "=?", data.get(f));
}
if (this.exists()) {
for (String f : ff) {
data.remove(f);
}
this.update(data);
} else {
this.insert(data);
}
}
public int update(Act1<IDataItem> fun) throws SQLException
{
DataItem item = new DataItem();
fun.run(item);
return update(item);
}
public int update(IDataItem data) throws SQLException{
if (data == null || data.count() == 0)
return 0;
List<Object> args = new ArrayList<Object>();
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ").append(_table).append(" SET ");
data.forEach((key,value)->{
if(value==null)
return;
if (value instanceof String) {
String val2 = (String)value;
if (isSqlExpr(val2)) {
sb.append(_context.field(key)).append("=").append(val2.substring(1)).append(",");
}
else {
sb.append(_context.field(key)).append("=?,");
args.add(value);
}
}
else {
sb.append(_context.field(key)).append("=?,");
args.add(value);
}
});
sb.deleteCharAt(sb.length() - 1);
_builder.insert(sb.toString(), args.toArray());
return compile().execute();
}
public <T> boolean updateList(String pk, List<T> valuesList, Act2<T,DataItem> hander) throws SQLException {
List<DataItem> list2 = new ArrayList<>();
for (T values : valuesList) {
DataItem item = new DataItem();
hander.run(values, item);
list2.add(item);
}
if (list2.size() > 0) {
return updateList(pk, list2.get(0), list2);
}else{
return false;
}
}
public boolean updateList(String pk, List<DataItem> valuesList) throws SQLException {
if (valuesList == null || valuesList.size() == 0)
return false;
return updateList(pk, valuesList.get(0), valuesList);
}
protected <T extends GetHandler> boolean updateList(String pk, IDataItem cols, List<T> valuesList)throws SQLException{
if(valuesList == null || valuesList.size()==0)
return false;
if (cols == null || cols.count() == 0)
return false;
List<Object> args = new ArrayList<Object>();
StringBuilder sb = new StringBuilder();
sb.append(" INSERT INTO ").append(_table).append(" (");
for(String key : cols.keys()){
sb.append(_context.field(key)).append(",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(") ");
sb.append("VALUES");
for(GetHandler item : valuesList){
sb.append("(");
for(String key : cols.keys()) {
Object val = item.get(key);
if(val == null){
sb.append("null,");
}else {
if (val instanceof String) {
String val2 = (String) val;
if (isSqlExpr(val2)) { //说明是SQL函数
sb.append(val2.substring(1)).append(",");
} else {
sb.append("?,");
args.add(val);
}
} else {
sb.append("?,");
args.add(val);
}
}
}
sb.deleteCharAt(sb.length() - 1);
sb.append("),");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(" ON DUPLICATE KEY UPDATE");
for(String key : cols.keys()){
if(pk.equals(key))
continue;
sb.append(" ").append(key).append("=VALUES(").append(key).append("),");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(";");
_builder.append(sb.toString(), args.toArray());
return compile().execute() > 0;
}
public int delete() throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append("DELETE ");
if(_builder.indexOf(" FROM ")<0){
sb.append(" FROM ").append(_table);
}else{
sb.append(_table);
}
_builder.insert(sb.toString());
return compile().execute();
}
public T innerJoin(String table) {
_builder.append(" INNER JOIN ").append(table);
return (T)this;
}
public T leftJoin(String table) {
_builder.append(" LEFT JOIN ").append(table);
return (T)this;
}
public T rightJoin(String table) {
_builder.append(" RIGHT JOIN ").append(table);
return (T)this;
}
public T on(String on) {
_builder.append(" ON ").append(on);
return (T)this;
}
public T groupBy(String groupBy) {
_builder.append(" GROUP BY ").append(groupBy);
return (T)this;
}
public T orderBy(String orderBy) {
_builder.append(" ORDER BY ").append(orderBy);
return (T)this;
}
public T limit(int start, int rows) {
_builder.append(" LIMIT " + start + "," + rows + " ");
return (T)this;
}
public T limit(int rows) {
_builder.append(" LIMIT " + rows + " ");
return (T)this;
}
private int _top = 0;
public T top(int num) {
_top = num;
//_builder.append(" TOP " + num + " ");
return (T)this;
}
public boolean exists() throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append("SELECT 1 FROM ").append(_table);
_builder.backup();
_builder.insert(sb.toString());
_builder.append(" LIMIT 1");
//1.构建sql
if(_hint!=null) {
_builder.insert(_hint);
_hint = null;
}
DbQuery rst = compile();
if(_cache != null){
rst.cache(_cache);
}
_builder.restore();
return rst.getValue() != null;
}
String _hint = null;
public T hint(String hint){
_hint = hint;
return (T)this;
}
public long count() throws SQLException{
return count("COUNT(*)");
}
public long count(String expr) throws SQLException{
return select(expr).getVariate().longValue(0l);
}
public IQuery select(String columns) {
StringBuilder sb = new StringBuilder();
//1.构建sql
if(_hint!=null) {
sb.append(_hint);
_hint = null;
}
sb.append("SELECT ");
if(_top>0){
sb.append(" TOP ").append(_top).append(" ");
}
sb.append(columns).append(" FROM ").append(_table);
_builder.backup();
_builder.insert(sb.toString());
DbQuery rst = compile();
if(_cache != null){
rst.cache(_cache);
}
_builder.restore();
return rst;
}
protected DbTran _tran = null;
public T tran(DbTran transaction)
{
_tran = transaction;
return (T)this;
}
public T tran()
{
_tran = _context.tran();
return (T)this;
}
//编译(成DbQuery)
private DbQuery compile() {
DbQuery temp = new DbQuery(_context).sql(_builder);
_builder.clear();
if(_tran!=null)
temp.tran(_tran);
return temp.onCommandBuilt((cmd)->{
cmd.tag = _table;
cmd.isLog = _isLog;
});
}
private boolean _usingExpression = WeedConfig.isUsingValueExpression;
public T usingExpr(boolean isUsing){
_usingExpression = isUsing;
return (T)this;
}
private boolean isSqlExpr(String txt){
if(_usingExpression == false){
return false;
}
if(txt.startsWith("$") && txt.indexOf(" ")<0){ //不许有空隔(否则为非正常表达式)
return true;
}else{
return false;
}
}
//=======================
//
// 缓存控制相关
//
protected CacheUsing _cache = null;
/*引用一个缓存服务*/
public T caching(ICacheService service)
{
_cache = new CacheUsing(service);
return (T)this;
}
/*是否使用缓存*/
public T usingCache (boolean isCache)
{
_cache.usingCache(isCache);
return (T)this;
}
/*使用缓存时间(单位:秒)*/
public T usingCache (int seconds)
{
_cache.usingCache(seconds);
return (T)this;
}
/*添加缓存标签*/
public T cacheTag(String tag)
{
_cache.cacheTag(tag);
return (T)this;
}
}
| 24.802932 | 122 | 0.487622 |
889c81c004858b842680674ebf62fb4d24dfbcd9 | 864 | public class Main {
static Long sum = 0l;
public static void main(String[] args) {
int value = 123;
int k = 0;
long newValue = getNewValue(value, k);
System.out.println(getSuperDigit(newValue));
}
private static long getNewValue(int n, int k) {
if ((n > -10 && n < 10) && k == 0) {
return n;
}
String valueToString = String.valueOf(n);
StringBuilder builder = new StringBuilder(String.valueOf(n));
for (int i = 1; i < k; i++) {
builder.append(valueToString);
}
return Long.parseLong(builder.toString());
}
private static int getSuperDigit(long n) {
while (n > 10) {
sum += n % 10;
n = n / 10;
getSuperDigit(n);
}
return new Long(n + sum).intValue();
}
}
| 22.153846 | 69 | 0.509259 |
187258936d24b8523db0ea504ce4017fac5dca40 | 11,909 | package org.cosette;
import com.google.common.collect.ImmutableList;
import org.apache.calcite.adapter.java.JavaTypeFactory;
import org.apache.calcite.avatica.util.Quoting;
import org.apache.calcite.config.CalciteConnectionConfig;
import org.apache.calcite.config.CalciteConnectionConfigImpl;
import org.apache.calcite.config.CalciteConnectionProperty;
import org.apache.calcite.config.CalciteSystemProperty;
import org.apache.calcite.jdbc.CalciteSchema;
import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
import org.apache.calcite.plan.*;
import org.apache.calcite.plan.volcano.VolcanoPlanner;
import org.apache.calcite.prepare.CalciteCatalogReader;
import org.apache.calcite.rel.RelCollationTraitDef;
import org.apache.calcite.rel.RelRoot;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeSystem;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexExecutor;
import org.apache.calcite.runtime.Hook;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.sql.SqlInsert;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlOperatorTable;
import org.apache.calcite.sql.parser.SqlParseException;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.sql.util.SqlOperatorTables;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.sql.validate.SqlValidatorImpl;
import org.apache.calcite.sql2rel.RelDecorrelator;
import org.apache.calcite.sql2rel.SqlRexConvertletTable;
import org.apache.calcite.sql2rel.SqlToRelConverter;
import org.apache.calcite.tools.*;
import org.apache.calcite.util.SourceStringReader;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.Reader;
import java.util.List;
import static java.util.Objects.requireNonNull;
/**
* A copy of the PlannerImpl that disables all rewrite rules.
*/
public class RawPlanner implements RelOptTable.ViewExpander {
private final SqlOperatorTable operatorTable;
private final ImmutableList<Program> programs;
private final @Nullable RelOptCostFactory costFactory;
private final Context context;
private final CalciteConnectionConfig connectionConfig;
/**
* Holds the trait definitions to be registered with planner. May be null.
*/
private final @Nullable ImmutableList<RelTraitDef> traitDefs;
private final SqlParser.Config parserConfig;
private final SqlValidator.Config sqlValidatorConfig;
private final SqlToRelConverter.Config sqlToRelConverterConfig;
private final SqlRexConvertletTable convertletTable;
// set in STATE_2_READY
private @Nullable
final SchemaPlus defaultSchema;
private @Nullable
final RexExecutor executor;
// set in STATE_1_RESET
@SuppressWarnings("unused")
private boolean open;
private @Nullable JavaTypeFactory typeFactory;
private @Nullable RelOptPlanner planner;
// set in STATE_4_VALIDATE
private @Nullable SqlValidator validator;
private @Nullable SqlNode validatedSqlNode;
public RawPlanner(SchemaPlus schema) {
SqlToRelConverter.Config converterConfig = SqlToRelConverter.config()
.withRelBuilderConfigTransform(c -> c.withPushJoinCondition(false)
.withSimplify(false)
.withSimplifyValues(false)
.withBloat(-1)
.withDedupAggregateCalls(false)
.withPruneInputOfAggregate(false))
.withDecorrelationEnabled(false)
.withExpand(false)
.withTrimUnusedFields(false);
FrameworkConfig config = Frameworks.newConfigBuilder()
.defaultSchema(schema)
.parserConfig(SqlParser.Config.DEFAULT.withQuoting(Quoting.BACK_TICK).withCaseSensitive(false))
.sqlToRelConverterConfig(converterConfig)
.build();
this.costFactory = config.getCostFactory();
this.defaultSchema = config.getDefaultSchema();
this.operatorTable = config.getOperatorTable();
this.programs = config.getPrograms();
this.parserConfig = config.getParserConfig();
this.sqlValidatorConfig = config.getSqlValidatorConfig();
this.sqlToRelConverterConfig = config.getSqlToRelConverterConfig();
this.traitDefs = config.getTraitDefs();
this.convertletTable = config.getConvertletTable();
this.executor = config.getExecutor();
this.context = config.getContext();
this.connectionConfig = connConfig(context, parserConfig);
}
private static CalciteConnectionConfig connConfig(Context context,
SqlParser.Config parserConfig) {
CalciteConnectionConfigImpl config =
context.maybeUnwrap(CalciteConnectionConfigImpl.class)
.orElse(CalciteConnectionConfig.DEFAULT);
if (!config.isSet(CalciteConnectionProperty.CASE_SENSITIVE)) {
config = config.set(CalciteConnectionProperty.CASE_SENSITIVE,
String.valueOf(parserConfig.caseSensitive()));
}
if (!config.isSet(CalciteConnectionProperty.CONFORMANCE)) {
config = config.set(CalciteConnectionProperty.CONFORMANCE,
String.valueOf(parserConfig.conformance()));
}
return config;
}
private static SchemaPlus rootSchema(SchemaPlus schema) {
for (; ; ) {
SchemaPlus parentSchema = schema.getParentSchema();
if (parentSchema == null) {
return schema;
}
schema = parentSchema;
}
}
private void ready() {
RelDataTypeSystem typeSystem =
connectionConfig.typeSystem(RelDataTypeSystem.class,
RelDataTypeSystem.DEFAULT);
typeFactory = new JavaTypeFactoryImpl(typeSystem);
RelOptPlanner planner = this.planner = new VolcanoPlanner(costFactory, context);
RelOptUtil.registerDefaultRules(planner,
connectionConfig.materializationsEnabled(),
Hook.ENABLE_BINDABLE.get(false));
planner.setExecutor(executor);
// If user specify own traitDef, instead of default default trait,
// register the trait def specified in traitDefs.
if (this.traitDefs == null) {
planner.addRelTraitDef(ConventionTraitDef.INSTANCE);
if (CalciteSystemProperty.ENABLE_COLLATION_TRAIT.value()) {
planner.addRelTraitDef(RelCollationTraitDef.INSTANCE);
}
} else {
for (RelTraitDef def : this.traitDefs) {
planner.addRelTraitDef(def);
}
}
}
public SqlNode parse(String sql) throws SqlParseException, ValidationException {
ready();
Reader reader = new SourceStringReader(sql);
SqlParser parser = SqlParser.create(reader, parserConfig);
SqlNode sqlNode = parser.parseStmt();
this.validator = createSqlValidator(createCatalogReader());
try {
validatedSqlNode = validator.validate(sqlNode);
} catch (RuntimeException e) {
throw new ValidationException(e);
}
return validatedSqlNode;
}
private SqlValidator createSqlValidator(CalciteCatalogReader catalogReader) {
final SqlOperatorTable opTab =
SqlOperatorTables.chain(operatorTable, catalogReader);
return new RawSqlValidator(opTab,
catalogReader,
getTypeFactory(),
sqlValidatorConfig
.withDefaultNullCollation(connectionConfig.defaultNullCollation())
.withLenientOperatorLookup(connectionConfig.lenientOperatorLookup())
.withSqlConformance(connectionConfig.conformance())
.withIdentifierExpansion(true));
}
private CalciteCatalogReader createCatalogReader() {
SchemaPlus defaultSchema = requireNonNull(this.defaultSchema, "defaultSchema");
final SchemaPlus rootSchema = rootSchema(defaultSchema);
return new CalciteCatalogReader(
CalciteSchema.from(rootSchema),
CalciteSchema.from(defaultSchema).path(null),
getTypeFactory(), connectionConfig);
}
public JavaTypeFactory getTypeFactory() {
return requireNonNull(typeFactory, "typeFactory");
}
public RelRoot rel(SqlNode sql) {
SqlNode validatedSqlNode = requireNonNull(this.validatedSqlNode,
"validatedSqlNode is null. Need to call #validate() first");
final RexBuilder rexBuilder = createRexBuilder();
final RelOptCluster cluster = RelOptCluster.create(
requireNonNull(planner, "planner"),
rexBuilder);
final SqlToRelConverter.Config config =
sqlToRelConverterConfig.withTrimUnusedFields(false);
final SqlToRelConverter sqlToRelConverter =
new SqlToRelConverter(this, validator,
createCatalogReader(), cluster, convertletTable, config);
return sqlToRelConverter.convertQuery(validatedSqlNode, false, true);
}
private RexBuilder createRexBuilder() {
return new RexBuilder(getTypeFactory());
}
@Override
public RelRoot expandView(RelDataType rowType, String queryString, List<String> schemaPath, @Nullable List<String> viewPath) {
RelOptPlanner planner = this.planner;
if (planner == null) {
ready();
planner = requireNonNull(this.planner, "planner");
}
SqlParser parser = SqlParser.create(queryString, parserConfig);
SqlNode sqlNode;
try {
sqlNode = parser.parseQuery();
} catch (SqlParseException e) {
throw new RuntimeException("parse failed", e);
}
final CalciteCatalogReader catalogReader =
createCatalogReader().withSchemaPath(schemaPath);
final SqlValidator validator = createSqlValidator(catalogReader);
final RexBuilder rexBuilder = createRexBuilder();
final RelOptCluster cluster = RelOptCluster.create(planner, rexBuilder);
final SqlToRelConverter.Config config =
sqlToRelConverterConfig.withTrimUnusedFields(false);
final SqlToRelConverter sqlToRelConverter =
new SqlToRelConverter(this, validator,
catalogReader, cluster, convertletTable, config);
final RelRoot root =
sqlToRelConverter.convertQuery(sqlNode, true, false);
final RelRoot root2 =
root.withRel(sqlToRelConverter.flattenTypes(root.rel, true));
final RelBuilder relBuilder =
config.getRelBuilderFactory().create(cluster, null);
return root2.withRel(
RelDecorrelator.decorrelateQuery(root.rel, relBuilder));
}
}
class RawSqlValidator extends SqlValidatorImpl {
RawSqlValidator(SqlOperatorTable opTab,
CalciteCatalogReader catalogReader, JavaTypeFactory typeFactory,
Config config) {
super(opTab, catalogReader, typeFactory, config);
}
@Override
protected RelDataType getLogicalSourceRowType(
RelDataType sourceRowType, SqlInsert insert) {
final RelDataType superType =
super.getLogicalSourceRowType(sourceRowType, insert);
return ((JavaTypeFactory) typeFactory).toSql(superType);
}
@Override
protected RelDataType getLogicalTargetRowType(
RelDataType targetRowType, SqlInsert insert) {
final RelDataType superType =
super.getLogicalTargetRowType(targetRowType, insert);
return ((JavaTypeFactory) typeFactory).toSql(superType);
}
} | 42.838129 | 130 | 0.683013 |
0cab5b39fa46e9a7ef633afca7bffcf5b4e1ca5c | 1,312 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Order {
private int orderId;
public int getOrderId() {
return orderId;
}
private Set<OrderLine> orderLines = new HashSet<OrderLine>();
public Set<OrderLine> getLines() {
return Collections.unmodifiableSet(orderLines);
}
public void addLine(OrderLine orderLine){
orderLine.setOrder(this);
this.orderLines.add(orderLine);
}
private Set<OrderContact> orderContacts = new HashSet<OrderContact>();
public Set<OrderContact> getContacts() {
return Collections.unmodifiableSet(orderContacts);
}
public void addContact(OrderContact orderContact){
orderContact.getOrders().add( this );
this.orderContacts.add(orderContact);
}
public OrderAddress orderAddress;
public OrderAddress getOrderAddress() {
return orderAddress;
}
public void setOrderAddress(OrderAddress orderAddress) {
this.orderAddress = orderAddress;
}
public String toString() {
return "" + getOrderId() + " - " + getLines();
}
}
| 23.017544 | 94 | 0.737043 |
77b83986a1fca04a243bb693a914df1ba474ce31 | 1,879 | package rocks.process.acrm.data.domain;
/*
* Copyright (c) 2020. University of Applied Sciences and Arts Northwestern Switzerland FHNW.
* All rights reserved.
*/
import com.fasterxml.jackson.annotation.JsonProperty;
import rocks.process.acrm.data.domain.Job;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import java.util.List;
@Entity
@Table(name = "t_member")
public class Member {
@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private Integer id;
@Email(message = "Please provide a valid e-mail.")
@NotEmpty(message = "Please provide an e-mail.")
private String email;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY) // only create object property from JSON
private String password;
private String phone;
@OneToMany(
mappedBy ="member", cascade = CascadeType.ALL, orphanRemoval = true
)
private List<Job> jobs;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
String transientPassword = this.password;
this.password = null;
return transientPassword;
}
public void setPassword(String password) {
this.password = password;
}
public List<Job> getJobs() {
return jobs;
}
public void setJobs(List<Job> jobs) {
this.jobs = jobs;
}
private void addJob(Job job){
jobs.add(job);
}
private void removeJob(Job job){
jobs.remove(job);
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
} | 21.11236 | 99 | 0.642363 |
1ad452980cd678d2522e80f554cbb2e897d06e37 | 1,485 | package goveed20.LiteraryAssociationApplication.services;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelException;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.instance.UserTask;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperties;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperty;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class TaskExtensionsService {
public Map<String, String> getExtensions(String bpmnFile, String taskId) {
String bpmnFilePath = String.format("Literary-Association-Application/src/main/resources/%s.bpmn", bpmnFile);
File file = new File(bpmnFilePath);
BpmnModelInstance modelInstance = Bpmn.readModelFromFile(file);
UserTask task = modelInstance.getModelElementById(taskId);
CamundaProperties properties;
try {
properties = task.getExtensionElements().getElementsQuery().filterByType(CamundaProperties.class)
.singleResult();
} catch (BpmnModelException e) {
return new HashMap<>();
}
return properties.getCamundaProperties().stream()
.collect(
Collectors.toMap(CamundaProperty::getCamundaName, CamundaProperty::getCamundaValue)
);
}
}
| 38.076923 | 117 | 0.721886 |
2b5fe1d8f0f195dec0ad74795242d6711887b4db | 7,102 | /**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2015, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package ch.qos.logback.classic;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.classic.pattern.ConverterTest;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.classic.testUtil.SampleConverter;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.pattern.PatternLayoutBase;
import ch.qos.logback.core.pattern.parser.AbstractPatternLayoutBaseTest;
import ch.qos.logback.core.testUtil.StringListAppender;
import ch.qos.logback.core.util.OptionHelper;
import ch.qos.logback.core.util.StatusPrinter;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.MDC;
import static ch.qos.logback.classic.ClassicTestConstants.ISO_REGEX;
import static ch.qos.logback.classic.ClassicTestConstants.MAIN_REGEX;
import static org.junit.Assert.*;
public class PatternLayoutTest extends AbstractPatternLayoutBaseTest<ILoggingEvent> {
private PatternLayout pl = new PatternLayout();
private LoggerContext lc = new LoggerContext();
Logger logger = lc.getLogger(ConverterTest.class);
Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME);
ILoggingEvent le;
public PatternLayoutTest() {
super();
Exception ex = new Exception("Bogus exception");
le = makeLoggingEvent(ex);
}
@Before
public void setUp() {
pl.setContext(lc);
}
ILoggingEvent makeLoggingEvent(Exception ex) {
return new LoggingEvent(
ch.qos.logback.core.pattern.FormattingConverter.class.getName(),
logger, Level.INFO, "Some message", ex, null);
}
@Override
public ILoggingEvent getEventObject() {
return makeLoggingEvent(null);
}
public PatternLayoutBase<ILoggingEvent> getPatternLayoutBase() {
return new PatternLayout();
}
@Test
public void testOK() {
pl.setPattern("%d %le [%t] %lo{30} - %m%n");
pl.start();
String val = pl.doLayout(getEventObject());
// 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some
// message
//2010-12-29 19:04:26,137 INFO [pool-1-thread-47] c.q.l.c.pattern.ConverterTest - Some message
String regex = ISO_REGEX + " INFO " + MAIN_REGEX
+ " c.q.l.c.pattern.ConverterTest - Some message\\s*";
assertTrue("val="+val, val.matches(regex));
}
@Test
public void testNoExeptionHandler() {
pl.setPattern("%m%n");
pl.start();
String val = pl.doLayout(le);
assertTrue(val.contains("java.lang.Exception: Bogus exception"));
}
@Test
public void testCompositePattern() {
pl.setPattern("%-56(%d %lo{20}) - %m%n");
pl.start();
String val = pl.doLayout(getEventObject());
// 2008-03-18 21:55:54,250 c.q.l.c.pattern.ConverterTest - Some message
String regex = ISO_REGEX
+ " c.q.l.c.p.ConverterTest - Some message\\s*";
assertTrue(val.matches(regex));
}
@Test
public void contextProperty() {
pl.setPattern("%property{a}");
pl.start();
lc.putProperty("a", "b");
String val = pl.doLayout(getEventObject());
assertEquals("b", val);
}
@Test
public void testNopExeptionHandler() {
pl.setPattern("%nopex %m%n");
pl.start();
String val = pl.doLayout(le);
assertTrue(!val.contains("java.lang.Exception: Bogus exception"));
}
@Test
public void testWithParenthesis() {
pl.setPattern("\\(%msg:%msg\\) %msg");
pl.start();
le = makeLoggingEvent(null);
String val = pl.doLayout(le);
// System.out.println("VAL == " + val);
assertEquals("(Some message:Some message) Some message", val);
}
@Test
public void testWithLettersComingFromLog4j() {
// Letters: p = level and c = logger
pl.setPattern("%d %p [%t] %c{30} - %m%n");
pl.start();
String val = pl.doLayout(getEventObject());
// 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some
// message
String regex = ClassicTestConstants.ISO_REGEX + " INFO " + MAIN_REGEX
+ " c.q.l.c.pattern.ConverterTest - Some message\\s*";
assertTrue(val.matches(regex));
}
@Test
public void mdcWithDefaultValue() {
String pattern = "%msg %mdc{foo} %mdc{bar:-[null]}";
pl.setPattern(OptionHelper.substVars(pattern, lc));
pl.start();
MDC.put("foo", "foo");
try {
String val = pl.doLayout(getEventObject());
assertEquals("Some message foo [null]", val);
} finally {
MDC.remove("foo");
}
}
@Test
public void contextNameTest() {
pl.setPattern("%contextName");
lc.setName("aValue");
pl.start();
String val = pl.doLayout(getEventObject());
assertEquals("aValue", val);
}
@Test
public void cnTest() {
pl.setPattern("%cn");
lc.setName("aValue");
pl.start();
String val = pl.doLayout(getEventObject());
assertEquals("aValue", val);
}
@Override
public Context getContext() {
return lc;
}
void configure(String file) throws JoranException {
JoranConfigurator jc = new JoranConfigurator();
jc.setContext(lc);
jc.doConfigure(file);
}
@Test
public void testConversionRuleSupportInPatternLayout() throws JoranException {
configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "conversionRule/patternLayout0.xml");
root.getAppender("LIST");
String msg = "Simon says";
logger.debug(msg);
StringListAppender<ILoggingEvent> sla = (StringListAppender<ILoggingEvent>) root.getAppender("LIST");
assertNotNull(sla);
assertEquals(1, sla.strList.size());
assertEquals(SampleConverter.SAMPLE_STR + " - " + msg, sla.strList.get(0));
}
@Test
public void somekeReplace() {
pl.setPattern("%replace(a1234b){'\\d{4}', 'XXXX'}");
pl.start();
StatusPrinter.print(lc);
String val = pl.doLayout(getEventObject());
assertEquals("aXXXXb", val);
}
@Test
public void replaceWithJoran() throws JoranException {
configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "pattern/replace0.xml");
StatusPrinter.print(lc);
root.getAppender("LIST");
String msg = "And the number is 4111111111110000, expiring on 12/2010";
logger.debug(msg);
StringListAppender<ILoggingEvent> sla = (StringListAppender<ILoggingEvent>) root.getAppender("LIST");
assertNotNull(sla);
assertEquals(1, sla.strList.size());
assertEquals("And the number is XXXX, expiring on 12/2010", sla.strList.get(0));
}
}
| 31.564444 | 106 | 0.661645 |
9b0e7180666931f4ca7aae90f6032cb7eb9169e4 | 1,202 | package net.ignissak.discoverareas.events.worldguard;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
public abstract class RegionEvent extends PlayerEvent {
private static final HandlerList handlerList;
private ProtectedRegion region;
private MovementWay movement;
public Event parentEvent;
public RegionEvent(final ProtectedRegion region, final Player player, final MovementWay movement, final Event parent) {
super(player);
this.region = region;
this.movement = movement;
this.parentEvent = parent;
}
public HandlerList getHandlers() {
return RegionEvent.handlerList;
}
public ProtectedRegion getRegion() {
return this.region;
}
public static HandlerList getHandlerList() {
return RegionEvent.handlerList;
}
public MovementWay getMovementWay() {
return this.movement;
}
public Event getParentEvent() {
return this.parentEvent;
}
static {
handlerList = new HandlerList();
}
}
| 25.041667 | 123 | 0.705491 |
c2c6fb678aa728f186d30de467e388af8a634bbf | 989 | package chapter7classes;
public class Rectangle {
private int length;
private int width;
private String color;
// constructor method - name must match the class, no return type
public Rectangle(){
length = 0;
width = 0;
color = ""; // this avoid the string being null
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
public String getColor() {
return color;
}
public void setLength(int length) {
if (length > 0) {
this.length = length;
} else {
this.length = 0;
}
}
public void setWidth(int width) {
if (width > 0) {
this.width = width;
} else {
this.width = 0;
}
}
public void setColor(String color) {
this.color = color;
}
public int getArea() {
int area = length * width;
return area;
}
}
| 18.660377 | 69 | 0.512639 |
bdab50160b6994703b5df648488da9cf41f91a9b | 3,351 | package us.rjks.gui;
import us.rjks.utils.MorseCodierung;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Copyright Ⓒ Robert J. Kratz 2021
* Created: 01.09.2021 / 17:50
* Contact: https://link.rjks.us/support
*/
public class Formatter extends JFrame {
private MorseCodierung morseCodierung;
private JPanel main;
private JTextArea output;
private JButton submit;
private JButton toggle;
private JTextArea input;
private JLabel title;
private State state;
public Formatter() {
this.state = State.ENCODE;
this.morseCodierung = new MorseCodierung();
this.setTitle("Morse decoder/encoder by rjks.us");
this.setSize(300, 488);
this.setResizable(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.main = new JPanel();
this.main.setLayout(new FlowLayout());
this.title = new JLabel("Encoding is enabled");
this.output = new JTextArea("The output will be printed here", 10, 20);
this.output.setMargin(new Insets(5, 5, 5, 5));
this.output.setEditable(false);
this.output.setLineWrap(true);
JScrollPane out = new JScrollPane (this.output, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.input = new JTextArea("", 10, 20);
this.input.setToolTipText("Input your code here");
this.input.setMargin(new Insets(5, 5, 5, 5));
this.input.setLineWrap(true);
JScrollPane in = new JScrollPane (this.input, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.submit = new JButton("Submit");
this.toggle = new JButton("Decode");
this.main.add(this.title);
this.main.add(in);
this.main.add(submit);
this.main.add(out);
this.main.add(toggle);
this.main.add(new JLabel("Robert J. Kratz (rjks.us) © 2021"));
addListeners();
this.getContentPane().add(main);
}
private void addListeners() {
submit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (input.getText() == null || input.getText().isEmpty()) {
output.setText("An error has occurred, no translations were made");
return;
}
String out;
if (state.equals(State.ENCODE)) {
out = morseCodierung.encodeString(input.getText());
} else {
out = morseCodierung.decodeString(input.getText());
}
output.setText(out);
}
});
toggle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(state.equals(State.ENCODE)) {
title.setText("Decoding is enabled");
toggle.setText("Decode");
state = State.DECODE;
} else {
title.setText("Encoding is enabled");
toggle.setText("Encode");
state = State.ENCODE;
}
}
});
}
}
| 29.654867 | 135 | 0.583408 |
16a796b3bcdf858176dc2a2a538cd5dc41a4cbaf | 1,573 | /*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.apimgt.authenticator.oidc.common;
/**
* Class to hold OIDC server configuration
*/
public class ServerConfiguration {
String issuer;
String jwksUri;
String userInfoUri;
String tokenEndpointUri;
public String getIssuer() {
return issuer;
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
public String getJwksUri() {
return jwksUri;
}
public void setJwksUri(String jwksUri) {
this.jwksUri = jwksUri;
}
public String getUserInfoUri() {
return userInfoUri;
}
public void setUserInfoUri(String userInfoUri) {
this.userInfoUri = userInfoUri;
}
public String getTokenEndpointUri() {
return tokenEndpointUri;
}
public void setTokenEndpointUri(String tokenEndpointUri) {
this.tokenEndpointUri = tokenEndpointUri;
}
}
| 24.968254 | 80 | 0.689765 |
5818ca79013a87b130c9dfe641ea031e9b72c952 | 4,627 | package org.mybatis.pagination.helpers;
/**
* <p>
* Help class by String.
* </p>
*
* @author mumu@yfyang
* @version 1.0 2013-09-09 11:26 AM
* @since JDK 1.5
*/
public final class StringHelper {
/** The empty String {@code ""}. */
public static final String EMPTY = "";
/** The dot String {@code ","}. */
public static final String DOT_CHAR = ",";
/** The blank String {@code " "}. */
public static final String BLANK_CHAR = " ";
/** The equal sign String {@code "="} */
public static final String EQUAL_SIGN_CHAR = "=";
/**
* The like String {@code "like"}
*/
public static final String LIKE_CHAR = " like ";
private static final String INJECTION_SQL = ".*([';]+|(--)+).*";
private static final String LIKE_FORMAT = "'%%s%'";
/**
* <p>Checks if a CharSequence is not empty ("") and not null.</p>
* <p/>
* <pre>
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
* StringUtils.isNotEmpty(" ") = true
* StringUtils.isNotEmpty("bob") = true
* StringUtils.isNotEmpty(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is not empty and not null
* @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence)
*/
public static boolean isNotEmpty(CharSequence cs) {
return !isEmpty(cs);
}
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
* <p/>
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
* <p/>
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the CharSequence.
* That functionality is available in isBlank().</p>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is empty or null
* @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* <p>Capitalizes a String changing the first letter to title case as
* per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
* <p/>
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#capitalize(String)}.
* A {@code null} input String returns {@code null}.</p>
* <p/>
* <pre>
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
* </pre>
*
* @param str the String to capitalize, may be null
* @return the capitalized String, {@code null} if null String input
*/
public static String capitalize(String str) {
if (str == null || (str.length()) == 0) {
return str;
}
return String.valueOf(Character.toTitleCase(str.charAt(0))) + str.substring(1);
}
/**
* <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
* <p/>
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is null, empty or whitespace
* @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
*/
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* Transact sQL injection.
*
* @param sql the sql
* @return the string
*/
public static String transactSQLInjection(String sql) {
return sql.replaceAll(INJECTION_SQL, " ");
}
/**
* Like value.
*
* @param value the value
* @return the string
*/
public static String likeValue(String value) {
return String.format(LIKE_FORMAT, transactSQLInjection(value));
}
}
| 31.910345 | 109 | 0.5697 |
ed7703d0c8c21bd4ab7f93fddd19c74e418a95e4 | 1,041 | package com.document.domain;
import java.io.Serializable;
import javax.persistence.Entity;
public class SearchCriteria implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 5474704433187825976L;
private String authorFirstName;
private String authorLastName;
private String fileName;
private String fileDescription;
public String getAuthorFirstName() {
return authorFirstName;
}
public String getAuthorLastName() {
return authorLastName;
}
public void setAuthorFirstName(String authorFirstName) {
this.authorFirstName = authorFirstName;
}
public void setAuthorLastName(String authorLastName) {
this.authorLastName = authorLastName;
}
public String getFileName() {
return fileName;
}
public String getFileDescription() {
return fileDescription;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setFileDescription(String fileDescription) {
this.fileDescription = fileDescription;
}
}
| 22.630435 | 68 | 0.742555 |
d65a92b89987e779a57eb5ec89fea8e5f9f00e7c | 8,002 | /*
* Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.datastore.server.snomed.merge.rules;
import static com.b2international.snowowl.datastore.utils.ComponentUtils2.getDetachedObjects;
import static com.b2international.snowowl.datastore.utils.ComponentUtils2.getNewObjects;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.stream.Collectors.toSet;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import com.b2international.commons.Pair;
import com.b2international.snowowl.core.domain.IComponent;
import com.b2international.snowowl.core.merge.ConflictingAttributeImpl;
import com.b2international.snowowl.core.merge.MergeConflict;
import com.b2international.snowowl.core.merge.MergeConflict.ConflictType;
import com.b2international.snowowl.core.merge.MergeConflictImpl;
import com.b2international.snowowl.core.terminology.ComponentCategory;
import com.b2international.snowowl.datastore.BranchPathUtils;
import com.b2international.snowowl.snomed.Component;
import com.b2international.snowowl.snomed.Concept;
import com.b2international.snowowl.snomed.Description;
import com.b2international.snowowl.snomed.Relationship;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember;
import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMembers;
import com.b2international.snowowl.snomed.datastore.SnomedDatastoreActivator;
import com.b2international.snowowl.snomed.datastore.id.SnomedIdentifiers;
import com.b2international.snowowl.snomed.datastore.request.SnomedRequests;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetMember;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
/**
* @since 4.7
*/
public class SnomedRefsetMemberReferencingDetachedComponentRule extends AbstractSnomedMergeConflictRule {
@Override
public Collection<MergeConflict> validate(CDOTransaction transaction) {
List<MergeConflict> conflicts = newArrayList();
// If SNOMED CT components were detached on target, but SNOMED CT reference set members are referencing them on source branch:
Map<String, String> idToComponentTypeMap = newHashMap();
for (Component component : getDetachedObjects(transaction, Component.class)) {
idToComponentTypeMap.put(component.getId(), component.eClass().getName());
}
if (!idToComponentTypeMap.isEmpty()) { // if there was any detached Component on target branch
final Set<String> detachedMemberIds = FluentIterable.from(getDetachedObjects(transaction, SnomedRefSetMember.class))
.transform(MEMBER_TO_ID_FUNCTION).toSet();
final SnomedReferenceSetMembers membersReferencingDetachedComponents = SnomedRequests
.prepareSearchMember()
.filterByReferencedComponent(idToComponentTypeMap.keySet())
.all()
.build(SnomedDatastoreActivator.REPOSITORY_UUID, BranchPathUtils.createPath(transaction).getPath())
.execute(getEventBus())
.getSync();
for (SnomedReferenceSetMember member : membersReferencingDetachedComponents) {
if (!detachedMemberIds.contains(member.getId())) {
conflicts.add(MergeConflictImpl.builder()
.componentId(member.getReferencedComponent().getId())
.componentType(idToComponentTypeMap.get(member.getReferencedComponent().getId()))
.type(ConflictType.CAUSES_MISSING_REFERENCE)
.build());
}
}
}
// If SNOMED CT components were detached on source, but SNOMED CT reference set members are referencing them on target:
Multimap<String, Pair<String, String>> referencedComponentIdToRefsetMemberMap = HashMultimap.<String, Pair<String, String>> create();
for (SnomedRefSetMember member : getNewObjects(transaction, SnomedRefSetMember.class)) {
referencedComponentIdToRefsetMemberMap.put(member.getReferencedComponentId(),
Pair.<String, String>of(member.eClass().getName(), member.getUuid()));
}
if (!referencedComponentIdToRefsetMemberMap.isEmpty()) { // if there was any new reference set member on target
Set<String> conceptIds = newHashSet(
FluentIterable.from(getNewObjects(transaction, Concept.class)).transform(COMPONENT_TO_ID_FUNCTION).toSet());
Set<String> descriptionIds = newHashSet(
FluentIterable.from(getNewObjects(transaction, Description.class)).transform(COMPONENT_TO_ID_FUNCTION).toSet());
Set<String> relationshipIds = newHashSet(
FluentIterable.from(getNewObjects(transaction, Relationship.class)).transform(COMPONENT_TO_ID_FUNCTION).toSet());
String branchPath = BranchPathUtils.createPath(transaction).getPath();
Set<String> referencedComponentIds = referencedComponentIdToRefsetMemberMap.keySet();
Set<String> referencedConceptIds = referencedComponentIds.stream()
.filter(id -> SnomedIdentifiers.getComponentCategory(id) == ComponentCategory.CONCEPT).collect(toSet());
Set<String> referencedRelationshipIds = referencedComponentIds.stream()
.filter(id -> SnomedIdentifiers.getComponentCategory(id) == ComponentCategory.RELATIONSHIP).collect(toSet());
Set<String> referencedDescriptionIds = referencedComponentIds.stream()
.filter(id -> SnomedIdentifiers.getComponentCategory(id) == ComponentCategory.DESCRIPTION).collect(toSet());
if (!referencedConceptIds.isEmpty()) {
conceptIds.addAll(FluentIterable
.from(SnomedRequests.prepareSearchConcept()
.filterByIds(referencedConceptIds)
.setLimit(referencedConceptIds.size())
.build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath)
.execute(getEventBus())
.getSync())
.transform(IComponent.ID_FUNCTION).toSet());
}
if (!referencedDescriptionIds.isEmpty()) {
descriptionIds.addAll(FluentIterable
.from(SnomedRequests.prepareSearchDescription()
.filterByIds(referencedDescriptionIds)
.setLimit(referencedDescriptionIds.size())
.build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath)
.execute(getEventBus())
.getSync()).transform(IComponent.ID_FUNCTION).toSet());
}
if (!referencedRelationshipIds.isEmpty()) {
relationshipIds.addAll(FluentIterable
.from(SnomedRequests.prepareSearchRelationship()
.filterByIds(referencedRelationshipIds)
.setLimit(referencedRelationshipIds.size())
.build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath)
.execute(getEventBus())
.getSync()).transform(IComponent.ID_FUNCTION).toSet());
}
Set<String> missingConceptIds = Sets.difference(referencedComponentIds, Sets.union(Sets.union(conceptIds, descriptionIds), relationshipIds));
for (String id : missingConceptIds) {
for (Pair<String, String> entry : referencedComponentIdToRefsetMemberMap.get(id)) {
conflicts.add(MergeConflictImpl
.builder()
.componentId(entry.getB())
.componentType(entry.getA())
.conflictingAttribute(ConflictingAttributeImpl.builder().property("referencedComponent").value(id).build())
.type(ConflictType.HAS_MISSING_REFERENCE).build());
}
}
}
return conflicts;
}
}
| 45.465909 | 144 | 0.776056 |
614b059dab34cdd2c2851340bd7bbcbc78a5a1e9 | 1,151 | package leetcode.editor.cn;
//给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
//
// 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
//
//
//
// 示例:
//
// 给定 nums = [2, 7, 11, 15], target = 9
//
//因为 nums[0] + nums[1] = 2 + 7 = 9
//所以返回 [0, 1]
//
// Related Topics 数组 哈希表
// 👍 9824 👎 0
import java.util.HashMap;
import java.util.Map;
public class P1TwoSum {
public static void main(String[] args) {
Solution solution = new P1TwoSum().new Solution();
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums.length == 0) {
return new int[0];
}
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (hash.containsKey(target - nums[i])) {
return new int[]{hash.get(target - nums[i]), i};
}
hash.put(nums[i], i);
}
return new int[0];
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | 25.577778 | 70 | 0.5404 |
b7ebbcecc1f192db2ebbb83b6f9d1dc2d485a09b | 11,690 | package dentaira.cobaco.server.file.infra;
import com.github.database.rider.core.api.dataset.DataSet;
import com.github.database.rider.core.api.dataset.ExpectedDataSet;
import dentaira.cobaco.server.file.DataSize;
import dentaira.cobaco.server.file.FileType;
import dentaira.cobaco.server.file.Owner;
import dentaira.cobaco.server.file.StoredFile;
import dentaira.cobaco.server.test.annotation.DatabaseRiderTest;
import dentaira.cobaco.server.test.builder.TestStoredFileBuilder;
import org.assertj.core.api.SoftAssertions;
import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mybatis.spring.boot.test.autoconfigure.AutoConfigureMybatis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
@JdbcTest
@AutoConfigureMybatis
@DatabaseRiderTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class JdbcFileRepositoryTest {
@Autowired
DataSource dataSource;
JdbcFileRepository sut;
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
FileMapper fileMapper;
@BeforeEach
void setUp() {
sut = new JdbcFileRepository(jdbcTemplate, fileMapper);
}
@Nested
@DisplayName("searchRoot(UserAccount)はUserAccountが所有するRoot直下のFileを取得する")
class SearchRootTest {
@Test
@DataSet("dentaira/cobaco/server/file/infra/JdbcFileRepositoryTest-data/SearchRootTest/setup-testFindOne.yml")
@DisplayName("Root配下のFileが1つの場合は1つ取得する")
void testFindOne() {
var owner = new Owner(UUID.fromString("B0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11"));
List<StoredFile> actual = sut.searchRoot(owner);
assertEquals(1, actual.size());
}
@Test
@DataSet("dentaira/cobaco/server/file/infra/JdbcFileRepositoryTest-data/SearchRootTest/setup-testFindThree.yml")
@DisplayName("Root配下のFileが3つの場合は3つ取得する")
void testFindThree() {
var owner = new Owner(UUID.fromString("B0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A13"));
List<StoredFile> actual = sut.searchRoot(owner);
assertEquals(3, actual.size());
}
}
@Nested
@DataSet("dentaira/cobaco/server/file/infra/JdbcFileRepositoryTest-data/SearchTest/setup-search.yml")
@DisplayName("search(String,UserAccount)はUserAccountが所有する指定したFolder直下にあるFileを取得する")
class SearchTest {
@Test
@DisplayName("指定したFolder配下のFileが1つの場合は1つ取得する")
void testFindOne() {
var owner = new Owner(UUID.fromString("B0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A13"));
List<StoredFile> actual = sut.search("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380B13", owner);
assertEquals(1, actual.size());
}
@Test
@DisplayName("指定したFolder配下のFileが3つの場合は3つ取得する")
void testFindThree() {
var owner = new Owner(UUID.fromString("B0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A14"));
List<StoredFile> actual = sut.search("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11", owner);
assertEquals(3, actual.size());
}
@Test
@DisplayName("指定したFolder配下にFileが存在しない場合は空のListを返す")
void testFindZero() {
var owner = new Owner(UUID.fromString("B0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A13"));
List<StoredFile> actual = sut.search("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380B12", owner);
assertEquals(0, actual.size());
}
@Test
@DisplayName("指定したFileのtypeがFileだった場合は例外が発生する")
void testSearchFile() {
var owner = new Owner(UUID.fromString("B0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A13"));
List<StoredFile> actual = sut.search("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A12", owner);
assertEquals(0, actual.size());
}
}
@Nested
@DataSet("dentaira/cobaco/server/file/infra/JdbcFileRepositoryTest-data/FindByIdTest/setup-findById.yml")
@ExtendWith(SoftAssertionsExtension.class)
@DisplayName("findById(String,Owner)はOwnerが所有するidが一致するFileを取得する")
class FindByIdTest {
@Test
void testFindOneDirectory(SoftAssertions softly) {
// given
var owner = new Owner(UUID.fromString("B0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A13"));
UUID fileId = UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11");
// when
StoredFile actual = sut.findById(fileId.toString(), owner);
// then
softly.assertThat(actual.getId()).isEqualTo(fileId);
softly.assertThat(actual.getName()).isEqualTo("フォルダ1");
softly.assertThat(actual.getPath()).isEqualTo(Path.of("/A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11/"));
softly.assertThat(actual.getType()).isEqualTo(FileType.DIRECTORY);
softly.assertThat(actual.getSize()).isEqualTo(DataSize.of(0L));
softly.assertThat(actual.getContent()).isNull();
}
@Test
void testFindOneFile(SoftAssertions softly) throws Exception {
// given
var owner = new Owner(UUID.fromString("B0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A14"));
UUID fileId = UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380B11");
// when
StoredFile actual = sut.findById(fileId.toString(), owner);
// then
softly.assertThat(actual.getId()).isEqualTo(fileId);
softly.assertThat(actual.getName()).isEqualTo("ファイル4");
softly.assertThat(actual.getPath()).isEqualTo(Path.of("/A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11/A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380B11/"));
softly.assertThat(actual.getType()).isEqualTo(FileType.FILE);
softly.assertThat(actual.getSize()).isEqualTo(DataSize.of(3L));
try (var in = actual.getContent()) {
softly.assertThat(in).hasContent("file4 content");
}
}
@Test
void testUserNotMatched() {
// given
var owner = new Owner(UUID.fromString("B0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A13"));
UUID fileId = UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380B11");
// when
StoredFile actual = sut.findById(fileId.toString(), owner);
// then
assertThat(actual).isNull();
}
@Test
void testFileNotFound() {
// given
var owner = new Owner(UUID.fromString("B0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A13"));
UUID fileId = UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380B99");
// when
StoredFile actual = sut.findById(fileId.toString(), owner);
// then
assertThat(actual).isNull();
}
}
@Nested
@DataSet("dentaira/cobaco/server/file/infra/JdbcFileRepositoryTest-data/SearchForAncestorsTest/setup-searchForAncestors.yml")
@DisplayName("searchForAncestorsは祖先フォルダ全てのListを返す")
class SearchForAncestorsTest {
@Test
void testFindTwo() {
// given
Path path = Path.of("/A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11/A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380B12/A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380B13/");
StoredFile file = new TestStoredFileBuilder().withPath(path).build();
// when
List<StoredFile> actual = sut.searchForAncestors(file);
// then
assertEquals(2, actual.size());
assertEquals(UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11"), actual.get(0).getId());
assertEquals(UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380B12"), actual.get(1).getId());
}
@Test
void whenFileUnderRootThenReturnEmptyList() {
// given
Path path = Path.of("/A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11/");
StoredFile file = new TestStoredFileBuilder().withPath(path).build();
// when
List<StoredFile> actual = sut.searchForAncestors(file);
// then
assertEquals(0, actual.size());
}
}
@Nested
@DataSet("dentaira/cobaco/server/file/infra/JdbcFileRepositoryTest-data/SaveTest/setup-save.yml")
@DisplayName("saveはStoredFileを登録する")
class SaveTest {
@Test
@ExpectedDataSet("dentaira/cobaco/server/file/infra/JdbcFileRepositoryTest-data/SaveTest/expected-testSaveBible.yml")
void testSaveBible() {
// given
StoredFile file = new TestStoredFileBuilder()
.withId(UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11"))
.withName("Bible")
.withPath(Path.of("/parent/" + UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11").toString() + "/"))
.withType(FileType.FILE)
.withSize(DataSize.of(3L))
.withContent(new ByteArrayInputStream("content".getBytes(StandardCharsets.UTF_8)))
.build();
// when
sut.save(file);
}
@Test
@ExpectedDataSet("dentaira/cobaco/server/file/infra/JdbcFileRepositoryTest-data/SaveTest/expected-testSavePandora.yml")
void testSavePandora() {
// given
StoredFile file = new TestStoredFileBuilder()
.withId(UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A12"))
.withName("Pandora")
.withPath(Path.of("/parent/" + UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A12").toString() + "/"))
.withType(FileType.DIRECTORY)
.withSize(DataSize.of(0L))
.build();
// when
sut.save(file);
}
}
@Nested
@DataSet("dentaira/cobaco/server/file/infra/JdbcFileRepositoryTest-data/DeleteTest/setup-delete.yml")
@DisplayName("deleteはStoredFileを削除する")
class DeleteTest {
@Test
@ExpectedDataSet("dentaira/cobaco/server/file/infra/JdbcFileRepositoryTest-data/DeleteTest/expected-testDeleteFile.yml")
@DisplayName("削除するFileのtypeがFileの場合は指定したFileのみ削除する")
void testDeleteFile() {
// given
StoredFile file = new TestStoredFileBuilder()
.withId(UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A12"))
.withType(FileType.FILE)
.build();
// when
sut.delete(file);
}
@Test
@ExpectedDataSet("dentaira/cobaco/server/file/infra/JdbcFileRepositoryTest-data/DeleteTest/expected-testDeleteFolder.yml")
@DisplayName("削除するFileのtypeがFolderの場合は指定したFileと配下のFile全てを削除する")
void testDeleteFolder() {
// given
StoredFile file = new TestStoredFileBuilder()
.withId(UUID.fromString("A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11"))
.withPath(Path.of("/A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11/"))
.withType(FileType.DIRECTORY)
.build();
// when
sut.delete(file);
}
}
} | 41.899642 | 148 | 0.648674 |
11f180bae5d1561f8928a0abaff910132893af5d | 4,830 | /*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.basicfunctions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.template.soy.data.SoyValue;
import com.google.template.soy.data.restricted.FloatData;
import com.google.template.soy.data.restricted.IntegerData;
import com.google.template.soy.exprtree.Operator;
import com.google.template.soy.jssrc.restricted.JsExpr;
import com.google.template.soy.jssrc.restricted.SoyJsCodeUtils;
import com.google.template.soy.jssrc.restricted.SoyJsSrcFunction;
import com.google.template.soy.shared.restricted.SoyJavaFunction;
import com.google.template.soy.shared.restricted.SoyPureFunction;
import java.util.List;
import java.util.Set;
/**
* Soy function that rounds a number to a specified number of digits before or after the decimal
* point.
*
* @author Kai Huang
*/
@Singleton
@SoyPureFunction
class RoundFunction implements SoyJavaFunction, SoyJsSrcFunction {
@Inject
RoundFunction() {}
@Override public String getName() {
return "round";
}
@Override public Set<Integer> getValidArgsSizes() {
return ImmutableSet.of(1, 2);
}
@Override public SoyValue computeForJava(List<SoyValue> args) {
SoyValue value = args.get(0);
int numDigitsAfterPt = (args.size() == 2) ? args.get(1).integerValue() : 0 /* default */;
if (numDigitsAfterPt == 0) {
if (value instanceof IntegerData) {
return IntegerData.forValue(value.longValue());
} else {
return IntegerData.forValue((int) Math.round(value.numberValue()));
}
} else if (numDigitsAfterPt > 0) {
double valueDouble = value.numberValue();
double shift = Math.pow(10, numDigitsAfterPt);
return FloatData.forValue(Math.round(valueDouble * shift) / shift);
} else {
double valueDouble = value.numberValue();
double shift = Math.pow(10, -numDigitsAfterPt);
return IntegerData.forValue((int) (Math.round(valueDouble / shift) * shift));
}
}
@Override public JsExpr computeForJsSrc(List<JsExpr> args) {
JsExpr value = args.get(0);
JsExpr numDigitsAfterPt = (args.size() == 2) ? args.get(1) : null;
int numDigitsAfterPtAsInt = 0;
if (numDigitsAfterPt != null) {
try {
numDigitsAfterPtAsInt = Integer.parseInt(numDigitsAfterPt.getText());
} catch (NumberFormatException nfe) {
numDigitsAfterPtAsInt = Integer.MIN_VALUE; // indicates it's not a simple integer literal
}
}
if (numDigitsAfterPtAsInt == 0) {
// Case 1: round() has only one argument or the second argument is 0.
return new JsExpr("Math.round(" + value.getText() + ")", Integer.MAX_VALUE);
} else if ((numDigitsAfterPtAsInt >= 0 && numDigitsAfterPtAsInt <= 12) ||
numDigitsAfterPtAsInt == Integer.MIN_VALUE) {
String shiftExprText;
if (numDigitsAfterPtAsInt >= 0 && numDigitsAfterPtAsInt <= 12) {
shiftExprText = "1" + "000000000000".substring(0, numDigitsAfterPtAsInt);
} else {
shiftExprText = "Math.pow(10, " + numDigitsAfterPt.getText() + ")";
}
JsExpr shift = new JsExpr(shiftExprText, Integer.MAX_VALUE);
JsExpr valueTimesShift = SoyJsCodeUtils.genJsExprUsingSoySyntax(
Operator.TIMES, Lists.newArrayList(value, shift));
return new JsExpr(
"Math.round(" + valueTimesShift.getText() + ") / " + shift.getText(),
Operator.DIVIDE_BY.getPrecedence());
} else if (numDigitsAfterPtAsInt < 0 && numDigitsAfterPtAsInt >= -12) {
String shiftExprText = "1" + "000000000000".substring(0, -numDigitsAfterPtAsInt);
JsExpr shift = new JsExpr(shiftExprText, Integer.MAX_VALUE);
JsExpr valueDivideByShift = SoyJsCodeUtils.genJsExprUsingSoySyntax(
Operator.DIVIDE_BY, Lists.newArrayList(value, shift));
return new JsExpr(
"Math.round(" + valueDivideByShift.getText() + ") * " + shift.getText(),
Operator.TIMES.getPrecedence());
} else {
throw new IllegalArgumentException(
"Second argument to round() function is " + numDigitsAfterPtAsInt +
", which is too large in magnitude.");
}
}
}
| 36.315789 | 98 | 0.694824 |
486fc925d8327830aa38ded5c499ff8ee835bf57 | 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.jackrabbit.rmi.server;
import java.rmi.RemoteException;
import javax.jcr.nodetype.ItemDefinition;
import javax.jcr.nodetype.NodeType;
import org.apache.jackrabbit.rmi.remote.RemoteItemDefinition;
import org.apache.jackrabbit.rmi.remote.RemoteNodeType;
/**
* Remote adapter for the JCR {@link javax.jcr.nodetype.ItemDefinition ItemDefinition}
* interface. This class makes a local item definition available as an
* RMI service using the
* {@link org.apache.jackrabbit.rmi.remote.RemoteItemDefinition RemoteItemDefinition}
* interface. Used mainly as the base class for the
* {@link org.apache.jackrabbit.rmi.server.ServerPropertyDefinition ServerPropertyDefinition}
* and
* {@link org.apache.jackrabbit.rmi.server.ServerNodeDefinition ServerNodeDefinition}
* adapters.
*
* @see javax.jcr.nodetype.ItemDefinition
* @see org.apache.jackrabbit.rmi.remote.RemoteItemDefinition
*/
public class ServerItemDefinition extends ServerObject implements RemoteItemDefinition {
/** The adapted local item definition. */
private ItemDefinition def;
/**
* Creates a remote adapter for the given local item definition.
*
* @param def local item definition
* @param factory remote adapter factory
* @throws RemoteException on RMI errors
*/
public ServerItemDefinition(ItemDefinition def, RemoteAdapterFactory factory)
throws RemoteException {
super(factory);
this.def = def;
}
/** {@inheritDoc} */
public RemoteNodeType getDeclaringNodeType() throws RemoteException {
NodeType nt = def.getDeclaringNodeType();
if (nt == null) {
return null;
} else {
return getFactory().getRemoteNodeType(nt);
}
}
/** {@inheritDoc} */
public String getName() throws RemoteException {
return def.getName();
}
/** {@inheritDoc} */
public boolean isAutoCreated() throws RemoteException {
return def.isAutoCreated();
}
/** {@inheritDoc} */
public boolean isMandatory() throws RemoteException {
return def.isMandatory();
}
/** {@inheritDoc} */
public int getOnParentVersion() throws RemoteException {
return def.getOnParentVersion();
}
/** {@inheritDoc} */
public boolean isProtected() throws RemoteException {
return def.isProtected();
}
}
| 33.631579 | 93 | 0.710172 |
586920d834a2dbc9d6a20bb20facf8a7cb72a701 | 1,039 | package storage;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import simulator.system.ships.StorageShip;
/**
Stores all ship data loaded from DB. Provides static access to all stored data
*/
public class ShipStorage {
private static Map<Integer, StorageShip> sStorageShips = new HashMap<>();
public static void addStorageShip(final StorageShip pStorageShip) {
sStorageShips.put(pStorageShip.getShipId(), pStorageShip);
}
public static String getShipLootID(final int pShipID) {
return getStorageShip(pShipID).getShipLootId();
}
public static StorageShip getStorageShip(final int pUserID) {
return sStorageShips.get(pUserID);
}
public static void removeStorageShip(final int pUserID) {
sStorageShips.remove(pUserID);
}
public static Collection<StorageShip> getStorageShipCollection() {
return sStorageShips.values();
}
public static int getStorageShipCount() {
return sStorageShips.size();
}
}
| 24.738095 | 79 | 0.715111 |
54b58bd06e691a153ec7ab7c07277015904b83a2 | 113 | package com.asodc.camel.contentenricher;
public class ContentEnricherPollEnrich {
// TODO: implementation
}
| 18.833333 | 40 | 0.787611 |
4985cfda01de4e6f27926c3b43130a97e52857b7 | 20,213 | package com.yilian.luckypurchase.activity;
import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.logger.Logger;
import com.yilian.luckypurchase.R;
import com.yilian.luckypurchase.adapter.ShowOffListAddPhotoAdapter;
import com.yilian.luckypurchase.widget.PopupMenu;
import com.yilian.mylibrary.BitmapUtil;
import com.yilian.mylibrary.CheckServiceReturnEntityUtil;
import com.yilian.mylibrary.CommonUtils;
import com.yilian.mylibrary.Constants;
import com.yilian.mylibrary.FileUtils;
import com.yilian.mylibrary.ImageCompressUtil;
import com.yilian.mylibrary.RequestOftenKey;
import com.yilian.mylibrary.ScreenUtils;
import com.yilian.networkingmodule.entity.UploadImageEnity;
import com.yilian.networkingmodule.httpresult.HttpResultBean;
import com.yilian.networkingmodule.retrofitutil.RetrofitUtils;
import com.yilian.networkingmodule.retrofitutil.RetrofitUtils2;
import java.io.File;
import java.util.ArrayList;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* @author LYQ 晒单界面
*/
public class LuckyShowOffListActivity extends BaseAppCompatActivity implements View.OnClickListener {
public static final int APPLY_CAMERA_PERMISSION_REQUEST_CODE = 999;//请求相机权限使用请求码
public static final int APPLY_READ_SDCARD_PERMISSION_REQUEST_CODE = 100;//请求读取SD卡的权限使用请求码
public static final int APPLY_WRITE_SDCARD_PERMISSION_REQUEST_CODE = 888;//请求读取SD卡的权限使用请求码
private static final int GO_CAMERA = 99;//打开相机请求码
private static final int GO_ALBUM = 97;//打开相册请求码
private ImageView v3Left;
private TextView v3Title;
private TextView tvRight;
private ImageView ivMore;
private ImageView v3Share;
private TextView tvRight2;
private ImageView v3Back;
private FrameLayout v3Layout;
private LinearLayout llTitle;
private EditText etRemark;
private RecyclerView recycleView;
private ArrayList<String> imageList = new ArrayList<>();
private ShowOffListAddPhotoAdapter adapter;
private PopupWindow popupWindow;
private String imageName;
private ArrayList<String> imageContentList = new ArrayList<>();
private int totalCount;
private TextView tvCommit;
private String activityId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lucky_activity_show_off_list);
activityId = getIntent().getStringExtra("activityId");
imageList.add("add");//添加一个标记(区别是添加的按钮还是上传过的图片内容)
initView();
initListener();
}
private void initListener() {
adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
int i = view.getId();
if (i == R.id.iv_add) {
//添加照片
showPopupWindow(view);
} else if (i == R.id.iv_del) {
//移除当前条目的内容,但是要判断是否是第一张
deleteItem(adapter, position);
}
}
});
}
private void deleteItem(BaseQuickAdapter adapter, int position) {
adapter.remove(position);
imageContentList.remove(position);
//判断最后一个
if (imageList.size() < 6 && !imageList.get(imageList.size() - 1).equals("add")) {
imageList.add("add");
}
}
/**
* 选择相册或者相机的弹窗
*
* @param view
*/
private void showPopupWindow(View view) {
getPopupWindow(view);
popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
backgroundAlpha(0.2f);
}
private void getPopupWindow(View view) {
if (null != popupWindow) {
popupWindow.dismiss();
} else {
initPopupWindow(R.layout.library_module_popupwindow_amenduserphoto, -1,
LinearLayout.LayoutParams.WRAP_CONTENT, R.style.library_module_AnimationFade);
}
}
public void initPopupWindow(int layout, int width, int height, int anim) {
View view = View.inflate(mContext, layout, null);
popupWindow = new PopupWindow(view, width, height, true);
popupWindow.setAnimationStyle(anim);
backgroundAlpha(0.2f);
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
}
private void backgroundAlpha(float alpha) {
//获取窗体的属性集重新设置
WindowManager.LayoutParams attributes = getWindow().getAttributes();
attributes.alpha = alpha;
getWindow().setAttributes(attributes);
ColorDrawable drawable = new ColorDrawable(0x000000);
popupWindow.setBackgroundDrawable(drawable);
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
backgroundAlpha(1f);//popupWindow消失时不透明
}
});
}
private void initView() {
v3Left = (ImageView) findViewById(R.id.v3Left);
v3Title = (TextView) findViewById(R.id.v3Title);
v3Title.setText("晒单");
tvRight = (TextView) findViewById(R.id.tv_right);
ivMore = (ImageView) findViewById(R.id.v3Shop);
ivMore.setImageResource(R.mipmap.library_module_v3_more_bottom);
ivMore.setVisibility(View.VISIBLE);
v3Share = (ImageView) findViewById(R.id.v3Share);
tvRight2 = (TextView) findViewById(R.id.tv_right2);
v3Back = (ImageView) findViewById(R.id.v3Back);
v3Layout = (FrameLayout) findViewById(R.id.v3Layout);
llTitle = (LinearLayout) findViewById(R.id.ll_title);
etRemark = (EditText) findViewById(R.id.et_remark);
recycleView = (RecyclerView) findViewById(R.id.recycleView);
recycleView.setLayoutManager(new GridLayoutManager(mContext, 3));
adapter = new ShowOffListAddPhotoAdapter(R.layout.lucky_item_add_photo, imageList);
tvCommit = (TextView) findViewById(R.id.tv_commit);
recycleView.setAdapter(adapter);
totalCount = 6;
tvRight2.setOnClickListener(this);
v3Back.setOnClickListener(this);
tvCommit.setOnClickListener(this);
ivMore.setOnClickListener(this);
}
/**
* 相册选择
*
* @param view
*/
public void photoalbum(View view) {
//相册的读取权限
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
APPLY_READ_SDCARD_PERMISSION_REQUEST_CODE);
showToast("请开启读写SD卡的权限");
return;
}
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, APPLY_WRITE_SDCARD_PERMISSION_REQUEST_CODE);
}
albumSelect();
}
/**
* 相册选择
*/
private void albumSelect() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GO_ALBUM);
if (null != popupWindow && popupWindow.isShowing()) {
popupWindow.dismiss();
backgroundAlpha(1f);
}
}
/**
* 拍照
*
* @param view
*/
public void camera(View view) {
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
//申请权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, APPLY_CAMERA_PERMISSION_REQUEST_CODE);
return;
}
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, APPLY_WRITE_SDCARD_PERMISSION_REQUEST_CODE);
return;
}
// 有权限了
openCamera();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case APPLY_CAMERA_PERMISSION_REQUEST_CODE:
//相机权限
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
showToast("拍照权限被拒绝,请前往设置开启");
}
}
break;
case APPLY_READ_SDCARD_PERMISSION_REQUEST_CODE:
//读SD卡的权限
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
albumSelect();
} else {
showToast("读取SD卡的权限暂未开启,请前往设置开启");
}
}
break;
case APPLY_WRITE_SDCARD_PERMISSION_REQUEST_CODE:
//写SD卡的权限
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
showToast("拍照权限被拒绝,请前往设置开启");
}
}
break;
default:
break;
}
}
/**
* 开启照相机
*/
private void openCamera() {
imageName = System.currentTimeMillis() + ".png";
File file = new File(Environment.getExternalStorageDirectory(), imageName);
FileUtils.startActionCapture(this, file, GO_CAMERA);
if (popupWindow != null && popupWindow.isShowing()) {
popupWindow.dismiss();
backgroundAlpha(1f);
}
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.v3Back) {
finish();
} else if (i == R.id.tv_commit) {
commit();
} else if (i == R.id.v3Shop) {
showMenu();
}
}
/**
* 右上角更多
*/
private void showMenu() {
final PopupMenu popupMenu = new PopupMenu(this, false);
popupMenu.showLocation(R.id.v3Shop);
popupMenu.setOnItemClickListener(new PopupMenu.OnItemClickListener() {
@Override
public void onClick(PopupMenu.MENUITEM item, String str) {
Intent intent = new Intent();
switch (item) {
case ITEM1:
if (isLogin()) {
intent.setComponent(new ComponentName(LuckyShowOffListActivity.this, "com.yilian.mall.ui.InformationActivity"));
} else {
intent.setComponent(new ComponentName(LuckyShowOffListActivity.this, "com.yilian.loginmodule.LeFenPhoneLoginActivity"));
}
break;
case ITEM2:
intent.setComponent(new ComponentName(LuckyShowOffListActivity.this, "com.yilian.mall.ui.JPMainActivity"));
intent.putExtra(Constants.INTENT_KEY_JUMP_TO_JP_MAIN_ACTIVITY, Constants.INTENT_VALUE_JUMP_TO_MT__HOME_FRAGMENT);
break;
case ITEM3:
break;
case ITEM4:
intent.setComponent(new ComponentName(LuckyShowOffListActivity.this, "com.yilian.mall.ui.JPMainActivity"));
intent.putExtra(Constants.INTENT_KEY_JUMP_TO_JP_MAIN_ACTIVITY, Constants.INTENT_VALUE_JUMP_TO_PERSON_CENTER_FRAGMENT);
break;
default:
break;
}
startActivity(intent);
}
});
}
private void commit() {
String content = etRemark.getText().toString().trim();
String imagUrls = "";
for (int i = 0; i < imageContentList.size(); i++) {
if (i == imageContentList.size() - 1) {
imagUrls += imageContentList.get(i);
} else {
imagUrls += imageContentList.get(i) + ",";
}
}
if (TextUtils.isEmpty(content)) {
showToast(R.string.lucky_show_no_tv);
return;
}
if (content.length() > 200) {
showToast(R.string.lucky_show_much_tv);
return;
}
if (TextUtils.isEmpty(imagUrls)) {
showToast(R.string.lucky_show_no_img);
return;
}
Logger.i("图片集合toString " + imageContentList.toString());
startMyDialog(false);
RetrofitUtils2.getInstance(mContext).setDeviceIndex(RequestOftenKey.getDeviceIndex(mContext)).setToken(RequestOftenKey.getToken(mContext))
.snatchShowCommit(activityId, content, imagUrls, new Callback<HttpResultBean>() {
@Override
public void onResponse(Call<HttpResultBean> call, Response<HttpResultBean> response) {
stopMyDialog();
if (CheckServiceReturnEntityUtil.checkServiceReturnEntity(mContext, response.body())) {
if (CommonUtils.serivceReturnCode(mContext, response.body().code, response.body().msg)) {
switch (response.body().code) {
case 1:
showToast(response.body().msg);
finish();
break;
default:
break;
}
}
}
}
@Override
public void onFailure(Call<HttpResultBean> call, Throwable t) {
stopMyDialog();
showToast(R.string.aliwx_net_null_setting);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GO_CAMERA:
//相机
Logger.i("相机回调 " + resultCode);
if (resultCode == RESULT_CANCELED) {
return;
}
Logger.i("data:: " + data);
String pathname = Environment.getExternalStorageDirectory() + File.separator + imageName;
File file2 = new File(pathname);
file2 = ImageCompressUtil.compressImage(file2, ScreenUtils.getScreenWidth(mContext)/2, ScreenUtils.getScreenHeight(mContext)/2, 50, mContext);
Logger.i("pathname:"+pathname);
file2= BitmapUtil.restoreFile(pathname, file2, "luckyComment");//处理图片旋转问题
sendImage(file2);
break;
case GO_ALBUM:
//相册
Logger.i("resultCode " + resultCode);
if (resultCode == RESULT_CANCELED) {
return;
}
Logger.i("data " + data);
if (null == data) {
return;
}
Logger.i("data.getData().getScheme() " + data.getData().getScheme() + " URI " + data.getData());
//解决低版本手机返回的URI模式为file
String fileStr;
if ("file".equals(data.getData().getScheme())) {
fileStr = data.getData().getPath();
} else {
Uri uri = data.getData();
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePathColumns, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumns[0]);
fileStr = cursor.getString(columnIndex);
cursor.close();
}
if (null != fileStr || !fileStr.equals("")) {
Logger.i("fileStr: "+ fileStr);
File file = ImageCompressUtil.compressImage(new File(fileStr), ScreenUtils.getScreenWidth(mContext)/2,
ScreenUtils.getScreenHeight(mContext)/2, 50, mContext);
file= BitmapUtil.restoreFile(fileStr, file, "luckyComment");//处理图片旋转问题
sendImage(file);
}
break;
default:
Logger.i("请求码 :: " + requestCode);
break;
}
}
/**
* 上传图片
*
* @param file
*/
private void sendImage(File file) {
startMyDialog(false);
final RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("file", System.currentTimeMillis() + "environment", requestBody);
RetrofitUtils.getInstance(mContext).setDeviceIndex(RequestOftenKey.getDeviceIndex(mContext)).setToken(RequestOftenKey.getToken(mContext))
.uploadFile(part, new Callback<UploadImageEnity>() {
@Override
public void onResponse(Call<UploadImageEnity> call, Response<UploadImageEnity> response) {
if (CheckServiceReturnEntityUtil.checkServiceReturnEntity(mContext, response.body())) {
if (CommonUtils.serivceReturnCode(mContext, response.body().code, response.body().msg)) {
switch (response.body().code) {
case 1:
initImageUrls(response);
break;
default:
showToast(response.body().msg);
break;
}
}
}
stopMyDialog();
}
@Override
public void onFailure(Call<UploadImageEnity> call, Throwable t) {
showToast("上传图片失败");
stopMyDialog();
}
});
}
private void initImageUrls(Response<UploadImageEnity> response) {
String filename = response.body().filename;
imageContentList.add(filename);
imageList.clear();
imageList.addAll(imageContentList);
if (imageList.size() < totalCount) {
imageList.add("add");
}
adapter.setNewData(imageList);
}
}
| 39.478516 | 158 | 0.584525 |
74eae3007b83c44638adc7786fa27f273606efc8 | 5,429 | package com.example.zhansha.testandroid;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.View;
import java.lang.reflect.Array;
import java.util.Arrays;
import static android.os.SystemClock.sleep;
public class MainHello extends AppCompatActivity {
private boolean start = false;
private int gf_number = 0;
private AudioRecord ar;
private int bs = 100;
private static int SAMPLE_RATE_IN_HZ = 8000;
private int number = 1;
private int tal = 1;
//到达该值之后 触发事件
private static int BLOW_ACTIVI=10000;
private static int MAX_NUMBER=2000;
private Button btn;
private TextView txtV;
boolean isblow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_hello);
btn = (Button) findViewById(R.id.confirm);
txtV = (TextView) findViewById(R.id.mainText);
bs = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
ar = findAudioRecord();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btn.setClickable(false);
btn.setActivated(false);
txtV.setText("aaa");
Moniting();
btn.setClickable(true);
btn.setActivated(true);
}
});
}
private static int[] mSampleRates = new int[] { 8000, 11025, 22050, 44100 };
public AudioRecord findAudioRecord() {
for (int rate : mSampleRates) {
for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT }) {
for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO }) {
try {
Log.e("xxxxxxxxxx", "Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: "
+ channelConfig);
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize != AudioRecord.ERROR_BAD_VALUE) {
// check if we can instantiate and have a success
AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, rate, channelConfig, audioFormat, bufferSize);
Log.e("xxxxxxxxxx", "Got available channel: "+ channelConfig);
if (recorder.getState() == AudioRecord.STATE_INITIALIZED)
txtV.setText("find recorder"+channelConfig);
return recorder;
}
} catch (Exception e) {
Log.e("xxxxxxxxxx", rate + "Exception, keep trying.",e);
}
}
}
}
return null;
}
public void Moniting() {
try {
if (ar==null)
{
txtV.setText("ar is null");
gf_number = gf_number % 4 +1;
Show();
return;
}
ar.startRecording();
isblow = true;
txtV.setText("startRecording");
// 用于读取的 buffer
txtV.invalidate();
byte[] buffer = new byte[bs];
boolean blowStart = false;
while (isblow) {
number++;
sleep(8);
int r = ar.read(buffer, 0, bs) + 1;
int v = 0;
for (int i = 0; i < buffer.length; i++) {
v += (buffer[i] * buffer[i]);
}
int value = v / (int) r;
if (!blowStart && value < BLOW_ACTIVI)
blowStart = true;
if (blowStart && (value > BLOW_ACTIVI))
isblow = false;
txtV.setText("belowing: "+number+"ms");
txtV.invalidate();
if (number >= MAX_NUMBER) {
isblow=false;
}
}
txtV.setText("endRecording: "+number);
ar.stop();
bs=100;
if (number>=600)
gf_number = 4;
else
gf_number = (number/200) % 4 +1;
//Show();
number = 1;
} catch (Exception e) {
e.printStackTrace();
txtV.setText(e.getLocalizedMessage());
}
}
private void Show() {
ImageView iv = (ImageView) findViewById(R.id.gfV);
switch (gf_number) {
case 1:
iv.setImageResource(R.drawable.f1);
break;
case 2:
iv.setImageResource(R.drawable.f2);
break;
case 3:
iv.setImageResource(R.drawable.f3);
break;
case 4:
iv.setImageResource(R.drawable.f4);
break;
}
}
}
| 33.512346 | 148 | 0.516117 |
6f697b0051551bc4eb68434b2a5d9e038d3caf0a | 699 | package com.iyzipay.google.cloud.vision.model;
public class Color {
private Double red;
private Double green;
private Double blue;
private Double alpha;
public Double getRed() {
return red;
}
public void setRed(Double red) {
this.red = red;
}
public Double getGreen() {
return green;
}
public void setGreen(Double green) {
this.green = green;
}
public Double getBlue() {
return blue;
}
public void setBlue(Double blue) {
this.blue = blue;
}
public Double getAlpha() {
return alpha;
}
public void setAlpha(Double alpha) {
this.alpha = alpha;
}
}
| 16.642857 | 46 | 0.575107 |
e367db20b1bb1cd7ecc2a887548a5bcb55964d6f | 1,003 | package custom.gateway.configuration;
import custom.gateway.configuration.swagger.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
/**
* @author zack <br>
* @create 2021-06-27<br>
* @project project-cloud-custom <br>
*/
@Configuration
public class SwaggerConfiguration {
@Bean
public SwaggerResourcesProvider swaggerResourcesProvider() {
return new SwaggerProvider();
}
@Bean
public SwaggerResourceHandler swaggerResourceHandler() {
return new SwaggerResourceHandler();
}
@Bean
public SwaggerSecurityHandler swaggerSecurityHandler() {
return new SwaggerSecurityHandler();
}
@Bean
public SwaggerUiHandler swaggerUiHandler() {
return new SwaggerUiHandler();
}
@Bean
public WebFluxConfiguration webFluxConfiguration() {
return new WebFluxConfiguration();
}
}
| 24.463415 | 68 | 0.727817 |
778840ed0e05c46ebb2c812979683ba8d112edc3 | 562 | package examples.pubhub.model;
public class BookTag {
String isbn13;
String tagName;
public BookTag(String isbn, String tag) {
this.isbn13 = isbn;
this.tagName = tag;
}
// Default constructor
public BookTag() {
this.isbn13 = null;
this.tagName = null;
}
public String getIsbn13() {
return isbn13;
}
public void setIsbn13(String isbn13) {
this.isbn13 = isbn13;
}
public String getTagName() {
return tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
public void add(BookTag bTag) {
// TODO Auto-generated method stub
}
}
| 16.057143 | 41 | 0.72242 |
318b8a018ae9b4e91ac837173b52552e000c5372 | 1,072 | package domain.model;
import java.util.*;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import lombok.Data;
@Data
@Entity
@Table(name ="FridgeItem")
public class FridgeItem implements Serializable{
private static final long serialVersionUID = -58439702578493L;
@Id
@SequenceGenerator(name = "FR_ITEM_SEQ", sequenceName = "FR_ITEM_SEQ")
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "FR_ITEM_SEQ")
private Long id;
@NotNull
private float quantity;
@NotNull
private String unit;
@NotNull
private Long ingredient;
public FridgeItem(){
this.quantity = 0.0f;
this.ingredient = new Long(0);
}
/*public FridgeItem(float quantity, String unit, Long ingredient){
this.quantity = quantity;
this.unit = unit;
this.ingredient = ingredient;
}*/
public FridgeItem(FridgeItem other){
if (other.id!=null)
this.id = other.id;
this.quantity = other.quantity;
this.unit = other.unit;
this.ingredient = other.ingredient;
}
}
| 20.226415 | 79 | 0.741604 |
661476010cbe99c926901c60169c73f439f6d3a5 | 560 | package com.helospark.tactview.core.timeline.clipfactory.sequence;
import java.io.File;
public class FileHolder implements Comparable<FileHolder> {
File file;
int frameIndex;
public FileHolder(File file, int frameIndex) {
this.file = file;
this.frameIndex = frameIndex;
}
@Override
public int compareTo(FileHolder other) {
return Integer.compare(frameIndex, other.frameIndex);
}
public File getFile() {
return file;
}
public int getFrameIndex() {
return frameIndex;
}
} | 20.740741 | 66 | 0.660714 |
a3c162fc9bd201d6fe8a0f09a31ee5c46e01863c | 3,543 | package com.redhat.service.smartevents.processor.actions.webhook;
import java.net.MalformedURLException;
import java.net.URL;
import javax.enterprise.context.ApplicationScoped;
import com.redhat.service.smartevents.infra.models.gateways.Action;
import com.redhat.service.smartevents.infra.validations.ValidationResult;
import com.redhat.service.smartevents.processor.GatewayValidator;
@ApplicationScoped
public class WebhookActionValidator implements WebhookAction, GatewayValidator<Action> {
public static final String MISSING_ENDPOINT_PARAM_MESSAGE = "Missing or empty \"endpoint\" parameter";
public static final String MALFORMED_ENDPOINT_PARAM_MESSAGE = "Malformed \"endpoint\" URL";
public static final String BASIC_AUTH_CONFIGURATION_MESSAGE = "Basic authentication configuration error. " +
"\"" + BASIC_AUTH_USERNAME_PARAM + "\" and \"" + BASIC_AUTH_PASSWORD_PARAM + "\" must be both present and non empty.";
public static final String INVALID_PROTOCOL_MESSAGE = "The \"endpoint\" protocol must be either \"http\" or \"https\"";
public static final String RESERVED_ATTRIBUTES_USAGE_MESSAGE = "Some reserved parameters have been added to the request.";
private static final String PROTOCOL_HTTP = "http";
private static final String PROTOCOL_HTTPS = "https";
@Override
public ValidationResult isValid(Action action) {
if (action.getParameters() == null) {
return ValidationResult.invalid();
}
String endpoint = action.getParameters().get(ENDPOINT_PARAM);
if (endpoint == null || endpoint.isEmpty()) {
return ValidationResult.invalid(MISSING_ENDPOINT_PARAM_MESSAGE);
}
if (action.getParameters().containsKey(USE_TECHNICAL_BEARER_TOKEN_PARAM)) {
return ValidationResult.invalid(RESERVED_ATTRIBUTES_USAGE_MESSAGE);
}
if (action.getParameters().containsKey(BASIC_AUTH_USERNAME_PARAM) && !action.getParameters().containsKey(BASIC_AUTH_PASSWORD_PARAM)
|| !action.getParameters().containsKey(BASIC_AUTH_USERNAME_PARAM) && action.getParameters().containsKey(BASIC_AUTH_PASSWORD_PARAM)) {
return ValidationResult.invalid(BASIC_AUTH_CONFIGURATION_MESSAGE);
}
if (action.getParameters().containsKey(BASIC_AUTH_USERNAME_PARAM) && action.getParameters().containsKey(BASIC_AUTH_PASSWORD_PARAM)
&& (action.getParameters().get(BASIC_AUTH_USERNAME_PARAM).isEmpty() || action.getParameters().get(BASIC_AUTH_PASSWORD_PARAM).isEmpty())) {
return ValidationResult.invalid(BASIC_AUTH_CONFIGURATION_MESSAGE);
}
URL endpointUrl;
try {
endpointUrl = new URL(endpoint);
} catch (MalformedURLException e) {
return ValidationResult.invalid(malformedUrlMessage(endpoint, e));
}
String protocol = endpointUrl.getProtocol();
if (!PROTOCOL_HTTP.equalsIgnoreCase(protocol) && !PROTOCOL_HTTPS.equalsIgnoreCase(protocol)) {
return ValidationResult.invalid(invalidProtocolMessage(protocol));
}
return ValidationResult.valid();
}
private static String invalidProtocolMessage(String actualProtocol) {
return String.format("%s (found: \"%s\")", INVALID_PROTOCOL_MESSAGE, actualProtocol);
}
private static String malformedUrlMessage(String endpoint, MalformedURLException exception) {
return String.format("%s \"%s\" (%s)", MALFORMED_ENDPOINT_PARAM_MESSAGE, endpoint, exception.getMessage());
}
}
| 48.534247 | 154 | 0.727632 |
ab675a8d46901d0c275e293cb7b3c83b185684a0 | 1,780 | package com.norswap.autumn.extensions.cluster.syntax;
import com.norswap.autumn.capture.ParseTree;
import com.norswap.autumn.extensions.SyntaxExtension;
import com.norswap.autumn.extensions.cluster.ClusterSyntax;
import com.norswap.autumn.extensions.cluster.expressions.Filter;
import com.norswap.autumn.support.GrammarCompiler;
import com.norswap.autumn.support.MetaGrammar;
import com.norswap.util.Array;
import static com.norswap.autumn.extensions.cluster.ClusterExpressionFactory.filter;
import static com.norswap.autumn.ParsingExpressionFactory.reference;
/**
* Describes the syntactic extension for cluster expression filters (see {@link Filter}).
* <p>
* Examples:
* <pre>{@code
* myRule1 = `filter { myClusterRule; allowed: myArrow1, myArrow2; }
* myRule2 = `filter { myClusterRule; forbidden: myArrow1, myArrow2; }
* }</pre>
*/
public final class SyntaxFilter extends SyntaxExtension
{
////////////////////////////////////////////////////////////////////////////////////////////////
public SyntaxFilter()
{
super(Type.EXPRESSION, "filter", ClusterSyntax.filter);
}
////////////////////////////////////////////////////////////////////////////////////////////////
@Override
public Object compile(
GrammarCompiler compiler,
ParseTree filter)
{
String ref = filter.value("ref");
Array<ParseTree> allowed = filter.group("allowed");
Array<ParseTree> forbidden = filter.group("forbidden");
return filter(
reference(ref),
allowed .mapToArray(t -> t.value, String[]::new),
forbidden .mapToArray(t -> t.value, String[]::new));
}
////////////////////////////////////////////////////////////////////////////////////////////////
}
| 34.230769 | 100 | 0.588202 |
06caa23d3ce0447cc206a7cc0a9f7d9cc28ef15d | 634 | package com.u8.server.sdk.jianpan;
/**
* Created by lvxinmin on 2016/11/10.
*/
public class VerifyResponse {
private String status;
private String msg;
private String userId;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
| 18.114286 | 43 | 0.561514 |
0ffe9c9157d30fd141f82992bfee48e8944559b4 | 2,300 | package com.aldebaran.demo.picture;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
public class ShowPicture extends Frame {
private static final long serialVersionUID = 1L;
private static final int HEIGHT = 640;
private static final int WIDTH = 480;
private BufferedImage image;
@SuppressWarnings("serial")
class PicturePanel extends Panel {
private BufferedImage image;
public PicturePanel(BufferedImage image) {
this.image = image;
}
@Override
public void paint(Graphics g) {
super.paint(g);
int w = getWidth();
int h = getHeight();
int imageWidth = image.getWidth(this);
int imageHeight = image.getHeight(this);
int x = (w - imageWidth) / 2;
int y = (h - imageHeight) / 2;
g.drawImage(image, x, y, this);
}
}
public ShowPicture(Picture picture) {
super("image frame");
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
image = picture.getImage();
PicturePanel picturePanel = new PicturePanel(image);
add(picturePanel);
Dimension preferredSize = new Dimension(WIDTH, HEIGHT);
picturePanel.setPreferredSize(preferredSize);
Font font = new Font("Cantarell", Font.PLAIN, 22);
Label caption = new Label("Hello Java One");
caption.setAlignment(Label.CENTER);
caption.setFont(font);
caption.setBackground(Color.WHITE);
caption.setBounds(0, HEIGHT - 22, WIDTH, HEIGHT);
add(caption);
setSize(HEIGHT, WIDTH + 30);
setVisible(true);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
public static void main(String[] args) throws Exception {
FileInputStream input = new FileInputStream("out.bmp");
byte[] rawData = new byte[3 * HEIGHT * WIDTH];
input.read(rawData);
input.close();
Picture picture = Util.toPicture(rawData);
new ShowPicture(picture);
}
}
| 25.555556 | 58 | 0.726957 |
70d56b20e8b86748ef1f3458dee95090a09dff76 | 187 | package com.gof.observer.vers2;
public class ErrObserver implements Observer {
@Override
public void notify(Event event) {
System.err.println(event.getClass());
}
}
| 18.7 | 46 | 0.68984 |
d6c6bbdcb621467e8cf41406f0bbd41dd3c0876e | 475 | package com.realdolmen.realjobs.mappers;
import com.realdolmen.realjobs.models.Vacancy;
import com.realdolmen.realjobs.dto.VacancyDTO;
import org.mapstruct.MapperConfig;
import org.mapstruct.MappingTarget;
@MapperConfig(componentModel = "spring")
public interface VacancyMapperConfig {
abstract VacancyDTO toVacancyDTO(Vacancy vacancy, @MappingTarget VacancyDTO vacancyDTO);
abstract Vacancy toVacancyModel(VacancyDTO vacancyDTO, @MappingTarget Vacancy vacancy);
}
| 36.538462 | 92 | 0.831579 |
db111d2d82818681f61b5d144c65c15f9dc2fef2 | 3,729 | package software.amazon.smithy.aws.go.codegen.customization;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.go.codegen.GoSettings;
import software.amazon.smithy.go.codegen.integration.GoIntegration;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.traits.DocumentationTrait;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.Pair;
import software.amazon.smithy.utils.SetUtils;
public class S3AddPutObjectUnseekableBodyDoc implements GoIntegration {
private static final Logger LOGGER = Logger.getLogger(S3AddPutObjectUnseekableBodyDoc.class.getName());
private static final Map<ShapeId, Set<Pair<ShapeId, String>>> SERVICE_TO_SHAPE_MAP = MapUtils.of(
ShapeId.from("com.amazonaws.s3#AmazonS3"), SetUtils.of(
new Pair(ShapeId.from("com.amazonaws.s3#PutObjectRequest"), "Body"),
new Pair(ShapeId.from("com.amazonaws.s3#UploadPartRequest"), "Body")
)
);
@Override
public byte getOrder() {
// This integration should happen before other integrations that rely on the presence of this trait
return -60;
}
@Override
public Model preprocessModel(
Model model, GoSettings settings
) {
ShapeId serviceId = settings.getService();
if (!SERVICE_TO_SHAPE_MAP.containsKey(serviceId)) {
return model;
}
Set<Pair<ShapeId, String>> shapeIds = SERVICE_TO_SHAPE_MAP.get(serviceId);
Model.Builder builder = model.toBuilder();
for (Pair<ShapeId, String> pair : shapeIds) {
ShapeId shapeId = pair.getLeft();
String memberName = pair.getRight();
StructureShape parent = model.expectShape(shapeId, StructureShape.class);
Optional<MemberShape> memberOpt = parent.getMember(memberName);
if (!memberOpt.isPresent()) {
// Throw in case member is not present, bad things must of happened.
throw new CodegenException("expect to find " + memberName + " member in shape " + parent.getId());
}
MemberShape member = memberOpt.get();
Shape target = model.expectShape(member.getTarget());
Optional<DocumentationTrait> docTrait = member.getTrait(DocumentationTrait.class);
String currentDocs = "";
if (docTrait.isPresent()) {
currentDocs = docTrait.get().getValue();
}
if (currentDocs.length() != 0) {
currentDocs += "<br/><br/>";
}
final String finalCurrentDocs = currentDocs;
StructureShape.Builder parentBuilder = parent.toBuilder();
parentBuilder.removeMember(memberName);
parentBuilder.addMember(memberName, target.getId(), (memberBuilder) -> {
memberBuilder
.addTraits(member.getAllTraits().values())
.addTrait(new DocumentationTrait(finalCurrentDocs +
"For using values that are not seekable (io.Seeker) see, " +
"https://aws.github.io/aws-sdk-go-v2/docs/sdk-utilities/s3/#unseekable-streaming-input"));
});
builder.addShape(parentBuilder.build());
}
return builder.build();
}
}
| 41.898876 | 122 | 0.652722 |
28031aae6e2b8c71b2c2e5adbb56affe9fb6f611 | 6,393 | package org.andengine.input.touch.detector;
import android.view.MotionEvent;
import org.andengine.input.touch.TouchEvent;
import org.andengine.util.math.MathUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @author Yarolav Havrylovych
*/
public class PinchZoomDetector extends BaseDetector {
// ===========================================================
// Constants
// ===========================================================
private static final float TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT = 10;
// ===========================================================
// Fields
// ===========================================================
private final IPinchZoomDetectorListener mPinchZoomDetectorListener;
private float mInitialDistance;
private float mCurrentDistance;
private float mTriggerPinchZoomMinimumDistance = TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT;
private boolean mPinchZooming;
// ===========================================================
// Constructors
// ===========================================================
public PinchZoomDetector(final IPinchZoomDetectorListener pPinchZoomDetectorListener) {
this.mPinchZoomDetectorListener = pPinchZoomDetectorListener;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isZooming() {
return this.mPinchZooming;
}
public void setTriggerPinchZoomMinimumDistance(float triggerPinchZoomMinimumDistance) {
this.mTriggerPinchZoomMinimumDistance = triggerPinchZoomMinimumDistance;
}
public float getTriggerPinchZoomMinimumDistance() {
return this.mTriggerPinchZoomMinimumDistance;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
/**
* When {@link #isZooming()} this method will call through to {@link IPinchZoomDetectorListener#onPinchZoomFinished(PinchZoomDetector, TouchEvent, float)}.
*/
@Override
public void reset() {
if (this.mPinchZooming) {
this.mPinchZoomDetectorListener.onPinchZoomFinished(this, null, this.getZoomFactor());
}
this.mInitialDistance = 0;
this.mCurrentDistance = 0;
this.mPinchZooming = false;
}
@Override
public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) {
final MotionEvent motionEvent = pSceneTouchEvent.getMotionEvent();
final int action = motionEvent.getAction() & MotionEvent.ACTION_MASK;
switch (action) {
case MotionEvent.ACTION_POINTER_DOWN:
if (!this.mPinchZooming && PinchZoomDetector.hasTwoPointers(motionEvent)) {
this.mInitialDistance = PinchZoomDetector.calculatePointerDistance(motionEvent);
this.mCurrentDistance = this.mInitialDistance;
if (this.mInitialDistance > this.mTriggerPinchZoomMinimumDistance) {
this.mPinchZooming = true;
this.mPinchZoomDetectorListener.onPinchZoomStarted(this, pSceneTouchEvent);
}
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
if (this.mPinchZooming) {
this.mPinchZooming = false;
this.mPinchZoomDetectorListener.onPinchZoomFinished(this, pSceneTouchEvent, this.getZoomFactor());
}
break;
case MotionEvent.ACTION_MOVE:
if (this.mPinchZooming) {
if (PinchZoomDetector.hasTwoPointers(motionEvent)) {
this.mCurrentDistance = PinchZoomDetector.calculatePointerDistance(motionEvent);
if (this.mCurrentDistance > this.mTriggerPinchZoomMinimumDistance) {
this.mPinchZoomDetectorListener.onPinchZoom(this, pSceneTouchEvent, this.getZoomFactor());
}
} else {
this.mPinchZooming = false;
this.mPinchZoomDetectorListener.onPinchZoomFinished(this, pSceneTouchEvent, this.getZoomFactor());
}
}
break;
}
return true;
}
/**
* check is there only two pointers (touches) present currently.
* <br/>
* one used for scroll
* <br/>
* more than two can be used for some other thing
*/
private static boolean hasTwoPointers(final MotionEvent pMotionEvent) {
return pMotionEvent.getPointerCount() == 2;
}
// ===========================================================
// Methods
// ===========================================================
/**
* Calculate the euclidian distance between the first two fingers.
*/
private static float calculatePointerDistance(final MotionEvent pMotionEvent) {
return MathUtils.distance(pMotionEvent.getX(0), pMotionEvent.getY(0), pMotionEvent.getX(1), pMotionEvent.getY(1));
}
private float getZoomFactor() {
return this.mCurrentDistance / this.mInitialDistance;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface IPinchZoomDetectorListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
void onPinchZoomStarted(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pSceneTouchEvent);
void onPinchZoom(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor);
void onPinchZoomFinished(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor);
}
}
| 38.981707 | 159 | 0.536994 |
db4f430cb3f458c14afa0bd9b8997ed08329344f | 6,114 | /*
* Copyright 2019 Qameta Software OÜ
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.qameta.allure.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* The model object that stores links between test results and test fixtures.
* <p>
* During report generation all {@link #befores} and {@link #afters} is added to each
* test result that {@link TestResult#getUuid()} matches values, specified in {@link #children}.
* <p>
* Containers that have empty {@link #children} are simply ignored.
*
* @author baev (Dmitry Baev)
* @see io.qameta.allure.model.TestResult
* @see io.qameta.allure.model.WithLinks
* @since 2.0
*/
@SuppressWarnings("PMD.ExcessivePublicCount")
public class TestResultContainer implements Serializable, WithLinks {
private static final long serialVersionUID = 1L;
private String uuid;
private String name;
private List<String> children = new ArrayList<>();
private String description;
private String descriptionHtml;
private List<FixtureResult> befores = new ArrayList<>();
private List<FixtureResult> afters = new ArrayList<>();
private List<Link> links;
private Long start;
private Long stop;
/**
* Gets uuid.
*
* @return the uuid
*/
public String getUuid() {
return uuid;
}
/**
* Sets uuid.
*
* @param value the value
* @return self for method chaining
*/
public TestResultContainer setUuid(final String value) {
this.uuid = value;
return this;
}
/**
* Gets name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Sets name.
*
* @param value the value
* @return self for method chaining
*/
public TestResultContainer setName(final String value) {
this.name = value;
return this;
}
/**
* Gets description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Sets description.
*
* @param value the value
* @return self for method chaining
*/
public TestResultContainer setDescription(final String value) {
this.description = value;
return this;
}
/**
* Gets description html.
*
* @return the description html
*/
public String getDescriptionHtml() {
return descriptionHtml;
}
/**
* Sets description html.
*
* @param value the value
* @return self for method chaining
*/
public TestResultContainer setDescriptionHtml(final String value) {
this.descriptionHtml = value;
return this;
}
/**
* Gets start.
*
* @return the start
*/
public Long getStart() {
return start;
}
/**
* Sets start.
*
* @param value the value
* @return self for method chaining
*/
public TestResultContainer setStart(final Long value) {
this.start = value;
return this;
}
/**
* Gets stop.
*
* @return the stop
*/
public Long getStop() {
return stop;
}
/**
* Sets stop.
*
* @param value the value
* @return self for method chaining
*/
public TestResultContainer setStop(final Long value) {
this.stop = value;
return this;
}
/**
* Gets children.
*
* @return the children
*/
public List<String> getChildren() {
return children;
}
/**
* Sets children.
*
* @param children the children
* @return self for method chaining
*/
public TestResultContainer setChildren(final List<String> children) {
this.children = children;
return this;
}
/**
* Gets befores.
*
* @return the befores
*/
public List<FixtureResult> getBefores() {
return befores;
}
/**
* Sets befores.
*
* @param befores the befores
* @return self for method chaining
*/
public TestResultContainer setBefores(final List<FixtureResult> befores) {
this.befores = befores;
return this;
}
/**
* Gets afters.
*
* @return the afters
*/
public List<FixtureResult> getAfters() {
return afters;
}
/**
* Sets afters.
*
* @param afters the afters
* @return self for method chaining
*/
public TestResultContainer setAfters(final List<FixtureResult> afters) {
this.afters = afters;
return this;
}
/**
* Gets links.
*
* @return the links
*/
@Override
public List<Link> getLinks() {
return links;
}
/**
* Sets links.
*
* @param links the links
* @return self for method chaining
*/
public TestResultContainer setLinks(final List<Link> links) {
this.links = links;
return this;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final TestResultContainer that = (TestResultContainer) o;
return Objects.equals(uuid, that.uuid) && Objects.equals(name, that.name);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Objects.hash(uuid, name);
}
}
| 22.152174 | 96 | 0.585868 |
6347111e965ee9e34c28748e5829a74fc7b3351a | 8,132 | import Commands.ExportCommand;
import Commands.IndexNowCommand;
import Enums.OutputMode;
import Exceptions.IncorrectParameterException;
import Executors.Executor;
import Factories.CommandFactory;
import Interfaces.Command;
import Interfaces.Query;
import Utils.ExportStatus;
import Utils.StringsMapping;
import Utils.Utils;
import org.apache.commons.cli.*;
import org.apache.commons.cli.ParseException;
import org.apache.commons.math3.analysis.function.Exp;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
*
* user@host:$> loGrep [-q field1=value1 field2=value2 field3=value3]
* [-ti time1 time2]
* [-di date1 date2]
* [-obt asc/desc]
* [-e file.txt]
* [-f]
* [-in]
*
* user@host:$> loGrep [--query field1=value1 field2=value2 field3=value3]
* [--time-interval time1 time2]
* [--date-interval date1 date2]
* [--order-by-timestamp asc/desc]
* [--export file.txt]
* [--fields]
* [--index-now]
*
* [--status]
* [--index-interval 1h]
*
*/
public class Main {
private static class OptionComparator implements Comparator<Option> {
public int compare(Option option1, Option option2) {
if(option1.getOpt().equals(StringsMapping.queryShort))
return 1;
return 0;
}
}
private static boolean containsExportCommand(List<Command> commands) {
for(int i = 0; i < commands.size(); i++) {
if(commands.get(i) instanceof ExportCommand)
return true;
}
return false;
}
private static boolean containsIndexNowCommand(List<Command> commands) {
for(int i = 0; i < commands.size(); i++) {
if(commands.get(i) instanceof IndexNowCommand)
return true;
}
return false;
}
private static void printHelper(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.setOptionComparator(new OptionComparator());
formatter.setWidth(80);
formatter.printHelp( "loGrep", options );
}
private static void handleResults() throws IOException{
if(ExportStatus.outputMode.equals(OutputMode.STDOUT)) {
while(true) {
String results = Executor.getMoreResults();
if(results == null)
break;
System.out.println(results);
System.out.println("\nDisplay the next batch of results? (ENTER): ");
System.in.read();
}
} else if(ExportStatus.outputMode.equals(OutputMode.FILE)) {
boolean exportAllResults = false;
FileWriter writer = new FileWriter(ExportStatus.fileName);
while(true) {
String results = Executor.getMoreResults();
if(results == null)
break;
writer.write(results);
if(!exportAllResults) {
System.out.println("\nOne batch of results was exported. Do you want to export the next batch of results (Y)? Export all the results to the file (A)?: ");
char c = (char)System.in.read();
while(c != 'Y' && c != 'A')
System.out.println("You need to type either \'Y\' or \'A\'");
if(c == 'A')
exportAllResults = true;
}
}
writer.close();
}
}
private static void accumulateQueries(List<Query> queries, CommandLine line, CommandFactory factory) throws IncorrectParameterException {
if(line.hasOption(StringsMapping.queryShort)) {
Query query = factory.getQuery(StringsMapping.queryShort);
query.setParams(line.getOptionValues(StringsMapping.queryShort));
queries.add(query);
}
if(line.hasOption(StringsMapping.dateIntervalShort)) {
Query query = factory.getQuery(StringsMapping.dateIntervalShort);
query.setParams(line.getOptionValues(StringsMapping.dateIntervalShort));
queries.add(query);
}
if(line.hasOption(StringsMapping.timeIntervalShort)) {
Query query = factory.getQuery(StringsMapping.timeIntervalShort);
query.setParams(line.getOptionValues(StringsMapping.timeIntervalShort));
queries.add(query);
}
if(line.hasOption(StringsMapping.orderByTimeStampShort)) {
Query query = factory.getQuery(StringsMapping.orderByTimeStampShort);
query.setParams(line.getOptionValues(StringsMapping.orderByTimeStampShort));
queries.add(query);
}
}
private static void accumulateCommands(List<Command> commands, CommandLine line, CommandFactory factory) throws IncorrectParameterException {
if(line.hasOption(StringsMapping.fieldsShort)) {
Command command = factory.getCommand(StringsMapping.fieldsShort);
commands.add(command);
}
if(line.hasOption(StringsMapping.statusShort)) {
Command command = factory.getCommand(StringsMapping.statusShort);
commands.add(command);
}
if(line.hasOption(StringsMapping.indexIntervalShort)) {
Command command = factory.getCommand(StringsMapping.indexIntervalShort);
command.setParams(line.getOptionValues(StringsMapping.indexIntervalShort));
commands.add(command);
}
if(line.hasOption(StringsMapping.indexNowShort)){
Command command = factory.getCommand(StringsMapping.indexNowShort);
commands.add(command);
}
if(line.hasOption(StringsMapping.guiShort)) {
Command command = factory.getCommand(StringsMapping.guiShort);
commands.add(command);
}
if(line.hasOption(StringsMapping.initCommand)) {
Command command = factory.getCommand(StringsMapping.initCommand);
commands.add(command);
}
if(line.hasOption(StringsMapping.exportShort)) {
Command command = factory.getCommand(StringsMapping.exportShort);
command.setParams(line.getOptionValues(StringsMapping.exportShort));
commands.add(command);
}
}
public static void main(String args[]) {
Options options = Utils.buildOptions();
List<Query> queries = new ArrayList<>();
List<Command> commands = new ArrayList<>();
CommandFactory factory = new CommandFactory();
CommandLineParser parser = new DefaultParser();
ExportStatus.outputMode = OutputMode.STDOUT;
try {
CommandLine line = parser.parse(options, args);
accumulateQueries(queries, line, factory);
accumulateCommands(commands, line, factory);
if(commands.size() > 0) {
Executor.executeCommands(commands);
if(containsExportCommand(commands) || containsIndexNowCommand(commands)) {
if(queries.size() > 0) {
Executor.executeQueries(queries);
handleResults();
}
}
}
else if(queries.size() > 0) {
Executor.executeQueries(queries);
handleResults();
}
else
printHelper(options);
}
catch(ParseException | IncorrectParameterException | HttpSolrClient.RemoteSolrException | SolrServerException | IOException exception) {
System.out.println(exception.getMessage());
printHelper(options);
}
}
}
| 33.327869 | 174 | 0.594934 |
31b169235cb2bb4ed6a1de2c854dd787d89d6b62 | 1,006 | package com.matera.repository;
import java.util.List;
import com.matera.exceptions.UserNotFoundException;
import com.matera.model.User;
/**
* Database access to manage user document.
* @author Lucas
*/
public interface UserRepository {
/**
* Saves a user.
* @param user User to be saved.
* @return User saved.
*/
User save(User user);
/**
* Checks the existence of a user.
* @param user User to be checked.
* @return true if user exists on database.
*/
boolean exists(User user);
/**
* Finds a User by it's login.
* @param login Login of user to be found.
* @return User
* @throws UserNotFoundException If the user is not found on database.
*/
User findByLogin(String login) throws UserNotFoundException;
/**
* Find all users on database.
* @return List of users found.
*/
List<User> findAll();
/**
* Delete user on database.
* @param user User to be deleted.
*/
void delete(User user);
} | 20.958333 | 73 | 0.639165 |
41c3d5745f5bbcb47768e7c6e3f326c5adce4de0 | 1,851 | /**
* Copyright 2015 - 2016 KeepSafe Software, 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.anchorfree.relinker;
import android.os.Build;
@SuppressWarnings("deprecation")
final class SystemLibraryLoader implements ReLinker.LibraryLoader {
@Override
public void loadLibrary(final String libraryName) {
System.loadLibrary(libraryName);
}
@Override
public void loadPath(final String libraryPath) {
System.load(libraryPath);
}
@Override
public String mapLibraryName(final String libraryName) {
if (libraryName.startsWith("lib") && libraryName.endsWith(".so")) {
// Already mapped
return libraryName;
}
return System.mapLibraryName(libraryName);
}
@Override
public String unmapLibraryName(String mappedLibraryName) {
// Assuming libname.so
return mappedLibraryName.substring(3, mappedLibraryName.length() - 3);
}
@Override
public String[] supportedAbis() {
if (Build.VERSION.SDK_INT >= 21 && Build.SUPPORTED_ABIS.length > 0) {
return Build.SUPPORTED_ABIS;
} else if (!TextUtils.isEmpty(Build.CPU_ABI2)) {
return new String[] {Build.CPU_ABI, Build.CPU_ABI2};
} else {
return new String[] {Build.CPU_ABI};
}
}
}
| 31.372881 | 78 | 0.675851 |
153e904c48c354dd0f86f3a6499463abfa351520 | 7,223 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
* applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package com.github.drinkjava2.jdialects;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.sql.DataSource;
/**
* Guess Dialect Utils
*
* @author Yong Zhu
* @since 1.0.1
*/
@SuppressWarnings("all")
public class GuessDialectUtils {
private static final Map<DataSource, Dialect> dataSourceDialectCache = new ConcurrentHashMap<DataSource, Dialect>();
/**
* Guess dialect based on given JDBC connection instance, Note: this method does
* not close connection
*
* @param jdbcConnection
* The connection
* @return dialect or null if can not guess out which dialect
*/
public static Dialect guessDialect(Connection jdbcConnection) {
String databaseName;
String driverName;
int majorVersion;
int minorVersion;
try {
DatabaseMetaData meta = jdbcConnection.getMetaData();
driverName = meta.getDriverName();
databaseName = meta.getDatabaseProductName();
majorVersion = meta.getDatabaseMajorVersion();
minorVersion = meta.getDatabaseMinorVersion();
} catch (SQLException e) {
return (Dialect) DialectException.throwEX(e);
}
return guessDialect(driverName, databaseName, majorVersion, minorVersion);
}
/**
* Guess dialect based on given dataSource
*
* @param datasource
* The dataSource
* @return dialect or null if can not guess out which dialect
*/
public static Dialect guessDialect(DataSource dataSource) {
Dialect result = dataSourceDialectCache.get(dataSource);
if (result != null)
return result;
Connection con = null;
try {
con = dataSource.getConnection();
result = guessDialect(con);
if (result == null)
return (Dialect) DialectException
.throwEX("Can not get dialect from DataSource, please submit this bug.");
dataSourceDialectCache.put(dataSource, result);
return result;
} catch (SQLException e) {
return (Dialect) DialectException.throwEX(e);
} finally {
try {
if (con != null && !con.isClosed()) {
try {// NOSONAR
con.close();
} catch (SQLException e) {
DialectException.throwEX(e);
}
}
} catch (SQLException e) {
DialectException.throwEX(e);
}
}
}
/**
* @param databaseName
* The database name
* @param majorVersionMinorVersion
* The major version,The minor version, Optional optional
* @return dialect or null if not found
*/
public static Dialect guessDialect(String driverName, String databaseName, Object... majorVersionMinorVersion) {// NOSONAR
int majorVersion = 0;
int minorVersion = 0;
for (int i = 0; i < majorVersionMinorVersion.length; i++) {
if (i == 0)
majorVersion = (Integer) majorVersionMinorVersion[i];
if (i == 1)
minorVersion = (Integer) majorVersionMinorVersion[i];
}
if ("CUBRID".equalsIgnoreCase(databaseName))
return Dialect.CUBRIDDialect;
if ("HSQL Database Engine".equals(databaseName))
return Dialect.HSQLDialect;
if ("H2".equals(databaseName))
return Dialect.H2Dialect;
if ("MySQL".equals(databaseName)) {
if (majorVersion < 5)
return Dialect.MySQLDialect;
else if (majorVersion == 5) {
if (minorVersion < 5)
return Dialect.MySQL5Dialect;
else if (minorVersion < 7)
return Dialect.MySQL55Dialect;
else
return Dialect.MySQL57Dialect;
}
return Dialect.MySQL57Dialect;
}
if (driverName != null && driverName.startsWith("MariaDB")) {
if (majorVersion == 10) {
if (minorVersion >= 3)
return Dialect.MariaDB103Dialect;
else if (minorVersion == 2)
return Dialect.MariaDB102Dialect;
else if (minorVersion >= 0)
return Dialect.MariaDB10Dialect;
return Dialect.MariaDB53Dialect;
} else if (majorVersion > 5 || (majorVersion == 5 && minorVersion >= 3)) {
return Dialect.MariaDB53Dialect;
}
return Dialect.MariaDBDialect;
}
if ("PostgreSQL".equals(databaseName)) {
if (majorVersion == 9) {
if (minorVersion >= 4) {
return Dialect.PostgreSQL94Dialect;
} else if (minorVersion >= 2) {
return Dialect.PostgreSQL92Dialect;
}
return Dialect.PostgreSQL9Dialect;
}
if (majorVersion == 8 && minorVersion >= 2) {
return Dialect.PostgreSQL82Dialect;
}
return Dialect.PostgreSQL81Dialect;
}
if ("EnterpriseDB".equals(databaseName))
return Dialect.PostgresPlusDialect;
if ("Apache Derby".equals(databaseName)) {
if (majorVersion > 10 || (majorVersion == 10 && minorVersion >= 7))
return Dialect.DerbyTenSevenDialect;
else if (majorVersion == 10 && minorVersion == 6)
return Dialect.DerbyTenSixDialect;
else if (majorVersion == 10 && minorVersion == 5)
return Dialect.DerbyTenFiveDialect;
else
return Dialect.DerbyDialect;
}
if ("ingres".equalsIgnoreCase(databaseName)) {
switch (majorVersion) {
case 9:
if (minorVersion > 2)
return Dialect.Ingres9Dialect;
else
return Dialect.IngresDialect;
case 10:
return Dialect.Ingres10Dialect;
default:
}
return Dialect.IngresDialect;
}
if (databaseName.startsWith("Microsoft SQL Server")) {
switch (majorVersion) {
case 8:
return Dialect.SQLServerDialect;
case 9:
return Dialect.SQLServer2005Dialect;
case 10:
return Dialect.SQLServer2008Dialect;
case 11:
case 12:
case 13:
return Dialect.SQLServer2012Dialect;
default:
if (majorVersion < 8)
return Dialect.SQLServerDialect;
else
return Dialect.SQLServer2012Dialect;
}
}
if ("Sybase SQL Server".equals(databaseName) || "Adaptive Server Enterprise".equals(databaseName))
return Dialect.SybaseASE15Dialect;
if (databaseName.startsWith("Adaptive Server Anywhere"))
return Dialect.SybaseAnywhereDialect;
if ("Informix Dynamic Server".equals(databaseName))
return Dialect.InformixDialect;
if ("DB2 UDB for AS/400".equals(databaseName))
return Dialect.DB2400Dialect;
if (databaseName.startsWith("DB2/"))
return Dialect.DB2Dialect;
if ("Oracle".equals(databaseName)) {
switch (majorVersion) {
case 12:
return Dialect.Oracle12cDialect;
case 11:
case 10:
return Dialect.Oracle10gDialect;
case 9:
return Dialect.Oracle9iDialect;
case 8:
return Dialect.Oracle8iDialect;
default:
}
return Dialect.Oracle12cDialect;
}
if ("HDB".equals(databaseName))
return Dialect.HANAColumnStoreDialect;
if (databaseName.startsWith("Firebird"))
return Dialect.FirebirdDialect;
if (StrUtils.containsIgnoreCase(databaseName, "sqlite"))
return Dialect.SQLiteDialect;
return null;
}
}
| 30.73617 | 123 | 0.703724 |
5f22d5cf1f08b6bb5bdec776ca047be6ade68e56 | 965 | package io.rocketbase.commons.model.converter;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.springframework.util.StringUtils;
import javax.persistence.AttributeConverter;
import javax.persistence.Convert;
import java.util.ArrayList;
import java.util.List;
@Convert
public class StringListConverter implements AttributeConverter<List<String>, String> {
@Override
public String convertToDatabaseColumn(List<String> attribute) {
String result = null;
if (attribute != null) {
result = Joiner.on(";").join(attribute);
}
return result;
}
@Override
public List<String> convertToEntityAttribute(String dbData) {
List<String> result = new ArrayList<>();
if (!StringUtils.isEmpty(dbData)) {
result = Lists.newArrayList(Splitter.on(";").split(dbData));
}
return result;
}
}
| 28.382353 | 86 | 0.693264 |
4cd19483eb8e6353e433321a2d95b2e30022b360 | 3,983 | /*
* AsTeRICS - Assistive Technology Rapid Integration and Construction Set
*
*
* d8888 88888888888 8888888b. 8888888 .d8888b. .d8888b.
* d88888 888 888 Y88b 888 d88P Y88b d88P Y88b
* d88P888 888 888 888 888 888 888 Y88b.
* d88P 888 .d8888b 888 .d88b. 888 d88P 888 888 "Y888b.
* d88P 888 88K 888 d8P Y8b 8888888P" 888 888 "Y88b.
* d88P 888 "Y8888b. 888 88888888 888 T88b 888 888 888 "888
* d8888888888 X88 888 Y8b. 888 T88b 888 Y88b d88P Y88b d88P
* d88P 888 88888P' 888 "Y8888 888 T88b 8888888 "Y8888P" "Y8888P"
*
*
* homepage: http://www.asterics.org
*
* This project has been funded by the European Commission,
* Grant Agreement Number 247730
*
*
* Dual License: MIT or GPL v3.0 with "CLASSPATH" exception
* (please refer to the folder LICENSE)
*
*/
package eu.asterics.mw.webservice;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.glassfish.grizzly.websockets.Broadcaster;
import org.glassfish.grizzly.websockets.OptimizedBroadcaster;
import org.glassfish.grizzly.websockets.WebSocket;
import org.glassfish.grizzly.websockets.WebSocketApplication;
//import com.corundumstudio.socketio.SocketConfig;
import eu.asterics.mw.data.ConversionUtils;
import eu.asterics.mw.model.runtime.IRuntimeInputPort;
import eu.asterics.mw.model.runtime.IRuntimeOutputPort;
import eu.asterics.mw.model.runtime.impl.DefaultRuntimeInputPort;
import eu.asterics.mw.model.runtime.impl.DefaultRuntimeOutputPort;
import eu.asterics.mw.services.AstericsErrorHandling;
/**
* This class handles registers as a websocket listener and acts as a proxy for AsTeRICS plugins. It receives and sends data from to the websocket by emulating
* {@link IRuntimeInputPort} and {@link IRuntimeOutputPort}
* @author mad
*
*/
public class AstericsDataApplication extends WebSocketApplication {
ScheduledExecutorService sendService=Executors.newScheduledThreadPool(1);
// broadcasts to all websocket clients
private final Broadcaster broadcaster = new OptimizedBroadcaster();
//IRuntimeOutputPort that manages the plugin input port listeners that want to receive the websocket data
final IRuntimeOutputPort opOut = new DefaultRuntimeOutputPort();
/**
* Callback which is called if a text message arrives at the websocket.
*/
@Override
public void onMessage(WebSocket socket, String text) {
//System.out.println("In onMessage: "+text);
super.onMessage(socket, text);
opOut.sendData(ConversionUtils.stringToBytes(text));
}
/**
* Callback which is called if a client connects to the websocket.
*/
@Override
public void onConnect(final WebSocket socket) {
// TODO Auto-generated method stub
super.onConnect(socket);
AstericsErrorHandling.instance.getLogger().fine("WebSocket onConnect");
}
/**
* Returns the {@link IRuntimeOutputPort} port of the WebSocket service. Is used to send data to AsTeRICS plugins.
* @param portID
* @return
*/
public IRuntimeOutputPort getOutputPort(String portID)
{
return opOut;
}
/**
* Returns the {@link IRuntimeInputPort} port of the WebSocket service. Is used to receive data from AsTeRICS plugins.
* @param portID
* @return
*/
public IRuntimeInputPort getInputPort(String portID)
{
return ipIn;
}
/**
* The IRuntimeInputPort instance that forwards the incoming data from the Asterics plugins to the websocket.
*/
private final IRuntimeInputPort ipIn = new DefaultRuntimeInputPort()
{
public void receiveData(byte[] data)
{
String dataStr=ConversionUtils.stringFromBytes(data);
//logger.fine("Sending value: "+dataStr);
broadcaster.broadcast(getWebSockets(), dataStr);
}
};
}
| 34.042735 | 160 | 0.699473 |
22920f750d9ec76a8e044ea192f9dc992bd6c8e8 | 3,296 | package de.ellpeck.prettypipes.pipe.modules.extraction;
import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.items.ModuleTier;
import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.network.PipeNetwork;
import de.ellpeck.prettypipes.pipe.PipeTileEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Direction;
import net.minecraftforge.items.IItemHandler;
public class ExtractionModuleItem extends ModuleItem {
private final int maxExtraction;
private final int speed;
private final boolean preventOversending;
public final int filterSlots;
public ExtractionModuleItem(String name, ModuleTier tier) {
super(name);
this.maxExtraction = tier.forTier(1, 8, 64);
this.speed = tier.forTier(20, 15, 10);
this.filterSlots = tier.forTier(3, 6, 9);
this.preventOversending = tier.forTier(false, false, true);
}
@Override
public void tick(ItemStack module, PipeTileEntity tile) {
if (!tile.shouldWorkNow(this.speed) || !tile.canWork())
return;
ItemFilter filter = this.getItemFilter(module, tile);
PipeNetwork network = PipeNetwork.get(tile.getWorld());
for (Direction dir : Direction.values()) {
IItemHandler handler = tile.getItemHandler(dir);
if (handler == null)
continue;
for (int j = 0; j < handler.getSlots(); j++) {
ItemStack stack = handler.extractItem(j, this.maxExtraction, true);
if (stack.isEmpty())
continue;
if (!filter.isAllowed(stack))
continue;
ItemStack remain = network.routeItem(tile.getPos(), tile.getPos().offset(dir), stack, this.preventOversending);
if (remain.getCount() != stack.getCount()) {
handler.extractItem(j, stack.getCount() - remain.getCount(), false);
return;
}
}
}
}
@Override
public boolean canNetworkSee(ItemStack module, PipeTileEntity tile) {
return false;
}
@Override
public boolean canAcceptItem(ItemStack module, PipeTileEntity tile, ItemStack stack) {
return false;
}
@Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) {
return !(other instanceof ExtractionModuleItem);
}
@Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) {
return true;
}
@Override
public AbstractPipeContainer<?> getContainer(ItemStack module, PipeTileEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) {
return new ExtractionModuleContainer(Registry.extractionModuleContainer, windowId, player, tile.getPos(), moduleIndex);
}
@Override
public ItemFilter getItemFilter(ItemStack module, PipeTileEntity tile) {
return new ItemFilter(this.filterSlots, module, tile);
}
}
| 37.454545 | 162 | 0.678095 |
6a84e5dca753ce3ff33c369aab7101de98abbf7b | 956 | package cn.fanrunqi.materiallogin.bmob;
import android.content.Context;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobConfig;
import cn.fanrunqi.materiallogin.config.Config;
/**
* Created by Wengdada on 2017/2/28.
*/
public class Mybmob {
public static void initBmob(Context initContext){
//提供以下两种方式进行Bmob初始化操作:
//第一:默认初始化
//Bmob.initialize(this, "Your Application ID");
//第二:自v3.4.7版本开始,设置BmobConfig,允许设置请求超时时间、文件分片上传时每片的大小、文件的过期时间(单位为秒),
BmobConfig config =new BmobConfig.Builder(initContext)
////设置appkey
.setApplicationId(Config.APP_ID)
////请求超时时间(单位为秒):默认15s
.setConnectTimeout(30)
////文件分片上传时每片的大小(单位字节),默认512*1024
.setUploadBlockSize(1024*1024)
////文件的过期时间(单位为秒):默认1800s
.setFileExpiration(2500)
.build();
Bmob.initialize(config);
}
}
| 23.9 | 76 | 0.604603 |
befc4a8ea410bc03dbabc7406d436b9805233ad0 | 4,414 | package ch.squix.extraleague.rest.ranking;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import ch.squix.extraleague.model.ranking.EternalRanking;
import ch.squix.extraleague.model.ranking.PlayerRanking;
import ch.squix.extraleague.model.ranking.Ranking;
public class RankingDtoMapper {
private static RankingsDto getRankingDtos(List<PlayerRanking> playerRankings, Date createdDate) {
List<RankingDto> playerRankingList = new ArrayList<>();
if (playerRankings != null) {
for (PlayerRanking playerRanking : playerRankings) {
RankingDto rankingDto = new RankingDto();
rankingDto.setPlayer(playerRanking.getPlayer());
rankingDto.setGamesWon(playerRanking.getGamesWon());
rankingDto.setGamesLost(playerRanking.getGamesLost());
rankingDto.setRanking(playerRanking.getRanking());
rankingDto.getBadges().clear();
rankingDto.getBadges().addAll(playerRanking.getBadges());
rankingDto.setGoalsMade(playerRanking.getGoalsMade());
rankingDto.setGoalsGot(playerRanking.getGoalsGot());
rankingDto.setOffensivePositionRate(playerRanking.getOffensivePositionRate());
rankingDto.setDefensivePositionRate(playerRanking.getDefensivePositionRate());
rankingDto.setOffensiveGoalsRate(playerRanking.getOffensiveGoalsRate());
rankingDto.setBestPartner(playerRanking.getBestPartner());
rankingDto.setBestPartnerRate(playerRanking.getBestPartnerRate());
rankingDto.setWorstPartner(playerRanking.getWorstPartner());
rankingDto.setWorstPartnerRate(playerRanking.getWorstPartnerRate());
rankingDto.setBestOpponent(playerRanking.getBestOpponent());
rankingDto.setBestOpponentRate(playerRanking.getBestOpponentRate());
rankingDto.setWorstOpponent(playerRanking.getWorstOpponent());
rankingDto.setWorstOpponentRate(playerRanking.getWorstOpponentRate());
rankingDto.setAverageSecondsPerMatch(playerRanking.getAverageSecondsPerMatch());
rankingDto.setCurrentShapeRate(playerRanking.getCurrentShapeRate());
rankingDto.setPlayedWith(playerRanking.getPlayedWith());
rankingDto.setNeverPlayedWith(playerRanking.getNeverPlayedWith());
rankingDto.setTightlyLostRate(playerRanking.getTightlyLostRate());
rankingDto.setTightlyWonRate(playerRanking.getTightlyWonRate());
rankingDto.setPartners(PlayerComboDtoMapper.mapToDtos(playerRanking.getPartners()));
rankingDto.setOpponents(PlayerComboDtoMapper.mapToDtos(playerRanking.getOpponents()));
rankingDto.setEloValue(playerRanking.getEloValue());
rankingDto.setAverageGoalsPerMatch(playerRanking.getAverageGoalsPerMatch());
rankingDto.setEloRanking(playerRanking.getEloRanking());
rankingDto.setScoreHistogram(playerRanking.getScoreHistogram());
rankingDto.setTrueSkillRating(playerRanking.getTrueSkillRating());
rankingDto.setTrueSkillRanking(playerRanking.getTrueSkillRanking());
rankingDto.setTrueSkillMean(playerRanking.getTrueSkillMean());
rankingDto.setTrueSkillSigma(playerRanking.getTrueSkillSigma());
rankingDto.setMaxGoalsPerGame(playerRanking.getMaxGoalsPerGame());
rankingDto.setAchievementPoints(playerRanking.getAchievementPoints());
rankingDto.setBestSlam(playerRanking.getBestSlam());
rankingDto.setRankingDelta(playerRanking.getRankingDelta());
rankingDto.setEloDelta(playerRanking.getEloDelta());
playerRankingList.add(rankingDto);
}
}
return new RankingsDto(playerRankingList, createdDate);
}
public static RankingsDto convertToDto(EternalRanking ranking) {
if (ranking != null) {
return getRankingDtos(ranking.getPlayerRankings(), ranking.getCreatedDate());
}
return new RankingsDto();
}
public static RankingsDto convertToDto(Ranking ranking) {
if (ranking == null || ranking.getPlayerRankings() == null) {
return new RankingsDto();
}
return getRankingDtos(ranking.getPlayerRankings(), ranking.getCreatedDate());
}
public static RankingDto getPlayerRanking(String player, Ranking ranking) {
RankingsDto rankings = convertToDto(ranking);
for (RankingDto dto : rankings.getRankings()) {
if (dto.getPlayer().equals(player)) {
return dto;
}
}
return null;
}
public static RankingDto getPlayerRanking(String player, EternalRanking ranking) {
RankingsDto rankings = convertToDto(ranking);
for (RankingDto dto : rankings.getRankings()) {
if (dto.getPlayer().equals(player)) {
return dto;
}
}
return null;
}
}
| 44.585859 | 98 | 0.791119 |
d5a547c1e415b5cb566aa4ba3e0dc8c56fe9ed2e | 866 | package sample;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(filterName = "TimeOfDayFilter", urlPatterns = {"/resources/sample"})
public class SampleFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println(request.getLocalPort());
System.out.println(request.getLocalAddr());
System.out.println(request.getProtocol());
System.out.println(request.getServerName());
System.out.println(request.getServletContext().getContextPath());
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
| 28.866667 | 132 | 0.720554 |
a3ad0e814afbde02222027bd094a040ddc124367 | 342 | package com.piggybank.com.coins;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CoinsApplication
{
public static void main(String[] args)
{
SpringApplication.run(CoinsApplication.class,
args);
}
}
| 20.117647 | 68 | 0.751462 |
bed7caccd2350ee3bcdca9a41acea071ce56897d | 282 | package de.zalando.sprocwrapper.proxy;
import de.zalando.sprocwrapper.sharding.VirtualShardKeyStrategy;
/**
* @author Soroosh Sarabadani
*/
public class HellVirtualShardKeyStrategy extends VirtualShardKeyStrategy {
public HellVirtualShardKeyStrategy(String dummy) {
}
}
| 23.5 | 74 | 0.801418 |
714a99548a60c28e0e31c805424ec10536603a69 | 1,224 | package com.helpfooter.magicmainland.Classes.MenuExtendes;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import com.helpfooter.magicmainland.Common.StaticObject;
import com.helpfooter.magicmainland.Classes.SceneBuilder;
import com.helpfooter.magicmainland.Classes.DialogExtends.EquipmentDialog;
import com.helpfooter.magicmainland.Classes.DialogExtends.ItemShowDialog;
import com.helpfooter.magicmainland.Classes.PersonExtends.Hero;
import com.helpfooter.magicmainland.ClassesItemExtends.ItemQty;
import com.helpfooter.magicmainland.Utils.EnumControllerButton;
public class EquipmentListMenu extends BaseItemListMenu {
public EquipmentListMenu(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public void itemListInitialization(){
Hero hero=StaticObject.StarHero;
itemQties=hero.luggage.alEquipments;
itemShowDialog=new EquipmentDialog(itemQties);
}
public void buttonAEvent(){
if(itemQties.size()>0){
ItemQty iq=itemQties.get(pcoursor-1);
selectedMenu=new EquipmentLoadMenu(iq);
selectedMenu.setSuperMenu(this);
selectedMenu.initialization();
this.isOptionSeleted=true;
}
}
}
| 30.6 | 75 | 0.788399 |
8b5698634715f10771dc0b07e3d6944d8ea123c4 | 4,336 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.engine.spi;
import org.jboss.logging.Logger;
import org.hibernate.MappingException;
import org.hibernate.id.IdentifierGeneratorHelper;
import org.hibernate.internal.CoreMessageLogger;
/**
* A strategy for determining if a version value is an version of
* a new transient instance or a previously persistent transient instance.
* The strategy is determined by the <tt>unsaved-value</tt> attribute in
* the mapping file.
*
* @author Gavin King
*/
public class VersionValue implements UnsavedValueStrategy {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, VersionValue.class.getName());
private final Object value;
/**
* Assume the transient instance is newly instantiated if the version
* is null, otherwise assume it is a detached instance.
*/
public static final VersionValue NULL = new VersionValue() {
@Override
public final Boolean isUnsaved(Object version) {
LOG.trace( "Version unsaved-value strategy NULL" );
return version==null;
}
@Override
public Object getDefaultValue(Object currentValue) {
return null;
}
@Override
public String toString() {
return "VERSION_SAVE_NULL";
}
};
/**
* Assume the transient instance is newly instantiated if the version
* is null, otherwise defer to the identifier unsaved-value.
*/
public static final VersionValue UNDEFINED = new VersionValue() {
@Override
public final Boolean isUnsaved(Object version) {
LOG.trace( "Version unsaved-value strategy UNDEFINED" );
return version==null ? Boolean.TRUE : null;
}
@Override
public Object getDefaultValue(Object currentValue) {
return currentValue;
}
@Override
public String toString() {
return "VERSION_UNDEFINED";
}
};
/**
* Assume the transient instance is newly instantiated if the version
* is negative, otherwise assume it is a detached instance.
*/
public static final VersionValue NEGATIVE = new VersionValue() {
@Override
public final Boolean isUnsaved(Object version) throws MappingException {
LOG.trace( "Version unsaved-value strategy NEGATIVE" );
if (version==null) return Boolean.TRUE;
if ( version instanceof Number ) {
return ( (Number) version ).longValue() < 0l;
}
throw new MappingException( "unsaved-value NEGATIVE may only be used with short, int and long types" );
}
@Override
public Object getDefaultValue(Object currentValue) {
return IdentifierGeneratorHelper.getIntegralDataTypeHolder( currentValue.getClass() )
.initialize( -1L )
.makeValue();
}
@Override
public String toString() {
return "VERSION_NEGATIVE";
}
};
protected VersionValue() {
this.value = null;
}
/**
* Assume the transient instance is newly instantiated if
* its version is null or equal to <tt>value</tt>
* @param value value to compare to
*/
public VersionValue(Object value) {
this.value = value;
}
@Override
public Boolean isUnsaved(Object version) throws MappingException {
LOG.tracev( "Version unsaved-value: {0}", value );
return version==null || version.equals(value);
}
@Override
public Object getDefaultValue(Object currentValue) {
return value;
}
@Override
public String toString() {
return "version unsaved-value: " + value;
}
} | 31.42029 | 128 | 0.736162 |
4bfeaa92502264b9c4e608eaa4ec3d186121ac5b | 854 | package brige;
/**
* @author : CodeWater
* @create :2022-05-10-16:12
* @Function Description :
*/
public class Client {
public static void main(String[] args) {
//获取折叠式手机 (样式 + 品牌 )
Phone phone1 = new FoldedPhone(new XiaoMi());
phone1.open();
phone1.call();
phone1.close();
System.out.println("=======================");
Phone phone2 = new FoldedPhone(new Vivo());
phone2.open();
phone2.call();
phone2.close();
System.out.println("==============");
UpRightPhone phone3 = new UpRightPhone(new XiaoMi());
phone3.open();
phone3.call();
phone3.close();
System.out.println("==============");
UpRightPhone phone4 = new UpRightPhone(new Vivo());
phone4.open();
phone4.call();
phone4.close();
}
}
| 26.6875 | 61 | 0.517564 |
9088be45fc51a2f5ad6d7edcf0912dd05b593196 | 64 | /**
* 画面オンライン処理方式の主要APIを収めたパッケージ。
*/
package nablarch.fw.web;
| 12.8 | 30 | 0.71875 |
07d2ff927c2ee52b5daec5f29925916289773732 | 2,221 | /*
* ******************************************************************************
* Copyright 2011-2015 CovertJaguar
*
* This work (the API) is licensed under the "MIT" License, see LICENSE.md for details.
* ***************************************************************************
*/
package mods.railcraft.api.core.items;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
/**
*
* @author CovertJaguar <http://www.railcraft.info>
*/
public interface IToolCrowbar {
/**
* Controls non-rotational interactions with blocks. Crowbar specific stuff.
*
* Rotational interaction is handled by the Block.rotateBlock() function,
* which should be called from the Item.onUseFirst() function of your tool.
*
* @param player
* @param crowbar
* @param x
* @param y
* @param z
* @return
*/
public boolean canWhack(EntityPlayer player, ItemStack crowbar, int x, int y, int z);
/**
* Callback to do damage to the item.
*
* @param player
* @param crowbar
* @param x
* @param y
* @param z
*/
public void onWhack(EntityPlayer player, ItemStack crowbar, int x, int y, int z);
/**
* Controls whether you can link a cart.
*
* @param player
* @param crowbar
* @param cart
* @return
*/
public boolean canLink(EntityPlayer player, ItemStack crowbar, EntityMinecart cart);
/**
* Callback to do damage.
*
* @param player
* @param crowbar
* @param cart
*/
public void onLink(EntityPlayer player, ItemStack crowbar, EntityMinecart cart);
/**
* Controls whether you can boost a cart.
*
* @param player
* @param crowbar
* @param cart
* @return
*/
public boolean canBoost(EntityPlayer player, ItemStack crowbar, EntityMinecart cart);
/**
* Callback to do damage, boosting a cart usually does more damage than
* normal usage.
*
* @param player
* @param crowbar
* @param cart
*/
public void onBoost(EntityPlayer player, ItemStack crowbar, EntityMinecart cart);
}
| 26.129412 | 89 | 0.584421 |
50beac07025dcc7c5a0e6170a6ece483ff8e5f95 | 3,160 | package com.yapp18.retrospect.service;
import com.yapp18.retrospect.domain.user.User;
import com.yapp18.retrospect.domain.user.UserRepository;
import com.yapp18.retrospect.exception.OAuth2AuthenticationProcessingException;
import com.yapp18.retrospect.security.UserPrincipal;
import com.yapp18.retrospect.security.oauth2.AuthProvider;
import com.yapp18.retrospect.security.oauth2.user.OAuth2UserInfo;
import com.yapp18.retrospect.security.oauth2.user.OAuth2UserInfoFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Optional;
@RequiredArgsConstructor
@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private final UserRepository userRepository;
private final UserService userService;
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(userRequest);
try {
return processOAuth2User(userRequest, oAuth2User);
} catch (AuthenticationException ex) {
throw ex;
} catch (Exception ex) {
// Throwing an instance of AuthenticationException will trigger the OAuth2AuthenticationFailureHandler
throw new InternalAuthenticationServiceException(ex.getMessage(), ex.getCause());
}
}
private OAuth2User processOAuth2User(OAuth2UserRequest userRequest, OAuth2User oAuth2User){
String registrationId = userRequest.getClientRegistration().getRegistrationId();
OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(registrationId, oAuth2User.getAttributes());
if(!StringUtils.hasText(oAuth2UserInfo.getEmail())) {
throw new OAuth2AuthenticationProcessingException("OAuth2 공급자(구글, 카카오, ...) 에서 이메일을 찾을 수 없습니다.");
}
Optional<User> userOptional = userRepository.findByEmail(oAuth2UserInfo.getEmail());
User user;
boolean isNew = false;
if(userOptional.isPresent()) {
user = userOptional.get();
if(!user.getProvider().equals(AuthProvider.valueOf(registrationId))) {
throw new OAuth2AuthenticationProcessingException(
user.getProvider() + " 계정을 사용하기 위해서 로그인을 해야 합니다.");
}
} else {
isNew = true;
user = userService.registerNewUser(registrationId, oAuth2UserInfo);
}
return UserPrincipal.builder()
.user(user)
.attributes(oAuth2UserInfo.getAttributes())
.isNew(isNew)
.build();
}
}
| 44.507042 | 124 | 0.738291 |
12b444a60f6209c74abfc08cbfc2dca0db44e566 | 6,530 | /*
* 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 co.edu.uniandes.csw.escarabajos.resources;
import co.edu.uniandes.csw.escarabajos.dtos.ListaDeseosDetailDTO;
import co.edu.uniandes.csw.escarabajos.dtos.ClienteDTO;
import co.edu.uniandes.csw.escarabajos.ejb.ListaDeseosLogic;
import co.edu.uniandes.csw.escarabajos.ejb.ClienteLogic;
import co.edu.uniandes.csw.escarabajos.entities.ListaDeseosEntity;
import co.edu.uniandes.csw.escarabajos.entities.ClienteEntity;
import co.edu.uniandes.csw.escarabajos.exceptions.BusinessLogicException;
import co.edu.uniandes.csw.escarabajos.mappers.BusinessLogicExceptionMapper;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
/**
* <pre>Clase que implementa el recurso "listadeseos".
* URL: /api/clientes/{idCliente}/listadeseos
* </pre>
* <i>Note que la aplicación (definida en {@link RestConfig}) define la ruta
* "/api" y este recurso tiene la ruta "listadeseos".</i>
*
* <h2>Anotaciones </h2>
* <pre>
* Path: indica la dirección después de "api" para acceder al recurso
* Produces/Consumes: indica que los servicios definidos en este recurso reciben y devuelven objetos en formato JSON
* RequestScoped: Inicia una transacción desde el llamado de cada método (servicio).
* </pre>
*
* @author Mateo
* @version 1.0
*/
@Path("clientes/{idCliente: \\d+}/listadeseos")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RequestScoped
public class ClienteListaDeseosResource {
/**
* Inyecta la logica de lista de deseos.
*/
@Inject
ListaDeseosLogic logic;
/**
* Inyecta la logica de cliente.
*/
@Inject
ClienteLogic logicCliente;
/**
* Constante que modela el string no existe.
*/
private static final String NOEXISTE = "No existe";
/**
* <h1>POST /api/clientes/{idCLiente}/listadeseos : Agrega el
* listadeseos.</h1>
* no deberia haber esta solicitud http porque el listadeseos se agrega
* automaticamente cuando se crea el cliente se creo solo por motivos de
* prueba ya que clienteResource aun no funciona. En un futuro deberia
* borrarse.
*/
@POST
public ListaDeseosDetailDTO createListaDeseosDeCliente(@PathParam("idCliente") Long idCliente) throws BusinessLogicException {
ClienteEntity clienteEntity = logicCliente.getCliente(idCliente);
if (clienteEntity == null) {
throw new WebApplicationException("El recurso /clientes/" + idCliente + NOEXISTE, 404);
}
if (clienteEntity.getListaDeseos() != null) {
throw new WebApplicationException("El recurso /clientes/" + idCliente + " ya tiene un listadeseos.", 400);
}
ListaDeseosDetailDTO listadeseos = new ListaDeseosDetailDTO(new ClienteDTO(clienteEntity));
ListaDeseosEntity listadeseosEntity = logic.createListaDeseos(listadeseos.toEntity());
return new ListaDeseosDetailDTO(listadeseosEntity);
}
/**
* <h1>GET /api/clientes/{idCliente}/listadeseos : Obtener el listadeseos
* del cliente.</h1>
*
* <pre>Busca y devuelve el listadeseos del cliente.
*
* Codigos de respuesta:
* <code style="color: mediumseagreen; background-color: #eaffe0;">
* 200 OK Devueve el listadeseos del cliente.</code>
* <code style="color: #c7254e; background-color: #f9f2f4;">
* 412 Precodition Failed: No existe el cliente.
* </code>
* </pre>
*
* @param idCliente Identificador del cliente dueño del listadeseos que se
* desa buscar. Este debe ser una cadena de dígitos.
* @return JSON {@link ListaDeseosDetailDTO} - el listadeseos buscado.
*/
@GET
public ListaDeseosDetailDTO getListaDeseos(@PathParam("idCliente") Long idCliente) throws BusinessLogicException {
ClienteEntity cliente = logicCliente.getCliente(idCliente);
if (cliente == null) {
throw new WebApplicationException("El recurso /cliente/" + idCliente + NOEXISTE, 404);
}
ListaDeseosEntity listadeseos = logic.getListaDeseosByClienteId(idCliente);
if (listadeseos == null) {
return createListaDeseosDeCliente(idCliente);
} else {
return new ListaDeseosDetailDTO(listadeseos);
}
}
/**
* <h1>PUT /api/clientes/{idCLiente}/listadeseos : Actualizar el listadeseos
* del cliente.</h1>
* <pre>Cuerpo de petición: JSON {@link ListaDeseosDetailDTO}.
*
* Actualiza el listadeseos del cliente.
*
* Codigos de respuesta:
* <code style="color: mediumseagreen; background-color: #eaffe0;">
* 200 OK Actualiza el listadeseos del cliente. Retorna un objeto identico.</code>
* </pre>
*
* @return JSON {@link ListaDeseosDetailDTO} - El listadeseos actualizado.
* @throws BusinessLogicException {@link BusinessLogicExceptionMapper} -
* Error de lógica que se genera al no poder actualizar el listadeseos.
*/
@PUT
public ListaDeseosDetailDTO updateListaDeseos(@PathParam("idCliente") Long idCliente, ListaDeseosDetailDTO listadeseos) throws BusinessLogicException {
ClienteEntity cliente = logicCliente.getCliente(idCliente);
if (cliente == null) {
throw new WebApplicationException("El recurso /cliente/" + idCliente + NOEXISTE, 404);
}
ListaDeseosEntity listadeseosLlega = listadeseos.toEntity();
Double precio = listadeseosLlega.getPrecioTotal();
ListaDeseosEntity listadeseos2 = logic.getListaDeseosByClienteId(idCliente);
listadeseos2.setPrecioTotal(precio);
return new ListaDeseosDetailDTO(logic.updateListaDeseos(listadeseos2));
}
/**
* <h1>DELETE /api/clientes/{idCLiente}/listadeseos : Agrega el
* listadeseos.</h1>
* no deberia haber esta solicitud http porque el listadeseos se borra
* automaticamente cuando se borra el cliente
*/
}
| 36.480447 | 156 | 0.684227 |
8d77cf06c450b93ad5081890a7463610998c5065 | 372 | package org.svgroz.vacationdb.datastore.api.model.table;
import org.svgroz.vacationdb.datastore.api.model.row.Row;
/**
* @author Simon Grozovsky [email protected]
*/
public interface MutableTable extends Table {
/**
* @param row supposed to be not null
* @return false if table already has had row with same keys
*/
boolean addRow(Row row);
}
| 23.25 | 64 | 0.706989 |
a0a646be8b3ab846bdea20c27337505248c8e578 | 538 | package com.soze.common.exceptions;
/**
* Requires to use either of parent's constuctors (for logging),
* but this information should not be exposed to the user.
* A generic "invalid username or password" should be returned instead.
* @author sozek
*
*/
@SuppressWarnings("serial")
public class CannotLoginException extends RuntimeException {
public CannotLoginException(String message) {
super(message);
}
public CannotLoginException(String message, Throwable cause) {
super(message, cause);
}
}
| 24.454545 | 72 | 0.72119 |
559730511e517d18e61f5d42152e19c78ca71137 | 1,112 | package com.elvin.io.tcpip;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* @author : Haifeng Pang.
* @version 0.1 : ServerHandler v0.1 2018/5/27 21:09 By Haifeng Pang.
* @description :
*/
public class ServerHandler implements Runnable {
private Socket socket;
public ServerHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(), true);
String body = null;
while (true) {
body = in.readLine();
if (body == null) {
break;
}
System.out.println("Server :" + body);
out.println("服务器端回送响的应数据.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 25.860465 | 89 | 0.566547 |
6f8854b355f8d0616a9cf981f55c74a9eef7739c | 1,903 | package com.siyehua.wechathotfix;
import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Build;
import android.support.multidex.MultiDex;
import com.tencent.tinker.anno.DefaultLifeCycle;
import com.tencent.tinker.lib.tinker.TinkerInstaller;
import com.tencent.tinker.loader.app.DefaultApplicationLike;
import com.tencent.tinker.loader.shareutil.ShareConstants;
/**
* Created by siyehua on 2016/11/15.
*/
@DefaultLifeCycle(application = BuildConfig.APPLICATION_NAME,
flags = ShareConstants.TINKER_ENABLE_ALL,
loadVerifyFlag = false)
public class SampleApplicationLike extends DefaultApplicationLike {
public SampleApplicationLike(Application application, int tinkerFlags, boolean
tinkerLoadVerifyFlag, long applicationStartElapsedTime, long
applicationStartMillisTime, Intent tinkerResultIntent, Resources[] resources,
ClassLoader[] classLoader, AssetManager[] assetManager) {
super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime,
applicationStartMillisTime, tinkerResultIntent, resources, classLoader,
assetManager);
}
@Override
public void onBaseContextAttached(Context base) {
super.onBaseContextAttached(base);
MultiDex.install(base);
TinkerInstaller.install(this);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback) {
getApplication().registerActivityLifecycleCallbacks(callback);
}
@Override
public void onCreate() {
super.onCreate();
//set content form your old custom application
}
}
| 38.836735 | 101 | 0.753022 |
14e813170c891aed7e7ed1a49cd3825d3a2e31c4 | 195 | package substitute;
import java.io.IOException;
import substitute.model.Parameter;
public interface Analyzer {
void showHelp();
void analyze(final Parameter p) throws IOException;
}
| 15 | 55 | 0.758974 |
47deb534e98271caa21a06b4705bdee9c7bbb177 | 712 | package net.darkmorford.pleasewait;
import net.darkmorford.pleasewait.message.MessageStreamStatus;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
public class PacketHandler
{
public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel(PleaseWait.MODID);
public static void registerMessages()
{
// Packets sent from the server to the client
INSTANCE.registerMessage(MessageStreamStatus.Handler.class, MessageStreamStatus.class, 0, Side.CLIENT);
// Packets sent from the client to the server
}
}
| 35.6 | 116 | 0.792135 |
1a32f6dbe3557452398360c5bf0553466fa8abb2 | 382 | package forestry.api.apiculture;
import java.util.ArrayList;
import forestry.api.genetics.IFlowerProvider;
import net.minecraft.item.ItemStack;
public class FlowerManager {
/**
* ItemStacks representing simple flower blocks. Meta-sensitive, processed by the basic {@link IFlowerProvider}.
*/
public static ArrayList<ItemStack> plainFlowers = new ArrayList<ItemStack>();
}
| 25.466667 | 113 | 0.78534 |
78b165753b0061f294ac92aa9d151b7281a11b80 | 2,667 | /*
* 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 org.mage.test.cards.single.soi;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestPlayerBase;
/**
* Tests for Asylum Visitor:
* {1}{B} 3/1 Vampire Wizard Creature
*
* At the beginning of each player's upkeep, if that player has no cards in hand, you draw a card and you lose 1 life.
* Madness {1}{B}
*
* @author escplan9 (Derek Monturo - dmontur1 at gmail dot com)
*/
public class AsylumVisitorTest extends CardTestPlayerBase {
/**
* No cards in own hand - draw card and lose life.
*/
@Test
public void testNoCardsInOwnHand() {
addCard(Zone.BATTLEFIELD, playerA, "Asylum Visitor", 1);
setStopAt(1, PhaseStep.UPKEEP);
execute();
assertLife(playerA, 19);
assertLife(playerB, 20);
assertHandCount(playerA, 1);
}
/**
* Cards in own hand.
*/
@Test
public void testCardsInOwnHand() {
addCard(Zone.BATTLEFIELD, playerA, "Asylum Visitor", 1);
addCard(Zone.HAND, playerA, "Bronze Sable", 3); // 2/1 artifact creature
setStopAt(1, PhaseStep.UPKEEP);
execute();
assertLife(playerA, 20);
assertLife(playerB, 20);
assertHandCount(playerA, 3); // 3 bronze sables!
}
/**
* No cards in opponent's hand - draw card and lose life.
*/
@Test
public void testNoCardsInOpponentsHand() {
addCard(Zone.HAND, playerA, "Asylum Visitor", 1);
addCard(Zone.BATTLEFIELD, playerA, "Swamp", 3);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Asylum Visitor");
setStopAt(2, PhaseStep.UPKEEP);
execute();
assertLife(playerA, 19);
assertLife(playerB, 20);
assertHandCount(playerA, 1);
}
/**
* Cards in opponent's hand.
*/
@Test
public void testCardsInOpponentsHand() {
addCard(Zone.HAND, playerA, "Asylum Visitor", 1);
addCard(Zone.BATTLEFIELD, playerA, "Swamp", 3);
addCard(Zone.HAND, playerB, "Bronze Sable", 3); // 2/1 artifact creature
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Asylum Visitor");
setStopAt(2, PhaseStep.UPKEEP);
execute();
assertLife(playerA, 20);
assertLife(playerB, 20);
assertHandCount(playerA, 0);
assertHandCount(playerB, 3); // 3 bronze sables!
}
}
| 28.37234 | 118 | 0.616048 |
64dfbefdeaecf95887410c3bc24a7fa85f9edbcb | 2,539 | package com.simpligility.maven.plugins.android.config;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.testing.stubs.MavenProjectStub;
import org.apache.maven.project.MavenProject;
import org.junit.Before;
import org.junit.Test;
import com.simpligility.maven.plugins.android.config.ConfigHandler;
public class ConfigHandlerTest {
private DummyMojo mojo = new DummyMojo();
private MavenSession session;
private MojoExecution execution;
@Before
public void setUp()
{
session = createNiceMock( MavenSession.class );
final MavenProject project = new MavenProjectStub();
MojoDescriptor mojoDesc = new MojoDescriptor();
this.execution = new MojoExecution( mojoDesc );
expect( session.getExecutionProperties() ).andReturn( project.getProperties() );
expect( session.getCurrentProject() ).andReturn( project );
replay( session );
}
@Test
public void testParseConfigurationDefault() throws Exception {
ConfigHandler configHandler = new ConfigHandler( mojo, this.session, this.execution );
configHandler.parseConfiguration();
assertTrue(mojo.getParsedBooleanValue());
}
@Test
public void testParseConfigurationFromConfigPojo() throws Exception {
mojo.setConfigPojo(new DummyConfigPojo("from config pojo", null));
ConfigHandler configHandler = new ConfigHandler( mojo, this.session, this.execution );
configHandler.parseConfiguration();
assertEquals("from config pojo",mojo.getParsedStringValue());
}
@Test
public void testParseConfigurationFromMaven() throws Exception {
mojo.setConfigPojoStringValue("maven value");
ConfigHandler configHandler = new ConfigHandler( mojo, this.session, this.execution );
configHandler.parseConfiguration();
assertEquals("maven value",mojo.getParsedStringValue());
}
@Test
public void testParseConfigurationDefaultMethodValue() throws Exception {
ConfigHandler configHandler = new ConfigHandler( mojo, this.session, this.execution );
configHandler.parseConfiguration();
assertArrayEquals(new String[] {"a","b"},mojo.getParsedMethodValue());
}
}
| 35.263889 | 94 | 0.767625 |
8b465f7e7d7b0a626f6127c4ad7543bf806db36b | 2,342 | package com.dm.material.dashboard.candybar.helpers;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.Log;
import com.dm.material.dashboard.candybar.utils.LogUtil;
import java.util.Locale;
/*
* CandyBar - Material Dashboard
*
* Copyright (c) 2014-2016 Dani Mahardhika
*
* 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.
*/
class LocaleHelper {
@Nullable
static String getOtherAppLocaleName(Context context, Locale locale, String packageName) {
try {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo info = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
Resources res = packageManager.getResourcesForApplication(packageName);
Context otherAppContext = context.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);
Configuration configuration = new Configuration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration = res.getConfiguration();
configuration.setLocale(locale);
return otherAppContext.createConfigurationContext(configuration).getString(info.labelRes);
}
configuration.locale = locale;
res.updateConfiguration(configuration, context.getResources().getDisplayMetrics());
return res.getString(info.labelRes);
} catch (Exception e) {
LogUtil.e(Log.getStackTraceString(e));
}
return null;
}
}
| 39.033333 | 114 | 0.703245 |
918a98ca5cc2906f53d304ebb10575463b299d71 | 5,168 | package net.i2p.android.i2ptunnel.preferences;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceGroup;
import android.support.v7.preference.PreferenceScreen;
import android.widget.Toast;
import net.i2p.android.i2ptunnel.util.SaveTunnelTask;
import net.i2p.android.i2ptunnel.util.TunnelUtil;
import net.i2p.android.preferences.util.CustomPreferenceFragment;
import net.i2p.android.router.R;
import net.i2p.android.router.util.Util;
import net.i2p.i2ptunnel.TunnelControllerGroup;
import net.i2p.i2ptunnel.ui.TunnelConfig;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
public abstract class BaseTunnelPreferenceFragment extends CustomPreferenceFragment {
protected static final String ARG_TUNNEL_ID = "tunnelId";
protected TunnelControllerGroup mGroup;
protected int mTunnelId;
@Override
public void onCreatePreferences(Bundle paramBundle, String s) {
String error;
try {
mGroup = TunnelControllerGroup.getInstance();
error = mGroup == null ? getResources().getString(R.string.i2ptunnel_not_initialized) : null;
} catch (IllegalArgumentException iae) {
mGroup = null;
error = iae.toString();
}
if (mGroup == null) {
Toast.makeText(getActivity().getApplicationContext(),
error, Toast.LENGTH_LONG).show();
getActivity().finish();
} else if (getArguments().containsKey(ARG_TUNNEL_ID)) {
mTunnelId = getArguments().getInt(ARG_TUNNEL_ID, 0);
try {
TunnelUtil.writeTunnelToPreferences(getActivity(), mGroup, mTunnelId);
} catch (IllegalArgumentException e) {
// Tunnel doesn't exist, or the tunnel config file could not be read
Util.e("Could not load tunnel details", e);
Toast.makeText(getActivity().getApplicationContext(),
R.string.i2ptunnel_no_tunnel_details, Toast.LENGTH_LONG).show();
getActivity().finish();
}
// https://stackoverflow.com/questions/17880437/which-settings-file-does-preferencefragment-read-write
getPreferenceManager().setSharedPreferencesName(TunnelUtil.getPreferencesFilename(mTunnelId));
try {
loadPreferences();
} catch (IllegalArgumentException iae) {
// mGroup couldn't load its config file
Toast.makeText(getActivity().getApplicationContext(),
iae.toString(), Toast.LENGTH_LONG).show();
getActivity().finish();
}
}
}
@Override
public void onPause() {
super.onPause();
// Pre-Honeycomb: onPause() is the last method guaranteed to be called.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
saveTunnel();
}
@Override
public void onStop() {
super.onStop();
// Honeycomb and above: onStop() is the last method guaranteed to be called.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
saveTunnel();
}
private void saveTunnel() {
if (mGroup != null) {
TunnelConfig cfg = TunnelUtil.createConfigFromPreferences(getActivity(), mGroup, mTunnelId);
SaveTunnelTask task = new SaveTunnelTask(mGroup, mTunnelId, cfg);
try {
// TODO: There used to be a possible ANR here, because the underlying I2P code
// checks if the session is open as part of updating its config. We may need to save
// completely asynchronously (and ensure we do actually save before the app closes).
task.execute().get(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Util.e("Interrupted while saving tunnel config", e);
} catch (ExecutionException e) {
Util.e("Error while saving tunnel config", e);
} catch (CancellationException e) {
Util.e("Cancelled while saving tunnel config", e);
} catch (TimeoutException e) {
Util.e("Timed out while savomg tunnel config", e);
}
}
}
protected abstract void loadPreferences();
/**
* http://stackoverflow.com/a/20806812
*
* @param id the Preferences XML to load
* @param newParent the parent PreferenceGroup to add the new Preferences to.
*/
protected void addPreferencesFromResource(int id, PreferenceGroup newParent) {
PreferenceScreen screen = getPreferenceScreen();
int last = screen.getPreferenceCount();
addPreferencesFromResource(id);
while (screen.getPreferenceCount() > last) {
Preference p = screen.getPreference(last);
screen.removePreference(p); // decreases the preference count
newParent.addPreference(p);
}
}
}
| 41.015873 | 114 | 0.643769 |
b35828e15c6dba91664936542e631518e18b8260 | 5,305 | package com.sleepy.blog.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sleepy.blog.common.Constant;
import com.sleepy.blog.entity.ImgEntity;
import com.sleepy.blog.repository.ImgRepository;
import com.sleepy.blog.service.CacheService;
import com.sleepy.blog.service.ImgService;
import com.sleepy.blog.util.DateUtil;
import com.sleepy.blog.util.FileUtil;
import com.sleepy.blog.util.ImageUtil;
import com.sleepy.blog.util.StringUtil;
import com.sleepy.blog.vo.ImgVO;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 图片服务实现类
*
* @author gehoubao
* @create 2019-10-30 16:05
**/
@Service
@Slf4j
public class ImgServiceImpl implements ImgService {
@Autowired
CacheService cacheService;
@Autowired
ImgRepository imgRepository;
@Override
public byte[] getImg(HttpServletResponse response, String id) throws IOException {
String imgPath;
if (id.contains(Constant.POINT)) {
imgPath = cacheService.getCache("ImageLocalPath") + "resource/" + id;
} else {
imgPath = cacheService.getCache("ImageLocalPath") + imgRepository.findLocalPathById(id);
}
File file = new File(imgPath);
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
inputStream.close();
return bytes;
}
@Override
public void compressImg(HttpServletResponse response, String ratio, String url) {
OutputStream outputStream = null;
try {
if (url != null) {
URL path = new URL(StringUtil.formatUrl(url));
response.setContentType("image/jpeg");
response.addHeader("Connection", "keep-alive");
response.addHeader("Cache-Control", "max-age=604800");
outputStream = response.getOutputStream();
Thumbnails.of(path).scale(Float.parseFloat(ratio)).outputFormat("jpeg").toOutputStream(outputStream);
}
} catch (NumberFormatException e) {
log.error("图片压缩失败,ratio值应为float类型,如ratio=0.25f(缩小至0.25倍),失败URL:{}", url);
} catch (Exception e) {
e.printStackTrace();
log.error("{} 获取图片失败!{} {}", "/compress请求", e.getMessage(), url);
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
log.error("{} 流关闭失败!{}", "/compress请求", e.getMessage());
}
}
}
@Override
public String upload(ImgVO vo) throws IOException {
ImgEntity entity = JSON.parseObject(JSON.toJSONString(vo), ImgEntity.class);
Date current = DateUtil.getDateWithCurrent(0, Calendar.DAY_OF_YEAR);
if (StringUtil.isNullOrEmpty(entity.getType())) {
entity.setType(Constant.IMG_TYPE_OTHERS);
}
// 图片名称的路径: 图片的类型/图片上传日期/图片的UUID, 例如: 封面/2019-10-31/2fc9e266e21f4fe18f92da2fc56567f8
String randomName = entity.getType() + File.separator + DateUtil.dateFormat(current, DateUtil.DEFAULT_DATE_PATTERN) + File.separator + StringUtil.getRandomUuid("");
String imgPath = ImageUtil.base64ToImgFile(vo.getImgOfBase64(), cacheService.getCache("ImageLocalPath") + randomName);
try {
FileUtil.ImgMetaHolder imgMetaHolder = new FileUtil.ImgMetaHolder(imgPath);
Map imgMeta = imgMetaHolder.getMetaInfo();
entity.setUploadTime(current);
entity.setPath(imgPath.substring(cacheService.getCache("ImageLocalPath").length()));
entity.setCreateTime(imgMeta.get("创建时间") != null ? DateUtil.toDate(imgMeta.get("创建时间").toString(), DateUtil.DEFAULT_DATETIME_PATTERN) : current);
entity.setImgSize(imgMeta.get("图片大小").toString());
entity.setImgFormat(imgMeta.get("图片格式").toString());
entity.setResolutionRatio(imgMeta.get("宽") + " × " + imgMeta.get("高"));
entity = imgRepository.save(entity);
} catch (Exception e) {
File file = new File(imgPath);
file.delete();
throw e;
}
Map<String, Object> result = new HashMap<>(2);
result.put("id", entity.getId());
result.put("url", Constant.IMG_SERVER_URL_PLACEHOLDER + entity.getId());
return new JSONObject(result).toJSONString();
}
@Override
public String delete(ImgVO vo) throws IOException {
if (!StringUtil.isNullOrEmpty(vo.getId())) {
String imgPath = cacheService.getCache("ImageLocalPath") + imgRepository.findLocalPathById(vo.getId());
File file = new File(imgPath);
file.delete();
imgRepository.deleteById(vo.getId());
}
return "success";
}
} | 40.496183 | 172 | 0.652969 |
393e55bf500201fb9591c867dc95d7b0faee26fd | 1,343 | package sample;
import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
public class Producer {
public static void main(String[] args) throws Exception {
final Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "cloudera-01.tambunan.com:9092");
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.RETRIES_CONFIG, 0);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://cloudera-01.tambunan.com:8081");
KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props);
for (int i = 0; i < 10; i++) {
ProducerRecord<String, String> record = new ProducerRecord<String, String>("lizzy", "lizzy", "value");
producer.send(record).get();
}
}
}
| 44.766667 | 115 | 0.744602 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.