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
1de24bfaa96ba4fd8aa330a3e250ce393a9c9c9a
465
package jpabook.jpashop.repository; import jpabook.jpashop.domain.Order; import jpabook.jpashop.repository.custom.CustomOrderRepository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * User: HolyEyE * Date: 2013. 12. 3. Time: 오후 10:28 */ public interface OrderRepository extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order>, CustomOrderRepository { }
31
125
0.815054
9f21c2f4bc7f86422974dacc74a19aff88a576fe
4,112
/* * 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 ns_graph; import javax.swing.JPanel; /** * * @author liuyupeng */ public class JDW extends javax.swing.JPanel { /** * Creates new form JDW */ public JDW() { initComponents(); } public JDW(String text) { initComponents(); jLabel1.setText(text); } public JPanel getPanelLoop(){ return jPanelLoop; } /** * 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() { jPanelLoop = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(50, 0), new java.awt.Dimension(50, 0), new java.awt.Dimension(50, 32767)); setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); setPreferredSize(new java.awt.Dimension(500, 500)); jPanelLoop.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanelLoop.setPreferredSize(new java.awt.Dimension(450, 450)); javax.swing.GroupLayout jPanelLoopLayout = new javax.swing.GroupLayout(jPanelLoop); jPanelLoop.setLayout(jPanelLoopLayout); jPanelLoopLayout.setHorizontalGroup( jPanelLoopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanelLoopLayout.setVerticalGroup( jPanelLoopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 565, Short.MAX_VALUE) ); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("jLabel1"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 341, Short.MAX_VALUE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelLoop, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelLoop, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE) .addComponent(filler1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.Box.Filler filler1; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanelLoop; // End of variables declaration//GEN-END:variables }
42.833333
156
0.684095
498146277160ab8cee43c6bdb6c3dd1cdd9cc614
1,514
package it.auties.whatsapp4j.protobuf.message.model; import com.fasterxml.jackson.annotation.JsonProperty; import it.auties.whatsapp4j.protobuf.info.ContextInfo; import it.auties.whatsapp4j.protobuf.message.business.ProductMessage; import it.auties.whatsapp4j.protobuf.message.business.TemplateButtonReplyMessage; import it.auties.whatsapp4j.protobuf.message.business.TemplateMessage; import it.auties.whatsapp4j.protobuf.message.standard.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import lombok.experimental.SuperBuilder; /** * A model interface that represents a WhatsappMessage sent by a contact that provides a context. * Classes that implement this interface provide an accessor named contextInfo to access said property. * * This interface is sealed to prepare for <a href="https://openjdk.java.net/jeps/406">pattern matching for instanceof in switch statements</a>, set to be released in Java 17. */ @AllArgsConstructor @NoArgsConstructor @SuperBuilder(buildMethodName = "create") @Data @Accessors(fluent = true) public sealed abstract class ContextualMessage implements Message permits ContactMessage, ProductMessage, TemplateButtonReplyMessage, ContactsArrayMessage, TextMessage, GroupInviteMessage, LiveLocationMessage, LocationMessage, MediaMessage, TemplateMessage { /** * The context info of this message */ @JsonProperty(value = "17") private ContextInfo contextInfo; }
43.257143
175
0.806473
8da55d9be1345fcb4750a309539841ddd328c2f0
653
package org.kilocraft.essentials.config.messages.sections; import ninja.leaping.configurate.objectmapping.Setting; import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; @ConfigSerializable public class EventsConfigSection { @Setting(value = "disableOnProxyMode", comment = "If set to true and the Proxy Mode is also enabled the event messages will be disabled") public boolean disableOnProxyMode = false; @Setting(value = "userJoin") public String userJoin = "&e%USER_DISPLAYNAME%&e joined the game"; @Setting(value = "userLeave") public String userLeave = "&e%USER_DISPLAYNAME%&e left the game."; }
34.368421
141
0.767228
a614bf8fc2ffa3dbddcddf9229966e56f64548b2
7,509
/*- * ========================LICENSE_START================================= * JSoagger * %% * Copyright (C) 2019 JSOAGGER * %% * 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. * =========================LICENSE_END================================== */ package io.github.jsoagger.cloud.stub.operations; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Properties; import java.util.function.Consumer; import io.github.jsoagger.core.bridge.operation.IOperation; import io.github.jsoagger.core.bridge.operation.IOperationResult; import io.github.jsoagger.core.bridge.result.MultipleResult; import io.github.jsoagger.core.bridge.result.OperationData; import io.github.jsoagger.core.utils.FileUtils; import io.github.jsoagger.core.utils.StringUtils; import com.google.gson.JsonObject; /** * @author Ramilafananana VONJISOA * */ public class StubGetIllustrationOperation implements IOperation { private static String DATASET_IMAGE_LOCATION = "io.github.jsoagger.demoapp.dataset.image.location"; @SuppressWarnings("unused") private static String DATASET = "demo.data.set.key"; Properties platformProperties; IOperation getPreferenceValueOperation; private String imagesLocation; /** * {@inheritDoc} */ @Override public void doOperation(JsonObject params, Consumer<IOperationResult> resultHandler, Consumer<Throwable> exHandler) { loadImagesLocation(); MultipleResult multipleResult = new MultipleResult(); List<OperationData> datas = new ArrayList<>(); multipleResult.setData(datas); if (StringUtils.isNotBlank(imagesLocation)) { try { byte[] one = FileUtils.toByteArray(new File(imagesLocation + "/12.png")); OperationData dataone = new OperationData(); dataone.getAttributes().put("illustration", Base64.getEncoder().encode(one)); datas.add(dataone); byte[] two = FileUtils.toByteArray(new File(imagesLocation + "/13.png")); OperationData datatwo = new OperationData(); datatwo.getAttributes().put("illustration", Base64.getEncoder().encode(two)); datas.add(datatwo); byte[] three = FileUtils.toByteArray(new File(imagesLocation + "/14.png")); OperationData datathree = new OperationData(); datathree.getAttributes().put("illustration", Base64.getEncoder().encode(three)); datas.add(datathree); byte[] four = FileUtils.toByteArray(new File(imagesLocation + "/15.png")); OperationData datafour = new OperationData(); datafour.getAttributes().put("illustration", Base64.getEncoder().encode(four)); datas.add(datafour); byte[] five = FileUtils.toByteArray(new File(imagesLocation + "/16.png")); OperationData datafive = new OperationData(); datafive.getAttributes().put("illustration", Base64.getEncoder().encode(five)); datas.add(datafive); } catch (Exception e) { // e.printStackTrace(); } } else { try { byte[] one = getBytesFromInputStream(StubGetIllustrationOperation.class.getResourceAsStream("/defaultimages" + "/12.png")); OperationData dataone = new OperationData(); dataone.getAttributes().put("illustration", Base64.getEncoder().encode(one)); datas.add(dataone); byte[] two = getBytesFromInputStream(StubGetIllustrationOperation.class.getResourceAsStream("/defaultimages" + "/13.png")); OperationData datatwo = new OperationData(); datatwo.getAttributes().put("illustration", Base64.getEncoder().encode(two)); datas.add(datatwo); byte[] three = getBytesFromInputStream(StubGetIllustrationOperation.class.getResourceAsStream("/defaultimages" + "/14.png")); OperationData datathree = new OperationData(); datathree.getAttributes().put("illustration", Base64.getEncoder().encode(three)); datas.add(datathree); byte[] four = getBytesFromInputStream(StubGetIllustrationOperation.class.getResourceAsStream("/defaultimages" + "/15.png")); OperationData datafour = new OperationData(); datafour.getAttributes().put("illustration", Base64.getEncoder().encode(four)); datas.add(datafour); byte[] five = getBytesFromInputStream(StubGetIllustrationOperation.class.getResourceAsStream("/defaultimages" + "/16.png")); OperationData datafive = new OperationData(); datafive.getAttributes().put("illustration", Base64.getEncoder().encode(five)); datas.add(datafive); } catch (Exception e) { // e.printStackTrace(); } } resultHandler.accept(multipleResult); } public static byte[] getBytesFromInputStream(InputStream is) { ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[0xFFFF]; try { for (int len = is.read(buffer); len != -1; len = is.read(buffer)) { os.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } byte[] b = os.toByteArray(); try { is.close(); os.close(); } catch (IOException e) { e.printStackTrace(); } return b; } private String getDatasetKey() { StubPaginatedTableDataOperation.Key key = new StubPaginatedTableDataOperation.Key("foods"); if (getPreferenceValueOperation != null) { JsonObject query = new JsonObject(); query.addProperty("key", "io.github.jsoagger.demoapp.dataset"); getPreferenceValueOperation.doOperation(query, res -> { MultipleResult r = (MultipleResult) res; if (r.getData().size() > 0) { String vo = (String) r.getData().get(0).getAttributes().get("savedValue"); key.setValue(vo); } }); } return key.value; } private void loadImagesLocation() { if (getPreferenceValueOperation != null) { com.google.gson.JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("key", DATASET_IMAGE_LOCATION); getPreferenceValueOperation.doOperation(jsonObject, res -> { MultipleResult r = (MultipleResult) res; if (r.getData().size() > 0) setImagesLocation((String) r.getData().get(0).getAttributes().get("savedValue")); }); } } private void setImagesLocation(String location) { this.imagesLocation = location; } public Properties getPlatformProperties() { return platformProperties; } public void setPlatformProperties(Properties platformProperties) { this.platformProperties = platformProperties; } public IOperation getGetPreferenceValueOperation() { return getPreferenceValueOperation; } public void setGetPreferenceValueOperation(IOperation getPreferenceValueOperation) { this.getPreferenceValueOperation = getPreferenceValueOperation; } public String getImagesLocation() { return imagesLocation; } }
35.92823
133
0.685577
52178a7bad66aedbafe3e06d08c5ce0b6b4b7539
4,348
/* * 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.jmeter.protocol.jms.sampler; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Request/reply executor with a fixed reply queue. <br> * * Used by JMS Sampler (Point to Point) * */ public class FixedQueueExecutor implements QueueExecutor { private static final Logger log = LoggerFactory.getLogger(FixedQueueExecutor.class); /** Sender. */ private final MessageProducer producer; /** Timeout used for waiting on message. */ private final int timeout; private final boolean useReqMsgIdAsCorrelId; /** * Constructor. * * @param producer * the queue to send the message on * @param timeout * timeout to use for the return message * @param useReqMsgIdAsCorrelId * whether to use the request message id as the correlation id */ public FixedQueueExecutor(MessageProducer producer, int timeout, boolean useReqMsgIdAsCorrelId) { this.producer = producer; this.timeout = timeout; this.useReqMsgIdAsCorrelId = useReqMsgIdAsCorrelId; } /** * {@inheritDoc} */ @Override public Message sendAndReceive(Message request, int deliveryMode, int priority, long expiration) throws JMSException { String id = request.getJMSCorrelationID(); if(id == null && !useReqMsgIdAsCorrelId){ throw new IllegalArgumentException("Correlation id is null. Set the JMSCorrelationID header."); } final CountDownLatch countDownLatch = new CountDownLatch(1); final MessageAdmin admin = MessageAdmin.getAdmin(); if(useReqMsgIdAsCorrelId) {// msgId not available until after send() is called // Note: there is only one admin object which is shared between all threads synchronized (admin) {// interlock with Receiver producer.send(request, deliveryMode, priority, expiration); id=request.getJMSMessageID(); admin.putRequest(id, request, countDownLatch); } } else { admin.putRequest(id, request, countDownLatch); producer.send(request, deliveryMode, priority, expiration); } try { log.debug("{} will wait for reply {} started on {}", Thread.currentThread().getName(), id, System.currentTimeMillis()); // This used to be request.wait(timeout_ms), where 0 means forever // However 0 means return immediately for the latch if (timeout == 0){ countDownLatch.await(); // } else { if(!countDownLatch.await(timeout, TimeUnit.MILLISECONDS)) { log.debug("Timeout reached before getting a reply message"); } } log.debug("{} done waiting for {} on {} ended on {}", Thread.currentThread().getName(), id, request, System.currentTimeMillis()); } catch (InterruptedException e) { log.warn("Interrupt exception caught", e); Thread.currentThread().interrupt(); } return admin.get(id); } }
38.140351
108
0.624655
32122cd4603cbb3f00850d2be71db5014a885579
3,087
package com.fntj.app.view; import android.app.Activity; import android.text.Html; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.fntj.app.R; import com.fntj.app.model.FinishedItem; import com.fntj.lib.zb.util.StringUtil; public class ProgressFinishedView extends RecyclerView.ViewHolder { private static final String TAG = "ProgressFinishedView"; public Activity context; public ImageView ivHead; public TextView tvName; public TextView tvsense; public TextView tvitems; public TextView tvtip; public TextView tvdoneTime; public ProgressFinishedView(Activity context, ViewGroup parent, int viewType) { super(context.getLayoutInflater().inflate(R.layout.progress_detail_view, parent, false)); context = context; //initView(); } public View initView() { ivHead = findView(R.id.ivHead); tvName = findView(R.id.tvName); tvsense = findView(R.id.tvsense); tvitems = findView(R.id.tvitems); tvtip = findView(R.id.tvtip); tvdoneTime = findView(R.id.tvdoneTime); return itemView; } private <V extends View> V findView(int id) { return itemView.findViewById(id); } private String getString(String s) { return StringUtil.isEmpty(s) ? "--" : s; } public void bindView(FinishedItem j, int position, int viewType) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { tvName.setText(Html.fromHtml("<span style='color:black;font-weight:bold;'>项目名称:</span>" + getString(j.getName()), Html.FROM_HTML_MODE_LEGACY)); tvsense.setText(Html.fromHtml("<span style='color:black;font-weight:bold;'>检查意义:</span>" + getString(j.getSense()), Html.FROM_HTML_MODE_LEGACY)); tvitems.setText(Html.fromHtml("<span style='color:black;font-weight:bold;'>检查内容:</span>" + getString(j.getItems()), Html.FROM_HTML_MODE_LEGACY)); tvtip.setText(Html.fromHtml("<span style='color:black;font-weight:bold;'>注意事项:</span>" + getString(j.getTip()), Html.FROM_HTML_MODE_LEGACY)); tvdoneTime.setText(Html.fromHtml("<span style='color:black;font-weight:bold;'>完成时间:</span>" + getString(j.getDoneTime()), Html.FROM_HTML_MODE_LEGACY)); } else{ tvName.setText(Html.fromHtml("<span style='color:black;font-weight:bold;'>项目名称:</span>" + getString(j.getName()))); tvsense.setText(Html.fromHtml("<span style='color:black;font-weight:bold;'>检查意义:</span>" + getString(j.getSense()))); tvitems.setText(Html.fromHtml("<span style='color:black;font-weight:bold;'>检查内容:</span>" + getString(j.getItems()))); tvtip.setText(Html.fromHtml("<span style='color:black;font-weight:bold;'>注意事项:</span>" + getString(j.getTip()))); tvdoneTime.setText(Html.fromHtml("<span style='color:black;font-weight:bold;'>完成时间:</span>" + getString(j.getDoneTime()))); } } }
40.090909
163
0.678976
d74ee80112cb35664f7cc7edb425ee4be4adc072
1,345
package com.computablefacts.nona.functions.stringoperators; import org.junit.Assert; import org.junit.Test; import com.computablefacts.asterix.Span; import com.computablefacts.asterix.SpanSequence; import com.computablefacts.nona.Function; import com.computablefacts.nona.types.BoxedType; public class MatchRegexTest { @Test public void testExtractPointInTime() { String text = "THE GUATEMALA ARMY ATTACKED THE FARM 2 DAYS AGO"; Span span = new Span(text, 37, 47); span.setGroup(1, "2"); SpanSequence sequence = new SpanSequence(); sequence.add(span); Function fn = new Function("MATCH_REGEX(" + text + ", _((?is:([1-9][0-9]?)\\s+days\\s+ago)))"); Assert.assertEquals(BoxedType.create(sequence), fn.evaluate(Function.definitions())); } @Test public void testExtractIsoDatePattern() { String text = "GUATEMALA CITY, 4 FEB 90 (ACAN-EFE)"; Span span = new Span(text, 16, 24); span.setGroup(1, "4"); span.setGroup(2, "FEB"); span.setGroup(3, "90"); SpanSequence sequence = new SpanSequence(); sequence.add(span); Function fn = new Function("MATCH_REGEX(_(" + text + "), _((?is:([0-9]{1,2})\\s+(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\\s+([0-9]{2}))))"); Assert.assertEquals(BoxedType.create(sequence), fn.evaluate(Function.definitions())); } }
29.888889
106
0.679554
26f049b99de6478d2b064296b9578b38e93fa037
499
package com.chinalwb.are.styles; import android.view.View; import com.chinalwb.are.Constants; public class ARE_Helper { /** * Updates the check status. * * @param areStyle * @param checked */ public static void updateCheckStatus(IARE_Style areStyle, boolean checked) { areStyle.setChecked(checked); View imageView = areStyle.getImageView(); int color = checked ? Constants.CHECKED_COLOR : Constants.UNCHECKED_COLOR; imageView.setBackgroundColor(color); } }
20.791667
78
0.721443
08d9c0d120168409a5f7066b5f11d7078a213526
157
package com.iluwatar.dependency.injection; /** * * OldTobyTobacco concrete Tobacco implementation * */ public class OldTobyTobacco extends Tobacco { }
15.7
49
0.757962
ee88036467e86bbea39f5064a99c312eebecd366
3,460
/** * STAR TREK * 2017-03-01 K.OHWADA */ package jp.ohwada.android.startrek.util; import android.util.Log; import java.lang.Math; import java.util.ArrayList; import java.util.List; import jp.ohwada.android.startrek.Constant; /* * Course */ public class Course { // debug private static final boolean D = Constant.DEBUG; private static final String TAG_SUB = "Course"; public static final int COURSE_MIN = 1; public static final int COURSE_MAX = 8; private static final int COURSE_NONE = 0; private static final int COURSE_RIGHT = 1; private static final int COURSE_UP_RIGHT = 2; private static final int COURSE_UP = 3; private static final int COURSE_UP_LEFT = 4; private static final int COURSE_LEFT = 5; private static final int COURSE_DOWN_LEFT = 6; private static final int COURSE_DOWN = 7; private static final int COURSE_DOWN_RIGHT = 8; /** * Course */ public Course() { // dummy } // end of Course /** * getDelta * @ param int course * @ return int[] delta */ public static int[] getDelta( int course ) { log_d( "getDelta " + course ); int xd = 0; int yd = 0; // right if ( course == COURSE_RIGHT ) { xd = 0; yd = 1; // up right } else if ( course == COURSE_UP_RIGHT ) { xd = -1; yd = 1; // up } else if ( course == COURSE_UP ) { xd = -1; yd = 0; // up left } else if ( course == COURSE_UP_LEFT ) { xd = -1; yd = -1; // left } else if ( course == COURSE_LEFT ) { xd = 0; yd = -1; // down left } else if ( course == COURSE_DOWN_LEFT ) { xd = 1; yd = -1; // down } else if ( course == COURSE_DOWN ) { xd = 1; yd = 0; // down right } else if ( course == COURSE_DOWN_RIGHT ) { xd = 1; yd = 1; } // if int[] ret = new int[2]; log_d( "delta " +xd + ", "+ yd ); ret[0] = xd; ret[1] = yd; return ret; } // getdelta /** * getCourse * @ param int orig_x. int orig_y, int x, int y * @ return int course */ public static int getCourse( int orig_x, int orig_y, int x, int y ) { log_d( "getCourse " + orig_x + ","+ orig_y + ","+ x + ","+ y ); int ret = COURSE_NONE; if( orig_x == x ){ if( orig_y < y ) { ret = COURSE_RIGHT; } else { ret = COURSE_LEFT; } // if } else if( orig_y == y ){ if( orig_x < x ) { ret = COURSE_DOWN; } else { ret = COURSE_UP; } // if } else if( Math.abs( orig_x - x ) == Math.abs( orig_y - y ) ){ if(( orig_x > x )&&( orig_y > y )) { ret = COURSE_UP_LEFT; } else if(( orig_x > x )&&( orig_y < y )) { ret = COURSE_UP_RIGHT; } else if(( orig_x < x )&&( orig_y > y )) { ret = COURSE_DOWN_LEFT; } else if(( orig_x > x )&&( orig_y < y )) { ret = COURSE_DOWN_RIGHT; } // if } // if return ret; } // getCourse /** * log_d */ private static void log_d ( String msg ) { if (Constant.DEBUG) Log.d(Constant.TAG, TAG_SUB + " " + msg ); } // end of log_d } // end of class
23.221477
97
0.489306
2cf0d3d881580339b32799bec07f36df5911bc32
414
package com.ad.restauranticecream.service; import com.onesignal.NotificationExtenderService; import com.onesignal.OSNotificationReceivedResult; /** * Created by androidbash on 12/14/2016. */ public class MyNotificationExtenderService extends NotificationExtenderService { @Override protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) { return true; } }
25.875
93
0.801932
b96317174fe313b9113e6cd1a4d9091a2d10940b
10,001
/* * Copyright 2021 Andreas Textor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.atextor.owlcli.diagram.mappers; import de.atextor.owlcli.diagram.graph.Edge; import de.atextor.owlcli.diagram.graph.Graph; import de.atextor.owlcli.diagram.graph.GraphElement; import de.atextor.owlcli.diagram.graph.Node; import de.atextor.owlcli.diagram.graph.node.Literal; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLPropertyExpression; import org.semanticweb.owlapi.model.SWRLArgument; import org.semanticweb.owlapi.model.SWRLAtom; import org.semanticweb.owlapi.model.SWRLBinaryAtom; import org.semanticweb.owlapi.model.SWRLBuiltInAtom; import org.semanticweb.owlapi.model.SWRLClassAtom; import org.semanticweb.owlapi.model.SWRLDataPropertyAtom; import org.semanticweb.owlapi.model.SWRLDataRangeAtom; import org.semanticweb.owlapi.model.SWRLDifferentIndividualsAtom; import org.semanticweb.owlapi.model.SWRLIArgument; import org.semanticweb.owlapi.model.SWRLIndividualArgument; import org.semanticweb.owlapi.model.SWRLLiteralArgument; import org.semanticweb.owlapi.model.SWRLObjectPropertyAtom; import org.semanticweb.owlapi.model.SWRLObjectVisitorEx; import org.semanticweb.owlapi.model.SWRLRule; import org.semanticweb.owlapi.model.SWRLSameIndividualAtom; import org.semanticweb.owlapi.model.SWRLVariable; import org.semanticweb.owlapi.vocab.Namespaces; import org.semanticweb.owlapi.vocab.OWL2Datatype; import javax.annotation.Nonnull; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class SWRLObjectMapper implements SWRLObjectVisitorEx<Graph> { /** * During traversal of the rule expression tree, both Literal nodes and other GraphElements * (mainly Edges) are collected. The values of the Literal nodes are concatenated in the end * to render the final rule representation. In order to differentiate the to-be-concatenated * Literal nodes from "regular" Literal nodes that might occur, they are given an internal * identifier "marker" IRI. The concatenation is done in * {@link de.atextor.owlcli.diagram.mappers.OWLAxiomMapper#visit(SWRLRule)}. */ private static final IRI LITERAL_ID = IRI.create( "urn:owl-cli:literal-id" ); public static final Predicate<GraphElement> IS_RULE_SYNTAX_PART = graphElement -> graphElement.is( Literal.class ) && graphElement.as( Literal.class ).getId().getIri().map( iri -> iri.equals( LITERAL_ID ) ).orElse( false ); private final MappingConfiguration mappingConfig; public SWRLObjectMapper( final MappingConfiguration mappingConfig ) { this.mappingConfig = mappingConfig; } @Override public Graph visit( final @Nonnull SWRLClassAtom atom ) { final List<GraphElement> argumentGraphElements = argumentElements( atom ); final String arguments = printArgumentElements( argumentGraphElements ); final String label = String.format( "%s(%s)", atom.getPredicate().accept( mappingConfig.getOwlClassExpressionPrinter() ), arguments ); final Graph classGraph = atom.getPredicate().accept( mappingConfig.getOwlClassExpressionMapper() ); final Literal literal = new Literal( mappingConfig.getIdentifierMapper() .getSyntheticIdForIri( LITERAL_ID ), label ); final Edge edge = new Edge.Plain( Edge.Type.DASHED_ARROW, literal, classGraph.getNode() ); return Graph.of( literal ).and( classGraph ).and( edge ) .and( argumentGraphElements.stream().filter( IS_RULE_SYNTAX_PART.negate() ) ); } @Override public Graph visit( final @Nonnull SWRLDataRangeAtom atom ) { final List<GraphElement> argumentGraphElements = argumentElements( atom ); final String arguments = printArgumentElements( argumentGraphElements ); final String label = String.format( "%s(%s)", atom.getPredicate().accept( mappingConfig.getOwlDataPrinter() ), arguments ); final Literal literal = new Literal( mappingConfig.getIdentifierMapper() .getSyntheticIdForIri( LITERAL_ID ), label ); return Graph.of( literal ); } private List<GraphElement> argumentElements( final SWRLAtom atom ) { return atom.allArguments().flatMap( argument -> argument.accept( this ).toStream() ).collect( Collectors.toList() ); } private String printArgumentElements( final List<GraphElement> argumentElements ) { return argumentElements.stream() .flatMap( element -> element.view( Literal.class ) ) .filter( IS_RULE_SYNTAX_PART ) .map( Literal::getValue ) .collect( Collectors.joining( ", " ) ); } @Override public Graph visit( final @Nonnull SWRLObjectPropertyAtom atom ) { return visitPropertyAtom( atom, atom.getPredicate() ); } private <T extends SWRLArgument> Graph visitPropertyAtom( final SWRLBinaryAtom<SWRLIArgument, T> atom, final OWLPropertyExpression predicate ) { final List<GraphElement> argumentGraphElements = argumentElements( atom ); final String arguments = printArgumentElements( argumentGraphElements ); final String label = String.format( "%s(%s)", predicate.accept( mappingConfig.getOwlPropertyExpressionPrinter() ), arguments ); final Node dataProperty = predicate.accept( mappingConfig.getOwlPropertyExpressionMapper() ).getNode(); final Literal literal = new Literal( mappingConfig.getIdentifierMapper() .getSyntheticIdForIri( LITERAL_ID ), label ); final Edge edge = new Edge.Plain( Edge.Type.DASHED_ARROW, literal, dataProperty ); return Graph.of( literal ).and( dataProperty ).and( edge ) .and( argumentGraphElements.stream().filter( IS_RULE_SYNTAX_PART.negate() ) ); } @Override public Graph visit( final @Nonnull SWRLDataPropertyAtom atom ) { return visitPropertyAtom( atom, atom.getPredicate() ); } @Override public Graph visit( final @Nonnull SWRLBuiltInAtom atom ) { final List<GraphElement> argumentGraphElements = argumentElements( atom ); final String arguments = printArgumentElements( argumentGraphElements ); final String builtin = Namespaces.SWRLB.inNamespace( atom.getPredicate() ) ? String.format( "swrlb:%s", atom.getPredicate().getFragment() ) : mappingConfig.getNameMapper().getName( atom.getPredicate() ); final String label = String.format( "%s(%s)", builtin, arguments ); return Graph.of( new Literal( mappingConfig.getIdentifierMapper().getSyntheticIdForIri( LITERAL_ID ), label ) ); } @Override public Graph visit( final @Nonnull SWRLVariable variable ) { // Do not call namemapper for variable IRI fragment: variable name is not subject to be // rendered with prefix return Graph.of( new Literal( mappingConfig.getIdentifierMapper().getSyntheticIdForIri( LITERAL_ID ), "?" + variable.getIRI().getFragment() ) ); } @Override public Graph visit( final @Nonnull SWRLIndividualArgument argument ) { final Node individual = argument.getIndividual().accept( mappingConfig.getOwlIndividualMapper() ).getNode(); final String label = argument.getIndividual().accept( mappingConfig.getOwlIndividualPrinter() ); final Literal literal = new Literal( mappingConfig.getIdentifierMapper() .getSyntheticIdForIri( LITERAL_ID ), label ); final Edge edge = new Edge.Plain( Edge.Type.DASHED_ARROW, literal, individual ); return Graph.of( literal ).and( individual ).and( edge ); } @Override public Graph visit( final @Nonnull SWRLLiteralArgument argument ) { final OWL2Datatype literalType = argument.getLiteral().getDatatype().getBuiltInDatatype(); final boolean quote = switch ( literalType.getCategory() ) { case CAT_STRING_WITH_LANGUAGE_TAG, CAT_STRING_WITHOUT_LANGUAGE_TAG, CAT_URI -> true; default -> false; }; final String labelContent = argument.getLiteral().accept( mappingConfig.getOwlDataPrinter() ); final String label = quote ? "\"" + labelContent + "\"" : labelContent; final Literal literal = new Literal( mappingConfig.getIdentifierMapper() .getSyntheticIdForIri( LITERAL_ID ), label ); return Graph.of( literal ); } @Override public Graph visit( final @Nonnull SWRLSameIndividualAtom atom ) { final List<GraphElement> argumentGraphElements = argumentElements( atom ); final String arguments = printArgumentElements( argumentGraphElements ); final String label = String.format( "sameAs(%s)", arguments ); final Literal literal = new Literal( mappingConfig.getIdentifierMapper() .getSyntheticIdForIri( LITERAL_ID ), label ); return atom.individualsInSignature().map( owlIndividual -> { final Node individual = owlIndividual.accept( mappingConfig.getOwlIndividualMapper() ).getNode(); final Edge edge = new Edge.Plain( Edge.Type.DASHED_ARROW, literal, individual ); return Graph.of( individual ).and( edge ); } ).reduce( Graph.of( literal ), Graph::and ); } @Override public Graph visit( final @Nonnull SWRLDifferentIndividualsAtom node ) { return null; } }
49.509901
118
0.710529
4bcf0badc8d1b50397d6c95baa7ba6d3aee53cc0
3,152
package garage; import java.util.ArrayList; import java.util.HashMap; public class Garage { // Task requested List, but using a map gave a better "idea" for an ID. private HashMap<Integer, Vehicle> vehicleList = new HashMap<Integer, Vehicle>(); private int uniqueId = 0; public Garage() { } /** * Adds a vehicle to the garage list. * * @param v. */ public void addVehicle(Vehicle v) { v.setId(uniqueId); vehicleList.put(uniqueId, v); uniqueId++; } public Vehicle getVehicle(int id) throws Exception { if (vehicleList.containsKey(id)) { return vehicleList.get(id); } else { throw new Exception("No vehicle exists at that index in the garage."); } } /** * Deleted vehicle by it's ID. * * @param id * Number for the vehicle ID. */ public boolean delVehicle(int id) { if (vehicleList.containsKey(id)) { //System.out.println("Removing Vehicle by ID: " + vehicleList.get(id).stringify()); vehicleList.remove(id); return true; } System.out.println("Vehicle does not exist in garage. ID: " + id); return false; } /** * Deleted vehicle by the "physical" vehicle object/instance. * * @param v * Vehicle object/instance. */ public boolean delVehicle(Vehicle v) { if (vehicleList.containsValue(v)) { ///System.out.println("Removing Vehicle by instance: " + v.stringify()); vehicleList.values().remove(v); return true; } System.out.println("Vehicle does not exist in garage. Instance: " + v.stringify()); return false; } /** * Deletes all vehicle by type. */ public boolean delVehicle(String type) { ArrayList<Vehicle> temp = new ArrayList<Vehicle>(); for (Vehicle v : vehicleList.values()) { if (v.getClass().getName().equals("garage." + type)) { // System.out.println("Deleted: " + v.stringify() + ", is part of the '" + type + "' class."); temp.add(v); } else { System.out.println("Did NOT delete: " + v.stringify() + ", is not part of the '" + type + "' class."); return false; } } vehicleList.values().removeAll(temp); return true; } /** * Fix Vehicle requirement was vague, just returns a random price based on * vehicle the vehicle type. */ public int calculateBill(Vehicle v) { if (v.getClass() == Motorcycle.class) { return 30; } if (v.getClass() == Car.class) { return 40; } if (v.getClass() == Hovercraft.class) { return 100; } return 0; } /** * Prints the list of the inventory to the screen or returns "no vehicles * found" * * @return * @throws Exception */ public void printInventory() throws Exception { if (vehicleList.size() > 0) { for (Vehicle v : vehicleList.values()) { System.out.println(v.stringify()); } } else { throw new Exception("Failed to print inventory, there are no Vehicles in the inventory."); } } /** * Returns a list of all vehicles. * * @return list of vehicles */ public HashMap<Integer, Vehicle> getAll() { return vehicleList; } /** * Deletes all items from the garage list. */ public void emptyGarage() { vehicleList.clear(); } }
21.737931
106
0.632614
2a1f20fac1b037b7771d5c85913362d8f1933713
7,829
/* * MIT License * * Copyright (c) 2016. * Bucher Andreas, Fink Simon Dominik, Fraedrich Christoph, Popp Wolfgang, * Sell Leon, Werli Philemon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package de.unipassau.isl.evs.ssh.core.naming; import android.content.Context; import android.content.SharedPreferences; import android.test.InstrumentationTestCase; import org.spongycastle.x509.X509V3CertificateGenerator; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.Date; import javax.security.auth.x500.X500Principal; import de.unipassau.isl.evs.ssh.core.CoreConstants; import de.unipassau.isl.evs.ssh.core.container.Container; import de.unipassau.isl.evs.ssh.core.container.ContainerService; import de.unipassau.isl.evs.ssh.core.container.SimpleContainer; import de.unipassau.isl.evs.ssh.core.sec.KeyStoreController; public class NamingManagerTest extends InstrumentationTestCase { private static final int ASYMMETRIC_KEY_SIZE = 256; private static final String KEY_PAIR_ALGORITHM = "ECIES"; private static final String KEY_PAIR_SIGNING_ALGORITHM = "SHA224withECDSA"; private X509Certificate createCert() throws java.security.GeneralSecurityException { KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM); generator.initialize(ASYMMETRIC_KEY_SIZE); KeyPair keyPair = generator.generateKeyPair(); //Check Certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1L)); certGen.setSubjectDN(new X500Principal("CN=evs")); certGen.setIssuerDN(new X500Principal("CN=evs")); certGen.setPublicKey(keyPair.getPublic()); certGen.setNotBefore(new Date()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, 100); certGen.setNotAfter(calendar.getTime()); certGen.setSignatureAlgorithm(KEY_PAIR_SIGNING_ALGORITHM); return certGen.generate(keyPair.getPrivate()); } private DeviceID createEnvironmentAsAfterHandshake(Container container) throws GeneralSecurityException { Context context = container.require(ContainerService.KEY_CONTEXT); NamingManager naming = container.require(NamingManager.KEY); // Clear SharedPreferences SharedPreferences sharedPref = context.getSharedPreferences(CoreConstants.FILE_SHARED_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.remove(NamingManager.PREF_MASTER_ID); editor.commit(); // Generate a master certificate, X509Certificate certificate = createCert(); // write master id to SharedPreferences, DeviceID masterId = DeviceID.fromCertificate(certificate); editor.putString(NamingManager.PREF_MASTER_ID, masterId.getIDString()); editor.commit(); // save the certificate container.require(KeyStoreController.KEY).saveCertificate(certificate, masterId.getIDString()); return masterId; } private Container createDefaultEnvironment(boolean isMasterEnv) { Context context = getInstrumentation().getTargetContext(); // Clear SharedPreferences SharedPreferences sharedPref = context.getSharedPreferences(CoreConstants.FILE_SHARED_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.remove(NamingManager.PREF_MASTER_ID); editor.commit(); // Setup environment SimpleContainer container = new SimpleContainer(); container.register(ContainerService.KEY_CONTEXT, new ContainerService.ContextComponent(context)); container.register(KeyStoreController.KEY, new KeyStoreController()); container.register(NamingManager.KEY, new NamingManager(isMasterEnv)); return container; } public void testGetMasterID() throws Exception { // simulate a non-master environment Container container = createDefaultEnvironment(false); NamingManager naming = container.require(NamingManager.KEY); // Ensure Master is still unknown assertFalse(naming.isMasterIDKnown()); // Now Handshake is complete and master is known DeviceID masterId = createEnvironmentAsAfterHandshake(container); // read Master id assertEquals(masterId, naming.getMasterID()); // simulate a master environment container = createDefaultEnvironment(true); naming = container.require(NamingManager.KEY); assertNotNull(naming.getMasterID()); assertNotNull(naming.getOwnID()); assertEquals(naming.getOwnID(), naming.getMasterID()); } public void testGetMasterCert() throws Exception { // simulate a non-master environment Container container = createDefaultEnvironment(false); DeviceID masterId = createEnvironmentAsAfterHandshake(container); NamingManager naming = container.require(NamingManager.KEY); assertNotNull(naming.getMasterCertificate()); // simulate a master environment container = createDefaultEnvironment(false); masterId = createEnvironmentAsAfterHandshake(container); naming = container.require(NamingManager.KEY); assertNotNull(naming.getMasterCertificate()); assertNotNull(naming.getCertificate(naming.getMasterID())); assertEquals(naming.getMasterCertificate(), naming.getCertificate(naming.getMasterID())); } public void testGetLocalDeviceId() throws Exception { Container container = createDefaultEnvironment(false); NamingManager naming = container.require(NamingManager.KEY); assertNotNull(naming.getOwnID()); } public void testGetDeviceID() throws Exception { Container container = createDefaultEnvironment(true); NamingManager naming = container.require(NamingManager.KEY); X509Certificate cert = createCert(); assertNotNull(DeviceID.fromCertificate(cert)); } public void testGetCertificate() throws Exception { Container container = createDefaultEnvironment(true); NamingManager naming = container.require(NamingManager.KEY); // generate and save the certificate X509Certificate cert = createCert(); DeviceID id = DeviceID.fromCertificate(cert); container.require(KeyStoreController.KEY).saveCertificate(cert, id.getIDString()); assertEquals(naming.getCertificate(id), cert); } public void testGetPublicKey() throws Exception { // } }
41.86631
123
0.735982
747b42500d7f5ca01ca1dc0bc893130444327fe3
14,649
package com.sinapsi.android.persistence; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.sinapsi.android.AndroidAppConsts; import com.sinapsi.android.Lol; import com.sinapsi.client.persistence.LocalDBManager; import com.sinapsi.engine.Action; import com.sinapsi.engine.ComponentFactory; import com.sinapsi.engine.Trigger; import com.sinapsi.model.MacroInterface; import com.sinapsi.model.impl.FactoryModel; import java.util.ArrayList; import java.util.List; /** * LocalDBManager implementation for Android */ public class AndroidLocalDBManager implements LocalDBManager { public static final int LOCAL_DB_VERSION = 2; public static final String TABLE_MACROS = "macro"; public static final String TABLE_ACTION_LISTS = "action_list"; public static final String COL_MACRO_ROW_ID = "row_id"; public static final String COL_MACRO_ID = "id"; public static final String COL_MACRO_NAME = "name"; public static final String COL_MACRO_ICON_NAME = "icon_name"; public static final String COL_MACRO_ICON_COLOR = "icon_color"; public static final String COL_MACRO_VALID = "valid"; public static final String COL_MACRO_FAILURE_POLICY = "failure_policy"; public static final String COL_MACRO_ENABLED = "enabled"; public static final String COL_MACRO_TRIGGER_DEVICE_ID = "trigger_device_id"; public static final String COL_MACRO_TRIGGER_NAME = "trigger_name"; public static final String COL_MACRO_TRIGGER_JSON = "trigger_json"; public static final String[] ALL_COLUMNS_MACROS = new String[]{ COL_MACRO_ROW_ID, COL_MACRO_ID, COL_MACRO_NAME, COL_MACRO_ICON_NAME, COL_MACRO_ICON_COLOR, COL_MACRO_VALID, COL_MACRO_FAILURE_POLICY, COL_MACRO_ENABLED, COL_MACRO_TRIGGER_DEVICE_ID, COL_MACRO_TRIGGER_NAME, COL_MACRO_TRIGGER_JSON }; public static final String COL_ACTIONLIST_MACRO_ID = "macro_id"; public static final String COL_ACTIONLIST_ACTION_ORDER = "action_order"; public static final String COL_ACTIONLIST_ACTION_DEVICE_ID = "action_device_id"; public static final String COL_ACTIONLIST_ACTION_NAME = "action_name"; public static final String COL_ACTIONLIST_ACTION_JSON = "action_json"; public static final String[] ALL_COLUMNS_ACTIONLISTS = new String[]{ COL_ACTIONLIST_MACRO_ID, COL_ACTIONLIST_ACTION_ORDER, COL_ACTIONLIST_ACTION_DEVICE_ID, COL_ACTIONLIST_ACTION_NAME, COL_ACTIONLIST_ACTION_JSON }; public static final String SQL_STATEMENT_CREATE_TABLE_MACROS = "" + "CREATE TABLE " + TABLE_MACROS + " (" + COL_MACRO_ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_MACRO_ID + " INTEGER, " + COL_MACRO_NAME + " TEXT, " + COL_MACRO_ICON_NAME + " TEXT, " + COL_MACRO_ICON_COLOR + " VARCHAR(8), " + COL_MACRO_VALID + " INTEGER, " + COL_MACRO_FAILURE_POLICY + " TEXT, " + COL_MACRO_ENABLED + " INTEGER, " + COL_MACRO_TRIGGER_DEVICE_ID + " INTEGER, " + COL_MACRO_TRIGGER_NAME + " TEXT, " + COL_MACRO_TRIGGER_JSON + " TEXT"+ ");"; public static final String SQL_STATEMENT_CREATE_TABLE_ACTION_LISTS = "" + "CREATE TABLE " + TABLE_ACTION_LISTS + " (" + COL_ACTIONLIST_MACRO_ID + " INTEGER, " + COL_ACTIONLIST_ACTION_NAME + " TEXT, " + COL_ACTIONLIST_ACTION_ORDER + " INTEGER, " + COL_ACTIONLIST_ACTION_DEVICE_ID + " INTEGER, " + COL_ACTIONLIST_ACTION_JSON + " TEXT" + ");"; private String dbname; public AndroidLocalDBOpenHelper localDBOpenHelper; private ComponentFactory componentFactory; private FactoryModel factoryModel = new FactoryModel(); public AndroidLocalDBManager(Context c, String name, ComponentFactory cfactory){ this.dbname = name; this.componentFactory = cfactory; this.localDBOpenHelper = new AndroidLocalDBOpenHelper(c, dbname, null, LOCAL_DB_VERSION); } @Override public boolean addOrUpdateMacro(MacroInterface macro) { SQLiteDatabase db = localDBOpenHelper.getWritableDatabase(); Cursor checkCursor = db.rawQuery("SELECT * FROM " + TABLE_MACROS + " WHERE " + COL_MACRO_ID + " = ?", new String[]{"" + macro.getId()}); if(checkCursor == null || checkCursor.getCount() == 0){ Lol.d(this, "addOrUpdateMacro() called: macro does not exist, inserting new one '"+macro.getId()+":"+macro.getName()+"'"); //there are no macros with same id as macro //so this will insert it in the db long rowid = db.insertOrThrow(TABLE_MACROS, null, macroToContentValues(macro)); if(rowid != -1){ Lol.d(this, "addOrUpdateMacro() called: "+ rowid +" macro inserted, proceeding with actions..."); insertActionsForMacro(macro, db); }else{ localDBOpenHelper.close(); throw new RuntimeException("An error occured while inserting a new macro in the local db: "+dbname); } db.close(); localDBOpenHelper.close(); return true; }else{ Lol.d(this, "addOrUpdateMacro() called: macro exists, updating '"+macro.getId()+":"+macro.getName()+"'"); db.update( TABLE_MACROS, macroToContentValues(macro), COL_MACRO_ID + " = ?", new String[]{"" + macro.getId()}); deleteActionsForMacro(macro.getId(), db); insertActionsForMacro(macro, db); db.close(); localDBOpenHelper.close(); return false; } } @Override public List<MacroInterface> getAllMacros() { List<MacroInterface> result = new ArrayList<>(); SQLiteDatabase db = localDBOpenHelper.getReadableDatabase(); Cursor c = db.query(TABLE_MACROS, ALL_COLUMNS_MACROS, null, null, null, null, null); //Cursor c = db.rawQuery("SELECT * FROM " + TABLE_MACROS, null); Lol.d(this, "getAllMacros() called: cursor count: " + c.getCount()); c.moveToFirst(); while (!c.isAfterLast()){ MacroInterface m = cursorToMacro(c, db); result.add(m); c.moveToNext(); } c.close(); db.close(); localDBOpenHelper.close(); return result; } @SuppressWarnings("ConstantConditions") private MacroInterface cursorToMacro(Cursor c, SQLiteDatabase db) { boolean p = AndroidAppConsts.DEBUG_LOG_MACRO_CURSORS; if(p) Lol.d(this, "====== MACRO DB CURSOR CONTENT ======"); int id = c.getInt(1); String name = c.getString(2); if(p) Lol.d(this, "MACRO: '"+id+":"+name+"'"); String iconName = c.getString(3); String iconColor = c.getString(4); if(p) Lol.d(this, "--ICON: "+iconName+" COLOR: "+iconColor); boolean valid = c.getInt(5) != 0; String failurePolicy = c.getString(6); boolean enabled = c.getInt(7) != 0; if(p) { Lol.d(this, "--ENABLED: "+enabled+" VALID: "+valid); Lol.d(this, "--FAILURE_POLICY: "+failurePolicy); } int triggerDeviceId = c.getInt(8); String triggerName = c.getString(9); String triggerJSON = c.getString(10); if(p){ Lol.d(this, "--TRIGGER:"); Lol.d(this, "----TRIGGER NAME: "+triggerName+" EXECUTION DEVICE: "+triggerDeviceId); Lol.d(this, "----TRIGGER PARAMS: "+triggerJSON); Lol.d(this, "--END TRIGGER."); } MacroInterface m = factoryModel.newMacro(name, id); m.setIconName(iconName); m.setMacroColor(iconColor); m.setValid(valid); m.setExecutionFailurePolicy(failurePolicy); Trigger t = componentFactory.newTrigger( triggerName, triggerJSON, m, triggerDeviceId); m.setTrigger(t); m.setEnabled(enabled); if(p) Lol.d(this, "--ACTIONS:"); for(Action ac: getActionListForMacro(m.getId(), db)){ m.addAction(ac); } if(p) Lol.d(this, "--END ACTIONS."); if(p) Lol.d(this, "END MACRO (with id: "+ id + ")"); return m; } @Override public void removeMacro(int id) { Lol.d(this, "removeMacro() called on macro with id: " + id); SQLiteDatabase db = localDBOpenHelper.getWritableDatabase(); db.delete(TABLE_MACROS, COL_MACRO_ID + " = ?", new String[]{"" + id}); deleteActionsForMacro(id, db); db.close(); localDBOpenHelper.close(); } @Override public void clearDB() { Lol.d(this, "clearDB() called"); SQLiteDatabase db = localDBOpenHelper.getWritableDatabase(); db.delete(TABLE_MACROS,null, null); db.delete(TABLE_ACTION_LISTS, null, null); db.close(); localDBOpenHelper.close(); } @Override public int getMinMacroId() { SQLiteDatabase db = localDBOpenHelper.getWritableDatabase(); Cursor c = db.rawQuery("SELECT MIN(" + COL_MACRO_ID + ") FROM " + TABLE_MACROS, null); if(c == null || c.getCount() == 0) return 0; c.moveToFirst(); if(c.isNull(0)) return 0; int min = c.getInt(0); c.close(); db.close(); localDBOpenHelper.close(); return Math.min(min,0); } @Override public boolean containsMacro(int id) { SQLiteDatabase db = localDBOpenHelper.getWritableDatabase(); Cursor checkCursor = db.rawQuery("SELECT * FROM " + TABLE_MACROS + " WHERE " + COL_MACRO_ID + " = ?", new String[]{"" + id}); boolean result = !(checkCursor == null || checkCursor.getCount() == 0); if (checkCursor != null) checkCursor.close(); db.close(); localDBOpenHelper.close(); return result; } @Override public MacroInterface getMacroWithId(int id) { SQLiteDatabase db = localDBOpenHelper.getWritableDatabase(); Cursor c = db.rawQuery("SELECT * FROM " + TABLE_MACROS + " WHERE " + COL_MACRO_ID + " = ?", new String[]{"" + id}); if(c == null || c.getCount() == 0){ Lol.d(this, "getMacroWithId: "+id+" ----> returning null"); return null; } c.moveToFirst(); MacroInterface result = cursorToMacro(c,db); db.close(); localDBOpenHelper.close(); return result; } @Override public void deleteMacrosWithNegativeId() { SQLiteDatabase db = localDBOpenHelper.getWritableDatabase(); db.delete(TABLE_MACROS, COL_MACRO_ID + " < 0", null); db.delete(TABLE_ACTION_LISTS, COL_ACTIONLIST_MACRO_ID + " < 0", null); db.close(); localDBOpenHelper.close(); } private List<Action> getActionListForMacro(int macroid, SQLiteDatabase db){ List<Action> result = new ArrayList<>(); Cursor c = db.rawQuery("SELECT * FROM " + TABLE_ACTION_LISTS + " WHERE " + COL_ACTIONLIST_MACRO_ID + " = ? " + " ORDER BY " + COL_ACTIONLIST_ACTION_ORDER, new String[]{"" + macroid}); c.moveToFirst(); while(!c.isAfterLast()){ result.add(cursorToAction(c)); c.moveToNext(); } c.close(); return result; } private Action cursorToAction(Cursor c){ boolean p = AndroidAppConsts.DEBUG_LOG_MACRO_CURSORS; String actionName = c.getString(c.getColumnIndexOrThrow(COL_ACTIONLIST_ACTION_NAME)); int actionDeviceId = c.getInt(c.getColumnIndexOrThrow(COL_ACTIONLIST_ACTION_DEVICE_ID)); String actionParams = c.getString(c.getColumnIndexOrThrow(COL_ACTIONLIST_ACTION_JSON)); //noinspection ConstantConditions if(p){ Lol.d(this, "----ACTION:"); Lol.d(this, "------ACTION NAME: "+actionName+" EXECUTION DEVICE: "+actionDeviceId); Lol.d(this, "------ACTION PARAMS: "+actionParams); Lol.d(this, "----END ACTION."); } return componentFactory.newAction( actionName, actionParams, actionDeviceId); } private ContentValues macroToContentValues(MacroInterface macro){ ContentValues cv = new ContentValues(); cv.put(COL_MACRO_ID, macro.getId()); cv.put(COL_MACRO_NAME, macro.getName()); cv.put(COL_MACRO_ICON_NAME, macro.getIconName()); cv.put(COL_MACRO_ICON_COLOR, macro.getMacroColor()); cv.put(COL_MACRO_VALID, macro.isValid()); cv.put(COL_MACRO_FAILURE_POLICY, macro.getExecutionFailurePolicy()); cv.put(COL_MACRO_ENABLED, macro.isEnabled()); cv.put(COL_MACRO_TRIGGER_NAME, macro.getTrigger().getName()); cv.put(COL_MACRO_TRIGGER_DEVICE_ID, macro.getTrigger().getExecutionDevice().getId()); cv.put(COL_MACRO_TRIGGER_JSON, macro.getTrigger().getActualParameters()); return cv; } private ContentValues actionToContentValues(Action a, int macroid, int actionIndex){ ContentValues cv = new ContentValues(); cv.put(COL_ACTIONLIST_ACTION_NAME, a.getName()); cv.put(COL_ACTIONLIST_ACTION_DEVICE_ID, a.getExecutionDevice().getId()); cv.put(COL_ACTIONLIST_ACTION_JSON, a.getActualParameters()); cv.put(COL_ACTIONLIST_ACTION_ORDER, actionIndex); cv.put(COL_ACTIONLIST_MACRO_ID, macroid); return cv; } private void deleteActionsForMacro(int id, SQLiteDatabase db){ db.delete(TABLE_ACTION_LISTS, COL_ACTIONLIST_MACRO_ID + " = ?", new String[]{""+id}); } private void insertActionsForMacro(MacroInterface macro, SQLiteDatabase db){ List<Action> actions = macro.getActions(); for(int i = 0; i < actions.size(); ++i){ Action a = actions.get(i); long rowid = db.insert( TABLE_ACTION_LISTS, null, actionToContentValues(a, macro.getId(), i)); if(rowid == -1){ localDBOpenHelper.close(); throw new RuntimeException("An error occured while inserting a new action in the local db: "+dbname); } } } }
36.899244
134
0.614513
4e4c0051c3d96dcc256d5ecc6132393f249418ac
444
package com.artemas.codewars.fundamentals.kyu7; import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class RepTest { @Test public void testRepresentation() { Representation rep = new Representation(); assertEquals(17,rep.daysRepresented(new int[][] {{10,15},{25,35}})); assertEquals(24,rep.daysRepresented(new int[][] {{2,8},{220,229},{10,16}})); } }
29.6
84
0.684685
ac3785ca38ea836c7d35bc96ba79e7f1ffdd2f98
520
package org.openstreetmap.atlas.tags; import org.openstreetmap.atlas.tags.annotations.Tag; import org.openstreetmap.atlas.tags.annotations.TagKey; /** * OSM zoo tag * * @author stephencerqueira */ @Tag(taginfo = "http://taginfo.openstreetmap.org/keys/zoo#values", osm = "http://wiki.openstreetmap.org/wiki/Key%zoo") public enum ZooTag { AVIARY, BIRDS, ENCLOSURE, FALCONRY, PETTING_ZOO, REPTILE, SAFARI_PARK, WILDLIFE_PARK; @TagKey public static final String KEY = "zoo"; }
20
118
0.7
e01e06c1a272276973901ed9d6be5c7bf7c9083f
789
package net.splatcraft.api.particle; import com.mojang.serialization.Codec; import net.minecraft.particle.ParticleEffect; import net.minecraft.particle.ParticleType; import net.splatcraft.api.util.Color; @SuppressWarnings("deprecation") public class InkSplashParticleEffect extends ColorableScalableParticleEffect { public static final Codec<InkSplashParticleEffect> CODEC = createCodec(InkSplashParticleEffect::new); public static final ParticleEffect.Factory<InkSplashParticleEffect> PARAMETERS = createParameters(InkSplashParticleEffect::new); public InkSplashParticleEffect(Color color, float scale) { super(color, scale); } @Override public ParticleType<?> getType() { return SplatcraftParticleType.INK_SPLASH; } }
35.863636
133
0.769328
8e96ebdec1362690bd8ae1c80bbd942918fdeb01
2,202
package io.apitestbase; import com.google.common.collect.ImmutableMap; import io.dropwizard.Configuration; import io.dropwizard.db.DataSourceFactory; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Collections; import java.util.Map; public class APITestBaseConfiguration extends Configuration { private String mode; private String sslTrustStorePath; private String sslTrustStorePassword; @Valid @NotNull private DataSourceFactory systemDatabase = new DataSourceFactory(); private DataSourceFactory sampleDatabase = new DataSourceFactory(); private Map<String, Map<String, String>> viewRendererConfiguration = Collections.emptyMap(); private Map<String, String> wireMock = Collections.emptyMap(); public String getMode() { return mode; } public String getSslTrustStorePath() { return sslTrustStorePath; } public String getSslTrustStorePassword() { return sslTrustStorePassword; } public DataSourceFactory getSystemDatabase() { return systemDatabase; } public void setSystemDatabase(DataSourceFactory systemDatabase) { this.systemDatabase = systemDatabase; } public DataSourceFactory getSampleDatabase() { return sampleDatabase; } public void setSampleDatabase(DataSourceFactory sampleDatabase) { this.sampleDatabase = sampleDatabase; } public Map<String, Map<String, String>> getViewRendererConfiguration() { return viewRendererConfiguration; } public void setViewRendererConfiguration(Map<String, Map<String, String>> viewRendererConfiguration) { final ImmutableMap.Builder<String, Map<String, String>> builder = ImmutableMap.builder(); for (Map.Entry<String, Map<String, String>> entry : viewRendererConfiguration.entrySet()) { builder.put(entry.getKey(), ImmutableMap.copyOf(entry.getValue())); } this.viewRendererConfiguration = builder.build(); } public Map<String, String> getWireMock() { return wireMock; } public void setWireMock(Map<String, String> wireMock) { this.wireMock = wireMock; } }
31.457143
106
0.722071
eb836252b6512e157a695e7cb869b17382b75810
2,236
/* OpenRemote, the Home of the Digital Home. * Copyright 2008-2010, OpenRemote Inc. * * See the contributors.txt file in the distribution for a * full listing of individual contributors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openremote.controller.protocol.socket; import java.util.List; import org.jdom.Element; import org.openremote.controller.command.CommandBuilder; import org.openremote.controller.command.ExecutableCommand; import org.openremote.controller.utils.CommandUtil; /** * The Class SocketEventBuilder. * * @author Rich Turner 2011-04-15 */ public class UDPSocketCommandBuilder implements CommandBuilder { /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public ExecutableCommand build(Element element) { UDPSocketCommand tcpEvent = new UDPSocketCommand(); List<Element> propertyEles = element.getChildren("property", element.getNamespace()); for(Element ele : propertyEles){ if("name".equals(ele.getAttributeValue("name"))){ tcpEvent.setName(ele.getAttributeValue("value")); } else if("port".equals(ele.getAttributeValue("name"))){ tcpEvent.setPort(ele.getAttributeValue("value")); } else if("ipAddress".equals(ele.getAttributeValue("name"))){ tcpEvent.setIp(ele.getAttributeValue("value")); } else if("command".equals(ele.getAttributeValue("name"))){ tcpEvent.setCommand(CommandUtil.parseStringWithParam(element, ele.getAttributeValue("value"))); } } return tcpEvent; } }
37.898305
108
0.70483
7a19c92859c68ade488506edf7baae01cf1bdfd4
1,861
public class ShortcutTester { public static final int NUM_TESTS = 1; public static final int[] TEST_SIZES = {128, 256, 512, 1024, 2048}; public static void runTest (int size) { long avg = 0; long bavg = 0; long iterPerUS; long start, stop, bstart, bstop; boolean passed = true; for (int i = 0; i < NUM_TESTS; ++i) { // generate a random square matrix of size size SquareMatrix sm = new SquareMatrix(size); // generate baseline shortcut matrix bstart = System.nanoTime(); SquareMatrix baseline = sm.getShortcutMatrixBaseline(); bstop = System.nanoTime(); // generated optimized shortcut matrix, and time it start = System.nanoTime(); SquareMatrix optimized = sm.getShortcutMatrixOptimized(); stop = System.nanoTime(); // verify that baseline and optimized solution are the same if (!optimized.equals(baseline)) { passed = false; } bavg += (bstop - bstart); avg += (stop - start); } avg /= NUM_TESTS; bavg /= NUM_TESTS; // runtime improvement over baseline double improvement = (double) bavg / avg; // iterations per microsecond iterPerUS = (long) size * size * size / (avg / 1000); String isPassed = (passed) ? "yes" : " no"; System.out.printf("| %4d | %6d | %6.2f | %9d | %s |\n", size, avg / 1_000_000, improvement, iterPerUS, isPassed); } public static void main (String[] args) { System.out.printf("|------|------------------|-------------|------------------|---------|\n" + "| size | avg runtime (ms) | improvement | iteration per us | passed? |\n" + "|------|------------------|-------------|------------------|---------|\n"); for (int size : TEST_SIZES) { runTest(size); } System.out.printf("|------|------------------|-------------|------------------|---------|\n"); } }
29.078125
140
0.550242
9770a0a66457cafb946227eec33824f16ae3bd2f
295
/** * @author chaplind */ public interface HashTableInterface<K,V> { public V add(K key, V value); public V remove(K key); public V getValue(K key); public boolean contains(K key); public boolean isEmpty(); public int getHashIndex(K key); public int getSize(); public void clear(); }
18.4375
40
0.698305
c7d860ab803028e1d0bb83b35f5af65bbed9d6be
1,874
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hs.mail.pop3.processor; import java.util.Hashtable; import java.util.Map; import com.hs.mail.exception.LookupException; /** * * @author Won Chul Doh * @since April 12, 2018 * */ public class POP3ProcessorFactory { public static POP3Processor createPOP3Processor(String command) { POP3Processor processor = processorMap.get(command.toLowerCase()); if (null == processor) throw new LookupException("Class for '" + command + "' not found."); return processor; } static private Map<String, POP3Processor> processorMap = new Hashtable<String, POP3Processor>(); static { processorMap.put("capa", new CapaProcessor()); processorMap.put("dele", new DeleProcessor()); processorMap.put("list", new ListProcessor()); processorMap.put("noop", new NoopProcessor()); processorMap.put("pass", new PassProcessor()); processorMap.put("quit", new QuitProcessor()); processorMap.put("retr", new RetrProcessor()); processorMap.put("rset", new RsetProcessor()); processorMap.put("stat", new StatProcessor()); processorMap.put("top" , new TopProcessor()); processorMap.put("uidl", new UidlProcessor()); processorMap.put("user", new UserProcessor()); } }
34.072727
98
0.702241
2c609e64d8413a8c817d874e461a3dd541e779e4
841
package com.dao; import com.entity.NewsEntity; import com.baomidou.mybatisplus.mapper.BaseMapper; import java.util.List; import com.baomidou.mybatisplus.mapper.Wrapper; import com.baomidou.mybatisplus.plugins.pagination.Pagination; import org.apache.ibatis.annotations.Param; import com.entity.vo.NewsVO; import com.entity.view.NewsView; /** * 新闻资讯 * * @author * @email * @date 2020-05-13 10:02:23 */ public interface NewsDao extends BaseMapper<NewsEntity> { List<NewsVO> selectListVO(@Param("ew") Wrapper<NewsEntity> wrapper); NewsVO selectVO(@Param("ew") Wrapper<NewsEntity> wrapper); List<NewsView> selectListView(@Param("ew") Wrapper<NewsEntity> wrapper); List<NewsView> selectListView(Pagination page,@Param("ew") Wrapper<NewsEntity> wrapper); NewsView selectView(@Param("ew") Wrapper<NewsEntity> wrapper); }
25.484848
89
0.760999
74d571989b65396f57163197408727cf8b9b6e3f
4,210
/** * Copyright (C) 2016-2019 Expedia, 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.hotels.road.loadingbay.lander.kubernetes; import static java.util.stream.Collectors.joining; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.function.Supplier; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import io.fabric8.kubernetes.api.model.ConfigMap; import lombok.extern.slf4j.Slf4j; import com.google.common.collect.ImmutableMap; import com.hotels.road.loadingbay.lander.LanderConfiguration; import com.hotels.road.loadingbay.lander.OffsetRange; @Slf4j @Component public class ArgsFactory { private final String bootstrapServers; private final String roadModelTopic; private final String piiReplacerClassName; private final String s3Bucket; private final String s3EndpointUrl; private final String s3EndpointSigningRegion; private final String graphiteEndpoint; private final Supplier<ConfigMap> configMapSupplier; @Autowired ArgsFactory( @Value("${kafka.bootstrapServers}") String bootstrapServers, @Value("${kafka.road.topic}") String roadModelTopic, @Value("${piiReplacerClassName}") String piiReplacerClassName, @Value("${hive.table.location.bucket}") String s3Bucket, @Value("${s3.endpoint.url}") String s3EndpointUrl, @Value("${s3.endpoint.signingRegion}") String s3EndpointSigningRegion, @Value("${graphite.endpoint:disabled}") String graphiteEndpoint, Supplier<ConfigMap> configMapSupplier) { this.bootstrapServers = bootstrapServers; this.roadModelTopic = roadModelTopic; this.piiReplacerClassName = piiReplacerClassName; this.s3Bucket = s3Bucket; this.s3EndpointUrl = s3EndpointUrl; this.s3EndpointSigningRegion = s3EndpointSigningRegion; this.graphiteEndpoint = graphiteEndpoint; this.configMapSupplier = configMapSupplier; } public List<String> newInstance(LanderConfiguration config) { String formattedOffsets = formatOffsets(config.getOffsets()); log.info("Formatted offsets for topic: {} to launch Truck Park with: {}", config.getTopicName(), formattedOffsets); return ImmutableMap .<String, String> builder() .put("spring.profiles.active", configMapSupplier.get().getData().get("profiles")) .put("kafka.bootstrapServers", bootstrapServers) .put("road.name", config.getRoadName()) .put("road.topic", config.getTopicName()) .put("kafka.road.topic", roadModelTopic) .put("piiReplacerClassName", piiReplacerClassName) .put("road.offsets", formattedOffsets) .put("s3.bucket", s3Bucket) .put("s3.keyPrefix", config.getS3KeyPrefix()) .put("s3.endpoint.url", s3EndpointUrl) .put("s3.endpoint.signingRegion", s3EndpointSigningRegion) .put("s3.enableServerSideEncryption", Boolean.toString(config.isEnableServerSideEncryption())) .put("metrics.graphiteEndpoint", graphiteEndpoint) .build() .entrySet() .stream() .map(e -> String.format("--%s=%s", e.getKey(), e.getValue())) .collect(Collectors.toList()); } private String formatOffsets(Map<Integer, OffsetRange> offsets) { return offsets.entrySet().stream().map(this::format).collect(joining(";")); } private String format(Entry<Integer, OffsetRange> entry) { Integer partition = entry.getKey(); OffsetRange offsetRange = entry.getValue(); return partition + ":" + offsetRange.getStart() + "," + offsetRange.getEnd(); } }
39.345794
119
0.731116
2a1a67ebcdafb837d87148b17534eadcf4eff4b6
8,472
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static java.util.Objects.isNull; public class Example8JavaEquivalent { static class Email { public final String user; public final String domain; private Email(String user, String domain) { this.user = user; this.domain = domain; } public static Email fromString(String string) throws Exception { if (string == null) { throw new Exception("Email is null"); } String[] split = string.split("@"); if (split.length != 2) { throw new Exception("Email is malformed. Trying to parse '" + string + "'"); } return new Email(split[0], split[1]); } } static class SSN { public final Integer area; public final Integer group; public final Integer serial; private SSN(Integer area, Integer group, Integer serial) { this.area = area; this.group = group; this.serial = serial; } public static SSN fromString(String string) throws Exception { if (isNull(string)) { throw new Exception("SSN is null"); } String[] split = string.split("-"); if (split.length != 3) { throw new Exception("Email is malformed. Trying to parse '" + string + "'"); } validateForDigits(string, split); validateForInvalidDigits(string, split); return new SSN(Integer.valueOf(split[0]), Integer.valueOf(split[1]), Integer.valueOf(split[2])); } private static void validateForDigits(String string, String[] split) throws Exception { List<Character> areaList1 = new ArrayList<>(); for (char c : split[0].toCharArray()) { if (Character.isDigit(c)) areaList1.add(c); } if (areaList1.size() == 0) { throw new Exception("No digits found in area position '" + string + "'"); } List<Character> groupList1 = new ArrayList<>(); for (char c : split[1].toCharArray()) { if (Character.isDigit(c)) groupList1.add(c); } if (groupList1.size() == 0) { throw new Exception("No digits found in group position '" + string + "'"); } List<Character> serialList1 = new ArrayList<>(); for (char c : split[1].toCharArray()) { if (Character.isDigit(c)) serialList1.add(c); } if (serialList1.size() == 0) { throw new Exception("No digits found in serial position '" + string + "'"); } } private static void validateForInvalidDigits(String string, String[] split) throws Exception { List<Character> areaList2 = new ArrayList<>(); for (char c : split[0].toCharArray()) { if (!Character.isDigit(c)) areaList2.add(c); } if (areaList2.size() != 0) { throw new Exception("Invalid digit in area position '" + string + "'"); } List<Character> groupList2 = new ArrayList<>(); for (char c : split[1].toCharArray()) { if (!Character.isDigit(c)) groupList2.add(c); } if (groupList2.size() != 0) { throw new Exception("Invalid digit in group position '" + string + "'"); } List<Character> serialList2 = new ArrayList<>(); for (char c : split[1].toCharArray()) { if (!Character.isDigit(c)) serialList2.add(c); } if (serialList2.size() != 0) { throw new Exception("Invalid digit in serial position '" + string + "'"); } } } static class Age { public final int age; private Age(int age) { this.age = age; } public static Age fromString(String string) throws Exception { if (string == null) { throw new Exception("Age is null"); } if (string.isEmpty()) { throw new Exception("Age is empty"); } List<Character> characterList = new ArrayList<>(); for (char c : string.toCharArray()) { if (Character.isDigit(c)) characterList.add(c); } if (string.length() != characterList.size()) { throw new Exception("Age is malformed. trying to parse '" + string + "'"); } return new Age(Integer.valueOf(string)); } } public static void main(String[] args) { String goodEmail = "mrme@xmail.com"; String goodSSN = "111-11-2345"; String goodAge = "49"; Email goodEmailObject = null; String goodEmailError = ""; try { goodEmailObject = Email.fromString(goodEmail); } catch (Exception e) { goodEmailError = e.getMessage(); } SSN goodSSNObject = null; String goodSSNError = ""; try { goodSSNObject = SSN.fromString(goodSSN); } catch (Exception e) { goodSSNError = e.getMessage(); } Age goodAgeObject = null; String goodAgeError = ""; try { goodAgeObject = Age.fromString(goodAge); } catch (Exception e) { goodAgeError = e.getMessage(); } String goodResult = ""; String goodResultError = ""; if (!isNull(goodAgeObject) && !isNull(goodSSNObject) && !isNull(goodAgeObject)) { goodResult = String.format("email: %s@%s, ssn: %s-%s-%s, age %s", goodEmailObject.user, goodEmailObject.domain, goodSSNObject.area, goodSSNObject.group, goodSSNObject.serial, goodAgeObject.age); } else { if (!goodEmailError.isEmpty()) { goodResultError = goodEmailError; } else if (!goodSSNError.isEmpty()) { goodResultError = goodSSNError; } else if (!goodAgeError.isEmpty()) { goodResultError = goodAgeError; } } String badAge = "old"; String badSSN = "abc-22-2212"; Age badAgeObject = null; String badAgeError = ""; try { badAgeObject = Age.fromString(badAge); } catch (Exception e) { badAgeError = e.getMessage(); } SSN badSSNObject = null; String badSSNError = ""; try { badSSNObject = SSN.fromString(badSSN); } catch (Exception e) { badSSNError = e.getMessage(); } String badResult = ""; String badResultError = ""; if (!isNull(badAgeObject) && !isNull(badSSNObject) && !isNull(goodEmailObject)) { goodResult = String.format("email: %s@%s, ssn: %s-%s-%s, age %s", goodEmailObject.user, goodEmailObject.domain, badSSNObject.area, badSSNObject.group, badSSNObject.serial, badAgeObject.age); } else { if (!goodEmailError.isEmpty()) { badResultError = goodEmailError; } else if (!badSSNError.isEmpty()) { badResultError = badSSNError; } else if (!badAgeError.isEmpty()) { badResultError = badAgeError; } } if (badResultError.isEmpty()) { System.out.println(badResult); } else { System.out.println("I know at least one bad thing had happened. And I know what it is: " + badResultError); } if (goodResultError.isEmpty()) { System.out.println(goodResult); } else { System.out.println("I know at least one bad thing had happened. And I know what it is: " + goodResultError); } if (badSSNError.isEmpty()) { System.out.println(badSSNObject.area + "-" + badSSNObject.group + "-" + badSSNObject.serial); } else { System.out.println("BAD SSN TRACKER: ERROR: " + badSSNError); } } }
34.579592
120
0.513692
9e0c041f2f485887eb0d177de5de7408a688584a
1,923
package com.lqb.leetcode.mark.dfs; import org.junit.Test; import java.util.HashSet; import java.util.Set; /** * n 皇后问题 研究的是如何将 n 个皇后放置在 n × n 的棋盘上,并且使皇后彼此之间不能相互攻击。 * * 给你一个整数 n ,返回 n 皇后问题 不同的解决方案的数量。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/n-queens-ii * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class NQueens { @Test public void test() { // System.out.println(totalNQueens(1)); // System.out.println(totalNQueens(2)); // System.out.println(totalNQueens(3)); System.out.println(totalNQueens(4)); // System.out.println(totalNQueens(5)); // System.out.println(totalNQueens(6)); // System.out.println(totalNQueens(7)); // System.out.println(totalNQueens(8)); // System.out.println(totalNQueens(9)); } private int cnt = 0; public int totalNQueens(int n) { if (n <= 1) { return n; } Set<Integer> cols = new HashSet<>(n); Set<Integer> pY = new HashSet<>(n); Set<Integer> nY = new HashSet<>(n); totalNQueens(n, 0, cols, pY, nY); return cnt; } private void totalNQueens(int n, int curCol, Set<Integer> rows, Set<Integer> pYs, Set<Integer> nYs) { if (curCol >= n) { cnt++; return; } //在固定列的情况下,遍历行 for (int row = 0; row < n; row++) { //两根斜线,即y=x+a和y=-x+b存在一个公式能够唯一确定一根线 //即y-x=a,y+x=b,行下标和列下标相加或者相减总是一个常数,这个常数能够唯一确定是哪根斜线 int pY = curCol + row; int nY = curCol - row; if (rows.contains(row) || pYs.contains(pY) || nYs.contains(nY)) { continue; } rows.add(row); pYs.add(pY); nYs.add(nY); totalNQueens(n, curCol + 1, rows, pYs, nYs); rows.remove(row); pYs.remove(pY); nYs.remove(nY); } } }
27.471429
105
0.539262
351e354357b725847594c0b83b6ac3dbd304ae07
4,061
/* * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.nio.file.Path; import jdk.jpackage.test.JPackageCommand; import jdk.jpackage.test.PackageTest; import jdk.jpackage.test.PackageType; import jdk.jpackage.test.MacHelper; import jdk.jpackage.test.Annotations.Test; /** * Tests generation of dmg and pkg with --mac-sign and related arguments. * Test will generate pkg and verifies its signature. It verifies that dmg * is not signed, but app image inside dmg is signed. This test requires that * the machine is configured with test certificate for * "Developer ID Installer: jpackage.openjdk.java.net" in * jpackagerTest keychain with * always allowed access to this keychain for user which runs test. * note: * "jpackage.openjdk.java.net" can be over-ridden by systerm property * "jpackage.mac.signing.key.user.name", and * "jpackagerTest" can be over-ridden by system property * "jpackage.mac.signing.keychain" */ /* * @test * @summary jpackage with --type pkg,dmg --mac-sign * @library ../helpers * @library /test/lib * @library base * @key jpackagePlatformPackage * @build SigningBase * @build SigningCheck * @build jtreg.SkippedException * @build jdk.jpackage.test.* * @build SigningPackageTest * @modules jdk.jpackage/jdk.jpackage.internal * @requires (os.family == "mac") * @run main/othervm/timeout=360 -Xmx512m jdk.jpackage.test.Main * --jpt-run=SigningPackageTest */ public class SigningPackageTest { private static void verifyPKG(JPackageCommand cmd) { Path outputBundle = cmd.outputBundle(); SigningBase.verifyPkgutil(outputBundle); SigningBase.verifySpctl(outputBundle, "install"); } private static void verifyDMG(JPackageCommand cmd) { Path outputBundle = cmd.outputBundle(); SigningBase.verifyCodesign(outputBundle, false); } private static void verifyAppImageInDMG(JPackageCommand cmd) { MacHelper.withExplodedDmg(cmd, dmgImage -> { Path launcherPath = dmgImage.resolve(Path.of("Contents", "MacOS", cmd.name())); SigningBase.verifyCodesign(launcherPath, true); SigningBase.verifyCodesign(dmgImage, true); SigningBase.verifySpctl(dmgImage, "exec"); }); } @Test public static void test() throws Exception { SigningCheck.checkCertificates(); new PackageTest() .configureHelloApp() .forTypes(PackageType.MAC) .addInitializer(cmd -> { cmd.addArguments("--mac-sign", "--mac-signing-key-user-name", SigningBase.DEV_NAME, "--mac-signing-keychain", SigningBase.KEYCHAIN); }) .forTypes(PackageType.MAC_PKG) .addBundleVerifier(SigningPackageTest::verifyPKG) .forTypes(PackageType.MAC_DMG) .addBundleVerifier(SigningPackageTest::verifyDMG) .addBundleVerifier(SigningPackageTest::verifyAppImageInDMG) .run(); } }
38.67619
91
0.690717
faf67a71821f94f4919448d385cd7ddc47636d02
813
package org.jrenner.fps.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import org.jrenner.fps.Main; import org.jrenner.fps.utils.CommandArgs; public class DesktopLauncher { private static LwjglApplicationConfiguration cfg; public static void main (String[] args) { cfg = new LwjglApplicationConfiguration(); cfg.title = "FPS"; cfg.resizable = true; cfg.samples = 2; // anti-aliasing cfg.width = 1280; cfg.height = 720; cfg.fullscreen = false; cfg.r = 8; cfg.g = 8; cfg.b = 8; cfg.a = 8; CommandArgs.ScreenSize screenSize = CommandArgs.process(args); if (screenSize != null) { cfg.width = screenSize.width; cfg.height = screenSize.height; } new LwjglApplication(new Main(), cfg); } }
27.1
69
0.725707
b71812a3497e09122320ef5380d143486cfbd1b2
2,064
package hermitstate.patches; import com.evacipated.cardcrawl.modthespire.lib.SpirePatch; import com.evacipated.cardcrawl.modthespire.lib.SpirePostfixPatch; import com.evacipated.cardcrawl.modthespire.lib.SpirePrefixPatch; import com.megacrit.cardcrawl.actions.GameActionManager; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.powers.AbstractPower; import com.megacrit.cardcrawl.powers.watcher.VigorPower; import hermit.patches.VigorPatch; import hermit.powers.BigShotPower; import ludicrousspeed.simulator.ActionSimulator; /** * Duplicate Hermit Mod's Vigor patch to work around the simulator's action loop. */ public class VigorPowerPatch { @SpirePatch(clz = ActionSimulator.class, method = "ActionManageUpdate", paramtypez = {boolean.class}) public static class DisableHealing { @SpirePrefixPatch public static void Prefix(boolean shouldLog) { GameActionManager m = AbstractDungeon.actionManager; if (m.actions.isEmpty() && m.preTurnActions.isEmpty() && m.cardQueue .isEmpty() && VigorPatch.isActive) { VigorPatch.thisRun = true; } } @SpirePostfixPatch public static void Postfix(boolean shouldLog) { GameActionManager m = AbstractDungeon.actionManager; if (VigorPatch.thisRun) { if (AbstractDungeon.player.hasPower(BigShotPower.POWER_ID)) { AbstractPlayer p = AbstractDungeon.player; AbstractPower pow = AbstractDungeon.player.getPower(BigShotPower.POWER_ID); pow.flash(); AbstractDungeon.actionManager .addToBottom(new ApplyPowerAction(p, p, new VigorPower(p, pow.amount), pow.amount)); } VigorPatch.thisRun = false; VigorPatch.isActive = false; } } } }
41.28
112
0.682171
198e0a72e9bda0147d2d1577d40fd183a24f641f
2,106
package io.basc.framework.math; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Comparator; public class NumberComparator implements MathFunction<Number, Integer>, Comparator<Number> { public static final NumberComparator INSTANCE = new NumberComparator(); @Override public int compare(Number left, Number right) { if (left == right) { return 0; } if (left == null) { return -1; } if (right == null) { return 1; } if (left.equals(right)) { return 0; } if (left instanceof BigDecimal) { if (right instanceof BigDecimal) { return ((BigDecimal) left).compareTo((BigDecimal) right); } else if (right instanceof BigInteger) { return ((BigDecimal) left).compareTo(new BigDecimal((BigInteger) right)); } else if (right instanceof Float || right instanceof Double) { return ((BigDecimal) left).compareTo(new BigDecimal(right.doubleValue())); } else { return ((BigDecimal) left).compareTo(new BigDecimal(right.longValue())); } } else if (left instanceof BigInteger) { if (right instanceof BigDecimal) { return -compare(right, left); } else if (right instanceof BigInteger) { return ((BigInteger) left).compareTo((BigInteger) right); } else if (right instanceof Float || right instanceof Double) { return new BigDecimal((BigInteger) left).compareTo(new BigDecimal(right.doubleValue())); } else { return ((BigInteger) left).compareTo(BigInteger.valueOf(right.longValue())); } } else if (left instanceof Float || left instanceof Double) { if (right instanceof BigDecimal || right instanceof BigInteger) { return -compare(right, left); } else { return Double.compare(left.doubleValue(), right.doubleValue()); } } else { if (right instanceof BigDecimal || right instanceof BigInteger || right instanceof Float || right instanceof Double) { return -compare(right, left); } else { return Long.compare(left.longValue(), right.longValue()); } } } @Override public Integer eval(Number left, Number right) { return compare(left, right); } }
30.085714
92
0.689459
6e412ea868b92817fc4fe70116b5528a26fedbf8
246
public static String reverseIt(String source) { int i, len = source.length(); StringBuilder dest = new StringBuilder(len); for (i = (len - 1); i >= 0; i--){ dest.append(source.charAt(i)); } return dest.toString(); }
22.363636
48
0.593496
522a24d2299f209b3199578f72e49b1e6482ce94
7,640
/* * Copyright 2016-2017 Hippo B.V. (http://www.onehippo.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onehippo.cms.channelmanager.content.document.util; import java.io.Serializable; import java.rmi.RemoteException; import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.hippoecm.repository.api.Document; import org.hippoecm.repository.api.HippoWorkspace; import org.hippoecm.repository.api.Workflow; import org.hippoecm.repository.api.WorkflowException; import org.hippoecm.repository.standardworkflow.EditableWorkflow; import org.onehippo.cms.channelmanager.content.error.ErrorInfo; import org.onehippo.cms.channelmanager.content.error.InternalServerErrorException; import org.onehippo.repository.security.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * EditingUtils provides utility methods for dealing with the workflow of a document. */ public class EditingUtils { private static final Logger log = LoggerFactory.getLogger(EditingUtils.class); private static final String HINT_IN_USE_BY = "inUseBy"; private static final String HINT_COMMIT_EDITABLE_INSTANCE = "commitEditableInstance"; private static final String HINT_DISPOSE_EDITABLE_INSTANCE = "disposeEditableInstance"; private static final String HINT_OBTAIN_EDITABLE_INSTANCE = "obtainEditableInstance"; private static final String HINT_REQUESTS = "requests"; private EditingUtils() { } /** * Check if a workflow indicates that editing of a document can be started. * * @param workflow workflow for the current user on a specific document * @return true/false. */ public static boolean canCreateDraft(final EditableWorkflow workflow) { return isActionAvailable(workflow, HINT_OBTAIN_EDITABLE_INSTANCE); } /** * Check if a document can be updated, given its workflow. * * @param workflow editable workflow of a document * @return true if document can be updated, false otherwise */ public static boolean canUpdateDraft(final EditableWorkflow workflow) { return isActionAvailable(workflow, HINT_COMMIT_EDITABLE_INSTANCE); } /** * Check if a document can be updated, given its workflow. * * @param workflow editable workflow of a document * @return true if document can be updated, false otherwise */ public static boolean canDeleteDraft(final EditableWorkflow workflow) { return isActionAvailable(workflow, HINT_DISPOSE_EDITABLE_INSTANCE); } private static boolean isActionAvailable(final EditableWorkflow workflow, final String action) { try { Map<String, Serializable> hints = workflow.hints(); return hints.containsKey(action) && ((Boolean)hints.get(action)); } catch (WorkflowException | RemoteException | RepositoryException e) { log.warn("Failed reading hints from workflow", e); } return false; } /** * Determine the reason why editing failed for the present workflow. * * @param workflow workflow for the current user on a specific document * @param session current user's JCR session * @return Specific reason or nothing (unknown), wrapped in an Optional */ public static Optional<ErrorInfo> determineEditingFailure(final Workflow workflow, final Session session) { try { final Map<String, Serializable> hints = workflow.hints(); if (hints.containsKey(HINT_IN_USE_BY)) { final Map<String, Serializable> params = new HashMap<>(); final String userId = (String) hints.get(HINT_IN_USE_BY); params.put("userId", userId); getUserName(userId, session).ifPresent(userName -> params.put("userName", userName)); return Optional.of(new ErrorInfo(ErrorInfo.Reason.OTHER_HOLDER, params)); } if (hints.containsKey(HINT_REQUESTS)) { return Optional.of(new ErrorInfo(ErrorInfo.Reason.REQUEST_PENDING)); } } catch (RepositoryException | WorkflowException | RemoteException e) { log.warn("Failed to retrieve hints for workflow '{}'", workflow, e); } return Optional.empty(); } /** * Look up the real user name pertaining to a user ID * * @param userId ID of some user * @param session current user's JCR session * @return name of the user or nothing, wrapped in an Optional */ public static Optional<String> getUserName(final String userId, final Session session) { try { final HippoWorkspace workspace = (HippoWorkspace) session.getWorkspace(); final User user = workspace.getSecurityService().getUser(userId); final String firstName = user.getFirstName(); final String lastName = user.getLastName(); StringBuilder sb = new StringBuilder(); if (firstName != null) { sb.append(firstName.trim()); sb.append(" "); } if (lastName != null) { sb.append(lastName.trim()); } return Optional.of(sb.toString().trim()); } catch (RepositoryException e) { log.debug("Unable to determine displayName of user '{}'.", userId, e); } return Optional.empty(); } /** * Create a draft variant node for a document represented by handle node. * * @param workflow Editable workflow for the desired document * @param session JCR session for obtaining the draft node * @return JCR draft node or nothing, wrapped in an Optional */ public static Optional<Node> createDraft(final EditableWorkflow workflow, final Session session) { try { final Document document = workflow.obtainEditableInstance(); return Optional.of(document.getNode(session)); } catch (WorkflowException | RepositoryException | RemoteException e) { log.warn("Failed to obtain draft for user '{}'.", session.getUserID(), e); } return Optional.empty(); } /** * Copy the (validated) draft to the preview, and re-obtain the editable instance. * * @param workflow Editable workflow for the desired document * @param session JCR session for re-obtaining the draft node * @return JCR draft node or nothing, wrapped in an Optional */ public static Optional<Node> copyToPreviewAndKeepEditing(final EditableWorkflow workflow, final Session session) throws InternalServerErrorException { try { workflow.commitEditableInstance(); } catch (WorkflowException | RepositoryException | RemoteException e) { log.warn("Failed to commit changes for user '{}'.", session.getUserID(), e); return Optional.empty(); } return createDraft(workflow, session); } }
40.638298
116
0.675393
39980f044166403d746526310629301e86895f72
108
package com.vaadin.flow.uitest.ui.push; public class BasicPollIT extends AbstractClientServerCounterIT { }
21.6
64
0.833333
352a7bb4f95116854c93a655b0699c310c7dbee2
1,472
/* * 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.ulf.api.direct; import org.ulf.api.IMessage; /** * * @author jbytecoder */ public class M { public static IMessage me( Class c, String method ) { return L.m().at(L.LEVEL_ERROR).from(c.getName(), method); } public static IMessage me( Throwable th ) { return L.m().at(L.LEVEL_ERROR).about(th); } public static IMessage mw( Class c, String method ) { return L.m().at(L.LEVEL_WARNING).from(c.getName(), method); } public static IMessage mw( Throwable th ) { return L.m().at(L.LEVEL_WARNING).about(th); } public static IMessage mi( Class c, String method ) { return L.m().at(L.LEVEL_INFO).from(c.getName(), method); } public static IMessage mi( Throwable th ) { return L.m().at(L.LEVEL_INFO).about(th); } public static IMessage md( Class c, String method ) { return L.m().at(L.LEVEL_DEBUG).from(c.getName(), method); } public static IMessage md( Throwable th ) { return L.m().at(L.LEVEL_DEBUG).about(th); } public static IMessage mv( Class c, String method ) { return L.m().at(L.LEVEL_VERBOSE).from(c.getName(), method); } public static IMessage mv( Throwable th ) { return L.m().at(L.LEVEL_VERBOSE).about(th); } }
29.44
79
0.629076
46cec385d906aeafaee18f3cfdd87c23ce4a033a
718
package outside; import inside.*; public class test { public static void main(String[] args){ inside.moutherBoard mb = new inside.moutherBoard(); inside.cpu cpu = new inside.cpu(); inside.HardDisk hd = new inside.HardDisk(); inside.Screen sc = new inside.Screen(); sc.setRefresh_rate(240); sc.setSize((float) 15.6); mb.setId("msi"); mb.setPrice(6000); cpu.setName("i7"); cpu.setSpeed(2200); hd.setAmount(200); hd.setSpeed(5400); pc pc = new pc(); pc.setScreen(sc); pc.setCpu(cpu); pc.setHardDisk(hd); pc.setMoutherBoard(mb); pc.show(); } }
27.615385
60
0.538997
9318d0ce7cf5ddd469108fed2d9590177be5ab62
780
package cn.tedu.oop2; //本类测试继承中变量的使用 public class ExendsDome1 { public static void main(String[] args) { new Son().study(); } } //1.创建父类father类 class Father{ //3.创建父类的成员变量 int sum = 1; int count = 2; } //2.创建子类 class Son extends Father{ //4.创建子类的成员变量 int sum = 10; //5.创建子类的普通方法 public void study(){ System.out.println("good good study,day day up"); //6.创建子类的局部变量 int sum =100; //测试打印子类的局部变量-sum System.out.println(sum); //测试打印子类的成部变量-sum System.out.println(this.sum); //打印父类的成员变量 /*当父类的成员变量和子类的成员变量同名时,可以使用super指定父类的成员变量 * 我们可以把super看作是父类的对象:Father super = new Father();*/ System.out.println(super.sum); System.out.println(count); } }
22.941176
59
0.596154
ce3c727ba6fd22f926064ef8f035105656eefd47
227
package io.agrest.it.fixture.cayenne.iso; import io.agrest.it.fixture.cayenne.iso.auto._SqlDateTestEntity; public class SqlDateTestEntity extends _SqlDateTestEntity { private static final long serialVersionUID = 1L; }
22.7
64
0.801762
d7a0d0223d0e4235eb42a4c69eb78fadba027b12
1,637
package net.floodlightcontroller.egp.egpkeepalive; import java.util.Map; import net.floodlightcontroller.egp.event.LinkDownEvent; import net.floodlightcontroller.egp.event.LinkUpEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KeepAliveTimerThread extends Thread { protected static long timer = 10; private static Logger logger = LoggerFactory.getLogger("egp.egpkeepalive.KeepAliveTimerThread"); public void run() { while (true){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } long currentTime = System.currentTimeMillis(); for(Map.Entry<String,Long> entry : EGPKeepAlive.timermap.entrySet()){ String key = entry.getKey(); Long val = entry.getValue(); if (timer < (currentTime - val) / 1000) { if (EGPKeepAlive.statusmap.get(key).booleanValue() == true){ logger.warn("Link from {} is down!", key); String switchPortArray[] = key.split(": "); EGPKeepAlive.controllerMain.switchPortToRemoteController(switchPortArray[0], switchPortArray[1]) .getReceiveEvent().addEvent(new LinkDownEvent()); EGPKeepAlive.statusmap.put(key, Boolean.valueOf(false)); } } else{ if (EGPKeepAlive.statusmap.get(key).booleanValue() == false){ logger.warn("Link from {} is up!", key); String switchPortArray[] = key.split(": "); EGPKeepAlive.controllerMain.switchPortToRemoteController(switchPortArray[0], switchPortArray[1]) .getReceiveEvent().addEvent(new LinkUpEvent()); EGPKeepAlive.statusmap.put(key, Boolean.valueOf(true)); } } } } } }
32.74
102
0.697618
f5647d041699844d9501598b14863748a1fbd991
3,031
package admob.plus.cordova.ads; import com.google.android.gms.ads.AdError; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.FullScreenContentCallback; import com.google.android.gms.ads.LoadAdError; import com.google.android.gms.ads.appopen.AppOpenAd; import admob.plus.cordova.ExecuteContext; import admob.plus.cordova.Generated.Events; import admob.plus.core.Context; public class AppOpen extends AdBase { private final AdRequest mAdRequest; private final int mOrientation; private AppOpenAd mAd = null; public AppOpen(ExecuteContext ctx) { super(ctx); mAdRequest = ctx.optAdRequest(); Integer o = ctx.optInt("orientation"); mOrientation = o == null || o == 1 || o == 2 ? AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT : AppOpenAd.APP_OPEN_AD_ORIENTATION_LANDSCAPE; } @Override public void onDestroy() { clear(); super.onDestroy(); } @Override public void load(Context ctx) { clear(); AppOpenAd.load(getActivity(), adUnitId, mAdRequest, mOrientation, new AppOpenAd.AppOpenAdLoadCallback() { @Override public void onAdLoaded(AppOpenAd ad) { mAd = ad; ad.setFullScreenContentCallback(new FullScreenContentCallback() { @Override public void onAdDismissedFullScreenContent() { clear(); emit(Events.AD_DISMISS); } @Override public void onAdFailedToShowFullScreenContent(AdError adError) { clear(); emit(Events.AD_SHOW_FAIL, adError); } @Override public void onAdShowedFullScreenContent() { emit(Events.AD_SHOW); } @Override public void onAdImpression() { emit(Events.AD_IMPRESSION); } }); emit(Events.AD_LOAD); ctx.resolve(); } @Override public void onAdFailedToLoad(LoadAdError loadAdError) { clear(); emit(Events.AD_LOAD_FAIL, loadAdError); ctx.reject(loadAdError.toString()); } }); } @Override public boolean isLoaded() { return mAd != null; } @Override public void show(Context ctx) { mAd.show(getActivity()); ctx.resolve(true); } private void clear() { if (mAd != null) { mAd = null; } } }
30.616162
144
0.490927
01b70523f99f2e9ba0d5c5ccec06b3db186a8ec5
2,933
/* * Copyright 2018 Waldemar Kłaczyński. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ssoft.faces.impl.state.tag.scxml; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.state.scxml.model.Finalize; import javax.faces.state.scxml.model.OnEntry; import javax.faces.state.scxml.model.OnExit; import javax.faces.state.scxml.model.Transition; import javax.faces.view.facelets.FaceletContext; import javax.faces.view.facelets.TagAttribute; import javax.faces.view.facelets.TagConfig; import org.ssoft.faces.impl.state.tag.AbstractFlowTagHandler; import javax.faces.state.scxml.model.ActionsContainer; import javax.faces.state.scxml.model.Foreach; import javax.faces.state.scxml.model.SCXML; /** * * @author Waldemar Kłaczyński */ public class ForeathTagHandler extends AbstractFlowTagHandler<Foreach> { /** * */ protected final TagAttribute array; /** * */ protected final TagAttribute item; /** * */ protected final TagAttribute index; /** * * @param config */ public ForeathTagHandler(TagConfig config) { super(config, Foreach.class); in("onentry", OnEntry.class); in("onexit", OnExit.class); in("transition", Transition.class); in("finalize", Finalize.class); impl("actions continer", ActionsContainer.class); top("onentry", OnEntry.class); top("onexit", OnExit.class); top("transition", Transition.class); top("finalize", Finalize.class); this.array = this.getRequiredAttribute("array"); this.item = this.getRequiredAttribute("item"); this.index = this.getAttribute("index"); } /** * * @param ctx * @param parent * @param chart * @param parentElement * @throws IOException */ @Override public void apply(FaceletContext ctx, UIComponent parent, SCXML chart, Object parentElement) throws IOException { Foreach action = new Foreach(); decorate(ctx, parent, action); action.setArray(array.getValueExpression(ctx, Object.class)); action.setItem(item.getValueExpression(ctx, Object.class)); action.setIndex(index != null ? index.getValue() : null); addAction(ctx, parent, action); applyNext(ctx, parent, action); } }
29.33
117
0.672349
fe2a09fd21ea8c2790e4815b7340e5cadec4d63e
1,552
package be.unamur.info.b314.compiler.language.helper; import be.unamur.info.b314.compiler.PlayPlusParser; import be.unamur.info.b314.compiler.application.Application; import be.unamur.info.b314.compiler.exception.PlayPlusException; import java.util.ArrayList; import java.util.List; public class EnumExpression { /** * Method that parse an EnumerationDeclaration * @param ctx current EnumerationDeclaration context * @param application current application * @return the EnumerationDeclaration context */ public static Object parseEnumerationDeclaration(PlayPlusParser.EnumDeclarationContext ctx, Application application) { EnumExpression.parseEnumeration((PlayPlusParser.EnumerationContext)ctx, application); return ctx; } /** * Method that parse an Enumeration * @param ctx current enumeration context * @param application current application * @return the enumeration context */ public static Object parseEnumeration(PlayPlusParser.EnumerationContext ctx, Application application) { List<String> values = new ArrayList<>(); for (int i = 1; i < ctx.ID().size(); i++) { if (values.contains(ctx.ID(i).getText())) { throw new PlayPlusException("Cannot have duplicate value in an enumeration - Enum: " + ctx.ID(0).getText() + " Value: " + ctx.ID(i).getText()); } values.add(ctx.ID(i).getText()); } application.addEnum(ctx.ID(0).getText(), values); return ctx; } }
34.488889
159
0.686211
a5ed8fd6eb0cdea2fb83935912073e53202905f0
802
// Space: O(1) // Time: O(n) class Solution { public void rotate(int[][] matrix) { int m = matrix.length; int n = matrix[0].length; if (m == 1 && n == 1) return; int first = 0, last = n - 1; while (first < last) { int temp = last - first; for (int i = 0; i < temp; i++) { swap(matrix, first, first + i, first + i, last); swap(matrix, first, first + i, last, last - i); swap(matrix, first, first + i, last - i, first); } last--; first++; } } private void swap(int[][] matrix, int y1, int x1, int y2, int x2) { int temp = matrix[y1][x1]; matrix[y1][x1] = matrix[y2][x2]; matrix[y2][x2] = temp; } }
22.277778
71
0.437656
149ad053dfe3718a201b74ee1bbdfeb645d86920
2,150
package hec.dss.ensemble; import hec.stats.Statistics; import org.python.modules._hashlib; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * MetricPathTools methods support finding DSS paths that are used to * store statistical results with the following pattern. * * Time-Series: /A/B/parameter-statName//E/F/ * example: //Kanektok.BCAC1/flow-MIN/01Nov2013/1Hour/T:20131105-1200|V:20131105-120000|/ * * Paired-Data: /A/B/parameter-stats//E/F/ * example: //Kanektok.BCAC1/flow-stats///T:20131103-1200|V:20131103-120000|/ * */ class MetricPathTools { static private HashMap<String, Statistics> metricStringMap = new HashMap<>(); static private Pattern metricTimeSeriesPattern = Pattern.compile(getMetricPattern()); static private Pattern metricPairedDataPattern = Pattern.compile("-(stats)"); static { for (Statistics stat : Statistics.values()) metricStringMap.put(stat.toString(), stat); } static Statistics getMetricStatFromPath(String toString) { Statistics stat; Matcher matcher = metricTimeSeriesPattern.matcher(toString); if (matcher.find()) { String s = matcher.group(1); return metricStringMap.get(s); } return null; } static private String getMetricPattern() { StringBuilder builder = new StringBuilder(); Statistics[] stats = Statistics.values(); builder.append("-("); for (int i = 0; i < stats.length; i++) { if (i == stats.length - 1) builder.append(stats[i].toString()); else builder.append(stats[i].toString()).append("|"); } builder.append(")"); return builder.toString(); } static boolean isMetricTimeSeries(String cPart) { Matcher matcher = MetricPathTools.metricTimeSeriesPattern.matcher(cPart); return matcher.find(); } static boolean isMetricPairedData(String cPart) { Matcher matcher = MetricPathTools.metricPairedDataPattern.matcher(cPart); return matcher.find(); } }
31.15942
95
0.653488
8e6892507635ae3382e4a4925721ba2e6d37c784
10,151
package com.goim.bootstrap; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.util.Observable; import java.util.concurrent.atomic.AtomicReference; /** * An abstract blocking client, designed to connect to implementations of * AbstractServer in its own thread. Since the client only has a single * connection to a single server it can use blocking IO. This class provides a * set of callback methods for concrete implementations to know the state of the * client and its connection This client does not log, implementations should * handle this. * * This client does not support SSL or UDP connections. * */ public abstract class AbstractBlockingClient extends Observable implements Runnable { private enum State { STOPPED, STOPPING, RUNNING } private static short DEFAULT_MESSAGE_SIZE = 1024; private final AtomicReference<State> state = new AtomicReference<State>(State.STOPPED); protected final InetAddress server; protected final int port; private final int defaultBufferSize; private int defaultHeartBeatTimeOut = 20000; private int defaultSocketTimeOut = 3 * 60 * 1000; protected final Integer uid; protected final String game; private final AtomicReference<DataOutputStream> out = new AtomicReference<DataOutputStream>(); private final AtomicReference<DataInputStream> in = new AtomicReference<DataInputStream>(); /** * Construct an unstarted client which will attempt to connect to the given * server on the given port. * * @param server * the server address. * @param port * the port on which to connect to the server. */ public AbstractBlockingClient(InetAddress server, int port, Integer uid, String game) { this(server, port, uid, game, DEFAULT_MESSAGE_SIZE); } /** * Construct an unstarted client which will attempt to connect to the given * server on the given port. * * @param server * the server address. * @param port * the port on which to connect to the server. * @param defaultBufferSize * the default buffer size for reads. This should as small as * possible value that doesn't get exceeded often - see class * documentation. */ public AbstractBlockingClient(InetAddress server, int port, Integer uid, String game, int defaultBufferSize) { this.server = server; this.port = port; this.uid = uid; this.game = game; this.defaultBufferSize = defaultBufferSize; } /** * Returns the port to which this client will connect. * * @return the port to which this client will connect. */ public int getPort() { return port; } /** * Returns the host to which this client will connect. * * @return the host to which this client will connect. */ public InetAddress getServer() { return server; } /** * Returns true if this client is the running state (either connected or * trying to connect). * * @return true if this client is the running state (either connected or * trying to connect). */ public boolean isRunning() { return state.get() == State.RUNNING; } /** * Returns true if this client is the stopped state. * * @return true if this client is the stopped state. */ public boolean isStopped() { return state.get() == State.STOPPED; } /** * Attempt to connect to the server and receive messages. If the client is * already running, it will not be started again. This method is designed to * be called in its own thread and will not return until the client is * stopped. * * @throws RuntimeException * if the client fails */ public void run() { Socket socket = null; try { socket = new Socket(server, port); socket.setSoTimeout(defaultSocketTimeOut); out.set(new DataOutputStream(socket.getOutputStream())); in.set(new DataInputStream(socket.getInputStream())); if (!state.compareAndSet(State.STOPPED, State.RUNNING)) { return; } authWrite(); while (state.get() == State.RUNNING) { byte[] inBuffer = new byte[defaultBufferSize]; int readPoint = in.get().read(inBuffer); if (readPoint != -1) { byte[] result = BruteForceCoding.tail(inBuffer, inBuffer.length - 16); Long operation = BruteForceCoding.decodeIntBigEndian(inBuffer, 8, 4); if (3 == operation) { heartBeatReceived(); } else if (8 == operation) { authSuccess(); heartBeat(); } else if (5 == operation) { Long packageLength = BruteForceCoding.decodeIntBigEndian(inBuffer, 0, 4); Long headLength = BruteForceCoding.decodeIntBigEndian(inBuffer, 4, 2); Long version = BruteForceCoding.decodeIntBigEndian(inBuffer, 6, 2); Long sequenceId = BruteForceCoding.decodeIntBigEndian(inBuffer, 12, 4); //messageReceived(packageLength, headLength, version,operation, sequenceId,new String(result).trim()); messageReceived(new String(result).trim()); } } } } catch (Exception ioe) { System.out.println("Client failure: " + ioe.getMessage()); try { socket.close(); state.set(State.STOPPED); disconnected(); } catch (Exception e) { // do nothing - server failed } restart(); } } private void restart(){ if (true){ super.setChanged(); } notifyObservers(); } /** * Stop the client in a graceful manner. After this call the client may * spend some time in the process of stopping. A disconnected callback will * occur when the client actually stops. * * @return if the client was successfully set to stop. */ public boolean stop() { if (state.compareAndSet(State.RUNNING, State.STOPPING)) { try { in.get().close(); } catch (IOException e) { return false; } return true; } return false; } /** * Send the given message to the server. * * @param buffer * the message to send. * @return true if the message was sent to the server. * @throws IOException */ public synchronized Boolean authWrite() throws IOException { String msg = uid + "," + getGameCode(game); int packLength = msg.length() + 16; byte[] message = new byte[4 + 2 + 2 + 4 + 4]; // package length int offset = BruteForceCoding.encodeIntBigEndian(message, packLength, 0, 4 * BruteForceCoding.BSIZE); // header lenght offset = BruteForceCoding.encodeIntBigEndian(message, 16, offset, 2 * BruteForceCoding.BSIZE); // ver offset = BruteForceCoding.encodeIntBigEndian(message, 1, offset, 2 * BruteForceCoding.BSIZE); // operation offset = BruteForceCoding.encodeIntBigEndian(message, 7, offset, 4 * BruteForceCoding.BSIZE); // jsonp callback offset = BruteForceCoding.encodeIntBigEndian(message, 1, offset, 4 * BruteForceCoding.BSIZE); out.get().write(BruteForceCoding.add(message, msg.getBytes())); out.get().flush(); return true; } /** * Send the given message to the server. * * @param buffer * the message to send. * @return true if the message was sent to the server. * @throws IOException */ public synchronized Boolean heartBeatWrite() throws IOException { String msg = uid + "," + getGameCode(game); int packLength = msg.length() + 16; byte[] message = new byte[4 + 2 + 2 + 4 + 4]; // package length int offset = BruteForceCoding.encodeIntBigEndian(message, packLength, 0, 4 * BruteForceCoding.BSIZE); // header lenght offset = BruteForceCoding.encodeIntBigEndian(message, 16, offset, 2 * BruteForceCoding.BSIZE); // ver offset = BruteForceCoding.encodeIntBigEndian(message, 1, offset, 2 * BruteForceCoding.BSIZE); // operation offset = BruteForceCoding.encodeIntBigEndian(message, 2, offset, 4 * BruteForceCoding.BSIZE); // jsonp callback offset = BruteForceCoding.encodeIntBigEndian(message, 1, offset, 4 * BruteForceCoding.BSIZE); out.get().write(BruteForceCoding.add(message, msg.getBytes())); out.get().flush(); return true; } /**** * get game code */ private int getGameCode(String game) { int sum = 0; byte[] array = game.getBytes(); for (int i = 0; i < array.length; i++) { sum += array[i]; } return sum; } /***** * heart beat Thread */ private void heartBeat() { Thread hbThread = new Thread(new HeartbeatTask()); hbThread.start(); } /** * Callback method for when the client receives a message from the server. * * @param message * the message from the server. */ protected abstract void messageReceived(Long packageLength, Long headLength, Long version, Long operation, Long sequenceId, String message); /** * Callback method for when the client receives a message from the server. * * @param message * the message from the server. */ protected abstract void messageReceived(String message); /** * Callback method for when the client receives a message from the server. * * @param message * the message from the server. */ protected abstract void heartBeatReceived(); /** * Callback method for when the client receives a message from the server. * * @param message * the message from the server. */ protected abstract void authSuccess(); /** * Callback method for when the client connects to the server. * * @param alreadyConnected * whether the client was already connected to the server. */ protected abstract void connected(boolean alreadyConnected); /** * Callback method for when the client disconnects from the server. */ protected abstract void disconnected(); class HeartbeatTask implements Runnable { @Override public void run() { // TODO Auto-generated method stub // !Thread.currentThread().isInterrupted() while (true) { try { Thread.sleep(defaultHeartBeatTimeOut); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { heartBeatWrite(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
28.920228
141
0.681805
619447d454c4096cff3f8cef971ef0d03d12a13b
445
package core.validation; /** * Represents a result detail type. */ public enum ResultDetailType { /** * Represents an error result. */ Error(0), /** * Represents a warning result. */ Warning(1), /** * */ Information(2); private final int status; ResultDetailType(int status) { this.status = status; } public int status(){ return this.status; } }
14.354839
35
0.539326
2055fbe590d2467c5aa7cacb07e52f267b588e70
456
package tech.jhipster.lite.generator.init.infrastructure.primary.rest; import io.cucumber.java.en.When; import tech.jhipster.lite.generator.ModulesSteps; public class InitSteps extends ModulesSteps { @When("I init default project") public void initFull() { applyModuleForDefaultProject("/api/inits/full"); } @When("I init minimal default project") public void initMinimal() { applyModuleForDefaultProject("/api/inits/minimal"); } }
25.333333
70
0.754386
62ecabedb118f19c21718fbc8bdc3030cc116bb9
786
package com.ats.kbsearch.decorators; import com.ats.kbsearch.data.Data; import java.util.HashSet; import java.util.Set; /** * Created by amit on 5/15/17. */ public class ContextMapDecorator extends TokenDecorator { public ContextMapDecorator(Data data) { super(data); } @Override public Set<String> updateTokens(Set<String> tokens) { Set<String> tokensWithContext = new HashSet<>(); Set<Set> dataDictionary = super.getData().getContextMap(); for(Set<String> contextMap : dataDictionary) { if(contextMap.stream().anyMatch(word -> tokens.contains(word))) { tokensWithContext.addAll(contextMap); } } tokensWithContext.addAll(tokens); return tokensWithContext; } }
24.5625
77
0.648855
866cbf177946ab356aba528b3c70d692ca83e8ff
2,581
package com.nullspace.socket; import java.net.InetSocketAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.nullspace.command.NSCommandManager; import com.nullspace.logic.NSSessionManager; import com.nullspace.packet.NSMessage; import com.nullspace.packet.NSMessageHead; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class NSSocketChannelHandler extends SimpleChannelInboundHandler<NSMessage> { private static Logger mLogger = LoggerFactory.getLogger(NSSocketChannelHandler.class); @Override protected void channelRead0(ChannelHandlerContext ctx, NSMessage msg) throws Exception { NSSocketSession session = ctx.channel().attr(NSSocketChannelKey.SESSION).get(); NSCommandManager.instance.ExecuteMessage(session, msg); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { NSSocketSession session = new NSSocketSession(); NSSessionManager.manager.AddSession(session); ByteBuf buf = PooledByteBufAllocator.DEFAULT.directBuffer(NSMessageHead.Size()); NSMessageHead head = new NSMessageHead(); session.Channel(ctx.channel()); ctx.channel().attr(NSSocketChannelKey.SESSION).set(session); ctx.channel().attr(NSSocketChannelKey.SESSIONBUF).set(buf); ctx.channel().attr(NSSocketChannelKey.HEAD).set(head); ctx.channel().attr(NSSocketChannelKey.IsSharedHeadFilled).set(false); InetSocketAddress saddr = (InetSocketAddress)ctx.channel().remoteAddress(); session.IP(saddr.getHostString()); session.port(saddr.getPort()); System.out.println("connected: " + session.IP() + " " + session.port()); mLogger.info("connected: " + session.IP() + " " + session.port()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { NSSocketSession session = ctx.channel().attr(NSSocketChannelKey.SESSION).get(); ctx.channel().attr(NSSocketChannelKey.SESSIONBUF).get().release(); NSSessionManager.manager.Remove(session.id()); System.out.println("disconnected: " + session.IP() + " " + session.port()); mLogger.info("disconnected: " + session.IP() + " " + session.port()); ctx.close(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("exception: " + cause.getMessage()); ctx.close(); } }
37.405797
88
0.729562
f9430e921c9877f807420f6d861bcbd5c2758660
1,650
package com.cyc.baseclient.parser; //// Internal Imports import com.cyc.baseclient.cycobject.CycGuid; //// External Imports import java.util.*; /** * <P>Thrown whenever the CycL parser tries to parse a constant by its CycGuid, and the Cyc server does not already have a constant by that CycGuid defined. * * @version $Id: InvalidConstantGuidException.java 150787 2014-04-26 01:55:03Z nwinant $ * @author Tony Brusseau */ public class InvalidConstantGuidException extends Exception { //// Constructors /** Creates a new instance of InvalidConstantName. */ public InvalidConstantGuidException(CycGuid invalidConstantGuid) { this.invalidConstantGuids = new ArrayList(); this.invalidConstantGuids.add(invalidConstantGuid); } public InvalidConstantGuidException() { } //// Public Area public String getMessage() { StringBuffer buf = new StringBuffer("Invalid constant GUID(s): "); if (getInvalidConstantNames() != null) { for (Iterator iter = getInvalidConstantNames().iterator(); iter.hasNext(); ) { buf.append("#G").append(iter.next()); if (iter.hasNext()) { buf.append(", "); } } } return buf.toString(); } public void addInvalidConstantGuid(CycGuid invalidConstantGuid) { if (invalidConstantGuids == null) { invalidConstantGuids = new ArrayList(); } invalidConstantGuids.add(invalidConstantGuid); } public List getInvalidConstantNames() { return invalidConstantGuids; } //// Protected Area //// Private Area //// Internal Rep private List invalidConstantGuids; //// Main }
24.626866
88
0.68
488c704465144883820eb95839b58ba0d30ad924
925
package com.wch.gulimall.order.feign; import com.wch.common.utils.R; import com.wch.gulimall.order.vo.WareLockVo; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; /** * @author wch * @version 1.0 * @date 2022/4/1 21:58 */ @FeignClient("gulimall-warehouse") public interface WaresFeignService { /** * 获取库存 * @param skuIds * @return */ @PostMapping("/ware/waresku/hasstock") R getSkuStock(@RequestBody List<Long> skuIds); @GetMapping("/ware/wareinfo/fare") R getFare(@RequestParam("addrId") Long addrId); @PostMapping("/ware/waresku/lock/order") R orderWareLock(@RequestBody WareLockVo wareLockVo); }
27.205882
60
0.740541
0872c6e04a40788e832b26fe16244aa7cffe72bb
4,234
/* * 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.flink.streaming.api.windowing.windowbuffer; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; import org.apache.flink.api.common.functions.ReduceFunction; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.streaming.api.windowing.StreamWindow; /* * Grouped pre-reducer for sliding eviction policy * (the slide size is smaller than the window size). */ public abstract class SlidingGroupedPreReducer<T> extends SlidingPreReducer<T> { private static final long serialVersionUID = 1L; protected Map<Object, T> currentReducedMap = new HashMap<Object, T>(); protected LinkedList<Map<Object, T>> reducedMap = new LinkedList<Map<Object, T>>(); protected KeySelector<T, ?> key; public SlidingGroupedPreReducer(ReduceFunction<T> reducer, TypeSerializer<T> serializer, KeySelector<T, ?> key) { super(reducer, serializer); this.key = key; } public boolean addFinalAggregate(StreamWindow<T> currentWindow) throws Exception { Map<Object, T> finalReduce = null; if (!reducedMap.isEmpty()) { finalReduce = reducedMap.get(0); for (int i = 1; i < reducedMap.size(); i++) { finalReduce = reduceMaps(finalReduce, reducedMap.get(i)); } if (currentReducedMap != null) { finalReduce = reduceMaps(finalReduce, currentReducedMap); } } else { finalReduce = currentReducedMap; } if (finalReduce != null) { currentWindow.addAll(finalReduce.values()); return true; } else { return false; } } private Map<Object, T> reduceMaps(Map<Object, T> first, Map<Object, T> second) throws Exception { Map<Object, T> reduced = new HashMap<Object, T>(); // Get the common keys in the maps Set<Object> interSection = new HashSet<Object>(); Set<Object> diffFirst = new HashSet<Object>(); Set<Object> diffSecond = new HashSet<Object>(); for (Object key : first.keySet()) { if (second.containsKey(key)) { interSection.add(key); } else { diffFirst.add(key); } } for (Object key : second.keySet()) { if (!interSection.contains(key)) { diffSecond.add(key); } } // Reduce the common keys for (Object key : interSection) { reduced.put( key, reducer.reduce(serializer.copy(first.get(key)), serializer.copy(second.get(key)))); } for (Object key : diffFirst) { reduced.put(key, first.get(key)); } for (Object key : diffSecond) { reduced.put(key, second.get(key)); } return reduced; } protected void updateCurrent(T element) throws Exception { if (currentReducedMap == null) { currentReducedMap = new HashMap<Object, T>(); currentReducedMap.put(key.getKey(element), element); } else { Object nextKey = key.getKey(element); T last = currentReducedMap.get(nextKey); if (last == null) { currentReducedMap.put(nextKey, element); } else { currentReducedMap.put(nextKey, reducer.reduce(serializer.copy(last), element)); } } } @Override protected void removeLastReduced() { reducedMap.removeFirst(); } @Override protected void addCurrentToBuffer(T element) throws Exception { reducedMap.add(currentReducedMap); } @Override protected void resetCurrent() { currentReducedMap = null; } @Override protected boolean currentNotEmpty() { return currentReducedMap != null; } }
27.673203
98
0.712329
717b9b2f752906ba46897416cfb97676f78ed616
531
package com.google.android.gms.internal.ads; /* renamed from: com.google.android.gms.internal.ads.Pa */ final /* synthetic */ class C9055Pa implements zzbal { /* renamed from: a */ private final zzamd f21575a; /* renamed from: b */ private final Object f21576b; C9055Pa(zzamd zzamd, Object obj) { this.f21575a = zzamd; this.f21576b = obj; } /* renamed from: a */ public final zzbbh mo26658a(Object obj) { return this.f21575a.mo29813a(this.f21576b, (zzalf) obj); } }
24.136364
64
0.638418
29e08c6b3eac9bd9909274428ccd9d050feaf7a4
6,368
package org.jmisb.api.klv.st0601.dto; /** * Weapon Store data. * * <p>This class supports the ST0601 WeaponsStores implementation. */ public class WeaponStore { private int stationId; private int hardpointId; private int carriageId; private int storeId; private WeaponStoreStatus status; private boolean fuzeEnabled; private boolean laserEnabled; private boolean targetEnabled; private boolean weaponArmed; private String storeType; /** * Get the station identifier. * * <p>In this case, this is not a "weapon station" - see hardpoint. Instead it is the "payload * station" in the sense used by STANAG 4586 (see AEP-84) for the stores management system * (SMS). * * @return integer identifier for the station identifier */ public int getStationId() { return stationId; } /** * Set the station identifier. * * <p>In this case, this is not a "weapon station" - see hardpoint. Instead it is the "payload * station" in the sense used by STANAG 4586 (see AEP-84) for the stores management system * (SMS). * * @param stationId integer identifier for the station identifier */ public void setStationId(int stationId) { this.stationId = stationId; } /** * Get the hardpoint identifier. * * <p>This corresponds to the aircraft hardpoint where the stores suspension equipment starts * (e.g. a wing pylon, or bay location). Some platforms would call this a weapons station. * * @return the hardpoint identifier */ public int getHardpointId() { return hardpointId; } /** * Set the hardpoint identifier. * * <p>This corresponds to the aircraft hardpoint where the stores suspension equipment starts * (e.g. a wing pylon, or bay location). Some platforms would call this a weapons station. * * @param hardpointId the hardpoint identifier */ public void setHardpointId(int hardpointId) { this.hardpointId = hardpointId; } /** * Get the carriage identifier. * * <p>This corresponds to something between the hardpoint and the store-specific suspension * equipment, such as a dual-position rack (e.g. BRU-55/A). * * @return the carriage identifier */ public int getCarriageId() { return carriageId; } /** * Set the carriage identifier. * * <p>This corresponds to something between the hardpoint and the store-specific suspension * equipment, such as a dual-position rack (e.g. BRU-55/A). * * @param carriageId the carriage identifier */ public void setCarriageId(int carriageId) { this.carriageId = carriageId; } /** * Get the store identifier. * * <p>This corresponds to a position on store-specific suspension equipment, such as a launcher * or miniature store rack. * * @return the store identifier */ public int getStoreId() { return storeId; } /** * Set the store identifier. * * <p>This corresponds to a position on store-specific suspension equipment, such as a launcher * or miniature store rack. * * @param storeId the store identifier */ public void setStoreId(int storeId) { this.storeId = storeId; } /** * Get the general status of the store. * * @return store status (enumerated value) */ public WeaponStoreStatus getStatus() { return status; } /** * Set the general status of the store. * * @param status store status (enumerated value) */ public void setStatus(WeaponStoreStatus status) { this.status = status; } /** * Check if fuze engagement status is set. * * @return true if Fuze functions are set, otherwise false */ public boolean isFuzeEnabled() { return fuzeEnabled; } /** * Set fuze engagement status. * * @param fuzeEnabled true if Fuze functions are set, otherwise false */ public void setFuzeEnabled(boolean fuzeEnabled) { this.fuzeEnabled = fuzeEnabled; } /** * Check if laser engagement status is set. * * @return true if Laser functions are set, otherwise false */ public boolean isLaserEnabled() { return laserEnabled; } /** * Set laser engagement status. * * @param laserEnabled true if Laser functions are set, otherwise false */ public void setLaserEnabled(boolean laserEnabled) { this.laserEnabled = laserEnabled; } /** * Check if target engagement status is set. * * @return true if target functions are set, otherwise false */ public boolean isTargetEnabled() { return targetEnabled; } /** * Set target engagement status. * * @param targetEnabled true if target functions are set, otherwise false */ public void setTargetEnabled(boolean targetEnabled) { this.targetEnabled = targetEnabled; } /** * Check if weapon is armed in engagement status. * * <p>ST0601 suggests this is "master arm", but it probably is intended to be weapon specific. * * @return true if weapon is armed, otherwise false */ public boolean isWeaponArmed() { return weaponArmed; } /** * Set weapon arm status in engagement status. * * <p>ST0601 suggests this is "master arm", but it probably is intended to be weapon specific. * * @param weaponArmed true if weapon is armed, otherwise false */ public void setWeaponArmed(boolean weaponArmed) { this.weaponArmed = weaponArmed; } /** * Get the type of store. * * <p>This is the "name" of the store or weapon type (e.g. "Harpoon", or "GBU-15"). * * @return string representing the store type */ public String getStoreType() { return storeType; } /** * Set the type of store. * * <p>This is the "name" of the store or weapon type (e.g. "Harpoon", or "GBU-15"). * * @param storeType string representing the store type */ public void setStoreType(String storeType) { this.storeType = storeType; } }
27.213675
99
0.623901
386327f7ee119b3f82d96d032266f514deb18060
1,114
package engine.shader; import org.joml.Matrix4f; import org.joml.Vector3f; public class LightShader extends ShaderProgram{ private static final String VERTEX_FILE = "./res/shaders/lightVS.glsl"; private static final String FRAGMENT_FILE = "./res/shaders/lightFS.glsl"; private int location_projectionMatrix; private int location_rgb; private int location_time; public LightShader() { super(VERTEX_FILE, FRAGMENT_FILE); } @Override protected void bindAttributes() { super.bindAttribute(0, "position"); } @Override protected void getAllUniformLocations() { location_projectionMatrix = super.getUniformLocation("projection_matrix"); location_rgb = super.getUniformLocation("rgbColor"); location_time = super.getUniformLocation("pass_time"); } public void loadProjectionMatrix(Matrix4f projection) { super.loadMatrix(location_projectionMatrix, projection); } public void setLightColour(Vector3f colour) { super.loadVector(location_rgb, colour); } public void time(float time) { super.loadFloat(location_time, time); } }
25.318182
77
0.739677
fce63286c806caebdade341287e123fca38b6ce0
3,133
/* * Copyright (c) 2015 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.metric; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; public class PointSerialization { public static class Deserializer extends JsonDeserializer<Point> { @Override public Point deserialize(JsonParser p, DeserializationContext c) throws IOException, JsonProcessingException { if (p.getCurrentToken() != JsonToken.START_ARRAY) { throw c.mappingException( String.format("Expected start of array, not %s", p.getCurrentToken())); } if (!p.nextToken().isNumeric()) { throw c.wrongTokenException(p, JsonToken.VALUE_NUMBER_INT, "Expected timestamp (number)"); } final long timestamp = p.getLongValue(); if (!p.nextToken().isNumeric()) { throw c.wrongTokenException(p, JsonToken.VALUE_NUMBER_FLOAT, "Expected value (number)"); } final double value = p.getDoubleValue(); if (p.nextToken() != JsonToken.END_ARRAY) { throw c.mappingException( String.format("Expected end of array, not %s", p.getCurrentToken())); } return new Point(timestamp, value); } } public static class Serializer extends JsonSerializer<Point> { @Override public void serialize(Point d, JsonGenerator g, SerializerProvider provider) throws IOException, JsonProcessingException { g.writeStartArray(); g.writeNumber(d.getTimestamp()); final double value = d.getValue(); if (Double.isFinite(value)) { g.writeNumber(value); } else { g.writeNull(); } g.writeEndArray(); } } }
36.011494
95
0.649537
e30d0bc1a7d7d1cf04356cdd6dda2ec6755941c2
2,309
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: DunsAttribute.proto package io.daos.dfs.uns; public final class DunsClasses { private DunsClasses() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_uns_DunsAttribute_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_uns_DunsAttribute_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\023DunsAttribute.proto\022\003uns\"\301\001\n\rDunsAttri" + "bute\022\016\n\006poolId\030\001 \001(\t\022\016\n\006contId\030\002 \001(\t\022 \n\013" + "layout_type\030\003 \001(\0162\013.uns.Layout\022\023\n\013object" + "_type\030\004 \001(\t\022\022\n\nchunk_size\030\005 \001(\004\022\020\n\010rel_p" + "ath\030\006 \001(\t\022\021\n\ton_lustre\030\007 \001(\010\022\021\n\tno_prefi" + "x\030\t \001(\010\022\r\n\005flags\030\n \001(\r**\n\006Layout\022\013\n\007UNKN" + "OWN\020\000\022\t\n\005POSIX\020\001\022\010\n\004HDF5\020\002B \n\017io.daos.df" + "s.unsB\013DunsClassesP\001b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_uns_DunsAttribute_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_uns_DunsAttribute_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_uns_DunsAttribute_descriptor, new java.lang.String[] { "PoolId", "ContId", "LayoutType", "ObjectType", "ChunkSize", "RelPath", "OnLustre", "NoPrefix", "Flags", }); } // @@protoc_insertion_point(outer_class_scope) }
42.759259
141
0.726722
d0e338fdce1e19bdbfc272ec942337be6aeaad4d
1,050
package com.github.aha.sat.rest.city.resource; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.core.Relation; import com.github.aha.sat.rest.city.City; import com.github.aha.sat.rest.city.CityHateoasController; import lombok.EqualsAndHashCode; import lombok.Getter; @Getter @EqualsAndHashCode(callSuper = false) @Relation(collectionRelation = "cities") public class CityResource extends CityBaseResource { private long id; public CityResource(City city) { this.id = city.getId(); setName(city.getName()); setState(city.getState()); setCountry(city.getCountry()); } public EntityModel<CityResource> toResource() { return EntityModel.of(this, linkTo(methodOn(CityHateoasController.class).getOne(id)).withSelfRel(), linkTo(CityHateoasController.class).slash(id).withRel("delete")); } }
30
81
0.764762
36fe93fa61d15ab73d9ad045f0cd93369ee53302
274
package net.miginfocom.layout; public abstract class UnitConverter { public static final int UNABLE = -87654312; public abstract int convertToPixels(float f, String str, boolean z, float f2, ContainerWrapper containerWrapper, ComponentWrapper componentWrapper); }
34.25
152
0.79562
c014663659695d85477b9599f7c43af7dad933b1
3,081
package reciter.utils; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import reciter.model.identity.AuthorName; @RunWith(MockitoJUnitRunner.class) public class AuthorNameSanitizationUtilsTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public final void testSanitizeArticleAuthorNames() { //fail("Not yet implemented"); } @Test public final void testSanitizeIdentityAuthorNames() { //fail("Not yet implemented"); } @Test public final void testCheckToIgnoreNameVariants() { Map<AuthorName, AuthorName> sanitizedIdentityAuthorMap = new HashMap<AuthorName, AuthorName>(); AuthorNameSanitizationUtils authorNameSanitizationUtils = new AuthorNameSanitizationUtils(); sanitizedIdentityAuthorMap.put(new AuthorName("Joerg-Patrick", null, "Stuebgen"), new AuthorName("JoergPatrick", null, "Stuebgen")); sanitizedIdentityAuthorMap.put(new AuthorName("Jo", null, "Stuebgen"), new AuthorName("Jo", null, "Stuebgen")); authorNameSanitizationUtils.checkToIgnoreNameVariants(sanitizedIdentityAuthorMap); //Check for AuthorName firstName starts with other AuthorName and middle name is null or empty assertEquals("Removed one name", 1, sanitizedIdentityAuthorMap.size()); sanitizedIdentityAuthorMap.clear(); sanitizedIdentityAuthorMap.put(new AuthorName("Joerg-Patrick", null, "Stuebgen"), new AuthorName("JoergPatrick", null, "Stuebgen")); sanitizedIdentityAuthorMap.put(new AuthorName("JoE", null, "Stuebgen"), new AuthorName("JoE", null, "Stuebgen")); authorNameSanitizationUtils.checkToIgnoreNameVariants(sanitizedIdentityAuthorMap); assertEquals("Case ensitive check", 1, sanitizedIdentityAuthorMap.size()); sanitizedIdentityAuthorMap.clear(); sanitizedIdentityAuthorMap.put(new AuthorName("Joerg-Patrick", null, "Stuebgen"), new AuthorName("JoergPatrick", null, "Stuebgen")); sanitizedIdentityAuthorMap.put(new AuthorName("JoE", null, "Stuebgen"), new AuthorName("JoE", null, "Stuebgen")); sanitizedIdentityAuthorMap.put(new AuthorName("Jo", null, "Stuebgen"), new AuthorName("Jo", null, "Stuebgen")); sanitizedIdentityAuthorMap.put(new AuthorName("Joseph", "Patrick", "Stuebgen"), new AuthorName("Joseph", "Patrick", "Stuebgen")); sanitizedIdentityAuthorMap.put(new AuthorName("Jose", "Patrick", "Stuebgen"), new AuthorName("Jose", "Patrick", "Stuebgen")); authorNameSanitizationUtils.checkToIgnoreNameVariants(sanitizedIdentityAuthorMap); assertEquals("All check including case sensitive, first case & second case", 2, sanitizedIdentityAuthorMap.size()); } @Test public final void testGenerateSuffixRegex() { //fail("Not yet implemented"); } }
39
134
0.774748
dc438a696cc72b0c0343419e2bd908468b74e326
2,270
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.engine.impl.migration.validation.instruction; import org.camunda.bpm.engine.impl.bpmn.parser.EventSubscriptionDeclaration; import org.camunda.bpm.engine.impl.jobexecutor.TimerDeclarationImpl; import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl; import org.camunda.bpm.engine.impl.pvm.process.ScopeImpl; /** * Ensure that the option updateEventTriggers can only be used activities defining an event trigger * * @author Thorben Lindhauer */ public class UpdateEventTriggersValidator implements MigrationInstructionValidator { @Override public void validate(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, MigrationInstructionValidationReportImpl report) { ActivityImpl sourceActivity = instruction.getSourceActivity(); if (instruction.isUpdateEventTrigger() && !definesPersistentEventTrigger(sourceActivity)) { report.addFailure("Cannot update event trigger because the activity does not define a persistent event trigger"); } } public static boolean definesPersistentEventTrigger(ActivityImpl activity) { ScopeImpl eventScope = activity.getEventScope(); if (eventScope != null) { return TimerDeclarationImpl.getDeclarationsForScope(eventScope).containsKey(activity.getId()) || EventSubscriptionDeclaration.getDeclarationsForScope(eventScope).containsKey(activity.getId()); } else { return false; } } }
42.037037
119
0.782379
c5d1d777e3ce4c3de4f350713286b33af12cbb12
1,191
package com.codeflowcrafter.LogManagement; import com.codeflowcrafter.LogManagement.Interfaces.ILogEntry; import com.codeflowcrafter.LogManagement.Interfaces.ILogManager; import static org.junit.Assert.assertEquals; /** * Created by aiko on 4/29/17. */ public class LogManagerTests { GlobalLogExtender _logExtender = new GlobalLogExtender(); ILogManager _logManager = LogManager.GetInstance(); @org.junit.Before public void Initialize() { _logManager.SetEmitter(_logExtender); } @org.junit.Test public void TestLogEmission() { ILogEntry entry = _logManager.CreateLogEntry(Priority.Alert); entry.SetSystem("Security System"); entry.SetApplication("Security Tester"); entry.SetComponent("Authentication Component"); entry.SetEvent("Validation"); entry.SetDescription("Validation has been invoked but was failed"); entry.SetStatus(Status.Failure); entry.AddParameter("Param 1", "value 1"); entry.AddParameter("Param 2", "value 2"); _logManager.EmitLog(entry); ILogEntry log = _logExtender.GetOutputLog(); assertEquals(true, log != null); } }
28.357143
75
0.696893
e90200126e2dac8b17cf10563c38d16159a01ad8
357
package com.monri.android; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by jasminsuljic on 2019-09-26. * MonriAndroidSDK */ @Retention(RetentionPolicy.SOURCE) @IntDef({ ValidationCodes.CARD_INVALID }) public @interface ValidationCode { }
18.789474
44
0.733894
958a26fb77f90db3bd660ccf30e37c4b3a615093
280
package com.higlowx.scal.ebpp.common.consts; /** * @author Dylan.Lee * @date 2021/7/8 */ public class UriConsts { public static final String TRADE_PREFIX = "trade"; public static final String BILL_PREFIX = "bill"; public static final String MSG_PREFIX = "msg"; }
21.538462
54
0.696429
301924a234d297992d85b4bae12d4105cf0ced38
87
package com.olgapoduzdikova.testmanager.validation; public interface UpdateStatus { }
17.4
51
0.83908
c193cbdc6eb51330041c9ec6b6fe1742c66d1142
11,630
package de.bornemisza.ds.users.endpoint; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Function; import javax.ejb.Stateless; import javax.inject.Inject; import javax.mail.internet.AddressException; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; 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.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import de.bornemisza.rest.HttpHeaders; import de.bornemisza.rest.entity.EmailAddress; import de.bornemisza.rest.entity.User; import de.bornemisza.rest.exception.BusinessException; import de.bornemisza.rest.exception.UnauthorizedException; import de.bornemisza.rest.security.DoubleSubmitToken; import de.bornemisza.ds.users.boundary.UsersFacade; import de.bornemisza.ds.users.boundary.UsersType; import static de.bornemisza.ds.users.boundary.UsersType.EMAIL_ALREADY_EXISTS; import static de.bornemisza.ds.users.boundary.UsersType.USER_ALREADY_EXISTS; @Stateless @Path("/") public class Users { @Inject UsersFacade facade; public Users() { } // Constructor for Unit Tests public Users(UsersFacade facade) { this.facade = facade; } @GET @Path("{name}") @Produces(MediaType.APPLICATION_JSON) public Response getUser(@PathParam("name") String userName, @HeaderParam(HttpHeaders.COOKIE) String cookie, @HeaderParam(HttpHeaders.CTOKEN) String ctoken) { if (isVoid(userName) || hasIllegalCharacters(userName)) { return Response.status(Status.BAD_REQUEST).build(); } User user; try { user = facade.getUser(userName, new DoubleSubmitToken(cookie, ctoken)); } catch (UnauthorizedException ex) { return Response.status(Status.UNAUTHORIZED).build(); } catch (RuntimeException ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } if (user == null) { return Response.status(Status.NOT_FOUND).build(); } else { user.setStatus(Status.OK); return user.toResponse(); } } @POST @Consumes(MediaType.APPLICATION_JSON) public Response userAccountCreationRequest(User user) { if (user == null || user.getEmail() == null) { return Response.status(Status.BAD_REQUEST).entity("No User or E-Mail missing!").build(); } else if (hasIllegalCharacters(user.getName())) { return Response.status(Status.BAD_REQUEST).entity("Illegal Characters in User Name!").build(); } Consumer userAccountCreationRequestConsumer = new Consumer<UsersFacade>() { @Override public void accept(UsersFacade facade) { facade.addUser(user); } }; return executeRequest(userAccountCreationRequestConsumer); } @GET @Path("confirmation/user/{uuid}") @Produces(MediaType.APPLICATION_JSON) public Response confirmUser(@PathParam("uuid") String uuidStr) { if (! validateUuid(uuidStr)) { return Response.status(Status.BAD_REQUEST).entity("UUID missing or unparseable!").build(); } Function confirmUserFunction = new Function<UsersFacade, Response>() { @Override public Response apply(UsersFacade facade) { User user = facade.confirmUser(uuidStr); if (user == null) return Response.status(Status.CONFLICT).build(); else return Response.ok().entity(user).build(); } }; String expiryMsg = "User Account Creation Request does not exist - maybe expired?"; String conflictMsg = "User already exists!"; return executeConfirmation(confirmUserFunction, expiryMsg, conflictMsg); } @PUT @Path("{name}/email") @Consumes(MediaType.TEXT_PLAIN) public Response changeEmailRequest(@PathParam("name") String userName, String emailStr, @HeaderParam(HttpHeaders.COOKIE) String cookie, @HeaderParam(HttpHeaders.CTOKEN) String ctoken) { if (isVoid(userName)) return Response.status(Status.BAD_REQUEST).build(); EmailAddress email = validateEmail(emailStr); if (email == null) { return Response.status(Status.BAD_REQUEST).entity("E-Mail missing or unparseable!").build(); } User user; try { user = facade.getUser(userName, new DoubleSubmitToken(cookie, ctoken)); } catch (UnauthorizedException ex) { return Response.status(Status.UNAUTHORIZED).build(); } catch (RuntimeException ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } if (user == null) { return Response.status(Status.NOT_FOUND).build(); } user.setEmail(email); Consumer changeEmailRequestConsumer = new Consumer<UsersFacade>() { @Override public void accept(UsersFacade facade) { facade.changeEmail(user); } }; return executeRequest(changeEmailRequestConsumer); } @GET @Path("confirmation/email/{uuid}") @Produces(MediaType.APPLICATION_JSON) public Response confirmEmail(@PathParam("uuid") String uuidStr, @HeaderParam(HttpHeaders.AUTHORIZATION) String authHeader) { if (! validateUuid(uuidStr)) { return Response.status(Status.BAD_REQUEST).entity("UUID missing or unparseable!").build(); } Function confirmEmailFunction = new Function<UsersFacade, Response>() { @Override public Response apply(UsersFacade facade) { User user = facade.confirmEmail(uuidStr, authHeader); if (user == null) return Response.status(Status.CONFLICT).build(); else return Response.ok().entity(user).build(); } }; String expiryMsg = "E-Mail Change Request does not exist - maybe expired?"; String conflictMsg = "Newer Revision exists!"; return executeConfirmation(confirmEmailFunction, expiryMsg, conflictMsg); } @PUT @Path("{name}/password/{newpassword}") @Produces(MediaType.APPLICATION_JSON) public Response changePassword(@PathParam("name") String userName, @PathParam("newpassword") String password, @HeaderParam(HttpHeaders.AUTHORIZATION) String authHeader) { if (isVoid(userName) || isVoid(password)) return Response.status(Status.BAD_REQUEST).build(); User user; try { user = facade.getUser(userName, authHeader); } catch (UnauthorizedException ex) { return Response.status(Status.UNAUTHORIZED).build(); } catch (RuntimeException ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } if (user == null) { return Response.status(Status.NOT_FOUND).build(); } user.setPassword(password.toCharArray()); try { user = facade.changePassword(user, user.getRevision(), authHeader); } catch (RuntimeException ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } if (user == null) { return Response.status(Status.CONFLICT).entity("Newer Revision exists!").build(); } return Response.ok().entity(user).build(); } @DELETE @Path("{name}") public Response deleteUser(@PathParam("name") String userName, @HeaderParam(HttpHeaders.AUTHORIZATION) String authHeader) { if (isVoid(userName)) return Response.status(Status.NOT_FOUND).build(); User user; try { user = facade.getUser(userName, authHeader); } catch (UnauthorizedException ex) { return Response.status(Status.UNAUTHORIZED).build(); } catch (RuntimeException ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } if (user == null) { return Response.status(Status.NOT_FOUND).build(); } boolean success; try { success = facade.deleteUser(userName, user.getRevision(), authHeader); } catch (RuntimeException ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } if (!success) { return Response.status(Status.CONFLICT).entity("Newer Revision exists!").build(); } return Response.noContent().build(); } private boolean isVoid(String value) { if (value == null) { return true; } else if (value.length() == 0) { return true; } else { return value.equals("null"); } } private boolean hasIllegalCharacters(String value) { if (isVoid(value)) { return false; } String[] array = value.split("[<>\"&']", 2); return array.length > 1; } private boolean validateUuid(String uuidStr) { UUID uuid; try { uuid = isVoid(uuidStr) ? null : UUID.fromString(uuidStr); } catch (IllegalArgumentException iae) { uuid = null; } if (uuid == null) return false; else return true; } private EmailAddress validateEmail(String emailStr) { try { return isVoid(emailStr) ? null : new EmailAddress(emailStr); } catch (AddressException ae) { return null; } } private Response executeRequest(Consumer userAccountCreationRequestConsumer) { try { userAccountCreationRequestConsumer.accept(facade); } catch (BusinessException be) { Response.Status status = Status.INTERNAL_SERVER_ERROR; // default if (be.getType() instanceof UsersType) { UsersType type = (UsersType) be.getType(); if (type == USER_ALREADY_EXISTS || type == EMAIL_ALREADY_EXISTS) { status = Status.CONFLICT; } } return Response.status(status).entity(be.getMessage()).build(); } catch (RuntimeException ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } return Response.accepted().build(); } private Response executeConfirmation(Function<UsersFacade, Response> function, String expiryMsg, String conflictMsg) { try { return function.apply(facade); } catch (BusinessException e) { Status status = ((e.getType() instanceof UsersType && (UsersType) e.getType() == UsersType.UUID_NOT_FOUND) ? Status.NOT_FOUND : Status.INTERNAL_SERVER_ERROR); return Response.status(status).entity(expiryMsg).build(); } catch (RuntimeException ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } } }
37.516129
170
0.613844
4440fc62802660ab715846016fbf4f82a986bb66
2,594
package com.abr.springpatternsamples; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import static java.util.stream.Collectors.toMap; @SpringBootApplication public class SpringPatternSamples { public static void main(String[] args) { SpringApplication.run(SpringPatternSamples.class, args); } private ApplicationContext context; // @Autowired on single constructor exists implicitly, and because of that listOfResponders is filled by Spring public SpringPatternSamples(ApplicationContext context, List<Responder> listOfResponders) { this.context = context; // this demonstrates how Spring fills map with components using result of their method getRqType as key this.responders = listOfResponders.stream().collect(toMap(Responder::getRqType, p -> p)); } // this demonstrates how Spring puts components in map by their ID // IDs were set with annotations @Component("1") and @Component("2") @Autowired private Map<String, Responder> awResponders; private Map<String, Responder> responders; @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return agrs -> { // this demonstrates how to get component from map by it's ID Responder r = awResponders.get("2"); System.out.println(r.getResponse()); // this demonstrates, how to get component by it's unique key r = responders.get("MsgClientAccountListRq"); System.out.println(r.getResponse()); // this demonstrates ablity of components to register themself in ResponderRegistry ResponderRegistry respReg = ctx.getBean(ResponderRegistry.class); r = respReg.get("MsgClientAccountListRq"); System.out.println(r.getResponse()); // String rqBody = "///<MsgClientAccountListRq2>///"; try { r = respReg.getByRequestBody(rqBody); System.out.println(r.getResponse()); } catch(NotImplementedException ne) { System.err.println("Responder for request body " + rqBody + " is not implemented"); } }; } }
39.30303
112
0.703161
8c06ba673316b6c2c4acfc2fab0addf01bf7928f
4,127
package betterwithmods.common.blocks; import betterwithmods.util.FluidUtils; import betterwithmods.util.item.ToolsManager; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Enchantments; import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class BlockIce extends net.minecraft.block.BlockIce { private static final PropertyBool NATURAL = PropertyBool.create("natural"); public BlockIce() { super(); setHardness(0.5F); setLightOpacity(3); setSoundType(SoundType.GLASS); setTranslationKey("ice"); ToolsManager.setPickaxesAsEffectiveAgainst(this); setDefaultState(getDefaultState().withProperty(NATURAL, true)); } @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, NATURAL); } @Override public void harvestBlock(World worldIn, EntityPlayer player, BlockPos pos, IBlockState state, @Nullable TileEntity te, ItemStack stack) { player.addStat(StatList.getBlockStats(this)); player.addExhaustion(0.005F); if (this.canSilkHarvest(worldIn, pos, state, player) && EnchantmentHelper.getEnchantmentLevel(Enchantments.SILK_TOUCH, stack) > 0) { java.util.List<ItemStack> items = new java.util.ArrayList<ItemStack>(); items.add(this.getSilkTouchDrop(state)); net.minecraftforge.event.ForgeEventFactory.fireBlockHarvesting(items, worldIn, pos, state, 0, 1.0f, true, player); for (ItemStack is : items) spawnAsEntity(worldIn, pos, is); } else { if (worldIn.provider.doesWaterVaporize()) { worldIn.setBlockToAir(pos); return; } int i = EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, stack); harvesters.set(player); this.dropBlockAsItem(worldIn, pos, state, i); harvesters.set(null); Material material = worldIn.getBlockState(pos.down()).getMaterial(); if (material.blocksMovement() || material.isLiquid()) { setWater(worldIn, pos, state); } } } @Override protected void turnIntoWater(@Nonnull World worldIn, @Nonnull BlockPos pos) { if (worldIn.provider.doesWaterVaporize()) { worldIn.setBlockToAir(pos); } else { IBlockState state = worldIn.getBlockState(pos); this.dropBlockAsItem(worldIn, pos, state, 0); setWater(worldIn, pos, state); } } private void setWater(World world, BlockPos pos, IBlockState state) { if(state.getBlock() != this) return; if (state.getValue(NATURAL)) { world.setBlockState(pos, Blocks.FLOWING_WATER.getDefaultState()); } else { FluidUtils.setLiquid(world, pos, Blocks.WATER, 14, true); for (EnumFacing facing : EnumFacing.HORIZONTALS) { FluidUtils.setLiquid(world, pos.offset(facing), Blocks.WATER, 10, false); } } world.neighborChanged(pos, Blocks.WATER, pos); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(NATURAL) ? 1 : 0; } @Override public IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(NATURAL, meta == 1); } @Override protected ItemStack getSilkTouchDrop(IBlockState state) { return new ItemStack(this, 1, getMetaFromState(state)); } }
35.886957
141
0.67337
1e5ffec6c36fe39b79831f2772fe96210436c1e9
6,581
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.javascript.karma.preferences; import java.io.File; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; import org.netbeans.api.annotations.common.CheckForNull; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectUtils; import org.netbeans.modules.javascript.karma.util.KarmaUtils; import org.netbeans.modules.javascript.karma.util.StringUtils; import org.netbeans.modules.web.browser.api.WebBrowser; import org.netbeans.spi.project.support.ant.PropertyUtils; import org.openide.filesystems.FileUtil; /** * Project specific Karma preferences. */ public final class KarmaPreferences { public static final String CONFIG = "config"; // NOI18N private static final String ENABLED = "enabled"; // NOI18N private static final String AUTOWATCH = "autowatch"; // NOI18N private static final String DEBUG = "debug"; // NOI18N private static final String DEBUG_BROWSER_ID = "debug.browser.id"; // NOI18N private static final String BROWSER_ERROR_FAIL = "browser.error.fail"; // NOI18N private static final ConcurrentMap<Project, Preferences> CACHE = new ConcurrentHashMap<>(); private KarmaPreferences() { } public static boolean isEnabled(Project project) { return getPreferences(project).getBoolean(ENABLED, false); } public static void setEnabled(Project project, boolean enabled) { getPreferences(project).putBoolean(ENABLED, enabled); } @CheckForNull public static String getConfig(Project project) { return resolvePath(project, getPreferences(project).get(CONFIG, null)); } public static void setConfig(Project project, String config) { getPreferences(project).put(CONFIG, relativizePath(project, config)); } public static boolean isAutowatch(Project project) { return getPreferences(project).getBoolean(AUTOWATCH, false); } public static void setAutowatch(Project project, boolean autowatch) { getPreferences(project).putBoolean(AUTOWATCH, autowatch); } public static boolean isDebug(Project project) { return getPreferences(project).getBoolean(DEBUG, false); } public static void setDebug(Project project, boolean debug) { getPreferences(project).putBoolean(DEBUG, debug); } public static boolean isDebugBrowserIdSet(Project project) { return getPreferences(project).get(DEBUG_BROWSER_ID, null) != null; } @CheckForNull public static String getDebugBrowserId(Project project) { String browserId = getPreferences(project).get(DEBUG_BROWSER_ID, null); if (browserId != null) { return browserId; } WebBrowser preferredBrowser = KarmaUtils.getPreferredDebugBrowser(); if (preferredBrowser != null) { return preferredBrowser.getId(); } return null; } public static void setDebugBrowserId(Project project, String browserId) { getPreferences(project).put(DEBUG_BROWSER_ID, browserId); } public static boolean isFailOnBrowserError(Project project) { return getPreferences(project).getBoolean(BROWSER_ERROR_FAIL, true); } public static void setFailOnBrowserError(Project project, boolean fail) { getPreferences(project).putBoolean(BROWSER_ERROR_FAIL, fail); } public static void addPreferenceChangeListener(Project project, PreferenceChangeListener listener) { getPreferences(project).addPreferenceChangeListener(listener); } public static void removePreferenceChangeListener(Project project, PreferenceChangeListener listener) { getPreferences(project).removePreferenceChangeListener(listener); } public static void removeFromCache(final Project project) { CACHE.remove(project); } private static Preferences getPreferences(final Project project) { assert project != null; Preferences preferences = CACHE.get(project); if (preferences == null) { preferences = ProjectUtils.getPreferences(project, KarmaPreferences.class, false); Preferences currentPreferences = CACHE.putIfAbsent(project, preferences); if (currentPreferences != null) { preferences = currentPreferences; } else { // preferences put into cache, run autodetection detectConfig(project); } } assert preferences != null; return preferences; } private static void detectConfig(Project project) { if (getConfig(project) != null) { return; } File config = KarmaUtils.findKarmaConfig(KarmaUtils.getKarmaConfigDir(project)); if (config != null) { setConfig(project, config.getAbsolutePath()); } } private static String relativizePath(Project project, String filePath) { if (!StringUtils.hasText(filePath)) { return ""; // NOI18N } File file = new File(filePath); String path = PropertyUtils.relativizeFile(FileUtil.toFile(project.getProjectDirectory()), file); if (path == null || path.startsWith("../")) { // NOI18N // cannot be relativized or outside project path = file.getAbsolutePath(); } return path; } private static String resolvePath(Project project, String filePath) { if (!StringUtils.hasText(filePath)) { return null; } return PropertyUtils.resolveFile(FileUtil.toFile(project.getProjectDirectory()), filePath).getAbsolutePath(); } }
36.765363
117
0.69959
b634bb9ec166477e72fa4ad8430bc6c0928efae9
625
package network.warzone.tgm.modules.damage; import network.warzone.tgm.match.MatchModule; import org.bukkit.entity.Firework; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; public class FireworkDamageModule extends MatchModule implements Listener { @EventHandler(priority= EventPriority.LOWEST) public void onDamage(EntityDamageByEntityEvent event) { if (event.getDamager() instanceof Firework) { event.setCancelled(true); event.setDamage(0); } } }
31.25
75
0.7584
cbeeeaf7ef488936d78268f4766647968881923a
4,666
package com.timeset.photo.service; import com.baidu.aip.imageclassify.AipImageClassify; import com.baidu.aip.ocr.AipOcr; import com.google.gson.Gson; import com.timeset.photo.entity.Photo; import com.timeset.photo.entity.PhotoList; import com.timeset.photo.mapper.PhotoMapper; import org.json.JSONObject; import org.springframework.stereotype.Service; import org.springframework.util.ClassUtils; import javax.annotation.Resource; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.util.*; /** * @ClassName PhotoServiceImpl * @Description * @Author lz * @Date 2020-04-23 18:07 */ @Service public class PhotoServiceImpl { @Resource private PhotoMapper photoMapper; private AipOcr aipOcr = TextRecogintion.getAipOcr(); private AipImageClassify aipImageClassify = ImageRecogintion.getAipImageClassify(); public int addPhoto(Photo image,String path) { // 1. 识别生成image的文字信息 String text = TextRecogintion.test(path,aipOcr, image); JSONObject textObj = new JSONObject(text); System.out.println(textObj.names()); List<Map<String, String>> textList = new Gson().fromJson(textObj.get("words_result").toString(), List.class); System.out.println("获取的识别文本信息"); StringBuilder tex = new StringBuilder("["); for (int i = 0; i < textList.size(); i++) { tex.append("\""+textList.get(i).get("words")+"\","); } tex.append("]"); /* List<String> listTex = new Gson().fromJson(new String(tex),List.class); System.out.println("生成链表"+listTex.toString());*/ System.out.println("生成字符串"+new String(tex)); System.out.println(tex); //2. 识别生成image的物体和场景信息 String description = ImageRecogintion.getAdvancedGeneral(path,aipImageClassify, image); JSONObject desObj = new JSONObject(description); List<Map<String, Object>> desList = new Gson().fromJson(desObj.get("result").toString(), List.class); System.out.println("获取的识别物体和场景信息"); StringBuilder des = new StringBuilder("["); for (int i = 0; i < desList.size(); i++) { if (Double.parseDouble(desList.get(i).get("score").toString()) > 0.01) { des.append("\""+desList.get(i).get("keyword")+"\","); } } des.deleteCharAt(des.length()-1); des.append("]"); // List<String> listDec = new Gson().fromJson(new String(des),List.class); // System.out.println("生成链表"+listDec.toString()); System.out.println("生成字符串"+new String(des)); image.setIdentify(new String(tex)+new String(des)); System.out.println("图片信息:"+image.toString()); int result=photoMapper.addPhoto(image); if(result!=0){ return 0; } return -1; } public int deletePhoto(int id){ String destFileName = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/" + photoMapper.findPhotoNameById(id).getPath().trim(); File file = new File(destFileName); file.delete(); return photoMapper.deletePhoto(id); } public int updatePhotoDescription(String describe,int id){ return photoMapper.updatePhotoDescription(describe,id);} public List<Photo> findAll(int userId){return photoMapper.findAll(userId);}; public List<PhotoList> findByAlbum(int albumId, int userId){return photoMapper.findByAlbum(albumId,userId);}; public List<Photo> findByTime(String date,int userId){return photoMapper.findByTime(date,userId);}; public Map<String, List<Photo>> findPlaceOrDescribeOrIdentify(String str,int userId){ Map<String,List<Photo>> map1=new HashMap<>(); List<Photo> photos1 =photoMapper.findPlace(str,userId); List<Photo> photos2 =photoMapper.findDescribe(str,userId); List<Photo> photos3=photoMapper.findIdentify(str,userId); if(photos1.size()>0){ map1.put("place",photos1); } if(photos2.size()>0){ map1.put("contain",photos2); } if(photos3.size()>0){ map1.put("identify",photos3); } // lists.add(map1); // Map<String,List<Photo>> map2=new HashMap<>(); // lists.add(map2); // if(photos1.size()!=0){ // for(Photo p:photos1){ // photoAll.add(p); // } // } // if(photos2.size()!=0){ // for(Photo p:photos2){ // photoAll.add(p); // } // } // if(photoAll!=null){ // photos=new ArrayList(photoAll); // } return map1; } }
36.453125
156
0.630733
db8a76f8ec6db8bc1c17782eb56ebe580967f501
629
public class QuestionA { public static int findSmallestDifference(int[] array1, int[] array2) { if (array1.length == 0 || array2.length == 0) { return -1; } int min = Integer.MAX_VALUE; for (int i = 0; i < array1.length; i++) { for (int j = 0; j < array2.length; j++) { if (Math.abs(array1[i] - array2[j]) < min) { min = Math.abs(array1[i] - array2[j]); } } } return min; } public static void main(String[] args) { int[] array1 = {1, 3, 15, 11, 2}; int[] array2 = {23, 127, 234, 19, 8}; int difference = findSmallestDifference(array1, array2); System.out.println(difference); } }
25.16
71
0.594595
cdaecd3ffab4b2ccad7b61c9f1d754289feef26a
1,181
/** * A type variable. * @author Alan Jeffrey * @version v1.0 1998/06/02 */ public class PremonTypeVar extends PremonType { private String s; /** * The type variable <code>string</code>. */ public static PremonTypeVar string = new PremonTypeVar ("string"); /** * The type variable <code>int</code>. */ public static PremonTypeVar integer = new PremonTypeVar ("int"); /** * The type variable <code>double</code>. */ public static PremonTypeVar dubble = new PremonTypeVar ("double"); /** * Create a new type variable. * @param s the name of the type. */ public PremonTypeVar (String s) { this.s = s; } public void print (Printer p) { p.printRoman (s); } /** * Returns a generator. * @return s (viewed as a sort). */ public Obj semantics () { return new ObjGenerator (s); } public boolean equals (PremonType T) { if (T instanceof PremonTypeVar) { return s.equals (((PremonTypeVar)T).s); } else { return false; } } /** * Type variables are not traceable. * @return false. */ public boolean traceable () { return false; } }
17.626866
68
0.595258
2f7cd65e315dc0f6caf5bfe36634d4650ba58bd5
854
package com.fabiogouw.eventprocessingapp.core.dtos; public class Withdraw { private String _correlationId; private String _accountFrom; private double _amount; public String getCorrelationId() { return _correlationId; } public void setCorrelationId(String value) { _correlationId = value; } public String getAccountFrom() { return _accountFrom; } public void setAccountFrom(String value) { _accountFrom = value; } public double getAmount() { return _amount; } public void setAmount(double value) { _amount = value; } public Withdraw() { } public Withdraw(String correlationId, String accountFrom, double amount) { _correlationId = correlationId; _accountFrom = accountFrom; _amount = amount; } }
20.333333
78
0.645199
4905ecb79ed6a345e74f160ee8f8e698f352a8eb
928
/* * 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 com.j2ee.webcrawler.models; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; /** * * @author An Le */ public class ProductMapper implements RowMapper<Product>{ @Override public Product mapRow(ResultSet rs, int i) throws SQLException { Product product = new Product(); product.setId(rs.getString("id")); product.setName(rs.getString("name")); product.setPrice(rs.getInt("price")); product.setOriginalPrice(rs.getInt("originalPrice")); product.setUrl(rs.getString("url")); product.setRatingScore(rs.getFloat("ratingScore")); product.setImage(rs.getString("image")); return product; } }
29
79
0.6875
2064e4d80a261f2e1a1d329e480fa2adc525d408
14,330
/* * MIT License * * Copyright (c) 2020 Airbyte * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.airbyte.server.handlers; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.airbyte.api.model.CheckConnectionRead; import io.airbyte.api.model.ConnectionIdRequestBody; import io.airbyte.api.model.DestinationIdRequestBody; import io.airbyte.api.model.DestinationImplementationIdRequestBody; import io.airbyte.api.model.SourceIdRequestBody; import io.airbyte.api.model.SourceImplementationIdRequestBody; import io.airbyte.commons.docker.DockerUtils; import io.airbyte.commons.enums.Enums; import io.airbyte.commons.json.JsonValidationException; import io.airbyte.commons.json.Jsons; import io.airbyte.config.ConnectorSpecification; import io.airbyte.config.DestinationConnectionImplementation; import io.airbyte.config.JobOutput; import io.airbyte.config.SourceConnectionImplementation; import io.airbyte.config.StandardCheckConnectionOutput; import io.airbyte.config.StandardDestination; import io.airbyte.config.StandardGetSpecOutput; import io.airbyte.config.StandardSource; import io.airbyte.config.StandardSync; import io.airbyte.config.persistence.ConfigNotFoundException; import io.airbyte.config.persistence.ConfigRepository; import io.airbyte.scheduler.Job; import io.airbyte.scheduler.JobStatus; import io.airbyte.scheduler.persistence.SchedulerPersistence; import io.airbyte.server.helpers.ConnectionHelpers; import io.airbyte.server.helpers.DestinationImplementationHelpers; import io.airbyte.server.helpers.SourceImplementationHelpers; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class SchedulerHandlerTest { private static final long JOB_ID = 15L; private static final String SOURCE_DOCKER_REPO = "srcimage"; private static final String SOURCE_DOCKER_TAG = "tag"; private static final String SOURCE_DOCKER_IMAGE = DockerUtils.getTaggedImageName(SOURCE_DOCKER_REPO, SOURCE_DOCKER_TAG); private static final String DESTINATION_DOCKER_REPO = "dstimage"; private static final String DESTINATION_DOCKER_TAG = "tag"; private static final String DESTINATION_DOCKER_IMAGE = DockerUtils.getTaggedImageName(DESTINATION_DOCKER_REPO, DESTINATION_DOCKER_TAG); private SchedulerHandler schedulerHandler; private ConfigRepository configRepository; private SchedulerPersistence schedulerPersistence; private Job inProgressJob; private Job completedJob; @BeforeEach void setup() { inProgressJob = mock(Job.class); when(inProgressJob.getStatus()).thenReturn(JobStatus.RUNNING); completedJob = mock(Job.class); when(completedJob.getStatus()).thenReturn(JobStatus.COMPLETED); configRepository = mock(ConfigRepository.class); schedulerPersistence = mock(SchedulerPersistence.class); schedulerHandler = new SchedulerHandler(configRepository, schedulerPersistence); } @Test void testCheckSourceImplementationConnection() throws JsonValidationException, IOException, ConfigNotFoundException { SourceConnectionImplementation sourceImpl = SourceImplementationHelpers.generateSourceImplementation(UUID.randomUUID()); final SourceImplementationIdRequestBody request = new SourceImplementationIdRequestBody().sourceImplementationId(sourceImpl.getSourceImplementationId()); when(configRepository.getStandardSource(sourceImpl.getSourceId())) .thenReturn(new StandardSource() .withDockerRepository(SOURCE_DOCKER_REPO) .withDockerImageTag(SOURCE_DOCKER_TAG) .withSourceId(sourceImpl.getSourceId())); when(configRepository.getSourceConnectionImplementation(sourceImpl.getSourceImplementationId())).thenReturn(sourceImpl); when(schedulerPersistence.createSourceCheckConnectionJob(sourceImpl, SOURCE_DOCKER_IMAGE)).thenReturn(JOB_ID); when(schedulerPersistence.getJob(JOB_ID)).thenReturn(inProgressJob).thenReturn(completedJob); schedulerHandler.checkSourceImplementationConnection(request); verify(configRepository).getSourceConnectionImplementation(sourceImpl.getSourceImplementationId()); verify(schedulerPersistence).createSourceCheckConnectionJob(sourceImpl, SOURCE_DOCKER_IMAGE); verify(schedulerPersistence, times(2)).getJob(JOB_ID); } @Test void testGetSourceSpec() throws JsonValidationException, IOException, ConfigNotFoundException, URISyntaxException { SourceIdRequestBody sourceIdRequestBody = new SourceIdRequestBody().sourceId(UUID.randomUUID()); when(configRepository.getStandardSource(sourceIdRequestBody.getSourceId())) .thenReturn(new StandardSource() .withDockerRepository(SOURCE_DOCKER_REPO) .withDockerImageTag(SOURCE_DOCKER_TAG) .withSourceId(sourceIdRequestBody.getSourceId())); when(schedulerPersistence.createGetSpecJob(SOURCE_DOCKER_IMAGE)).thenReturn(JOB_ID); when(schedulerPersistence.getJob(JOB_ID)).thenReturn(inProgressJob).thenReturn(completedJob); StandardGetSpecOutput specOutput = new StandardGetSpecOutput().withSpecification( new ConnectorSpecification() .withDocumentationUrl(new URI("https://google.com")) .withChangelogUrl(new URI("https://google.com")) .withConnectionSpecification(Jsons.jsonNode(new HashMap<>()))); JobOutput jobOutput = mock(JobOutput.class); when(jobOutput.getGetSpec()).thenReturn(specOutput); when(completedJob.getOutput()).thenReturn(Optional.of(jobOutput)); schedulerHandler.getSourceSpecification(sourceIdRequestBody); verify(configRepository).getStandardSource(sourceIdRequestBody.getSourceId()); verify(schedulerPersistence).createGetSpecJob(SOURCE_DOCKER_IMAGE); verify(schedulerPersistence, atLeast(2)).getJob(JOB_ID); } @Test void testGetDestinationSpec() throws JsonValidationException, IOException, ConfigNotFoundException, URISyntaxException { DestinationIdRequestBody destinationIdRequestBody = new DestinationIdRequestBody().destinationId(UUID.randomUUID()); when(configRepository.getStandardDestination(destinationIdRequestBody.getDestinationId())) .thenReturn(new StandardDestination() .withDockerRepository(DESTINATION_DOCKER_REPO) .withDockerImageTag(DESTINATION_DOCKER_TAG) .withDestinationId(destinationIdRequestBody.getDestinationId())); when(schedulerPersistence.createGetSpecJob(DESTINATION_DOCKER_IMAGE)).thenReturn(JOB_ID); when(schedulerPersistence.getJob(JOB_ID)).thenReturn(inProgressJob).thenReturn(completedJob); StandardGetSpecOutput specOutput = new StandardGetSpecOutput().withSpecification( new ConnectorSpecification() .withDocumentationUrl(new URI("https://google.com")) .withChangelogUrl(new URI("https://google.com")) .withConnectionSpecification(Jsons.jsonNode(new HashMap<>()))); JobOutput jobOutput = mock(JobOutput.class); when(jobOutput.getGetSpec()).thenReturn(specOutput); when(completedJob.getOutput()).thenReturn(Optional.of(jobOutput)); schedulerHandler.getDestinationSpecification(destinationIdRequestBody); verify(configRepository).getStandardDestination(destinationIdRequestBody.getDestinationId()); verify(schedulerPersistence).createGetSpecJob(DESTINATION_DOCKER_IMAGE); verify(schedulerPersistence, atLeast(2)).getJob(JOB_ID); } @Test void testCheckDestinationImplementationConnection() throws IOException, JsonValidationException, ConfigNotFoundException { DestinationConnectionImplementation destinationImpl = DestinationImplementationHelpers.generateDestinationImplementation(UUID.randomUUID()); final DestinationImplementationIdRequestBody request = new DestinationImplementationIdRequestBody().destinationImplementationId(destinationImpl.getDestinationImplementationId()); when(configRepository.getStandardDestination(destinationImpl.getDestinationId())) .thenReturn(new StandardDestination() .withDockerRepository(DESTINATION_DOCKER_REPO) .withDockerImageTag(DESTINATION_DOCKER_TAG) .withDestinationId(destinationImpl.getDestinationId())); when(configRepository.getDestinationConnectionImplementation(destinationImpl.getDestinationImplementationId())).thenReturn(destinationImpl); when(schedulerPersistence.createDestinationCheckConnectionJob(destinationImpl, DESTINATION_DOCKER_IMAGE)).thenReturn(JOB_ID); when(schedulerPersistence.getJob(JOB_ID)).thenReturn(inProgressJob).thenReturn(completedJob); schedulerHandler.checkDestinationImplementationConnection(request); verify(configRepository).getDestinationConnectionImplementation(destinationImpl.getDestinationImplementationId()); verify(schedulerPersistence).createDestinationCheckConnectionJob(destinationImpl, DESTINATION_DOCKER_IMAGE); verify(schedulerPersistence, times(2)).getJob(JOB_ID); } @Test void testDiscoverSchemaForSourceImplementation() throws IOException, JsonValidationException, ConfigNotFoundException { SourceConnectionImplementation sourceImpl = SourceImplementationHelpers.generateSourceImplementation(UUID.randomUUID()); final SourceImplementationIdRequestBody request = new SourceImplementationIdRequestBody().sourceImplementationId(sourceImpl.getSourceImplementationId()); when(configRepository.getStandardSource(sourceImpl.getSourceId())) .thenReturn(new StandardSource() .withDockerRepository(SOURCE_DOCKER_REPO) .withDockerImageTag(SOURCE_DOCKER_TAG) .withSourceId(sourceImpl.getSourceId())); when(configRepository.getSourceConnectionImplementation(sourceImpl.getSourceImplementationId())).thenReturn(sourceImpl); when(schedulerPersistence.createDiscoverSchemaJob(sourceImpl, SOURCE_DOCKER_IMAGE)).thenReturn(JOB_ID); when(schedulerPersistence.getJob(JOB_ID)).thenReturn(inProgressJob).thenReturn(completedJob); schedulerHandler.discoverSchemaForSourceImplementation(request); verify(configRepository).getSourceConnectionImplementation(sourceImpl.getSourceImplementationId()); verify(schedulerPersistence).createDiscoverSchemaJob(sourceImpl, SOURCE_DOCKER_IMAGE); verify(schedulerPersistence, times(2)).getJob(JOB_ID); } @Test void testSyncConnection() throws JsonValidationException, IOException, ConfigNotFoundException { final StandardSync standardSync = ConnectionHelpers.generateSyncWithSourceImplId(UUID.randomUUID()); final ConnectionIdRequestBody request = new ConnectionIdRequestBody().connectionId(standardSync.getConnectionId()); SourceConnectionImplementation sourceImpl = SourceImplementationHelpers.generateSourceImplementation(UUID.randomUUID()) .withSourceImplementationId(standardSync.getSourceImplementationId()); DestinationConnectionImplementation destinationImpl = DestinationImplementationHelpers.generateDestinationImplementation(UUID.randomUUID()) .withDestinationImplementationId(standardSync.getDestinationImplementationId()); when(configRepository.getStandardSource(sourceImpl.getSourceId())) .thenReturn(new StandardSource() .withDockerRepository(SOURCE_DOCKER_REPO) .withDockerImageTag(SOURCE_DOCKER_TAG) .withSourceId(sourceImpl.getSourceId())); when(configRepository.getStandardDestination(destinationImpl.getDestinationId())) .thenReturn(new StandardDestination() .withDockerRepository(DESTINATION_DOCKER_REPO) .withDockerImageTag(DESTINATION_DOCKER_TAG) .withDestinationId(destinationImpl.getDestinationId())); when(configRepository.getStandardSync(standardSync.getConnectionId())).thenReturn(standardSync); when(configRepository.getSourceConnectionImplementation(sourceImpl.getSourceImplementationId())).thenReturn(sourceImpl); when(configRepository.getDestinationConnectionImplementation(destinationImpl.getDestinationImplementationId())).thenReturn(destinationImpl); when(schedulerPersistence.createSyncJob(sourceImpl, destinationImpl, standardSync, SOURCE_DOCKER_IMAGE, DESTINATION_DOCKER_IMAGE)) .thenReturn(JOB_ID); when(schedulerPersistence.getJob(JOB_ID)).thenReturn(inProgressJob).thenReturn(completedJob); schedulerHandler.syncConnection(request); verify(configRepository).getStandardSync(standardSync.getConnectionId()); verify(configRepository).getSourceConnectionImplementation(standardSync.getSourceImplementationId()); verify(configRepository).getDestinationConnectionImplementation(standardSync.getDestinationImplementationId()); verify(schedulerPersistence).createSyncJob(sourceImpl, destinationImpl, standardSync, SOURCE_DOCKER_IMAGE, DESTINATION_DOCKER_IMAGE); verify(schedulerPersistence, times(2)).getJob(JOB_ID); } @Test void testEnumConversion() { assertTrue(Enums.isCompatible(StandardCheckConnectionOutput.Status.class, CheckConnectionRead.StatusEnum.class)); } }
54.486692
144
0.807467
086d50a1acf6bfd2f01c6fa4d445aeb6beaf48fb
1,126
package com.demo.util; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; import java.io.File; import java.util.ArrayList; import java.util.List; /** * @author binvi * @version 1.0 * @Description: mybatis-generator in java * @date 2019/12/1 17:27 */ public class MybatisGeneratorUtil { private static final String CONFIG_FILE = "generatorConfig.xml"; public static void main(String[] args) throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; String path = MybatisGeneratorUtil.class.getClassLoader().getResource(CONFIG_FILE).getPath(); File configFile = new File(path); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } }
32.171429
95
0.786856
63b00b4ef25eaccad8755a87926fa6d4ad1d7dcb
2,611
/*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ package org.onap.so.adapters.vnfmadapter.extclients.vim.model; import java.util.Objects; public class VimCredentials { protected String username; protected String password; public String getUsername() { return username; } public void setUsername(final String value) { username = value; } public String getPassword() { return password; } public void setPassword(final String password) { this.password = password; } @Override public boolean equals(final java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final VimCredentials vimCredentials = (VimCredentials) o; return Objects.equals(this.username, vimCredentials.username) && Objects.equals(this.password, vimCredentials.password); } @Override public int hashCode() { return Objects.hash(username, password); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("class AccessInfo {\n"); sb.append(" username: ").append(toIndentedString(username)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(final java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
30.360465
102
0.581003
838884f17bf5d7f069ba678f945f0f8836c533ae
605
package com.neusoft.day13; import java.util.Arrays; public class TextSystem2 { public static void main(String[] args) { // 将 src 中前 3个元素, 赋值到dest的前3个位置上 // 操作之后: [1, 2, 3, 4, 5] dest [1, 2, 3, 9, 10] int[] src = new int[]{1, 2, 3, 4, 5}; int[] dest = new int[]{6, 7, 8, 9, 10}; System.arraycopy(src, 0, dest, 0, 3); System.out.println(Arrays.toString(dest)); int[] src1 = new int[]{1,2,3}; int[] dest1 = new int[]{6,7,7}; System.arraycopy(src1,0,dest1,0,3); System.out.println(Arrays.toString(dest1)); } }
23.269231
56
0.540496
d410fce8acf43930843f8c77cc70b522034ea63e
8,568
/* * 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.flink.table.module; import org.apache.flink.table.api.ValidationException; import org.apache.flink.table.utils.ModuleMock; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Tests for {@link ModuleManager}. */ class ModuleManagerTest { private ModuleManager manager; @BeforeEach public void before() { manager = new ModuleManager(); } @Test void testLoadModuleTwice() { // CoreModule is loaded by default assertThat(manager.getUsedModules()) .isEqualTo(Collections.singletonList(CoreModuleFactory.IDENTIFIER)); assertThat(manager.getLoadedModules().get(CoreModuleFactory.IDENTIFIER)) .isSameAs(CoreModule.INSTANCE); assertThatThrownBy( () -> manager.loadModule(CoreModuleFactory.IDENTIFIER, CoreModule.INSTANCE)) .isInstanceOf(ValidationException.class) .hasMessage("A module with name 'core' already exists"); } @Test void testLoadModuleWithoutUnusedModulesExist() { ModuleMock x = new ModuleMock("x"); ModuleMock y = new ModuleMock("y"); ModuleMock z = new ModuleMock("z"); manager.loadModule(x.getType(), x); manager.loadModule(y.getType(), y); manager.loadModule(z.getType(), z); Map<String, Module> expectedLoadedModules = new HashMap<>(); expectedLoadedModules.put(CoreModuleFactory.IDENTIFIER, CoreModule.INSTANCE); expectedLoadedModules.put("x", x); expectedLoadedModules.put("y", y); expectedLoadedModules.put("z", z); assertThat(manager.getUsedModules()) .containsSequence(CoreModuleFactory.IDENTIFIER, "x", "y", "z"); assertThat(manager.getLoadedModules()).isEqualTo(expectedLoadedModules); } @Test void testLoadModuleWithUnusedModulesExist() { ModuleMock y = new ModuleMock("y"); ModuleMock z = new ModuleMock("z"); manager.loadModule(y.getType(), y); manager.loadModule(z.getType(), z); Map<String, Module> expectedLoadedModules = new HashMap<>(); expectedLoadedModules.put(CoreModuleFactory.IDENTIFIER, CoreModule.INSTANCE); expectedLoadedModules.put("y", y); expectedLoadedModules.put("z", z); assertThat(manager.getUsedModules()) .containsSequence(CoreModuleFactory.IDENTIFIER, "y", "z"); assertThat(manager.getLoadedModules()).isEqualTo(expectedLoadedModules); // disable module y and z manager.useModules(CoreModuleFactory.IDENTIFIER); // load module x to test the order ModuleMock x = new ModuleMock("x"); manager.loadModule(x.getType(), x); expectedLoadedModules.put("x", x); assertThat(manager.getUsedModules()).containsSequence(CoreModuleFactory.IDENTIFIER, "x"); assertThat(manager.getLoadedModules()).isEqualTo(expectedLoadedModules); } @Test void testUnloadModuleTwice() { assertThat(manager.getUsedModules()).containsSequence(CoreModuleFactory.IDENTIFIER); manager.unloadModule(CoreModuleFactory.IDENTIFIER); assertThat(manager.getUsedModules()).isEmpty(); assertThat(manager.getLoadedModules()).isEmpty(); assertThatThrownBy(() -> manager.unloadModule(CoreModuleFactory.IDENTIFIER)) .isInstanceOf(ValidationException.class) .hasMessage("No module with name 'core' exists"); } @Test void testUseUnloadedModules() { assertThatThrownBy(() -> manager.useModules(CoreModuleFactory.IDENTIFIER, "x")) .isInstanceOf(ValidationException.class) .hasMessage("No module with name 'x' exists"); } @Test void testUseModulesWithDuplicateModuleName() { assertThatThrownBy( () -> manager.useModules( CoreModuleFactory.IDENTIFIER, CoreModuleFactory.IDENTIFIER)) .isInstanceOf(ValidationException.class) .hasMessage("Module 'core' appears more than once"); } @Test void testUseModules() { ModuleMock x = new ModuleMock("x"); ModuleMock y = new ModuleMock("y"); ModuleMock z = new ModuleMock("z"); manager.loadModule(x.getType(), x); manager.loadModule(y.getType(), y); manager.loadModule(z.getType(), z); assertThat(manager.getUsedModules()) .containsSequence(CoreModuleFactory.IDENTIFIER, "x", "y", "z"); // test order for used modules manager.useModules("z", CoreModuleFactory.IDENTIFIER); assertThat(manager.getUsedModules()).containsSequence("z", CoreModuleFactory.IDENTIFIER); // test unmentioned modules are still loaded Map<String, Module> expectedLoadedModules = new HashMap<>(); expectedLoadedModules.put(CoreModuleFactory.IDENTIFIER, CoreModule.INSTANCE); expectedLoadedModules.put("x", x); expectedLoadedModules.put("y", y); expectedLoadedModules.put("z", z); assertThat(manager.getLoadedModules()).isEqualTo(expectedLoadedModules); } @Test void testListModules() { ModuleMock y = new ModuleMock("y"); ModuleMock z = new ModuleMock("z"); manager.loadModule("y", y); manager.loadModule("z", z); manager.useModules("z", "y"); assertThat(manager.listModules()).containsSequence("z", "y"); } @Test void testListFullModules() { ModuleMock x = new ModuleMock("x"); ModuleMock y = new ModuleMock("y"); ModuleMock z = new ModuleMock("z"); manager.loadModule("y", y); manager.loadModule("x", x); manager.loadModule("z", z); manager.useModules("z", "y"); assertThat(manager.listFullModules()) .isEqualTo( getExpectedModuleEntries(2, "z", "y", CoreModuleFactory.IDENTIFIER, "x")); } @Test void testListFunctions() { ModuleMock x = new ModuleMock("x"); manager.loadModule(x.getType(), x); assertThat(manager.listFunctions()).contains(ModuleMock.DUMMY_FUNCTION_NAME); // hidden functions not in the default list assertThat(manager.listFunctions()).doesNotContain(ModuleMock.INTERNAL_FUNCTION_NAME); // should not return function name of an unused module manager.useModules(CoreModuleFactory.IDENTIFIER); assertThat(manager.listFunctions()).doesNotContain(ModuleMock.DUMMY_FUNCTION_NAME); } @Test void testGetFunctionDefinition() { ModuleMock x = new ModuleMock("x"); manager.loadModule(x.getType(), x); assertThat(manager.getFunctionDefinition(ModuleMock.DUMMY_FUNCTION_NAME)).isPresent(); assertThat(manager.getFunctionDefinition(ModuleMock.INTERNAL_FUNCTION_NAME)).isPresent(); // should not return function definition of an unused module manager.useModules(CoreModuleFactory.IDENTIFIER); assertThat(manager.getFunctionDefinition(ModuleMock.DUMMY_FUNCTION_NAME)).isEmpty(); } private static List<ModuleEntry> getExpectedModuleEntries(int index, String... names) { return IntStream.range(0, names.length) .mapToObj(i -> new ModuleEntry(names[i], i < index)) .collect(Collectors.toList()); } }
37.911504
100
0.663749
78497e3b79ae4ec07fbf8739712ebffc657ac233
5,579
package edu.fppi.idinner.steps.userinfo; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CalendarView; import android.widget.EditText; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Locale; import edu.fppi.idinner.R; public class FragUserInfo extends Fragment { private EditText mName; private CalendarView mCalendar; private EditText mBirthDate; private EditText mGenre; private EditText mEmail; private EditText mPhone; private Button mButtonNext; private OnButtonNextClick onButtonNextClick = () -> { }; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.layout_frag_user, container, false); mName = root.findViewById(R.id.Frag_User_Name); mCalendar = root.findViewById(R.id.Frag_User_Calendar); mBirthDate = root.findViewById(R.id.Frag_User_Birth); mGenre = root.findViewById(R.id.Frag_User_Genre); mEmail = root.findViewById(R.id.Frag_User_Email); mPhone = root.findViewById(R.id.Frag_User_Phone); mButtonNext = root.findViewById(R.id.Frag_User_NextButton); mCalendar.setVisibility(View.GONE); mBirthDate.setFocusable(false); mBirthDate.setOnClickListener(view -> mCalendar.setVisibility(View.VISIBLE)); mCalendar.setOnDateChangeListener((calendarView, i, i1, i2) -> { mBirthDate.setText(String.format(Locale.ENGLISH, "%02d/%02d/%04d", i2, i1, i)); calendarView.setVisibility(View.GONE); }); mButtonNext.setOnClickListener(view -> { boolean hasError = false; if (mName.getText().length() == 0) { mName.setError("Este campo não pode ficar vazio."); hasError = true; } if (mBirthDate.getText().length() == 0) { mBirthDate.setError("Este campo não pode ficar vazio."); hasError = true; } if (mEmail.getText().length() == 0) { mEmail.setError("Este campo não pode ficar vazio."); hasError = true; } if (mPhone.getText().length() == 0) { mPhone.setError("Este campo não pode ficar vazio."); hasError = true; } if (!checkDateFormat(String.valueOf(mBirthDate.getText()))) { mBirthDate.setError("Data inválida."); hasError = true; } if (!android.util.Patterns.EMAIL_ADDRESS.matcher(mEmail.getText().toString()).matches()) { mEmail.setError("Email inválido."); hasError = true; } if (!hasError) { saveUser(); onButtonNextClick.onButtonNextClick(); } }); mGenre.setFocusable(false); mGenre.setOnClickListener(view -> { if (mGenre.getText().toString().equals("")) mGenre.setText(R.string.masculino); else if (mGenre.getText().toString().equals("Masculino")) mGenre.setText(R.string.feminino); else if (mGenre.getText().toString().equals("Feminino")) mGenre.setText(R.string.outro); else if (mGenre.getText().toString().equals("Outro")) mGenre.setText(R.string.masculino); }); loadUser(); return root; } private void saveUser() { SharedPreferences saved_values = requireContext().getSharedPreferences("edu.fppi.idinner", Context.MODE_PRIVATE); SharedPreferences.Editor editor = saved_values.edit(); editor.putString("userName", mName.getText().toString()); editor.putString("userBirth", mBirthDate.getText().toString()); editor.putString("userGenre", mGenre.getText().toString()); editor.putString("userEmail", mEmail.getText().toString()); editor.putString("userPhone", mPhone.getText().toString()); editor.apply(); } private void loadUser() { SharedPreferences saved_values = requireContext().getSharedPreferences("edu.fppi.idinner", Context.MODE_PRIVATE); mName.setText(saved_values.getString("userName", "")); mBirthDate.setText(saved_values.getString("userBirth", "")); mGenre.setText(saved_values.getString("userGenre", "")); mEmail.setText(saved_values.getString("userEmail", "")); mPhone.setText(saved_values.getString("userPhone", "")); } public void setOnButtonNextClick(OnButtonNextClick onButtonNextClick) { this.onButtonNextClick = onButtonNextClick; } public Boolean checkDateFormat(String date) { if (date == null || !date.matches("^(1[0-9]|0[1-9]|3[0-1]|2[1-9])/(0[1-9]|1[0-2])/[0-9]{4}$")) return false; @SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); try { format.parse(date); return true; } catch (ParseException e) { return false; } } public interface OnButtonNextClick { void onButtonNextClick(); } }
39.013986
132
0.634164
e6d52731740aa28f5861975a528ba850e18bb32c
453
package uk.ac.ebi.gxa.utils; /** * {@link Comparable} {@link Pair} */ public class CPair<T1 extends Comparable<T1>, T2 extends Comparable<T2>> extends Pair<T1, T2> implements Comparable<CPair<T1, T2>> { public CPair(T1 first, T2 second) { super(first, second); } public int compareTo(CPair<T1, T2> o) { int d = getFirst().compareTo(o.getFirst()); return d != 0 ? d : getSecond().compareTo(o.getSecond()); } }
28.3125
132
0.624724
e4700010209c310e75054d8769eb67754eba4d45
3,013
package main; import java.io.*; import java.util.*; import cicontest.algorithm.abstracts.AbstractAlgorithm; import cicontest.algorithm.abstracts.DriversUtils; import cicontest.torcs.controller.Driver; import race.TorcsConfiguration; public class DefaultDriverAlgorithm extends AbstractAlgorithm { int numDrivers = 1; private static final long serialVersionUID = 654963126362653L; DefaultDriverGenome[] drivers = new DefaultDriverGenome[numDrivers]; int[] results = new int[numDrivers]; public Class<? extends Driver> getDriverClass() { return DefaultDriver.class; } // Select which tracks Map<String, String[]> tracks = new HashMap<String, String[]>() { { this.put("dirt", new String[]{ "mixed-3", //"corkscrew", //"alpine-1", //"brondehach", //"wheel-1", //"wheel-2" }); /*this.put("oval", new String[] { "a-speedway", "b-speedway", "e-speedway", "michigan" }); */ /* this.put("dirt", new String[] { "dirt-1", "dirt-2", "dirt-3", "mixed-1", "mixed-2" }); */ } }; public void run(boolean continue_from_checkpoint) { for (int i=0; i<numDrivers; i++) { drivers[i] = new DefaultDriverGenome(); } DefaultRace race = new DefaultRace(); race.tracktype = "road"; race.track = "aalborg"; race.laps = 3; race.runRace(drivers, true); } public static void main(String[] args) { //Set path to torcs.properties TorcsConfiguration.getInstance().initialize(new File("code/resources/torcs.properties")); /* * * Start without arguments to run the algorithm * Start with -continue to continue a previous run * Start with -show to show the best found * Start with -show-race to show a race with 10 copies of the best found * Start with -human to race against the best found * */ DefaultDriverAlgorithm algorithm = new DefaultDriverAlgorithm(); DriversUtils.registerMemory(algorithm.getDriverClass()); if (args.length > 0 && args[0].equals("-show")) { new DefaultRace().showBest(); } else if (args.length > 0 && args[0].equals("-show-race")) { new DefaultRace().showBestRace(); } else if (args.length > 0 && args[0].equals("-human")) { new DefaultRace().raceBest(); } else if (args.length > 0 && args[0].equals("-continue")) { if (DriversUtils.hasCheckpoint()) { DriversUtils.loadCheckpoint().run(true); } else { algorithm.run(); } } else { algorithm.run(); } } }
31.061856
97
0.534019
20a08f39a6ccf0622d7989ac3cc08f9891c4fcd8
38,532
/* * 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 com.codename1.webrtc; import java.util.LinkedHashMap; import java.util.Map; /** * The RTCPeerConnection interface represents a WebRTC connection between the * local computer and a remote peer. It provides methods to connect to a remote * peer, maintain and monitor the connection, and close the connection once it's * no longer needed. * * @author shannah * @see https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection */ public interface RTCPeerConnection extends EventTarget, RefCounted { /** * The RTCPeerConnection.onconnectionstatechange property specifies an * EventHandler which is called to handle the connectionstatechange event * when it occurs on an instance of RTCPeerConnection. This happens whenever * the aggregate state of the connection changes. */ public static final String EVENT_CONNECTIONSTATECHANGE = "connectionstatechange"; /** * The RTCPeerConnection.ondatachannel property is an EventHandler which * specifies a function which is called when the datachannel event occurs on * an RTCPeerConnection. This event, of type RTCDataChannelEvent, is sent * when an RTCDataChannel is added to the connection by the remote peer * calling createDataChannel(). */ public static final String EVENT_DATACHANNEL = "datachannel"; /** * The RTCPeerConnection property onicecandidate property is an EventHandler * which specifies a function to be called when the icecandidate event * occurs on an RTCPeerConnection instance. This happens whenever the local * ICE agent needs to deliver a message to the other peer through the * signaling server. */ public static final String EVENT_ICECANDIDATE = "icecandidate"; /** * The RTCPeerConnection.oniceconnectionstatechange property is an event * handler which specifies a function to be called when the * iceconnectionstatechange event is fired on an RTCPeerConnection instance. * This happens when the state of the connection's ICE agent, as represented * by the iceConnectionState property, changes. */ public static final String EVENT_ICECONNECTIONSTATECHANGE = "iceconnectionstatechange"; /** * The RTCPeerConnection.onicegatheringstatechange property is an * EventHandler which specifies a function to be called when the * icegatheringstatechange event is sent to an RTCPeerConnection instance. * This happens when the ICE gathering state - that is, whether or not the ICE * agent is actively gathering candidates - changes. */ public static final String EVENT_ICEGATHERINGSTATECHANGE = "icegatheringstatechange"; /** * The RTCPeerConnection.onidentityresult event handler is a property * containing the code to execute when the identityresult event, of type * RTCIdentityEvent, is received by this RTCPeerConnection. Such an event is * sent when an identity assertion is generated, via getIdentityAssertion() * or during the creation of an offer or an answer. */ public static final String EVENT_IDENTITYRESULT = "identityresult"; /** * The RTCPeerConnection interface's onnegotiationneeded property is an * EventListener which specifies a function which is called to handle the * negotiationneeded event when it occurs on an RTCPeerConnection instance. * This event is fired when a change has occurred which requires session * negotiation. This negotiation should be carried out as the offerer, * because some session changes cannot be negotiated as the answerer. */ public static final String EVENT_NEGOTIATIONNEEDED = "negotiationneeded"; /** * The onsignalingstatechange event handler property of the * RTCPeerConnection interface specifies a function to be called when the * signalingstatechange event occurs on an RTCPeerConnection interface. */ public static final String EVENT_SIGNALINGSTATECHANGE = "signalingstatechange"; /** * The RTCPeerConnection property ontrack is an EventHandler which specifies * a function to be called when the track event occurs, indicating that a * track has been added to the RTCPeerConnection. */ public static final String EVENT_TRACK = "track"; public static final String EVENT_REMOVETRACK = "removetrack"; public RTCPeerConnection addTrackListener(RTCTrackEventListener l); public RTCPeerConnection removeTrackListener(RTCTrackEventListener l); public RTCPeerConnection ontrack(RTCTrackEventListener l); public RTCPeerConnection addRemoveTrackListener(RTCTrackEventListener l); public RTCPeerConnection removeRemoveTrackListener(RTCTrackEventListener l); public RTCPeerConnection onremovetrack(RTCTrackEventListener l); public RTCPeerConnection addSignalingStateChangeListener(RTCSignalingStateChangeEventListener l); public RTCPeerConnection removeSignalingStateChangeListener(RTCSignalingStateChangeEventListener l); public RTCPeerConnection onsignalingstatechange(RTCSignalingStateChangeEventListener l); public RTCPeerConnection addNegotiationNeededListener(RTCNegotiationNeededEventListener l); public RTCPeerConnection removeNegotiationNeededListener(RTCNegotiationNeededEventListener l); public RTCPeerConnection onnegotiationneeded(RTCNegotiationNeededEventListener l); public RTCPeerConnection addIdentityResultListener(RTCIdentityResultEventListener l); public RTCPeerConnection removeIdentityResultListener(RTCIdentityResultEventListener l); public RTCPeerConnection onidentityresult(RTCIdentityResultEventListener l); public RTCPeerConnection addIceGatheringStateChangeListener(RTCIceGatheringStateChangeEventListener l); public RTCPeerConnection removeIceGatheringStateChangeListener(RTCIceGatheringStateChangeEventListener l); public RTCPeerConnection onicegatheringstatechange(RTCIceGatheringStateChangeEventListener l); public RTCPeerConnection addIceConnectionStateChangeListener(RTCIceConnectionStateChangeEventListener l); public RTCPeerConnection removeIceConnectionStateChangeListener(RTCIceConnectionStateChangeEventListener l); public RTCPeerConnection oniceconnectionstatechange(RTCIceConnectionStateChangeEventListener l); public RTCPeerConnection addIceCandidateListener(RTCIceCandidateEventListener l); public RTCPeerConnection removeIceCandidateListener(RTCIceCandidateEventListener l); public RTCPeerConnection onicecandidate(RTCIceCandidateEventListener l); public RTCPeerConnection addDataChannelListener(RTCDataChannelEventListener l); public RTCPeerConnection removeDataChannelListener(RTCDataChannelEventListener l); public RTCPeerConnection ondatachannel(RTCDataChannelEventListener l); public RTCPeerConnection addConnectionStateChangeListener(RTCConnectionStateChangeEventListener l); public RTCPeerConnection removeConnectionStateChangeListener(RTCConnectionStateChangeEventListener l); public RTCPeerConnection onconnectionstatechange(RTCConnectionStateChangeEventListener l); /** * The read-only RTCPeerConnection property canTrickleIceCandidates returns * a Boolean which indicates whether or not the remote peer can accept * trickled ICE candidates. * * @return * @see * https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/canTrickleIceCandidates */ public boolean canTrickleIceCandidates(); /** * The read-only connectionState property of the RTCPeerConnection interface * indicates the current state of the peer connection by returning one of * the string values specified by the enum RTCPeerConnectionState. * * @return * @see * https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState */ public RTCPeerConnectionState getConnectionState(); /** * The read-only property RTCPeerConnection.currentLocalDescription returns * an RTCSessionDescription object describing the local end of the * connection as it was most recently successfully negotiated since the last * time the RTCPeerConnection finished negotiating and connecting to a * remote peer. Also included is a list of any ICE candidates that may * already have been generated by the ICE agent since the offer or answer * represented by the description was first instantiated. * * @return * @see * https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/currentLocalDescription */ public RTCSessionDescription getCurrentLocalDescription(); /** * The read-only property RTCPeerConnection.currentRemoteDescription returns * an RTCSessionDescription object describing the remote end of the * connection as it was most recently successfully negotiated since the last * time the RTCPeerConnection finished negotiating and connecting to a * remote peer. Also included is a list of any ICE candidates that may * already have been generated by the ICE agent since the offer or answer * represented by the description was first instantiated. * * @return * @see * https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/currentRemoteDescription */ public RTCSessionDescription getCurrentRemoteDescription(); /** * The read-only property RTCPeerConnection.iceConnectionState returns an * enum of type RTCIceConnectionState which state of the ICE agent * associated with the RTCPeerConnection. * * @return */ public RTCIceConnectionState getIceConnectionState(); /** * The read-only property RTCPeerConnection.iceGatheringState returns an * enum of type RTCIceGatheringState that describes connection's ICE * gathering state. This lets you detect, for example, when collection of * ICE candidates has finished. * * @return */ public RTCIceGatheringState getIceGatheringState(); /** * The read-only property RTCPeerConnection.localDescription returns an * RTCSessionDescription describing the session for the local end of the * connection. If it has not yet been set, this is null. * * @return */ public RTCSessionDescription getLocalDescription(); /** * The read-only RTCPeerConnection property peerIdentity returns a * JavaScript Promise that resolves to an RTCIdentityAssertion which * contains a DOMString identifying the remote peer. * * @return */ public RTCIdentityAssertion getPeerIdentity(); /** * The read-only property RTCPeerConnection.pendingLocalDescription returns * an RTCSessionDescription object describing a pending configuration change * for the local end of the connection. This does not describe the * connection as it currently stands, but as it may exist in the near * future. Use RTCPeerConnection.currentLocalDescription or * RTCPeerConnection.localDescription to get the current state of the * endpoint. For details on the difference, see Pending and current * descriptions in WebRTC connectivity. * * @return */ public RTCSessionDescription getPendingLocalDescription(); /** * The read-only property RTCPeerConnection.pendingRemoteDescription returns * an RTCSessionDescription object describing a pending configuration change * for the remote end of the connection. This does not describe the * connection as it currently stands, but as it may exist in the near * future. Use RTCPeerConnection.currentRemoteDescription or * RTCPeerConnection.remoteDescription to get the current session * description for the remote endpoint. For details on the difference, see * Pending and current descriptions in WebRTC connectivity. * * @return */ public RTCSessionDescription getPendingRemoteDescription(); /** * The read-only property RTCPeerConnection.remoteDescription returns a * RTCSessionDescription describing the session (which includes * configuration and media information) for the remote end of the * connection. If this hasn't been set yet, this is null. * * @return */ public RTCSessionDescription getRemoteDescription(); /** * The read-only sctp property on the RTCPeerConnection interface returns an * RTCSctpTransport describing the SCTP transport over which SCTP data is * being sent and received. If SCTP hasn't been negotiated, this value is * null. * * @return */ public RTCSctpTransport getSctp(); /** * The read-only signalingState property on the RTCPeerConnection interface * returns one of the string values specified by the RTCSignalingState enum; * these values describe the state of the signaling process on the local end * of the connection while connecting or reconnecting to another peer. See * Signaling in Lifetime of a WebRTC session for more details about the * signaling process. * * @return */ public RTCSignalingState getSignalingState(); /** * When a web site or app using RTCPeerConnection receives a new ICE * candidate from the remote peer over its signaling channel, it delivers * the newly-received candidate to the browser's ICE agent by calling * RTCPeerConnection.addIceCandidate(). * * @param candidate * @return */ public Promise addIceCandidate(RTCIceCandidate candidate); /** * The RTCPeerConnection method addTrack() adds a new media track to the set * of tracks which will be transmitted to the other peer. * * @param track * @param stream * @return */ public RTCRtpSender addTrack(MediaStreamTrack track, MediaStream... stream); /** * The RTCPeerConnection.close() method closes the current peer connection. */ public void close(); /** * The createAnswer() method on the RTCPeerConnection interface creates an * SDP answer to an offer received from a remote peer during the * offer/answer negotiation of a WebRTC connection. The answer contains * information about any media already attached to the session, codecs and * options supported by the browser, and any ICE candidates already * gathered. The answer is delivered to the returned Promise, and should * then be sent to the source of the offer to continue the negotiation * process. * * @return */ public Promise<RTCSessionDescription> createAnswer(); /** * The createAnswer() method on the RTCPeerConnection interface creates an * SDP answer to an offer received from a remote peer during the * offer/answer negotiation of a WebRTC connection. The answer contains * information about any media already attached to the session, codecs and * options supported by the browser, and any ICE candidates already * gathered. The answer is delivered to the returned Promise, and should * then be sent to the source of the offer to continue the negotiation * process. * * @param options * @return */ public Promise<RTCSessionDescription> createAnswer(RTCAnswerOptions options); /** * The createDataChannel() method on the RTCPeerConnection interface creates * a new channel linked with the remote peer, over which any kind of data * may be transmitted. * * @param label * @param options * @return */ public RTCDataChannel createDataChannel(String label, RTCDataChannelInit options); /** * The createOffer() method of the RTCPeerConnection interface initiates the * creation of an SDP offer for the purpose of starting a new WebRTC * connection to a remote peer. * * @param options * @return */ public Promise<RTCSessionDescription> createOffer(RTCOfferOptions options); /** * The RTCPeerConnection.getReceivers() method returns an array of * RTCRtpReceiver objects, each of which represents one RTP receiver. Each * RTP receiver manages the reception and decoding of data for a * MediaStreamTrack on an RTCPeerConnection * * @return */ public RTCRtpReceivers getReceivers(); /** * The RTCPeerConnection method getSenders() returns an array of * RTCRtpSender objects, each of which represents the RTP sender responsible * for transmitting one track's data. * * @return */ public RTCRtpSenders getSenders(); /** * The RTCPeerConnection method getStats() returns a promise which resolves * with data providing statistics about either the overall connection or * about the specified MediaStreamTrack. * * @param selector * @return */ public Promise<RTCStatsReport> getStats(MediaStreamTrack selector); /** * The RTCPeerConnection.getStreamById() method returns the MediaStream with * the given id that is associated with local or remote end of the * connection. If no stream matches, it returns null. * * @param id * @return */ public MediaStream getStreamById(String id); /** * The RTCPeerConnection interface's getTransceivers() method returns a list * of the RTCRtpTransceiver objects being used to send and receive data on * the connection. * * @return */ public RTCRtpTransceivers getTransceivers(); /** * The RTCPeerConnection.removeTrack() method tells the local end of the * connection to stop sending media from the specified track, without * actually removing the corresponding RTCRtpSender from the list of senders * as reported by RTCPeerConnection.getSenders(). * * @param sender */ public void removeTrack(RTCRtpSender sender); /** * The WebRTC API's RTCPeerConnection interface offers the restartIce() * method to allow a web application to easily request that ICE candidate * gathering be redone on both ends of the connection. */ public void restartIce(); /** * The RTCPeerConnection.setIdentityProvider() method sets the Identity * Provider (IdP) to the triplet given in parameter: its name, the protocol * used to communicate with it (optional) and an optional username. The IdP * will be used only when an assertion is needed. * * @param domainName */ public void setIdentityProvider(String domainName); public void setIdentityProvider(String domainName, String protocol); public void setIdentityProvider(String domainName, String protocol, String username); /** * The RTCPeerConnection method setLocalDescription() changes the local * description associated with the connection. This description specifies * the properties of the local end of the connection, including the media * format. * * @param sessionDescription * @return */ public Promise setLocalDescription(RTCSessionDescription sessionDescription); /** * The RTCPeerConnection method setRemoteDescription() sets the specified * session description as the remote peer's current offer or answer. The * description specifies the properties of the remote end of the connection, * including the media format. * * @param sessionDescription * @return */ public Promise setRemoteDescription(RTCSessionDescription sessionDescription); public static class RTCDataChannelInit implements JSONStruct { /** * @return the ordered */ public boolean isOrdered() { return ordered; } /** * @param ordered the ordered to set */ public void setOrdered(boolean ordered) { this.ordered = ordered; } /** * @return the maxPacketLifeTime */ public Integer getMaxPacketLifeTime() { return maxPacketLifeTime; } /** * @param maxPacketLifeTime the maxPacketLifeTime to set */ public void setMaxPacketLifeTime(Integer maxPacketLifeTime) { this.maxPacketLifeTime = maxPacketLifeTime; } /** * @return the maxRetransmits */ public Integer getMaxRetransmits() { return maxRetransmits; } /** * @param maxRetransmits the maxRetransmits to set */ public void setMaxRetransmits(Integer maxRetransmits) { this.maxRetransmits = maxRetransmits; } /** * @return the protocol */ public String getProtocol() { return protocol; } /** * @param protocol the protocol to set */ public void setProtocol(String protocol) { this.protocol = protocol; } /** * @return the negotiated */ public boolean isNegotiated() { return negotiated; } /** * @param negotiated the negotiated to set */ public void setNegotiated(boolean negotiated) { this.negotiated = negotiated; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } private boolean ordered; private Integer maxPacketLifeTime; private Integer maxRetransmits; private String protocol; private boolean negotiated; private int id; @Override public Object toJSONStruct() { Map out = new LinkedHashMap(); out.put("ordered", ordered); if (maxPacketLifeTime != null) { out.put("maxPacketLifeTime", maxPacketLifeTime); } if (maxRetransmits != null) { out.put("maxRetransmits", maxRetransmits); } if (protocol != null) { out.put("protocol", protocol); } out.put("negotiated", negotiated); if (id != 0) { out.put("id", id); } return out; } } /** * The RTCBundlePolicy enum defines string constants which are used to * request a specific policy for gathering ICE candidates if the remote peer * isn't compatible with the SDP BUNDLE standard for bundling multiple media * streams on a single transport link. */ public static enum RTCBundlePolicy { /** * On BUNDLE-aware connections, the ICE agent should gather candidates * for all of the media types in use (audio, video, and data). * Otherwise, the ICE agent should only negotiate one audio and video * track on separate transports. */ Balanced("balanced"), /** * The ICE agent should gather candidates for each track, using separate * transports to negotiate all media tracks for connections which aren't * BUNDLE-compatible. */ MaxCompat("max-compat"), /** * The ICE agent should gather candidates for just one track. If the * connection isn't BUNDLE-compatible, then the ICE agent should * negotiate just one media track. */ MaxBundle("max-bundle"); String string; RTCBundlePolicy(String str) { this.string = str; } } /** * The RTCIceConnectionState enum defines the string constants used to * describe the current state of the ICE agent and its connection to the ICE * server (that is, the STUN or TURN server). */ public static enum RTCIceConnectionState { /** * The ICE agent is gathering addresses or is waiting to be given remote * candidates through calls to RTCPeerConnection.addIceCandidate() (or * both). */ New("new"), /** * The ICE agent has been given one or more remote candidates and is * checking pairs of local and remote candidates against one another to * try to find a compatible match, but has not yet found a pair which * will allow the peer connection to be made. It's possible that * gathering of candidates is also still underway. */ Checking("checking"), /** * A usable pairing of local and remote candidates has been found for * all components of the connection, and the connection has been * established. It's possible that gathering is still underway, and it's * also possible that the ICE agent is still checking candidates against * one another looking for a better connection to use. */ Connected("connected"), /** * The ICE agent has finished gathering candidates, has checked all * pairs against one another, and has found a connection for all * components. */ Completed("completed"), /** * The ICE candidate has checked all candidates pairs against one * another and has failed to find compatible matches for all components * of the connection. It is, however, possible that the ICE agent did * find compatible connections for some components. */ Failed("failed"), /** * Checks to ensure that components are still connected failed for at * least one component of the RTCPeerConnection. This is a less * stringent test than "failed" and may trigger intermittently and * resolve just as spontaneously on less reliable networks, or during * temporary disconnections. When the problem resolves, the connection * may return to the "connected" state. */ Disconnected("disconnected"), /** * The ICE agent for this RTCPeerConnection has shut down and is no * longer handling requests. */ Closed("closed"); String string; RTCIceConnectionState(String str) { this.string = str; } public boolean matches(String str) { return string.equals(str); } } /** * The RTCIceGatheringState enum defines string constants which reflect the * current status of ICE gathering, as returned using the * RTCPeerConnection.iceGatheringState property. You can detect when this * value changes by watching for an event of type icegatheringstatechange. */ public static enum RTCIceGatheringState { /** * The peer connection was just created and hasn't done any networking * yet. */ New("new"), /** * The ICE agent is in the process of gathering candidates for the * connection. */ Gathering("gathering"), /** * The ICE agent has finished gathering candidates. If something happens * that requires collecting new candidates, such as a new interface * being added or the addition of a new ICE server, the state will * revert to "gathering" to gather those candidates. */ Complete("complete"); String string; RTCIceGatheringState(String str) { this.string = str; } public boolean matches(String str) { return string.equals(str); } } /** * The RTCIceTransportPolicy enum defines string constants which can be used * to limit the transport policies of the ICE candidates to be considered * during the connection process. */ public static enum RTCIceTransportPolicy { /** * All ICE candidates will be considered. */ All("all"), /** * Only ICE candidates with public IP addresses will be considered. * Removed from the specification's May 13, 2016 working draft. */ Public("public"), /** * Only ICE candidates whose IP addresses are being relayed, such as * those being passed through a TURN server, will be considered. */ Relay("relay"); String string; RTCIceTransportPolicy(String str) { this.string = str; } } /** * The RTCPeerConnectionState enum defines string constants which describe * states in which the RTCPeerConnection may be. These values are returned * by the connectionState property. This state essentially represents the * aggregate state of all ICE transports (which are of type RTCIceTransport * or RTCDtlsTransport) being used by the connection. */ public static enum RTCPeerConnectionState { /** * At least one of the connection's ICE transports (RTCIceTransports or * RTCDtlsTransports) are in the "new" state, and none of them are in * one of the following states: "connecting", "checking", "failed", or * "disconnected", or all of the connection's transports are in the * "closed" state. */ New("new"), /** * One or more of the ICE transports are currently in the process of * establishing a connection; that is, their RTCIceConnectionState is * either "checking" or "connected", and no transports are in the * "failed" state. <<< Make this a link once I know where that will be * documented */ Connecting("connecting"), /** * Every ICE transport used by the connection is either in use (state * "connected" or "completed") or is closed (state "closed"); in * addition, at least one transport is either "connected" or * "completed". */ Connected("connected"), /** * At least one of the ICE transports for the connection is in the * "disconnected" state and none of the other transports are in the * state "failed", "connecting", or "checking". */ Disconnected("disconnected"), /** * One or more of the ICE transports on the connection is in the * "failed" state. */ Failed("failed"), /** * The RTCPeerConnection is closed. * * This value was in the RTCSignalingState enum (and therefore found by * reading the value of the signalingState) property until the May 13, * 2016 draft of the specification. */ Closed("closed"); String string; RTCPeerConnectionState(String str) { this.string = str; } /** * * @param stateStr * @return */ public boolean matches(String stateStr) { return string.equals(stateStr); } } /** * The RTCRtcpMuxPolicy enum defines string constants which specify what ICE * candidates are gathered to support non-multiplexed RTCP. <<<add a link to * info about multiplexed RTCP. */ public static enum RTCRtcpMuxPolicy { /** * Instructs the ICE agent to gather both RTP and RTCP candidates. If * the remote peer can multiplex RTCP, then RTCP candidates are * multiplexed atop the corresponding RTP candidates. Otherwise, both * the RTP and RTCP candidates are returned, separately. */ Negotiate("negotiate"), /** * Tells the ICE agent to gather ICE candidates for only RTP, and to * multiplex RTCP atop them. If the remote peer doesn't support RTCP * multiplexing, then session negotiation fails. */ Require("require"); String string; RTCRtcpMuxPolicy(String str) { this.string = str; } } /** * The RTCSignalingState enum specifies the possible values of * RTCPeerConnection.signalingState, which indicates where in the process of * signaling the exchange of offer and answer the connection currently is. */ public static enum RTCSignalingState { /** * There is no ongoing exchange of offer and answer underway. This may * mean that the RTCPeerConnection object is new, in which case both the * localDescription and remoteDescription are null; it may also mean * that negotiation is complete and a connection has been established. */ Stable("stable"), /** * The local peer has called RTCPeerConnection.setLocalDescription(), * passing in SDP representing an offer (usually created by calling * RTCPeerConnection.createOffer()), and the offer has been applied * successfully. */ HaveLocalOffer("have-local-offer"), /** * The remote peer has created an offer and used the signaling server to * deliver it to the local peer, which has set the offer as the remote * description by calling RTCPeerConnection.setRemoteDescription(). */ HaveRemoteOffer("have-remote-offer"), /** * The offer sent by the remote peer has been applied and an answer has * been created (usually by calling RTCPeerConnection.createAnswer()) * and applied by calling RTCPeerConnection.setLocalDescription(). This * provisional answer describes the supported media formats and so * forth, but may not have a complete set of ICE candidates included. * Further candidates will be delivered separately later. */ HaveLocalPranswer("have-local-pranswer"), /** * A provisional answer has been received and successfully applied in * response to an offer previously sent and established by calling * setLocalDescription(). */ HaveRemotePranswer("have-remote-pranswer"), /** * The connection is closed. */ Closed("closed"); String string; RTCSignalingState(String str) { this.string = str; } boolean matches(String str) { return string.equals(str); } } /** * The RTCOfferOptions dictionary is used to provide optional settings when * creating an RTCPeerConnection offer with the createOffer() method. * * @see https://developer.mozilla.org/en-US/docs/Web/API/RTCOfferOptions */ public static class RTCOfferOptions implements JSONStruct { /** * A Boolean which, when set to true, tells createOffer() to generate * and use new values for the identifying properties of the SDP it * creates, resulting in a request that triggers renegotiation of the * ICE connection. This is useful if network conditions have changed in * a way that make the current configuration untenable or impractical, * for instance. * * @return the iceRestart */ public Boolean isIceRestart() { return iceRestart; } /** * @param iceRestart the iceRestart to set */ public void setIceRestart(Boolean iceRestart) { this.iceRestart = iceRestart; } public RTCOfferOptions iceRestart(Boolean iceRestart) { setIceRestart(iceRestart); return this; } /** * @return the offerToReceiveAudio */ public Boolean isOfferToReceiveAudio() { return offerToReceiveAudio; } /** * @param offerToReceiveAudio the offerToReceiveAudio to set */ public void setOfferToReceiveAudio(Boolean offerToReceiveAudio) { this.offerToReceiveAudio = offerToReceiveAudio; } public RTCOfferOptions offerToReceiveAudio(Boolean offerToReceiveAudio) { setOfferToReceiveAudio(offerToReceiveAudio); return this; } /** * @return the offerToReceiveVideo */ public Boolean isOfferToReceiveVideo() { return offerToReceiveVideo; } /** * @param offerToReceiveVideo the offerToReceiveVideo to set */ public void setOfferToReceiveVideo(Boolean offerToReceiveVideo) { this.offerToReceiveVideo = offerToReceiveVideo; } public RTCOfferOptions offerToReceiveVideo(Boolean offerToReceiveVideo) { setOfferToReceiveVideo(offerToReceiveVideo); return this; } /** * @return the voiceActivityDetection */ public Boolean isVoiceActivityDetection() { return voiceActivityDetection; } /** * @param voiceActivityDetection the voiceActivityDetection to set */ public void setVoiceActivityDetection(Boolean voiceActivityDetection) { this.voiceActivityDetection = voiceActivityDetection; } public RTCOfferOptions voiceActivityDetection(Boolean voiceActivityDetection) { setVoiceActivityDetection(voiceActivityDetection); return this; } private Boolean iceRestart; private Boolean offerToReceiveAudio; private Boolean offerToReceiveVideo; private Boolean voiceActivityDetection; @Override public Object toJSONStruct() { Map out = new LinkedHashMap(); if (iceRestart != null) { out.put("iceRestart", iceRestart); } if (offerToReceiveAudio != null) { out.put("offerToReceiveAudio", offerToReceiveAudio); } if (offerToReceiveVideo != null) { out.put("offerToReceiveVideo", offerToReceiveVideo); } if (voiceActivityDetection != null) { out.put("voiceActivityDetection", voiceActivityDetection); } return out; } } }
37.555556
112
0.666018
014449d0d5f7165079b8a98b7c91622240002c01
552
package mp.jprime.dataaccess.params.query.filters; import mp.jprime.dataaccess.enums.FilterOperation; import java.time.LocalDate; /** * Больше или равно в днях */ public class GTEDay extends LocalDateDateFilter { /** * Конструктор * * @param attrCode Условие по значениям * @param value Условие */ public GTEDay(String attrCode, LocalDate value) { super(attrCode, value); } /** * Операция * * @return Операция */ @Override public FilterOperation getOper() { return FilterOperation.GTE_DAY; } }
17.806452
51
0.679348
a92933f6cba5ef5f8e9c5f8ee31a115c81d8b917
8,735
/** * * shopify-burst-crawler: Java Client for burst.shopify.com API * Copyright (c) 2017, Sandeep Gupta * * https://sangupta.com/projects/shopify-burst-crawler * * 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.sangupta.shopify.burst.crawler; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sangupta.jerry.consume.GenericConsumer; import com.sangupta.jerry.http.WebResponse; import com.sangupta.jerry.http.service.HttpService; import com.sangupta.jerry.io.AdvancedStringReader; import com.sangupta.jerry.util.AssertUtils; import com.sangupta.jerry.util.StringUtils; /** * Simple CLI tool to crawl Shopify Burst image site and provide a list of all * images and their details. This crawler uses the latest photos page to crawl * in from there. * * @author sangupta * */ public class BurstCrawler extends AbstractBurstCrawler { /** * My private logger */ private static final Logger LOGGER = LoggerFactory.getLogger(BurstCrawler.class); /** * Base URL to site */ private static final String BASE_URL = "https://burst.shopify.com/photos?sort=latest"; /** * Last page as detected */ private int lastPage = 0; /** * Total images collected till now */ private int totalCollected = 0; /** * Create {@link BurstCrawler} instance with default * {@link BurstCrawlerOptions}. * */ public BurstCrawler() { this(new BurstCrawlerOptions()); } /** * Create {@link BurstCrawler} instance with given {@link BurstCrawlerOptions}. * * @param options */ public BurstCrawler(BurstCrawlerOptions options) { super(options); this.lastPage = 0; this.totalCollected = 0; } /** * Start crawling using the given {@link GenericConsumer} collector. * * @param collector the {@link GenericConsumer} that will consume the crawled * {@link BurstImage}s */ public void crawl(GenericConsumer<BurstImage> collector) { int currentPage = this.options.startPage; int crawled = 1; do { doForPage(collector, currentPage); if (this.totalCollected == options.maxImages) { LOGGER.debug("Max images reached, breaking from crawling more images"); break; } if (crawled == options.maxPages) { LOGGER.debug("Max pages reached, breaking from crawling more images"); break; } if (currentPage == options.endPage) { LOGGER.debug("Last page limit reached, breaking from crawling more images"); break; } if (options.delayBetweenPagesMillis > 0) { sleepQuietly(options.delayBetweenPagesMillis); } currentPage++; crawled++; } while (currentPage < this.lastPage); LOGGER.debug("Total number of images crawled: {}", this.totalCollected); } /** * Make this thread sleep for a while. * * @param delay */ private void sleepQuietly(int delay) { if (delay <= 0) { return; } try { Thread.sleep(delay); } catch (InterruptedException e) { // eat up } } /** * Populate image details for given list of Burst images. * * @param images */ public void populateImageData(List<BurstImage> images) { if (AssertUtils.isEmpty(images)) { return; } LOGGER.info("Request to populate image data for {} images", images.size()); for (int index = 0; index < images.size(); index++) { BurstImage image = images.get(index); LOGGER.debug("[{}] Populating image data for url: {}", index, image.homeUrl); Document doc = this.getHtmlDoc(image.homeUrl); if (doc == null) { continue; } this.populateImageDetails(image, doc); this.sleepQuietly(this.options.delayBetweenImagesMillis); } } /** * Populate image details from HTML selector onto object. * * @param image * @param doc */ private void populateImageDetails(BurstImage image, Document doc) { Element mainNode = this.getMainNode(doc); if (mainNode == null) { return; } // populate image.title = mainNode.select("h1.heading--2").text(); image.description = mainNode.select("p.photo-info__description").text(); // meta tags Elements elements = mainNode.select(".photo__meta a"); if (elements != null && elements.size() > 0) { for (int index = 0; index < elements.size(); index++) { Element ele = elements.get(index); String href = ele.absUrl("href"); if (href.contains("/@")) { image.authorUrl = href; image.author = ele.text(); continue; } if (href.contains("/tags/")) { image.tags.add(ele.text()); continue; } if (href.contains("/licenses/")) { image.license = ele.text(); continue; } } } // download URL image.url = image.homeUrl + "/download"; } /** * Run crawler & parser over the given page index. * * @param images * @param options * * @param page */ private void doForPage(GenericConsumer<BurstImage> collector, int page) { LOGGER.debug("Crawling page: {}", page); String url = BASE_URL; if (page > 1) { url = url + "&page=" + page; } Document doc = this.getHtmlDoc(url); if (doc == null) { return; } if (page == 1) { extractLastPage(doc); } getPhotosFromPage(collector, options, doc); } /** * Get basic info on photos from the given page document * * @param collector * @param options * * @param doc */ private void getPhotosFromPage(GenericConsumer<BurstImage> collector, BurstCrawlerOptions options, Document doc) { // clear up noise Element mainNode = getMainNode(doc); if (mainNode == null) { return; } // start selecting pics Elements links = mainNode.select("a.photo-tile__image-wrapper"); if (links == null) { LOGGER.debug("No images on page"); return; } // loop over LOGGER.debug("Found num images in page: {}", links.size()); for (int index = 0; index < links.size(); index++) { String url = links.get(index).absUrl("href"); if (AssertUtils.isEmpty(url)) { continue; } final BurstImage image = this.getBurstImageFromURL(url); if(image == null) { continue; } // add that we have collected one more this.totalCollected++; // consume with collector boolean continueCrawling = collector.consume(image); if (!continueCrawling) { return; } // check max images? if (this.totalCollected == options.maxImages) { return; } } } /** * Select the <code>main</code> tag from the HTML document. * * @param doc * @return */ private Element getMainNode(Document doc) { Elements elements = doc.select("main"); if (elements == null) { return null; } // get main node return elements.first(); } /** * Extract last page details from the page. * * @param doc */ private void extractLastPage(Document doc) { LOGGER.debug("Extracting last page from HTML"); // get last page URL so that we can run a loop Elements elements = doc.select("span.last a"); if (elements == null || elements.isEmpty()) { return; } String href = elements.first().absUrl("href"); AdvancedStringReader reader = new AdvancedStringReader(href); String num = reader.readBetween("page=", "&"); int pageNum = StringUtils.getIntValue(num, -1); if (pageNum > 0) { LOGGER.info("Last page detected as: {}", pageNum); this.lastPage = pageNum; } } /** * Parse HTML from URL to a JSOUP document. * * @param url * @return */ private Document getHtmlDoc(String url) { String html = this.getHtml(url); if (AssertUtils.isEmpty(html)) { return null; } return Jsoup.parse(html, url); } /** * Get HTML content for the URL. * * @param url * @return */ private String getHtml(String url) { LOGGER.debug("Fetching HTML response from URL: {}", url); WebResponse response = this.httpService.getResponse(url); if (response == null || !response.isSuccess()) { return null; } return response.getContent(); } // Usual accessors follow /** * Allow to set the {@link HttpService} to be used. * * @param httpService */ public void setHttpService(HttpService httpService) { this.httpService = httpService; } }
22.986842
115
0.66308
7f136d26b1e4de35b3f8c66540ee99be0c2d6001
160
package im.actor.runtime; import im.actor.runtime.cocoa.CocoaNetworkProxyProvider; public class NetworkRuntimeProvider extends CocoaNetworkProxyProvider { }
20
71
0.85
fc2df0dcad9dd1bdce262e4aa3ac03f0406f9b04
7,826
package edu.washington.cs.practicegestures; import java.util.Random; import android.util.Log; import android.os.Bundle; import android.view.View; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.widget.TextView; import android.widget.ImageView; import android.widget.RelativeLayout; import org.opencv.android.OpenCVLoader; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.LoaderCallbackInterface; import edu.washington.cs.touchfreelibrary.sensors.ClickSensor; import edu.washington.cs.touchfreelibrary.sensors.CameraGestureSensor; /** This game has multiple rounds. In each round, a direction (left, right, * up, down, or a click) is displayed to the user. The user moves onto the * next round when they make the prompted gesture in front of the camera. * * @author Krittika D'Silva (krittika.dsilva@gmail.com) */ public class PracticeGesturesActivity extends Activity implements ClickSensor.Listener, CameraGestureSensor.Listener { private static final String TAG = "PracticeGesturesActivity"; /** The total number of rounds played. */ private static final int NUMBER_OF_ROUNDS = 25; /** Sensor that detects gestures. Calls the appropriate * functions when the motions are recognized. */ private CameraGestureSensor mGestureSensor; /** The current round that the user is playing on. */ private int mCurrentRound; /** Produces a random number - used to change the background. */ private Random mRandom; /** True if the openCV library has been initiated. * False otherwise*/ private boolean mOpenCVInitiated = false; /** The current direction that the user is being * prompted to gesture towards.*/ private Direction mCurrentDirection; /** */ private long mStartTime; /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start); // Initialize openCV OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback); mGestureSensor = new CameraGestureSensor(this); mGestureSensor.addGestureListener(this); mGestureSensor.addClickListener(this); mRandom = new Random(); mCurrentRound = 0; mStartTime = System.currentTimeMillis(); setRandomDirection(); } /** Moves onto the next screen. If all of the rounds are over, * opens the final screen. */ protected void setRandomDirection() { if(mCurrentRound >= NUMBER_OF_ROUNDS) { Intent intent = new Intent(this, FinishGame.class); Log.e(TAG, "" + System.currentTimeMillis() ); Log.e(TAG, "" + mStartTime ); long totalTime = System.currentTimeMillis() - mStartTime; intent.putExtra("time", totalTime); startActivity(intent); // Game is over runOnUiThread(new Runnable() { @Override public void run() { mGestureSensor.stop(); } }); } else { runOnUiThread(new Runnable() { @Override public void run() { TextView mCurrentScore = (TextView) findViewById(R.id.textView3); TextView mDirection = (TextView) findViewById(R.id.textView4); ImageView imageView1 = (ImageView) findViewById(R.id.imageView1); mCurrentRound++; mCurrentScore.setText("" + (mCurrentRound) + "/" + NUMBER_OF_ROUNDS); int randomNumb = mRandom.nextInt(5); switch(Integer.valueOf(randomNumb)) { case 0: mCurrentDirection = Direction.Up; imageView1.setImageResource(R.drawable.arrow_up); break; case 1: mCurrentDirection = Direction.Down; imageView1.setImageResource(R.drawable.arrow_down); break; case 2: mCurrentDirection = Direction.Left; imageView1.setImageResource(R.drawable.arrow_left); break; case 3: mCurrentDirection = Direction.Right; imageView1.setImageResource(R.drawable.arrow_right); break; case 4: mCurrentDirection = Direction.Click; imageView1.setImageResource(R.drawable.click); break; } // Makes the background color look quite nice int red = mRandom.nextInt(256-150) + 150; int green = mRandom.nextInt(256-150) + 150; int blue = mRandom.nextInt(256-150) + 150; RelativeLayout wholeScreen = (RelativeLayout) findViewById(R.id.setArrows); wholeScreen.setBackgroundColor(Color.rgb(red,green,blue)); imageView1.setBackgroundColor(Color.rgb(red,green,blue)); mDirection.setText("" + directionToString(mCurrentDirection)); } }); } } /** Closes the current activity. This method is called when the * user is finished with the game and is on the final screen; * closing that activity takes them back to the main screen. */ public void handleFinish(View v) { finish(); } /** Given a Direction, checks whether that direction is the * same as the currently anticipated gesture. Moves onto the next * screen if it is. */ private void checkGestureAccuracy(Direction direction) { final Direction userDirection = direction; runOnUiThread(new Runnable() { @Override public void run() { if(mCurrentDirection == userDirection) { setRandomDirection(); } } }); } /** Moves onto the next screen if an upwards gesture is received. */ @Override public void onGestureUp(CameraGestureSensor caller, long gestureLength) { Log.e(TAG, "Up gesture detected"); checkGestureAccuracy(Direction.Up); } /** Moves onto the next screen if an downwards gesture is received. */ @Override public void onGestureDown(CameraGestureSensor caller, long gestureLength) { Log.e(TAG, "Down gesture detected"); checkGestureAccuracy(Direction.Down); } /** Moves onto the next screen if an leftwards gesture is received. */ @Override public void onGestureLeft(CameraGestureSensor caller, long gestureLength) { Log.e(TAG, "Left gesture detected"); checkGestureAccuracy(Direction.Left); } /** Moves onto the next screen if an rightwards gesture is received. */ @Override public void onGestureRight(CameraGestureSensor caller, long gestureLength) { Log.e(TAG, "Right gesture detected"); checkGestureAccuracy(Direction.Right); } /** Moves onto the next screen if an click is received. */ @Override public void onSensorClick(ClickSensor caller) { checkGestureAccuracy(Direction.Click); } /** List of the five directions that the camera sensor can detect. */ private enum Direction { Up, Down, Left, Right, Click } /** Given a direction, returns the direction as a string. */ private String directionToString(Direction d) { switch(d) { case Up: return "Up"; case Down: return "Down"; case Left: return "Left"; case Click: return "Click"; default: return "Right"; } } /** OpenCV library initialization. */ private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) { @Override public void onManagerConnected(int status) { switch (status) { case LoaderCallbackInterface.SUCCESS: { mOpenCVInitiated = true; CameraGestureSensor.loadLibrary(); mGestureSensor.start(); } break; default: { super.onManagerConnected(status); } break; } } }; /** Called when the activity is resumed. The gesture detector is initialized. */ @Override public void onResume() { super.onResume(); if(!mOpenCVInitiated) return; mGestureSensor.start(); } /** Called when the activity is paused. The gesture detector is stopped * so that the camera is no longer working to recognize gestures. */ @Override public void onPause() { super.onPause(); if(!mOpenCVInitiated) return; mGestureSensor.stop(); } }
30.932806
83
0.703808
4e6a10c4ed2f16e8d37da69efb4744f759d8a143
2,601
/** * Copyright (C) 2019 杭州之乎者也科技有限公司 (http://knowway.cn). * All Rights Reserved. */ package net.jeebiz.admin.extras.article.utils; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.springframework.util.CollectionUtils; import com.google.common.collect.Lists; import net.jeebiz.admin.extras.article.dao.entities.ArticleAttachmentModel; import net.jeebiz.admin.extras.article.dao.entities.ArticleTargetModel; public class ArticleUtils { /** * 获取附件增量集合 * @param atts :此次提交的附件 * @param oldAtts : 已经保存附件 * @return */ public static List<ArticleAttachmentModel> incrementAtt(List<ArticleAttachmentModel> atts, List<ArticleAttachmentModel> oldAtts){ if(CollectionUtils.isEmpty(atts) || CollectionUtils.isEmpty(oldAtts)) { return Lists.newArrayList(); } return atts.stream() .filter(att -> !oldAtts.stream().anyMatch(oldAtt -> StringUtils.equalsIgnoreCase(att.getId(), oldAtt.getId()))) .collect(Collectors.toList()); } /** * 获取附件减量集合 * @param atts :此次提交的附件 * @param oldAtts : 已经保存附件 * @return */ public static List<ArticleAttachmentModel> decrementAtt(List<ArticleAttachmentModel> atts, List<ArticleAttachmentModel> oldAtts){ if(CollectionUtils.isEmpty(oldAtts)) { return Lists.newArrayList(atts); } return oldAtts.stream() .filter(oldAtt -> !atts.stream().anyMatch(att -> StringUtils.equalsIgnoreCase(att.getId(), oldAtt.getId()))) .collect(Collectors.toList()); } /** * 获取发布范围增量集合 * @param targets :此次提交的发布范围 * @param oldTargets : 已经发布范围 * @return */ public static List<ArticleTargetModel> incrementTarget(List<ArticleTargetModel> targets, List<ArticleTargetModel> oldTargets){ if(CollectionUtils.isEmpty(targets) || CollectionUtils.isEmpty(oldTargets)) { return Lists.newArrayList(); } return targets.stream() .filter(target -> !oldTargets.stream().anyMatch(oldTarget -> StringUtils.equalsIgnoreCase(target.getId(), oldTarget.getId()))) .collect(Collectors.toList()); } /** * 获取发布范围减量集合 * @param targets :此次提交的发布范围 * @param oldTargets : 已经发布范围 * @return */ public static List<ArticleTargetModel> decrementTarget(List<ArticleTargetModel> targets, List<ArticleTargetModel> oldTargets){ if(CollectionUtils.isEmpty(oldTargets)) { return Lists.newArrayList(targets); } return oldTargets.stream() .filter(oldTarget -> !targets.stream().anyMatch(target -> StringUtils.equalsIgnoreCase(target.getId(), oldTarget.getId()))) .collect(Collectors.toList()); } }
32.111111
130
0.720492
6fe3e25c7dd3d01c91bc01feeb30e29773a7c988
2,503
package org.vaadin.diagrambuilder; import org.vaadin.diagrambuilder.domain.Node; import org.vaadin.diagrambuilder.domain.NodeType; import org.vaadin.diagrambuilder.domain.Transition; import java.io.Serializable; import java.util.Arrays; import java.util.List; /** * * @author mattitahvonenitmill */ public class DiagramInitState implements Serializable { private List<org.vaadin.diagrambuilder.domain.NodeType> availableFields; private List<org.vaadin.diagrambuilder.domain.Node> fields; private List<org.vaadin.diagrambuilder.domain.Transition> transitions; private Boolean showDeleteNodeIcon = true; private Boolean enableDeleteByKeyStroke = true; private Boolean moveNodeOutSideGroup = false; public DiagramInitState() { } public DiagramInitState(org.vaadin.diagrambuilder.domain.NodeType[] availableFields, org.vaadin.diagrambuilder.domain.Node[] fields, org.vaadin.diagrambuilder.domain.Transition[] transitions) { this.availableFields = Arrays.asList(availableFields); this.fields = Arrays.asList(fields); this.transitions = Arrays.asList(transitions); } public List<org.vaadin.diagrambuilder.domain.Transition> getTransitions() { return transitions; } public void setTransitions(List<Transition> transitions) { this.transitions = transitions; } public List<org.vaadin.diagrambuilder.domain.NodeType> getAvailableFields() { return availableFields; } public void setAvailableFields(NodeType... availableFields) { this.availableFields = Arrays.asList(availableFields); } public List<org.vaadin.diagrambuilder.domain.Node> getFields() { return fields; } public void setFields(Node... fields) { this.fields = Arrays.asList(fields); } public Boolean getShowDeleteNodeIcon() { return showDeleteNodeIcon; } public void setShowDeleteNodeIcon(Boolean showDeleteNodeIcon) { this.showDeleteNodeIcon = showDeleteNodeIcon; } public Boolean getEnableDeleteByKeyStroke() { return enableDeleteByKeyStroke; } public void setEnableDeleteByKeyStroke(Boolean enableDeleteByKeyStroke) { this.enableDeleteByKeyStroke = enableDeleteByKeyStroke; } public Boolean getMoveNodeOutSideGroup() { return moveNodeOutSideGroup; } public void setMoveNodeOutSideGroup(Boolean moveNodeOutSideGroup) { this.moveNodeOutSideGroup = moveNodeOutSideGroup; } }
30.901235
197
0.736316
61dc94dd90cc9debcb6ab184553646eea4c4bf4b
817
package io.skeyer.api.client; import io.skeyer.api.client.constant.SkeyerConstants; import org.apache.commons.lang3.builder.ToStringBuilder; /** * Skeyer API error object. */ public class SkeyerApiError { /** * Error code. */ private int code; /** * Error message. */ private String msg; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public String toString() { return new ToStringBuilder(this, SkeyerConstants.TO_STRING_BUILDER_STYLE) .append("code", code) .append("msg", msg) .toString(); } }
18.155556
81
0.571603
a048e11ce9328180621ba6b7dd69978059c298c3
692
package pcell.evaluator; import pcell.model.Model; import utils.Data; public abstract class Evaluator { Data X, Y; // ProcessingCell cell; public void prepareData(Data x, Data y) { this.X = x; this.Y = y; } public abstract double evaluate(Model model); public abstract double evaluate(Model model, Data X, Data Y); public abstract void prepareNextBatch(); // public static Evaluator getErrorType(String errorType) { // switch (errorType.toLowerCase()) { // case "mae": // default: // return new Error(); // case "rmse": // return new RMSError(); // } // } }
21.625
65
0.57659
5bee26783c4579fe4ac505daa6525aabfed6092b
3,032
package it.polito.ai.mmap.pedibus.controller; import it.polito.ai.mmap.pedibus.configuration.PedibusString; import it.polito.ai.mmap.pedibus.entity.ChildEntity; import it.polito.ai.mmap.pedibus.repository.ChildRepository; import it.polito.ai.mmap.pedibus.repository.ReservationRepository; import it.polito.ai.mmap.pedibus.repository.UserRepository; import it.polito.ai.mmap.pedibus.services.DataCreationService; import it.polito.ai.mmap.pedibus.services.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import springfox.documentation.annotations.ApiIgnore; import java.io.IOException; import java.util.List; @Profile("dev") @RestController @ApiIgnore public class DebugController { @Autowired ChildRepository childRepository; @Autowired UserRepository userRepository; @Autowired ReservationRepository reservationRepository; @Autowired UserService userService; @Autowired DataCreationService dataCreationService; private Logger logger = LoggerFactory.getLogger(this.getClass()); /** * Endpoint di debug, cancella tutto dal database */ @GetMapping("/debug/delete") public void deleteAll() { logger.info(PedibusString.ENDPOINT_CALLED("GET", "/debug/delete")); dataCreationService.deleteAll(); } /** * Si può chiamare ripetutamente e creerà nuovi dati * Genera: * - countCreate genitori, ognuno con due figli * - 2*countCreate guide * - 1 admin della linea 1 * - 1 admin della linea 2 * * @param countCreate numero di oggetti * @throws IOException Eccezione lettura da file */ @GetMapping("/debug/make/{countCreate}") public void makeChildUser(@PathVariable("countCreate") int countCreate) throws IOException { logger.info(PedibusString.ENDPOINT_CALLED("GET", "/debug/make/" + countCreate)); dataCreationService.makeChildUser(countCreate); } /** * Si può chiamare ripetutamente e creerà nuovi dati * Genera: * - countCreate genitori, ognuno con due figli * * @throws IOException Eccezione lettura da file */ @GetMapping("/debug/make/child/{countCreate}") public void makeChild(@PathVariable("countCreate") int countCreate) throws IOException { logger.info(PedibusString.ENDPOINT_CALLED("GET", "/debug/make/child/" + countCreate)); dataCreationService.makeChild(countCreate); } /** * Unisce il json dei bimbi (childEntity_base.json) alla lista di cf (cf.txt) * * @return * @throws IOException */ @GetMapping("/debug/transform") public List<ChildEntity> debug() throws IOException { return dataCreationService.transform(); } }
33.318681
96
0.726913
3fac6c33a23f66e0f873051cb656974dc34fb560
374
package com.bq.corbel.resources.rem.resmi.ioc; /** * @author Francisco Sánchez - Rubén Carrasco */ public interface ResmiRemNames { String RESMI = "resmi"; String RESMI_GET = "resmi_get"; String RESMI_POST = "resmi_post"; String RESMI_PUT = "resmi_put"; String RESMI_DELETE = "resmi_delete"; String ELASTICSEARCH_HEALTHCHECK = "elasticsearch"; }
24.933333
55
0.708556
2caf8b82a5614aee0cfd51a189e9e1472b752e1a
460
package kloojj.com.autolinkmytest; import android.app.Activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; /** * Created by Pankaj Kumar on 23/02/18. * pankaj@kloojj.com * EAT | DRINK | CODE */ public class SeekBarRangeTest extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.seek_bar_range_layout); } }
24.210526
56
0.73913
575969cbb5d5a8194ef0c1912d4331d9840b2d88
4,359
/* * Copyright (c) 2014-2017 Neil Ellis * * 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.sillelien.dollar.api.json; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; import java.util.Set; public class ImmutableJsonObject { private final @NotNull JsonObject json; public ImmutableJsonObject(@NotNull JsonObject json) { this.json = json; } @NotNull public JsonArray asArray() { return json.asArray().copy(); } @NotNull public JsonObject asObject() { return json.copy().asObject(); } public boolean containsField(String fieldName) { return json.containsField(fieldName); } public String encode() { return json.encode(); } public String encodePrettily() { return json.encodePrettily(); } public JsonArray getArray(String fieldName, JsonArray def) { return json.getArray(fieldName, def); } @Nullable public JsonArray getArray(String fieldName) { return json.getArray(fieldName); } @Nullable public byte[] getBinary(String fieldName) { return json.getBinary(fieldName); } public byte[] getBinary(String fieldName, byte[] def) { return json.getBinary(fieldName, def); } @NotNull public Boolean getBoolean(String fieldName) { return json.getBoolean(fieldName); } public boolean getBoolean(String fieldName, boolean def) { return json.getBoolean(fieldName, def); } @Nullable public JsonElement getElement(String fieldName) { return json.getElement(fieldName); } public JsonElement getElement(String fieldName, JsonElement def) { return json.getElement(fieldName, def); } @NotNull public <T> T getField(String fieldName) { return json.getField(fieldName); } @NotNull public Set<String> getFieldNames() { return json.getFieldNames(); } @Nullable public Integer getInteger(String fieldName) { return json.getInteger(fieldName); } public Integer getInteger(String fieldName, int def) { return json.getInteger(fieldName, def); } @Nullable public Long getLong(String fieldName) { return json.getLong(fieldName); } public Long getLong(String fieldName, long def) { return json.getLong(fieldName, def); } public Number getNumber(String fieldName, int def) { return json.getNumber(fieldName, def); } @NotNull public Number getNumber(String fieldName) { return json.getNumber(fieldName); } public JsonObject getObject(String fieldName, JsonObject def) { return json.getObject(fieldName, def); } @Nullable public JsonObject getObject(String fieldName) { return json.getObject(fieldName); } @NotNull public String getString(String fieldName) { return json.getString(fieldName); } public String getString(String fieldName, String def) { return json.getString(fieldName, def); } @NotNull public <T> T getValue(String fieldName) { return json.getValue(fieldName); } @Override public int hashCode() { return json.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof JsonObject) { return json.equals(obj); } return obj instanceof ImmutableJsonObject && json.equals(((ImmutableJsonObject) obj).json); } @Override public String toString() { return json.toString(); } public boolean isArray() { return json.isArray(); } public boolean isObject() { return json.isObject(); } @NotNull public JsonObject mutable() { return json.copy(); } @NotNull public JsonObject putNumber(String fieldName, Number value) { return json.putNumber(fieldName, value); } public int size() { return json.size(); } @NotNull public Map<String, Object> toMap() { return json.toMap(); } }
24.216667
95
0.695572
720f1642b1085c09a9108a9cac63209493c0762c
6,467
package com.libreworks.stellarbase.web; import static org.junit.Assert.*; import java.net.URI; import org.junit.Test; import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockServletContext; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.google.common.collect.ImmutableMap; import com.libreworks.stellarbase.persistence.Pagination; public class PaginationFactoryTests { @Test public void testDojoStore() { PaginationFactory object = new PaginationFactory(); MockHttpServletRequest request1 = MockMvcRequestBuilders.request(HttpMethod.GET, URI.create("foo")) .header("Range", "items=1-25") .param("sort(+foo,-bar)", "") .buildRequest(new MockServletContext()); Pagination p1 = object.create(request1); assertEquals(Integer.valueOf(25), p1.getMax()); assertEquals(Integer.valueOf(1), p1.getOffset()); assertEquals(ImmutableMap.of("foo", Boolean.TRUE, "bar", Boolean.FALSE), p1.getOrder()); MockHttpServletRequest request2 = MockMvcRequestBuilders.request(HttpMethod.GET, URI.create("foo")) .param("sort(+foo)", "") .buildRequest(new MockServletContext()); Pagination p2 = object.create(request2); assertEquals(Integer.valueOf(Integer.MAX_VALUE), p2.getMax()); assertEquals(Integer.valueOf(0), p2.getOffset()); assertEquals(ImmutableMap.of("foo", Boolean.TRUE), p2.getOrder()); MockHttpServletRequest request3 = MockMvcRequestBuilders.request(HttpMethod.GET, URI.create("foo")) .header("Range", "items=0-") .param("sortBy", "+foo,-bar,baz") .buildRequest(new MockServletContext()); Pagination p3 = object.create(request3, "sortBy"); assertEquals(Integer.valueOf(Integer.MAX_VALUE), p3.getMax()); assertEquals(Integer.valueOf(0), p3.getOffset()); assertEquals(ImmutableMap.of("foo", Boolean.TRUE, "bar", Boolean.FALSE, "baz", Boolean.TRUE), p3.getOrder()); } @Test public void testDojoData() { PaginationFactory object = new PaginationFactory(); MockHttpServletRequest request1 = MockMvcRequestBuilders.request(HttpMethod.GET, URI.create("foo")) .param("count", "25") .param("start", "1") .param("sort", "+foo,-bar") .buildRequest(new MockServletContext()); Pagination p1 = object.create(request1); assertEquals(Integer.valueOf(25), p1.getMax()); assertEquals(Integer.valueOf(1), p1.getOffset()); assertEquals(ImmutableMap.of("foo", Boolean.TRUE, "bar", Boolean.FALSE), p1.getOrder()); } @Test public void testExtJs(){ PaginationFactory object = new PaginationFactory(); MockHttpServletRequest request1 = MockMvcRequestBuilders.request(HttpMethod.GET, URI.create("foo")) .param("start", "1") .param("limit", "25") .param("sort", "[{\"property\":\"foo\",\"direction\":\"asc\"},{\"property\":\"bar\",\"direction\":\"desc\"}]") .buildRequest(new MockServletContext()); Pagination p1 = object.create(request1); assertEquals(Integer.valueOf(25), p1.getMax()); assertEquals(Integer.valueOf(1), p1.getOffset()); assertEquals(ImmutableMap.of("foo", Boolean.TRUE, "bar", Boolean.FALSE), p1.getOrder()); } @Test public void testOpenSearchServer() { PaginationFactory object = new PaginationFactory(); MockHttpServletRequest request1 = MockMvcRequestBuilders.request(HttpMethod.GET, URI.create("foo")) .param("startIndex", "2") .param("count", "25") .param("sort", "foo", "-bar") .buildRequest(new MockServletContext()); Pagination p1 = object.create(request1); assertEquals(Integer.valueOf(25), p1.getMax()); assertEquals(Integer.valueOf(1), p1.getOffset()); assertEquals(ImmutableMap.of("foo", Boolean.TRUE, "bar", Boolean.FALSE), p1.getOrder()); MockHttpServletRequest request2 = MockMvcRequestBuilders.request(HttpMethod.GET, URI.create("foo")) .param("startPage", "2") .param("count", "25") .param("sort", "foo", "-bar") .buildRequest(new MockServletContext()); Pagination p2 = object.create(request2); assertEquals(Integer.valueOf(25), p2.getMax()); assertEquals(Integer.valueOf(25), p2.getOffset()); assertEquals(ImmutableMap.of("foo", Boolean.TRUE, "bar", Boolean.FALSE), p2.getOrder()); } @Test public void testOpenSearchExtension() { PaginationFactory object = new PaginationFactory(); MockHttpServletRequest request1 = MockMvcRequestBuilders.request(HttpMethod.GET, URI.create("foo")) .param("startIndex", "2") .param("count", "25") .param("sort", "foo:ascending", "bar:descending") .buildRequest(new MockServletContext()); Pagination p1 = object.create(request1); assertEquals(Integer.valueOf(25), p1.getMax()); assertEquals(Integer.valueOf(1), p1.getOffset()); assertEquals(ImmutableMap.of("foo", Boolean.TRUE, "bar", Boolean.FALSE), p1.getOrder()); MockHttpServletRequest request2 = MockMvcRequestBuilders.request(HttpMethod.GET, URI.create("foo")) .param("startPage", "2") .param("count", "25") .param("sort", "foo:ascending", "bar:descending") .buildRequest(new MockServletContext()); Pagination p2 = object.create(request2); assertEquals(Integer.valueOf(25), p2.getMax()); assertEquals(Integer.valueOf(25), p2.getOffset()); assertEquals(ImmutableMap.of("foo", Boolean.TRUE, "bar", Boolean.FALSE), p2.getOrder()); } @Test public void testSpringData() { PaginationFactory object = new PaginationFactory(); MockHttpServletRequest request2 = MockMvcRequestBuilders.request(HttpMethod.GET, URI.create("foo")) .param("page", "2") .param("limit", "25") .param("sort", "foo,asc", "bar,desc") .buildRequest(new MockServletContext()); Pagination p2 = object.create(request2); assertEquals(Integer.valueOf(25), p2.getMax()); assertEquals(Integer.valueOf(25), p2.getOffset()); assertEquals(ImmutableMap.of("foo", Boolean.TRUE, "bar", Boolean.FALSE), p2.getOrder()); } @Test public void testGrails() { PaginationFactory object = new PaginationFactory(); MockHttpServletRequest request1 = MockMvcRequestBuilders.request(HttpMethod.GET, URI.create("foo")) .param("max", "25") .param("offset", "1") .param("sort", "foo") .param("order", "asc") .buildRequest(new MockServletContext()); Pagination p1 = object.create(request1); assertEquals(Integer.valueOf(25), p1.getMax()); assertEquals(Integer.valueOf(1), p1.getOffset()); assertEquals(ImmutableMap.of("foo", Boolean.TRUE), p1.getOrder()); } }
36.536723
113
0.713314
9fe690227450df1ec6f0ec39702e546e60f207a8
4,431
package com.dmitrybrant.bettertooltips.demo; import android.app.Activity; import android.os.Bundle; import android.view.View; import com.dmitrybrant.bettertooltips.OnboardingTracker; import com.dmitrybrant.bettertooltips.ToolTip; import com.dmitrybrant.bettertooltips.ToolTipRelativeLayout; import com.dmitrybrant.bettertooltips.ToolTipSequence; import com.dmitrybrant.bettertooltips.ToolTipView; public class TrackerActivity extends Activity implements View.OnClickListener { private ToolTipRelativeLayout toolTipFrameLayout; private ToolTipSequence toolTipSequence; private ToolTipView delayToolTipView; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tracker_activity); toolTipFrameLayout = (ToolTipRelativeLayout) findViewById(R.id.activity_main_tooltipframelayout); OnboardingTracker sequenceTracker = new OnboardingTracker(this, "sequence").build(); toolTipSequence = new ToolTipSequence(sequenceTracker, toolTipFrameLayout); addDelayedToolTipView(); addSequenceOneToolTipView(); addTrackerToolTipView(); addSequenceTwoToolTipView(); addSequenceThreeToolTipView(); } private void addDelayedToolTipView() { ToolTip toolTip = ToolTipFactory.getToolTipWithText(this, "You don't seem to have \n found this button yet!"); toolTip.withDelay(5000); OnboardingTracker tracker = new OnboardingTracker(this, getString(R.string.tracker_delayed_button)) .build(); final View delayedButton = findViewById(R.id.activity_main_redtv); delayedButton.setOnClickListener(this); delayToolTipView = toolTipFrameLayout.showToolTipWithTracker(toolTip, delayedButton, tracker); toolTipFrameLayout.addToolTipView(delayToolTipView); } private void addSequenceOneToolTipView() { final ToolTip toolTip = ToolTipFactory.getToolTipWithText(this, "This is the first"); ToolTipView sequenceOneToolTipView = toolTipFrameLayout.showToolTipForView(toolTip, findViewById(R.id.activity_main_greentv)); toolTipSequence.addToSequence(sequenceOneToolTipView); } private void addSequenceTwoToolTipView() { final ToolTip toolTip = ToolTipFactory.getToolTipWithText(this, "In a sequence"); ToolTipView sequenceTwoToolTipView = toolTipFrameLayout.showToolTipForView(toolTip, findViewById(R.id.activity_main_bluetv)); toolTipSequence.addToSequence(sequenceTwoToolTipView); } private void addSequenceThreeToolTipView() { final ToolTip toolTip = ToolTipFactory.getToolTipWithText(this, "That is now done"); final View refreshButton = findViewById(R.id.activity_main_purpletv); refreshButton.setOnClickListener(this); ToolTipView sequenceThreeToolTipView = toolTipFrameLayout.showToolTipForView(toolTip, findViewById(R.id.activity_main_purpletv)); toolTipSequence.addToSequence(sequenceThreeToolTipView); } private void addTrackerToolTipView() { OnboardingTracker tracker = new OnboardingTracker(this, getString(R.string.tracker_first_button)) .withFirstShow(1) .withLastShow(3) .afterInitialOnboarding(true) .build(); final ToolTip toolTip = ToolTipFactory.getToolTipWithText(this, "You're already a pro with the top left button. Try this one. Shows on 2nd to 4th views after top left was pressed"); ToolTipView trackerToolTipView = toolTipFrameLayout.showToolTipWithTracker(toolTip, findViewById(R.id.activity_main_orangetv), tracker); toolTipFrameLayout.addToolTipView(trackerToolTipView); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.activity_main_redtv) { if (delayToolTipView != null) { final OnboardingTracker tracker = delayToolTipView.getTracker(); tracker.setDismissedPref(true); tracker.setInitialOnboardingComplete(true); } } else if ((id == R.id.activity_main_purpletv)) { if (delayToolTipView != null) { //Restart delayed ToolTip final OnboardingTracker tracker = delayToolTipView.getTracker(); tracker.setDismissedPref(false); } } } }
42.605769
189
0.722862
d84331d8a60f715618092a60c7d35cec9c03981c
5,978
package com.example.DietBoxAPI.models.data_enums; public enum Nutrients { CHICKEN(154.2355191160072, 297.17152796650964 , 6.04717021081533, 32.69640545254722, 17.83580210590874 , 4.890957143930871, 780.0918948948405 , 155.64933797240914, 7.494381354888844, 2.4266982420109824), PIG(107.9130736442456, 351.5177969434517 , 6.146302072560938, 19.47847756227281, 30.937706610784634 , 3.413031898103374, 383.90846399214 , 56.98245261895729, 11.371367999518133, 1.4611665965469074), COW(83.25, 184.18776257307246 , 8.520825897622093, 24.827127681771632, 20.787475781689913 , 8.25, 59.32973406862113 , 47.016752101181936, 12.176002835964388, 8.495472591841027), FISH(76.5, 143.5472856087947 , 1.6051776695296636, 20.36388293927314, 8.446880050865893 , 1.5, 127.9929387567577 , 55.08434902349896, 3.160376227585084, 1.5051450317547304), RAW_FISH(94.5, 125.70256175760775 , 20.769522599630008, 33.834026115422304, 24.546080900236895 , 19.5, 202.1161129479679 , 33.099669968139175, 20.345064418217866, 19.520105482696298), RAMEN(177.83804135931643, 347.71427012828326 , 66.20750297884769, 23.011320718171913, 26.402680916909674 , 19.440783868210048, 1148.8858143139175 , 31.110690823938242, 20.37055753751119, 15.028328607001907), COFFEE(172.1137206645626, 44.96437035812312 , 14.269639533787291, 4.926145471801578, 5.226424517211591 , 16.771758257616227, 47.86034492038998 , 4.625, 4.625, 4.625), DRINK(35.60310363079829, 65.932951990752 , 16.281286187291027, 0.7567116952719121, 0.6749999999999999 , 13.275, 1.801823762720666 , 0.5, 0.5, 0.5), BREAD(110.26995683407152, 334.41669214501144 , 69.93227964944657, 37.711038245507154, 39.220696836246695 , 45.225252835488675, 335.675645094218 , 56.78498943466577, 34.87513753512384, 32.27567324611235), PIZZA(92.08103447693415, 258.47832698054475 , 36.23832118835462, 10.538534851994285, 9.56466288443671 , 6.614607557484492, 421.47089612977203 , 12.508027312115436, 5.462385788674933, 0.75), KIMCHI(23.0, 3.151085085137254 , 0.9238813368509694, 0.6838192314226719, 0.5322821773229381 , 0.6477617158903733, 161.88260736114626 , 0.5, 0.5, 0.5), SOUP(419.43105685654626, 249.82799254533535 , 37.20081188778288, 35.00256995151759, 31.0087255120371 , 25.223645088516808, 1177.7360787043224 , 125.2063010362723, 23.618148012796137, 17.787924210236667), RICE(154.73504233964073, 230.30076057520688 , 51.138193909433, 4.42633545031537, 1.4686004233964074 , 0.375, 10.840010584910182 , 0.375, 0.5256677251576849, 0.375), RED_RICE_CAKE(229.21903446891116, 325.2369985523237 , 63.17832807607805, 8.460586809119896, 5.983001531567687 , 7.959113118861683, 851.184369471159 , 24.59722222222222, 2.989813352090062, 1.125), SUNDAE(168.79139072545127, 298.1278196716666 , 42.908271439823864, 8.108485159724045, 11.272748035818683 , 2.32071555075835, 762.8622022706611 , 22.885278257451645, 3.240820417609902, 0.4111602540378444), FRIED(130.1348315813801, 391.72135362169854 , 34.56782435959144, 21.300617472966337, 26.252391499944682 , 5.364275554157115, 576.4839133886344 , 83.60806173731426, 8.382272878340146, 2.295420493123259); private double total, kcal; private double carbohydrate, protein, fat; private double sugar, sodium; private double cholesterol, saturatedFattyAcid, transFat; Nutrients(double total, double kcal , double carbohydrate, double protein, double fat , double sugar, double sodium , double cholesterol, double saturatedFattyAcid, double transFat) { this.total = total; this.kcal = kcal; this.carbohydrate = carbohydrate; this.protein = protein; this.fat = fat; this.sugar = sugar; this.sodium = sodium; this.cholesterol = cholesterol; this.saturatedFattyAcid = saturatedFattyAcid; this.transFat = transFat; } public double getTotal() { return total; } public double getKcal() { return kcal; } public double getCarbohydrate() { return carbohydrate; } public double getProtein() { return protein; } public double getFat() { return fat; } public double getSugar() { return sugar; } public double getSodium() { return sodium; } public double getCholesterol() { return cholesterol; } public double getSaturatedFattyAcid() { return saturatedFattyAcid; } public double getTransFat() { return transFat; } public void setTotal(double total) { this.total = total; } public void setKcal(double kcal) { this.kcal = kcal; } public void setCarbohydrate(double carbohydrate) { this.carbohydrate = carbohydrate; } public void setProtein(double protein) { this.protein = protein; } public void setFat(double fat) { this.fat = fat; } public void setSugar(double sugar) { this.sugar = sugar; } public void setSodium(double sodium) { this.sodium = sodium; } public void setCholesterol(double cholesterol) { this.cholesterol = cholesterol; } public void setSaturatedFattyAcid(double saturatedFattyAcid) { this.saturatedFattyAcid = saturatedFattyAcid; } public void setTransFat(double transFat) { this.transFat = transFat; } }
35.164706
79
0.647876