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
|
---|---|---|---|---|---|
4013ab0796044d31915cfdda34215acdfc91c8cf | 373 | package com.extreme.data;
public enum Genre {
ACTION("Action"),
ADVENTURE("Adventure"),
DRAMA("Drama"),
SCIENCE_FICTION("Science Fiction"),
COMEDY("Comedy");
private String displayName;
Genre(String displayName) {
this.displayName = displayName;
}
@Override
public String toString() {
return displayName;
}
}
| 17.761905 | 39 | 0.627346 |
014c8a74133ec9199e63fbeafd9c08bb8a57bbfd | 1,292 | package cn.techaction.dao;
import cn.techaction.pojo.ActionUser;
public interface ActionUserDao {
/**
* 根据用户名和密码查找用户
* @param account
* @param password
* @return
*/
public ActionUser findUserByAccountAndPwd(String account,String password);
/**
* 根据账号判断用户是否存在
* @param account
* @return
*/
public int checkUserByAccount(String account);
/**
* 验证电子邮箱是否已经注册
* @param email
* @return
*/
public int checkUserByEmail(String email);
/**
* 验证手机号码是否已经注册
* @param phone
* @return
*/
public int checkUserByPhone(String phone);
/**
* 新增用户
* @param user
* @return
*/
public int insertUser(ActionUser user);
/**
* 查找用户设置的问题
* @param account
* @return
*/
public String findUserQuestion(String account);
/**
* 检查用户密码问题的答案
* @param account
* @param question
* @param asw
* @return
*/
public int checkUserAnswer(String account,String question,String asw);
/**
* 更新密码
* @param account
* @param password
* @return
*/
public int updatePasswordByAccount(String account,String password);
/**
* 验证用户是否已经存在
* @param account
* @param password
* @return
*/
public int checkPassword(String account,String password);
/**
* 更新用户信息
* @param user
* @return
*/
public int updateUserInfo(ActionUser user);
}
| 17 | 75 | 0.666409 |
1c98747d04e6d5519170dda062e57511f6003200 | 1,653 | /*
* Copyright 2014-2015 itas group
*
* 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.itas.xcnet.common.status.support;
import org.itas.xcnet.common.Extension;
import org.itas.xcnet.common.status.Status;
import org.itas.xcnet.common.status.StatusChecker;
import org.itas.xcnet.common.status.Status.Level;
/**
* Memory Status
*
* @author liuzhen<liuxing521a@163.com>
* @createTime 2015年5月15日下午2:18:14
*/
@Extension("memory")
public class MemoryStatusChecker implements StatusChecker {
@Override
public Status check() {
Runtime runtime = Runtime.getRuntime();
long freeMemory = runtime.freeMemory();
long totalMemory = runtime.totalMemory();
long maxMemory = runtime.maxMemory();
boolean warn = (maxMemory - (totalMemory - freeMemory)) > 2048; // 剩余空间小于2M报警
StringBuilder sb = new StringBuilder();
sb.append("maxMemory:").append(maxMemory/(1024*1024)).append("M, ");
sb.append("totalMemory:").append(totalMemory/(1024*1024)).append("M, ");
sb.append("usedMemory:").append((totalMemory - freeMemory)/(1024*1024)).append("M");
return new Status(warn ? Level.OK : Level.WARN, sb.toString());
}
}
| 33.734694 | 86 | 0.730792 |
7ba91b6c5374c9a358159487da342227e99c2933 | 1,413 | package pl.sdacademy.java16poz.wstep.klasy;
import pl.sdacademy.java16poz.wstep.obiekty.Zamowienie;
/**
* ZamowieniaMain
*
* @author: Jakub Olszewski [http://github.com/jakub-olszewski]
* @date: 30.03.2019 10:21
**/
public class ZamowieniaMain {
public static void main(String[] args) {
Zamowienie zamowienie1 = new Zamowienie(1);
// pobranie ceny zamowienia i wyswietlenie na konsoli
float aktualnaKwotaDoZaplaty = zamowienie1.pobierzCena();
System.out.println("Aktualny stan rachunku:"+aktualnaKwotaDoZaplaty);
/**
* Zadanie domowe
* ----------------------------
* dodaj metode dodajPozycje(float cena)
* dodaj kilka pozycji do zamowienia i
* na końcu pobierzCene()
* i wyświetl mini rachunek
*/
zamowienie1.dodajPozycje("Pomidor",1.99f);
zamowienie1.dodajPozycje("Reklamówka", 0.98f);
zamowienie1.dodajPozycje("Chleb", 3.97f);
zamowienie1.dodajPozycje("Sałata", 1.96f);
//zamowienie1.wypiszPozycje(); 1 petli (for,while)
/**
* Zadanie domowe
*
* Wypisać na konsolę z użyciem pętli
* ładnie - pretty print
*/
// do poprawki cena zamówienia
/**
* Zadanie domowe
* w pętli sumować i przypisać sumę
*/
zamowienie1.wypiszRachunek();
}
}
| 26.166667 | 77 | 0.593772 |
1cc05e5071d8bc2325872fcce3abbc26d027474e | 1,680 | /*
* Copyright 2014 AgentTroll
*
* 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.gmail.woodyc40.commons;
import com.gmail.woodyc40.commons.concurrent.ThreadPoolManager;
import com.gmail.woodyc40.commons.event.Events;
import com.gmail.woodyc40.commons.reflection.impl.ReflectionCache;
/**
* The main runner representing this plugin utility
*
* @author AgentTroll
* @version 1.0
* @since 1.0
*/
public class Commons {
public static Package getCaller(boolean ignore) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (StackTraceElement element : elements) {
if (!element.getClassName().startsWith("java.") &&
(!ignore || !element.getClassName().startsWith("com.gmail.woodyc40.commons."))) {
Class<?> clazz = ReflectionCache.getClass(element.getClassName());
if (clazz.getPackage().getName().contains("com.gmail.woodyc40.commons"))
return clazz.getPackage();
}
}
return null;
}
public void onDisable() { // TODO
ThreadPoolManager.shutdown();
Events.shutdown();
}
}
| 33.6 | 97 | 0.679167 |
003f2b7ea50fe9077c9a6f57a4b02b8f44d5b558 | 2,612 | package cz.vhromada.catalog.web.show.mo;
import java.io.Serializable;
import java.util.Objects;
import cz.vhromada.catalog.entity.Show;
import cz.vhromada.common.Time;
/**
* A class represents MO for show data.
*
* @author Vladimir Hromada
*/
public class ShowDataMO implements Serializable {
/**
* SerialVersionUID
*/
private static final long serialVersionUID = 1L;
/**
* Show
*/
private Show show;
/**
* Count of seasons
*/
private int seasonsCount;
/**
* Count of episodes
*/
private int episodesCount;
/**
* Total length
*/
private Time totalLength;
/**
* Returns show.
*
* @return show
*/
public Show getShow() {
return show;
}
/**
* Sets a new value to show.
*
* @param show new value
*/
public void setShow(final Show show) {
this.show = show;
}
/**
* Returns count of seasons.
*
* @return count of seasons
*/
public int getSeasonsCount() {
return seasonsCount;
}
/**
* Sets a new value to count of seasons.
*
* @param seasonsCount new value
*/
public void setSeasonsCount(final int seasonsCount) {
this.seasonsCount = seasonsCount;
}
/**
* Returns count of episodes.
*
* @return count of episodes
*/
public int getEpisodesCount() {
return episodesCount;
}
/**
* Sets a new value to count of episodes.
*
* @param episodesCount new value
*/
public void setEpisodesCount(final int episodesCount) {
this.episodesCount = episodesCount;
}
/**
* Returns total length.
*
* @return total length
*/
public Time getTotalLength() {
return totalLength;
}
/**
* Sets a new value to total length.
*
* @param totalLength new value
*/
public void setTotalLength(final Time totalLength) {
this.totalLength = totalLength;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ShowDataMO)) {
return false;
}
return Objects.equals(show, ((ShowDataMO) obj).show);
}
@Override
public int hashCode() {
return Objects.hashCode(show);
}
@Override
public String toString() {
return String.format("ShowDataMO [show=%s, seasonsCount=%d, episodesCount=%d, totalLength=%s]", show, seasonsCount, episodesCount, totalLength);
}
}
| 19.205882 | 152 | 0.570444 |
7d5ab9a5ecef48736d998e6b2a63f787ec51e7ac | 1,972 | package jdepend.client.ui.result.framework;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import jdepend.framework.util.BundleUtil;
import jdepend.client.ui.JDependCooper;
import jdepend.client.ui.framework.CooperTabbedPane;
public class ResultTab extends CooperTabbedPane {
private JPopupMenu popupMenu;
public ResultTab(JDependCooper frame) {
super(frame, true, true, CooperTabbedPane.Workspace);
this.popupMenu = new JPopupMenu();
JMenuItem closeItem = new JMenuItem(BundleUtil.getString(BundleUtil.Command_Close));
closeItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeSelf(e);
}
});
popupMenu.add(closeItem);
JMenuItem closeOthersItem = new JMenuItem("关闭其它");
closeOthersItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeOthers();
}
});
popupMenu.add(closeOthersItem);
JMenuItem closeAllItem = new JMenuItem("关闭所有");
closeAllItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeAll();
}
});
popupMenu.add(closeAllItem);
}
private void closeOthers() {
String title = this.getTitleAt(this.getSelectedIndex());
Component component = this.getComponentAt(this.getSelectedIndex());
this.removeAll();
addTab(title, component);
}
private void closeAll() {
this.removeAll();
}
private void closeSelf(ActionEvent e) {
int tabNumber = this.getSelectedIndex();
if (tabNumber < 0)
return;
this.removeTabAt(tabNumber);
}
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
ResultTab tab = (ResultTab) e.getSource();
if (e.getButton() == 3) {
popupMenu.show(tab, e.getX(), e.getY());
}
}
}
| 24.962025 | 87 | 0.709939 |
86d4e176cd8174a12e93d12adac02fbe5d93166a | 6,397 | /*
* Copyright (C) 2018 StarChart-Labs@github.com Authors
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package org.starchartlabs.calamari.core;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.starchartlabs.calamari.core.exception.RequestLimitExceededException;
import okhttp3.Response;
/**
* Provides streamlined checking for common responses from GitHub
*
* @author romeara
* @since 0.1.0
*/
public class ResponseConditions {
private static final String RATE_LIMIT_MAXIMUM_HEADER = "X-RateLimit-Limit";
private static final String RATE_LIMIT_RESET_HEADER = "X-RateLimit-Reset";
private static final String RATE_LIMIT_REMAINING_HEADER = "X-RateLimit-Remaining";
/**
* Analyzes a web response to determine if it represents exceeding GitHub's rate limits
*
* <p>
* If the response does represent exceeded rate limiting, throws a {@link RequestLimitExceededException}
*
* <p>
* To use this check with other web libraries, see {@link #checkRateLimit(Object, Function, BiFunction)}
*
* @param response
* OkHttp3 representation of a web response
* @since 0.1.0
*/
public static void checkRateLimit(Response response) throws RequestLimitExceededException {
Objects.requireNonNull(response);
checkRateLimit(response, Response::code, (res, header) -> res.headers().values(header));
}
/**
* Analyzes a web response to determine if it represents exceeding GitHub's rate limits
*
* <p>
* If the response does represent exceeded rate limiting, returns a {@link RequestLimitExceededException}
*
* <p>
* Intended for use in streamed responses, such as a Mono. If the exception should be thrown immediately, use
* {@link #checkRateLimit(Response)}
*
* <p>
* To use this check with other web libraries, see {@link #validateRateLimit(Object, Function, BiFunction)}
*
* @param response
* OkHttp3 representation of a web response
* @return A {@link RequestLimitExceededException} If the provided response represents exceeding GitHub's rate
* limiting, empty optional otherwise
* @since 1.0.3
*/
public static Optional<RequestLimitExceededException> validateRateLimit(Response response) {
Objects.requireNonNull(response);
return validateRateLimit(response, Response::code, (res, header) -> res.headers().values(header));
}
/**
* Analyzes a web response to determine if it represents exceeding GitHub's rate limits
*
* <p>
* If the response does represent exceeded rate limiting, throws a {@link RequestLimitExceededException}
*
* @param response
* Representation of a web response
* @param codeLookup
* Function which reads the HTTP status code from the provided response
* @param headerLookup
* Function which takes a response and header value as input, and produces all instances of that header
* from the response
* @param <T>
* Java type representing a web response
* @throws RequestLimitExceededException
* If the provided response represents exceeding GitHub's rate limiting
* @since 0.1.0
*/
public static <T> void checkRateLimit(T response, Function<T, Integer> codeLookup,
BiFunction<T, String, Collection<String>> headerLookup) throws RequestLimitExceededException {
Objects.requireNonNull(response);
Objects.requireNonNull(codeLookup);
Objects.requireNonNull(headerLookup);
Optional<RequestLimitExceededException> rateLimitViolation = validateRateLimit(response, codeLookup,
headerLookup);
if (rateLimitViolation.isPresent()) {
throw rateLimitViolation.get();
}
}
/**
* Analyzes a web response to determine if it represents exceeding GitHub's rate limits
*
* <p>
* If the response does represent exceeded rate limiting, returns a {@link RequestLimitExceededException}
*
* <p>
* Intended for use in streamed responses, such as a Mono. If the exception should be thrown immediately, use
* {@link #checkRateLimit(Object, Function, BiFunction)}
*
* @param response
* Representation of a web response
* @param codeLookup
* Function which reads the HTTP status code from the provided response
* @param headerLookup
* Function which takes a response and header value as input, and produces all instances of that header
* from the response
* @param <T>
* Java type representing a web response
* @return A {@link RequestLimitExceededException} If the provided response represents exceeding GitHub's rate
* limiting, empty optional otherwise
* @since 1.0.3
*/
public static <T> Optional<RequestLimitExceededException> validateRateLimit(T response,
Function<T, Integer> codeLookup, BiFunction<T, String, Collection<String>> headerLookup) {
Objects.requireNonNull(response);
Objects.requireNonNull(codeLookup);
Objects.requireNonNull(headerLookup);
String limit = Optional.ofNullable(headerLookup.apply(response, RATE_LIMIT_MAXIMUM_HEADER))
.orElse(Collections.emptyList())
.stream()
.findFirst()
.orElse("(unknown)");
String reset = Optional.ofNullable(headerLookup.apply(response, RATE_LIMIT_RESET_HEADER))
.orElse(Collections.emptyList())
.stream()
.findFirst()
.orElse("(unknown)");
Collection<String> remaining = Optional.ofNullable(headerLookup.apply(response, RATE_LIMIT_REMAINING_HEADER))
.orElse(Collections.emptyList());
boolean rateLimitExceeded = Objects.equals(codeLookup.apply(response), 403) && remaining.contains("0");
return rateLimitExceeded ? Optional.of(new RequestLimitExceededException(limit, reset)) : Optional.empty();
}
}
| 39.732919 | 118 | 0.673597 |
10f7f0f9b1ef59a456a69bbecc9725dc322c669e | 795 | package com.oath.cyclops.internal.stream.spliterators.push.grouping.sliding;
import cyclops.reactive.Spouts;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment;
import org.testng.annotations.Test;
@Test
public class SlidingTckPublisherTest extends PublisherVerification<Long>{
public SlidingTckPublisherTest(){
super(new TestEnvironment(300L));
}
@Override
public Publisher<Long> createPublisher(long elements) {
return Spouts.concat(Spouts.of(1l,2l,3l,4l,5l),Spouts.iterate(0l, i->i+1l).sliding(2,1).skip(4).map(l->l.getOrElse(0,-1l))).limit(elements);
}
@Override
public Publisher<Long> createFailedPublisher() {
return null; //not possible to forEachAsync to failed Stream
}
}
| 24.84375 | 142 | 0.78239 |
0fae3b99dadc680924b442781a55c9b32fdb3211 | 3,462 | package us.dot.its.jpo.ode.coder;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import us.dot.its.jpo.ode.context.AppContext;
import us.dot.its.jpo.ode.model.OdeBsmData;
import us.dot.its.jpo.ode.model.OdeBsmMetadata;
import us.dot.its.jpo.ode.model.OdeBsmPayload;
import us.dot.its.jpo.ode.plugin.j2735.builders.BsmBuilder;
import us.dot.its.jpo.ode.plugin.j2735.builders.BsmPart2ContentBuilder.BsmPart2ContentBuilderException;
import us.dot.its.jpo.ode.util.JsonUtils;
import us.dot.its.jpo.ode.util.XmlUtils;
import us.dot.its.jpo.ode.util.XmlUtils.XmlUtilsException;
public class OdeBsmDataCreatorHelper {
private OdeBsmDataCreatorHelper() {
}
// public static OdeBsmData createOdeBsmData(
// J2735Bsm rawBsm,
// IEEE1609p2Message message,
// BsmLogFileParser bsmFileParser) {
//
// OdeBsmPayload payload = new OdeBsmPayload(rawBsm);
//
// OdeLogMetadata metadata = new OdeBsmMetadata(payload);
// OdeLogMetadataCreatorHelper.updateLogMetadata(metadata, bsmFileParser);
//
// // If we have a valid message, override relevant data from the message
// if (message != null) {
// ZonedDateTime generatedAt;
// Date ieeeGenTime = message.getGenerationTime();
//
// if (ieeeGenTime != null) {
// generatedAt = DateTimeUtils.isoDateTime(ieeeGenTime);
// } else if (bsmFileParser != null) {
// generatedAt = bsmFileParser.getTimeParser().getGeneratedAt();
// } else {
// generatedAt = DateTimeUtils.nowZDT();
// }
// metadata.setRecordGeneratedAt(DateTimeUtils.isoDateTime(generatedAt));
// metadata.setRecordGeneratedBy(GeneratedBy.OBU);
// metadata.setSecurityResultCode(SecurityResultCode.success);
// }
//
// return new OdeBsmData(metadata, payload);
// }
//
// public static OdeBsmData createOdeBsmData(
// J2735Bsm rawBsm, String filename) {
// BsmLogFileParser bsmFileParser = new BsmLogFileParser();
// bsmFileParser.setFilename(filename).getTimeParser().setUtcTimeInSec(0).getSecResCodeParser().setSecurityResultCode(SecurityResultCode.unknown);
//
// return createOdeBsmData(rawBsm, null, bsmFileParser);
// }
public static OdeBsmData createOdeBsmData(String consumedData)
throws JsonProcessingException, IOException, XmlUtilsException, BsmPart2ContentBuilderException {
ObjectNode consumed = XmlUtils.toObjectNode(consumedData);
JsonNode metadataNode = consumed.findValue(AppContext.METADATA_STRING);
if (metadataNode instanceof ObjectNode) {
ObjectNode object = (ObjectNode) metadataNode;
object.remove(AppContext.ENCODINGS_STRING);
}
OdeBsmMetadata metadata = (OdeBsmMetadata) JsonUtils.fromJson(
metadataNode.toString(), OdeBsmMetadata.class);
/*
* ODE-755 and ODE-765 Starting with schemaVersion=5 receivedMessageDetails
* will be present in BSM metadata. None should be present in prior versions.
*/
if (metadata.getSchemaVersion() <= 4) {
metadata.setReceivedMessageDetails(null);
}
OdeBsmPayload payload = new OdeBsmPayload(
BsmBuilder.genericBsm(consumed.findValue("BasicSafetyMessage")));
return new OdeBsmData(metadata, payload );
}
}
| 39.340909 | 151 | 0.712016 |
eec35a787b8489ac0d9a8f50b744b6d6c8aefd7b | 3,741 | package com.ideal.flyerteacafes.ui.controls;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
import com.ideal.flyerteacafes.utils.LogFly;
/**
* Created by fly on 2016/12/5.
* 添加滚动监听
*/
public class MyHorizontalScrollView extends HorizontalScrollView {
public MyHorizontalScrollView(Context context,
AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public interface ScrollViewListener {
void onScrollChanged(ScrollType scrollType, int currentX);
}
private Handler mHandler = new Handler();
private ScrollViewListener scrollViewListener;
/**
* 滚动状态 IDLE 滚动停止 TOUCH_SCROLL 手指拖动滚动 FLING滚动
*
* @author DZC
* @version XHorizontalScrollViewgallery
* @Time 2014-12-7 上午11:06:52
*/
public enum ScrollType {
IDLE, TOUCH_SCROLL, FLING
}
;
/**
* 记录当前滚动的距离
*/
private int currentX = 0;
/**
* 当前滚动状态
*/
private ScrollType scrollType = ScrollType.IDLE;
/**
* 滚动监听间隔
*/
private int scrollDealy = 50;
/**
* 滚动监听runnable
*/
private Runnable scrollRunnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if (getScrollX() == currentX) {
currentX = getScrollX();
//滚动停止 取消监听线程
LogFly.d("", "停止滚动");
scrollType = ScrollType.IDLE;
if (scrollViewListener != null) {
scrollViewListener.onScrollChanged(scrollType, currentX);
}
mHandler.removeCallbacks(this);
return;
} else {
currentX = getScrollX();
//手指离开屏幕 view还在滚动的时候
LogFly.d("", "Fling。。。。。");
scrollType = ScrollType.FLING;
if (scrollViewListener != null) {
scrollViewListener.onScrollChanged(scrollType, currentX);
}
}
mHandler.postDelayed(this, scrollDealy);
}
};
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
float downX = 0;
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = ev.getX();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
int moveX = (int) Math.abs(downX - ev.getX());
if (moveX < 20) {
return false;
}
break;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_MOVE:
this.scrollType = ScrollType.TOUCH_SCROLL;
scrollViewListener.onScrollChanged(scrollType, currentX);
//手指在上面移动的时候 取消滚动监听线程
mHandler.removeCallbacks(scrollRunnable);
break;
case MotionEvent.ACTION_UP:
//手指移动的时候
mHandler.post(scrollRunnable);
break;
}
return super.onTouchEvent(ev);
}
/**
* 设置滚动监听
* 2014-12-7 下午3:59:51
*
* @param listener
* @return void
* @author DZC
* @TODO
*/
public void setOnScrollStateChangedListener(ScrollViewListener listener) {
this.scrollViewListener = listener;
}
}
| 25.979167 | 78 | 0.548784 |
2677c29784639ba97c53ef317ffab6484c60c47d | 599 | package edu.mit.mitmobile2.shuttles;
import android.app.Activity;
import edu.mit.mitmobile2.Module;
import edu.mit.mitmobile2.R;
public class ShuttlesModule extends Module {
@Override
public String getLongName() {
return "Shuttles";
}
@Override
public String getShortName() {
return "Shuttles";
}
@Override
public Class<? extends Activity> getModuleHomeActivity() {
return ShuttlesActivity.class;
}
@Override
public int getMenuIconResourceId() {
return R.drawable.menu_shuttles;
}
@Override
public int getHomeIconResourceId() {
return R.drawable.home_shuttles;
}
}
| 17.114286 | 59 | 0.749583 |
1f826ff4e909cd0488f203eb8daeb1830a9b4e47 | 914 | package com.github.cfogrady.dcom.digimon.dm20;
import com.github.cfogrady.dcom.serial.EventDrivenSerialPort;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.util.List;
@Slf4j
public class DM20RomWriterTest {
@Test
void testReader() {
String received = "s:0101 r:011A s:0101 r:0C05 s:800E r:382E s:008E r:171E s:05AE r:49FE s:01EE r:032E s:000E r:000E s:000E " +
"r:000E s:000E r:000E s:FF0E r:D0FE\r\n";
List<Integer> packetList = EventDrivenSerialPort.convertTextToReceivedPacket(received);
log.info("Packets: {}", packetList.size());
DM20RomReader romReader = new DM20RomReader();
DM20Rom rom = romReader.read(packetList);
DM20RomWriter writer = new DM20RomWriter();
String dcommROM = writer.getReceivingDCommRom(rom, false);
log.info("ROM: {}", dcommROM);
}
}
| 38.083333 | 136 | 0.66849 |
1c3db2152016b88f53d031d62d8b528aae16a2e2 | 6,385 | package org.protege.editor.owl.model.selection;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.protege.editor.owl.model.util.OWLAxiomInstance;
import org.semanticweb.owlapi.model.*;
import uk.ac.manchester.cs.owl.owlapi.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;
/**
* Matthew Horridge
* Stanford Center for Biomedical Informatics Research
* 5 Aug 16
*/
@RunWith(MockitoJUnitRunner.class)
public class OWLSelectionModelImpl_TestCase {
private OWLSelectionModelImpl selectionModel;
private final OWLClass cls = new OWLClassImpl(IRI.create("http://some.class"));
private final OWLObjectProperty objectProperty = new OWLObjectPropertyImpl(IRI.create("http://some.object.property"));
private final OWLDataProperty dataProperty = new OWLDataPropertyImpl(IRI.create("http://some.data.property"));
private final OWLAnnotationPropertyImpl annotationProperty = new OWLAnnotationPropertyImpl(IRI.create("http://some.anno.property"));
private final OWLNamedIndividual namedIndividual = new OWLNamedIndividualImpl(IRI.create("http://some.individual"));
private final OWLDatatype datatype = new OWLDatatypeImpl(IRI.create("http://some.datatype"));
@Mock
private OWLAxiomInstance axiomInstance;
@Before
public void setUp() {
selectionModel = new OWLSelectionModelImpl();
}
@Test
public void shouldGetLastSelectedClass() {
selectionModel.setSelectedEntity(cls);
OWLClass sel = selectionModel.getLastSelectedClass();
assertThat(sel, is(cls));
}
@Test
public void shouldNotGetLastSelectedClass() {
OWLClass cls = selectionModel.getLastSelectedClass();
assertThat(cls, is(nullValue()));
}
@Test
public void shouldGetLastSelectedObjectProperty() {
selectionModel.setSelectedEntity(objectProperty);
OWLObjectProperty sel = selectionModel.getLastSelectedObjectProperty();
assertThat(sel, is(objectProperty));
}
@Test
public void shouldNotGetLastSelectedObjectProperty() {
OWLObjectProperty p = selectionModel.getLastSelectedObjectProperty();
assertThat(p, is(nullValue()));
}
@Test
public void shouldGetLastSelectedDataProperty() {
selectionModel.setSelectedEntity(dataProperty);
OWLDataProperty sel = selectionModel.getLastSelectedDataProperty();
assertThat(sel, is(dataProperty));
}
@Test
public void shouldNotGetLastSelectedDataProperty() {
OWLDataProperty p = selectionModel.getLastSelectedDataProperty();
assertThat(p, is(nullValue()));
}
@Test
public void shouldGetLastSelectedAnnotationProperty() {
selectionModel.setSelectedEntity(annotationProperty);
OWLAnnotationProperty sel = selectionModel.getLastSelectedAnnotationProperty();
assertThat(sel, is(annotationProperty));
}
@Test
public void shouldNotGetLastSelectedAnnotationProperty() {
OWLAnnotationProperty p = selectionModel.getLastSelectedAnnotationProperty();
assertThat(p, is(nullValue()));
}
@Test
public void shouldGetLastSelectedNamedIndividual() {
selectionModel.setSelectedEntity(namedIndividual);
OWLNamedIndividual sel = selectionModel.getLastSelectedIndividual();
assertThat(sel, is(namedIndividual));
}
@Test
public void shouldNotGetLastSelectedNamedIndividual() {
OWLNamedIndividual i = selectionModel.getLastSelectedIndividual();
assertThat(i, is(nullValue()));
}
@Test
public void shouldGetLastSelectedDatatype() {
selectionModel.setSelectedEntity(datatype);
OWLDatatype sel = selectionModel.getLastSelectedDatatype();
assertThat(sel, is(datatype));
}
@Test
public void shouldNotGetLastSelectedDatatype() {
OWLDatatype d = selectionModel.getLastSelectedDatatype();
assertThat(d, is(nullValue()));
}
@Test
public void shouldGetLastSelectedAxiom() {
selectionModel.setSelectedAxiom(axiomInstance);
OWLAxiomInstance sel = selectionModel.getLastSelectedAxiomInstance();
assertThat(sel, is(axiomInstance));
}
@Test
public void shouldGetSelectedEntity() {
selectionModel.setSelectedEntity(cls);
assertThat(selectionModel.getSelectedEntity(), is(cls));
}
@Test
public void shouldNotGetSelectedEntity() {
assertThat(selectionModel.getSelectedEntity(), is(nullValue()));
}
@Test
public void shouldGetSelectedObject() {
selectionModel.setSelectedObject(cls);
assertThat(selectionModel.getSelectedObject(), is(cls));
}
@Test
public void shouldNotGetSelectedObject() {
assertThat(selectionModel.getSelectedObject(), is(nullValue()));
}
@Test
public void shouldNotThrowNullPointerExceptionOnSetSelectedEntityNull() {
try {
selectionModel.setSelectedEntity(null);
} catch (NullPointerException e) {
fail();
}
}
@Test
public void shouldNotifyListenerOnSelectionChange() throws Exception {
OWLSelectionModelListener listener = mock(OWLSelectionModelListener.class);
selectionModel.addListener(listener);
selectionModel.setSelectedEntity(cls);
verify(listener, times(1)).selectionChanged();
}
@Test
public void shouldNotNotifyListenerOnSelectionNoOp() throws Exception {
OWLSelectionModelListener listener = mock(OWLSelectionModelListener.class);
selectionModel.addListener(listener);
selectionModel.setSelectedEntity(cls);
selectionModel.setSelectedEntity(cls);
verify(listener, times(1)).selectionChanged();
}
@Test
public void shouldNotNotifyRemovedListener() throws Exception {
OWLSelectionModelListener listener = mock(OWLSelectionModelListener.class);
selectionModel.addListener(listener);
selectionModel.removeListener(listener);
selectionModel.setSelectedEntity(cls);
verify(listener, never()).selectionChanged();
}
}
| 32.576531 | 136 | 0.718246 |
952360bc96f81be8fdf57af17f17918d58c35ab4 | 332 | //
// Decompiled by Procyon v0.5.36
//
package org.mudebug.prapr.entry.report.compressedxml;
enum Tag
{
mutation,
sourceFile,
mutatedClass,
mutatedMethod,
methodDescription,
lineNumber,
mutator,
index,
coveringTests,
killingTests,
description,
suspValue,
block;
}
| 14.434783 | 53 | 0.629518 |
3e1bbc2e40cf4323206d1615f06ae4a712e086b8 | 2,051 | package adudecalledleo.tbsquared.data;
import java.util.Map;
import java.util.Optional;
public interface DataTracker extends Iterable<DataTracker.Entry<?>> {
static DataTracker empty() {
return EmptyDataTracker.INSTANCE;
}
static DataTrackerBuilder builder() {
return new DataTrackerBuilder();
}
static <T1> DataTracker of(DataKey<T1> k1, T1 v1) {
return new DefaultDataTracker(Map.of(k1, v1));
}
static <T1, T2> DataTracker of(DataKey<T1> k1, T1 v1,
DataKey<T2> k2, T2 v2) {
return new DefaultDataTracker(Map.of(k1, v1, k2, v2));
}
static <T1, T2, T3> DataTracker of(DataKey<T1> k1, T1 v1,
DataKey<T2> k2, T2 v2,
DataKey<T3> k3, T3 v3) {
return new DefaultDataTracker(Map.of(k1, v1, k2, v2, k3, v3));
}
static <T1, T2, T3, T4> DataTracker of(DataKey<T1> k1, T1 v1,
DataKey<T2> k2, T2 v2,
DataKey<T3> k3, T3 v3,
DataKey<T4> k4, T4 v4) {
return new DefaultDataTracker(Map.of(k1, v1, k2, v2, k3, v3, k4, v4));
}
static DataTracker copyOf(DataTracker tracker) {
if (tracker.size() == 0) {
return empty();
} else if (tracker instanceof DefaultDataTracker) {
return tracker;
}
return builder().setAll(tracker).build();
}
record Entry<T>(DataKey<T> key, T value) { }
int size();
<T> Optional<T> get(DataKey<T> key);
boolean containsKey(DataKey<?> key);
default boolean isEmpty() {
return size() == 0;
}
/**
* Compares the specified object with this data tracker for equality.<p>
*
* This uses a similar contract to {@link java.util.Collection#equals(Object)}: data trackers are considered equal
* if they have the same size and the same contents.
*/
boolean equals(Object o);
}
| 32.046875 | 118 | 0.551438 |
15f23306e6f585b7b246ba9d258e2a81fbe12df6 | 545 | package com.willlee.leetcode.problems1201_1300;
public class Leetcode1232 {
public boolean checkStraightLine(int[][] coordinates) {
int x1 = coordinates[1][0] - coordinates[0][0];
int y1 = coordinates[1][1] - coordinates[0][1];
for (int i = 2; i < coordinates.length; i++) {
int x2 = coordinates[i][0] - coordinates[0][0];
int y2 = coordinates[i][1] - coordinates[0][1];
if (x1 * y2 != x2 * y1) {
return false;
}
}
return true;
}
}
| 32.058824 | 59 | 0.533945 |
9ed1d08bc1aff63b3a4631dae347e083725f85dd | 8,425 | package org.lbd.process;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.rdfcontext.signing.RDFC14Ner;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import io.ipfs.api.IPFS;
import io.ipfs.api.MerkleNode;
import io.ipfs.api.NamedStreamable;
import io.ipfs.multihash.Multihash;
public class IPFSPingClientProcess implements Runnable {
private final Supplier<Object> sub;
final String channel_name;
private final Property merkle_node;
private final IPFS ipfs;
private final Model guid_directory_model = ModelFactory.createDefaultModel();
private final Model temp_model = ModelFactory.createDefaultModel();
private final String guid_uri = "http://ipfs/bim/ad8339ce-4378-4e54-b917-ed305724ca9b";
private String directory = "QmR3K1MmYJVS5Qojb2DzUQqp7PPDBcW9juUGCMU9BRHZkz";
private long start_time;
private long sent_time;
public IPFSPingClientProcess(IPFS ipfs, String channel_name) throws IOException {
this.merkle_node = guid_directory_model.createProperty("http://ipfs/MerkleNode_Hash");
this.guid_directory_model.setNsPrefix("ipfsbim", "http://ipfs/bim/");
this.guid_directory_model.setNsPrefix("ipfs", "http://ipfs/");
this.guid_directory_model.setNsPrefix("ifcowl", "http://www.buildingsmart-tech.org/ifcOWL/IFC2X3_TC1#");
this.temp_model.setNsPrefix("ipfsbim", "http://ipfs/bim/");
this.temp_model.setNsPrefix("ipfs", "http://ipfs/");
this.temp_model.setNsPrefix("ifcowl", "http://www.buildingsmart-tech.org/ifcOWL/IFC2X3_TC1#");
this.ipfs = new IPFS("/ip4/127.0.0.1/tcp/5001");
this.sub = ipfs.pubsub.sub(channel_name);
this.channel_name = channel_name;
}
public void run() {
System.out.println("Server listening process starts. Channel:" + this.channel_name);
initialMessage();
while (true) {
LinkedHashMap lhm = (LinkedHashMap) sub.get();
Object encoded_data = lhm.get("data");
if (encoded_data != null) {
byte[] decoded = Base64.getDecoder().decode(encoded_data.toString());
String msg = new String(decoded);
if (msg.startsWith("answer_")) {
System.out.println("Got answer in : " + (System.currentTimeMillis() - this.sent_time));
long start = System.currentTimeMillis();
String[] splitted = msg.split("_");
if (splitted.length > 1) {
System.out.println("Reading..." + splitted[1]);
readInNode(splitted[1]);
System.out.println("Read andwer in : " + (System.currentTimeMillis() - start));
temp_model.write(System.out, "TTL");
}
}
}
}
}
private MerkleNode createProjectMerkleNode(String project_version, Model m) {
List<MerkleNode> node = null;
try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
m.write(buf, "TTL");
NamedStreamable.ByteArrayWrapper file = new NamedStreamable.ByteArrayWrapper(project_version,
buf.toString("UTF-8").getBytes());
node = ipfs.add(file);
} catch (Exception e) {
e.printStackTrace();
}
if (node == null | node.size() == 0)
return null;
return node.get(0);
}
private void initialMessage() {
this.start_time = System.currentTimeMillis();
readInGuidTable(directory);
Resource guid_resource = this.guid_directory_model.getResource(this.guid_uri);
System.out.println("Read in directory: " + (System.currentTimeMillis() - start_time));
long start = System.currentTimeMillis();
guid_resource.listProperties(this.merkle_node).forEachRemaining(x -> readInNode(x.getObject().toString()));
System.out.println("Node was read in: " + (System.currentTimeMillis() - start));
Resource subject = temp_model.createResource("http://ipfs/task");
Property property = temp_model.createProperty("http://ipfs/timestamp");
Literal time_literal = guid_directory_model.createLiteral("" + System.currentTimeMillis());
temp_model.add(temp_model.createStatement(subject, property, time_literal));
start = System.currentTimeMillis();
RDFC14Ner r1 = new RDFC14Ner(temp_model);
// Converts C14 into N3
String output_format = r1.getCanonicalString().replaceAll("\\[", "").replaceAll("\\]", " \n").replaceAll(",",
" \n");
Model m = ModelFactory.createDefaultModel();
String[] model_splitted = output_format.split("\n");
StringBuilder sp = new StringBuilder();
for (String s : model_splitted) {
List<String> list = new ArrayList<String>();
try {
Matcher mx = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(s.trim());
while (mx.find())
list.add(mx.group(1));
if(list.size()==2)
list.add("\"\"");
String ls = list.get(0);
if (ls.matches("^(http|https|ftp)://.*$"))
ls = "<" + ls + ">";
String lp = list.get(1);
if (lp.matches("^(http|https|ftp)://.*$"))
lp = "<" + lp + ">";
String lo = list.get(2);
if (lo.matches("^(http|https|ftp)://.*$"))
lo = "<" + lo + ">";
sp.append(ls + " " + lp + " " + lo + " .\n");
}
catch (Exception e) {
System.err.println("Bad: pattern: "+s.trim());
System.err.println("list was"+list);
e.printStackTrace();
System.exit(1);
}
}
System.out.println("Convert to C14:N3: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
NamedStreamable.ByteArrayWrapper file = new NamedStreamable.ByteArrayWrapper("checked",
sp.toString().getBytes());
try {
List<MerkleNode> node = ipfs.add(file);
if (node.size() > 0) {
System.out.println("Node published: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
Literal hash_literal = guid_directory_model.createLiteral(node.get(0).hash.toBase58());
guid_resource.addLiteral(this.merkle_node, hash_literal);
MerkleNode dir = createProjectMerkleNode("v1.1", this.guid_directory_model);
System.out.println("Directory node generated and published: " + (System.currentTimeMillis() - start));
// event.respondWith("answer_"+node.get(0).hash.toBase58());
publish("IFCBIM", "ipfs_" + dir.hash.toBase58() + "_" + node.get(0).hash.toBase58());
this.sent_time = System.currentTimeMillis();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String publish(String topic, String content) {
System.out.println("Client publish topic: " + topic + " content: " + content);
String urlToRead = "http://127.0.0.1:5001/api/v0/pubsub/pub?arg=" + URLEncoder.encode(topic) + "&arg="
+ URLEncoder.encode(content);
StringBuilder result = new StringBuilder();
URL url;
try {
url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
private void readInGuidTable(String key) {
Multihash filePointer = Multihash.fromBase58(key);
try {
String table = new String(ipfs.cat(filePointer));
guid_directory_model.read(new ByteArrayInputStream(table.getBytes()), null, "TTL");
//System.out.println("dir");
//guid_directory_model.write(System.out, "TTL");
System.out.println("-------------------------------");
} catch (IOException e) {
e.printStackTrace();
}
}
private void readInNode(String key) {
Multihash filePointer = Multihash.fromBase58(key);
try {
temp_model.removeAll();
String tmp = new String(ipfs.cat(filePointer));
System.out.println("Model: " + tmp + "\n...");
ByteArrayInputStream bi = new ByteArrayInputStream(tmp.getBytes());
System.out.println("Model read....");
temp_model.read(bi, null, "TTL");
System.out.println("Model read ends");
temp_model.write(System.out, "TTL");
System.out.println("----------------------------------------");
} catch (IOException e) {
e.printStackTrace();
}
}
} | 35.699153 | 111 | 0.691395 |
26c42c185e43e8d28a2fb8f52dfe7c9af1fa5913 | 5,052 | package com.garrocho.cgplayer.mp3player;
import java.util.List;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import com.garrocho.MainActivity;
public class Player extends Service implements OnCompletionListener {
private MediaPlayer mediaPlayer;
//private Playlist playlistManager;
//private ArrayList<HashMap<String, String>> playlist;;
private List<Musica> playlist;
//private String path;
private int musicIndex;
public boolean playing;
public boolean paused;
private boolean changeMusic;
public Player() { }
public class PlayerBinder extends Binder implements PlayerInterface {
@Override
public String getMusicName() {
return playlist.get(musicIndex).getTitulo();
}
public boolean isPlay() {
return playing;
}
public boolean isPaused() {
return paused;
}
@Override
public int getDuration() {
return mediaPlayer.getDuration();
}
@Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
@Override
public void play() {
try {
if(!playing || changeMusic) {
mediaPlayer.reset();
mediaPlayer.setDataSource(playlist.get(musicIndex).getPath());
mediaPlayer.prepare();
}
playing = true;
paused = false;
changeMusic = false;
MainActivity.seekBar.setMax(mediaPlayer.getDuration());
MainActivity.musicaAtual.setText(playlist.get(musicIndex).getTitulo());
if(mediaPlayer != null) {
new Thread(new Runnable() {
@Override
public void run() {
while(mediaPlayer.isPlaying()) {
MainActivity.seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
}
}).start();
}
mediaPlayer.start();
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public void pause() {
mediaPlayer.pause();
paused = true;
}
@Override
public void stop() {
mediaPlayer.stop();
MainActivity.seekBar.setProgress(0);
playing = false;
}
@Override
public void next() {
if(musicIndex < playlist.size()-1) {
musicIndex += 1;
} else {
musicIndex = 0;
}
changeMusic = true;
this.play();
}
@Override
public void previous() {
if(musicIndex > 0) {
musicIndex -= 1;
} else {
musicIndex = playlist.size() - 1;
}
changeMusic = true;
this.play();
}
public void playMusic(int index){
if(index < playlist.size()){
musicIndex = index;
}
changeMusic = true;
this.play();
}
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//this.path = intent.getExtras().getString("path");
this.playlist = intent.getParcelableArrayListExtra("lista_musicas");
if(this.playlist != null) {
MainActivity.seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(MainActivity.seekBar.getProgress());
mediaPlayer.start();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
//this.playlistManager = new Playlist(this.path);
//this.playlist = this.playlistManager.getPlaylist();
this.musicIndex = 0;
this.mediaPlayer = new MediaPlayer();
this.mediaPlayer.setOnCompletionListener(this);
try {
this.mediaPlayer.setDataSource(this.playlist.get(musicIndex).getPath());
this.mediaPlayer.prepare();
//this.playing = true;
//this.play();
} catch(Exception e) {
e.printStackTrace();
}
}
return super.onStartCommand(intent, flags, startId);
}
public void play() {
try {
if(this.changeMusic) {
this.mediaPlayer.reset();
this.mediaPlayer.setDataSource(this.playlist.get(this.musicIndex).getPath());
this.mediaPlayer.prepare();
}
MainActivity.seekBar.setMax(mediaPlayer.getDuration());
if(this.mediaPlayer != null) {
new Thread(new Runnable() {
@Override
public void run() {
while(mediaPlayer.isPlaying()) {
MainActivity.seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
}
}).start();
this.mediaPlayer.start();
}
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public IBinder onBind(Intent intent) {
return new PlayerBinder();
}
@Override
public void onCompletion(MediaPlayer mp) {
if(this.musicIndex < this.playlist.size()-1) {
this.musicIndex += 1;
} else {
this.musicIndex = 0;
}
this.changeMusic = true;
this.play();
}
}
| 22.255507 | 82 | 0.659541 |
7d810206b9bac1308acd5bd558b643bcdc18b7de | 676 | // Copyright © 2019-2020 Andy Goryachev <andy@goryachev.com>
package goryachev.fxeditor;
/**
* Load Status.
*/
public class LoadStatus
{
public static final LoadStatus UNKNOWN = new LoadStatus(0.0, true, false);
private final double progress;
private final boolean loading;
private final boolean valid;
public LoadStatus(double progress, boolean loading, boolean valid)
{
this.progress = progress;
this.loading = loading;
this.valid = valid;
}
public double getProgress()
{
return progress;
}
public boolean isLoading()
{
return loading;
}
public boolean isValid()
{
return valid;
}
}
| 16.095238 | 76 | 0.659763 |
d8f37ce6ae1535e1b0ba3947f4510a6386569cc4 | 2,497 | /*-
* ========================LICENSE_START=================================
* TeamApps Application API
* ---
* Copyright (C) 2020 - 2021 TeamApps.org
* ---
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package org.teamapps.application.ux.org;
import edu.emory.mathcs.backport.java.util.Collections;
import org.teamapps.application.api.application.AbstractApplicationView;
import org.teamapps.application.api.application.ApplicationInstanceData;
import org.teamapps.model.controlcenter.OrganizationUnitView;
import org.teamapps.ux.component.template.BaseTemplate;
import org.teamapps.ux.component.template.Template;
import org.teamapps.ux.component.tree.Tree;
import org.teamapps.ux.component.tree.TreeNodeInfoImpl;
import org.teamapps.ux.model.ListTreeModel;
import java.util.*;
public class OrganizationTree extends AbstractApplicationView {
private Tree<OrganizationUnitView> tree;
private ListTreeModel<OrganizationUnitView> treeModel;
private Set<OrganizationUnitView> organizationUnits;
public OrganizationTree(ApplicationInstanceData applicationInstanceData) {
super(applicationInstanceData);
treeModel = new ListTreeModel<>(Collections.emptyList());
tree = new Tree<>(treeModel);
treeModel.setTreeNodeInfoFunction(unit -> new TreeNodeInfoImpl<>(unit.getParent() != null && organizationUnits.contains(unit.getParent()) ? unit.getParent() : null, false));
tree.setPropertyProvider(OrganizationViewUtils.creatOrganizationUnitViewPropertyProvider(getApplicationInstanceData()));
tree.setEntryTemplate(BaseTemplate.LIST_ITEM_SMALL_ICON_SINGLE_LINE);
}
public void setTemplate(Template template) {
tree.setEntryTemplate(template);
}
public void setOrganizationUnits(Collection<OrganizationUnitView> units) {
organizationUnits = new HashSet<>(units);
treeModel.setRecords(new ArrayList<>(units));
}
public Tree<OrganizationUnitView> getTree() {
return tree;
}
}
| 40.274194 | 175 | 0.754906 |
0462949ba169096e23433130bfe7d7c11db585cf | 2,376 | /*
* Copyright Beijing 58 Information Technology Co.,Ltd.
*
* 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.bj58.spat.gaea.server.util.tools;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class UDPClient {
private String encode;
private DatagramSocket sock = null;
private InetSocketAddress addr = null;
/**
* 获取UDPClient实例
* @param ip udp服务ip
* @param port udp服务端口
* @param encode 编码
* @return
* @throws SocketException
*/
public static UDPClient getInstrance(String ip, int port, String encode) throws SocketException {
UDPClient client = new UDPClient();
client.encode = encode;
client.sock = new DatagramSocket();
client.addr = new InetSocketAddress(ip, port);
return client;
}
private UDPClient() {
}
public void close() {
sock.close();
}
/**
* 发送udp消息
* @param msg 消息
* @param encode 编码
* @throws Exception
*/
public void send(String msg, String encode) throws Exception {
byte[] buf = msg.getBytes(encode);
send(buf);
}
/**
* 发送udp消息
* @param msg 消息
* @throws IOException
*/
public void send(String msg) throws IOException {
byte[] buf = msg.getBytes(encode);
send(buf);
}
/**
* 发送udp消息
* @param buf 消息
* @throws IOException
*/
public void send(byte[] buf) throws IOException {
DatagramPacket dp = new DatagramPacket(buf, buf.length, addr);
sock.send(dp);
}
} | 25.826087 | 99 | 0.677189 |
761048f194f29e5dd22d34ca4ea7d0ec67140a69 | 3,114 | package com.ruoyi.equipment.domain;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
public class DepFeedback extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 设备名称 */
@Excel(name = "意见填写人")
private String userId;
/** 设备名称 */
@Excel(name = "意见填写人")
private String userName;
/** 设备名称 */
@Excel(name = "填写人部门")
private String twoDep;
/** 设备名称 */
@Excel(name = "意见")
private String opinion;
/** 设备名称 */
@Excel(name = "意见填写时间")
private String opinionTime;
/** 设备名称 */
@Excel(name = "意见反馈人")
private String personId;
/** 设备名称 */
@Excel(name = "意见反馈人")
private String personName;
/** 设备名称 */
@Excel(name = "意见反馈")
private String feedback;
/** 设备名称 */
@Excel(name = "反馈时间")
private String feedbackTime;
/** 设备名称 */
@Excel(name = "编号")
private String seqNo;
public String getSeqNo() {
return seqNo;
}
public void setSeqNo(String seqNo) {
this.seqNo = seqNo;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTwoDep() {
return twoDep;
}
public void setTwoDep(String twoDep) {
this.twoDep = twoDep;
}
public String getOpinion() {
return opinion;
}
public void setOpinion(String opinion) {
this.opinion = opinion;
}
public String getOpinionTime() {
return opinionTime;
}
public void setOpinionTime(String opinionTime) {
this.opinionTime = opinionTime;
}
public String getPersonId() {
return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
public String getFeedback() {
return feedback;
}
public void setFeedback(String feedback) {
this.feedback = feedback;
}
public String getFeedbackTime() {
return feedbackTime;
}
public void setFeedbackTime(String feedbackTime) {
this.feedbackTime = feedbackTime;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
@Override
public String toString() {
return "DepFeedback{" +
"userId='" + userId + '\'' +
", userName='" + userName + '\'' +
", twoDep='" + twoDep + '\'' +
", opinion='" + opinion + '\'' +
", opinionTime='" + opinionTime + '\'' +
", personId='" + personId + '\'' +
", personName='" + personName + '\'' +
", feedback='" + feedback + '\'' +
", feedbackTime='" + feedbackTime + '\'' +
", seqNo='" + seqNo + '\'' +
'}';
}
}
| 21.328767 | 58 | 0.546243 |
88744c24a5f84e44433cceae09c92768868aa30e | 3,014 | /*
* 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.livy.rsc.rpc;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An implementation of ChannelInboundHandler that dispatches incoming messages to an instance
* method based on the method signature.
* <p>
* A handler's signature must be of the form:
* <p>
* <blockquote><tt>protected void handle(ChannelHandlerContext, MessageType)</tt></blockquote>
* <p>
* Where "MessageType" must match exactly the type of the message to handle. Polymorphism is not
* supported. Handlers can return a value, which becomes the RPC reply; if a null is returned, then
* a reply is still sent, with an empty payload.
*/
public abstract class RpcDispatcher extends SimpleChannelInboundHandler<Object> {
private static final Logger LOG = LoggerFactory.getLogger(RpcDispatcher.class);
private final Map<Channel, Rpc> channelRpc = new ConcurrentHashMap<>();
/**
* Override this to add a name to the dispatcher, for debugging purposes.
* @return The name of this dispatcher.
*/
protected String name() {
return getClass().getSimpleName();
}
public void registerRpc(Channel channel, Rpc rpc) {
channelRpc.put(channel, rpc);
}
public void unregisterRpc(Channel channel) {
channelRpc.remove(channel);
}
private Rpc getRpc(ChannelHandlerContext ctx) {
Channel channel = ctx.channel();
if (!channelRpc.containsKey(channel)) {
throw new IllegalArgumentException("not existed channel:" + channel);
}
return channelRpc.get(channel);
}
@Override
protected final void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
getRpc(ctx).handleMsg(ctx, msg, getClass(), this);
}
@Override
public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
getRpc(ctx).handleChannelException(ctx, cause);
}
@Override
public final void channelInactive(ChannelHandlerContext ctx) throws Exception {
getRpc(ctx).handleChannelInactive();
super.channelInactive(ctx);
}
}
| 34.25 | 99 | 0.748507 |
b002f4132dbdfdec47dacd92b8c594390c3aab36 | 1,364 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInspection;
import com.intellij.JavaTestUtil;
import com.intellij.codeInspection.equalsAndHashcode.EqualsAndHashcode;
import com.intellij.testFramework.JavaInspectionTestCase;
public class EqualsAndHashCodeTest extends JavaInspectionTestCase {
private EqualsAndHashcode myTool = new EqualsAndHashcode();
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath() + "/inspection";
}
private void doTest() {
doTest("equalsAndHashcode/" + getTestName(true), myTool);
}
@Override
protected void tearDown() throws Exception {
myTool = null;
super.tearDown();
}
public void testInnerClass() {
doTest();
}
public void testHierarchy() {
doTest();
}
}
| 26.745098 | 75 | 0.740469 |
d8d7c69a1f9ca9ec25479e0ca9e9fffbf1df5895 | 687 | package com.xp.ChainOfResponsibility;
import com.xp.ChainOfResponsibility.model.Request;
import com.xp.ChainOfResponsibility.model.RequestType;
/**
* Created by xp-zhao on 2018/12/27.
*/
public class Client
{
public static void main(String[] args) {
Handler createHandler = new CreateHandler(null);
Handler deleteHandler = new DeleteHandler(createHandler);
Handler updateHandler = new UpdateHandler(deleteHandler);
Handler queryHandler = new QueryHandler(updateHandler);
Request request = new Request(RequestType.CREATE , "create request");
// Request request = new Request(RequestType.ERROR , "error request");
System.out.println(queryHandler.handle(request));
}
}
| 29.869565 | 71 | 0.770015 |
e7386b5268c622bc5c54247f7ef6b4d4d41b7427 | 578 | package io.seldon.clustermanager.k8s;
import org.junit.Test;
import org.junit.Assert;
public class SeldonDeploymentUtilsTest {
@Test
public void getVersionTest()
{
String version = SeldonDeploymentUtils.getVersionFromApiVersion("machinelearning.seldon.io/v1alpha2");
Assert.assertEquals("v1alpha2", version);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void getVersionTestFailed()
{
String version = SeldonDeploymentUtils.getVersionFromApiVersion("machinelearning.seldon.io.v1alpha2");
Assert.assertEquals("v1alpha2", version);
}
}
| 23.12 | 104 | 0.787197 |
1947fb0359da2eaca48cd18efc52ded82dbc51d9 | 847 | package org.symphonyoss.symphony.messageml.markdown.nodes.form;
public interface PlaceholderLabelTooltipNode {
default String generateMarkdownPlaceholderLabelAndTooltip(String placeholder, String label, String tooltip) {
StringBuilder markdownRepresentation = new StringBuilder();
if(placeholder != null || label != null || tooltip != null) {
markdownRepresentation.append(":");
}
if(placeholder != null) {
markdownRepresentation.append("[")
.append(placeholder)
.append("]");
}
if(label != null) {
markdownRepresentation.append("[")
.append(label)
.append("]");
}
if(tooltip != null) {
markdownRepresentation.append("[")
.append(tooltip)
.append("]");
}
return markdownRepresentation.toString();
}
}
| 26.46875 | 111 | 0.624557 |
043fb34750dd6bda84f8e0cb4ae56a98075fa7e1 | 14,773 | /* Written in 2016 by David Blackman and Sebastiano Vigna (vigna@acm.org)
To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
See <http://creativecommons.org/publicdomain/zero/1.0/>. */
package squidpony.squidmath;
import squidpony.StringKit;
import java.io.Serializable;
/**
* A Linear Feedback Shift Register that may be used like a StatefulRandomness but is not truly random. This has a
* period of (2 to the 64) minus 1, and is based on Wikipedia's code for a Galois LFSR but uses data from
* http://web.archive.org/web/20161007061934/http://courses.cse.tamu.edu/csce680/walker/lfsr_table.pdf .
* It is important to note that an LFSR will produce each number from 1 until its maximum exactly once before repeating,
* so this may be useful as a way of generating test data in an unpredictable order.
* @author Tommy Ettinger
*/
public class LFSR implements StatefulRandomness, Serializable {
private static final long DOUBLE_MASK = (1L << 53) - 1;
private static final double NORM_53 = 1. / (1L << 53);
private static final long FLOAT_MASK = (1L << 24) - 1;
private static final double NORM_24 = 1. / (1L << 24);
private static final long serialVersionUID = -2373549048478690398L;
public long state;
/**
* Creates a new generator seeded using Math.random.
*/
public LFSR() {
this((long) (Math.random() * Long.MAX_VALUE));
}
public LFSR(final long seed) {
setState(seed);
}
public LFSR(final CharSequence seed)
{
this(CrossHash.hash64(seed));
}
@Override
public final int next(int bits) {
return (int)nextLong() >>> (32 - bits);
}
@Override
public final long nextLong() {
return state = (state >>> 1 ^ (-(state & 1L) & 0xD800000000000000L));
}
/**
* Produces a copy of this RandomnessSource that, if next() and/or nextLong() are called on this object and the
* copy, both will generate the same sequence of random numbers from the point copy() was called. This just needs to
* copy the state so it isn't shared, usually, and produce a new value with the same exact state.
*
* @return a copy of this RandomnessSource
*/
@Override
public LFSR copy() {
return new LFSR(state);
}
/**
* Can return any int, positive or negative, of any size permissible in a 32-bit signed integer.
* @return any int, all 32 bits are random
*/
public int nextInt() {
return (int)nextLong();
}
/**
* Exclusive on the outer bound; the inner bound is 0.
* The bound should not be negative; use {@link IRNG#nextSignedInt(int)} if you need a negative outer bound.
*
* @param bound the outer exclusive bound; should be positive
* @return a random long between 0 (inclusive) and bound (exclusive)
*/
public int nextInt( final int bound ) {
return (int)((bound * (nextLong() & 0x7FFFFFFFL)) >> 31);
}
/**
* Inclusive lower, exclusive upper.
* @param inner the inner bound, inclusive, can be positive or negative
* @param outer the outer bound, exclusive, should be positive, should be greater than inner
* @return a random int that may be equal to inner and will otherwise be between inner and outer
*/
public int nextInt(final int inner, final int outer) {
return inner + nextInt(outer - inner);
}
/**
* Exclusive on the outer bound; the inner bound is 0. The bound may be negative, which will produce a non-positive
* result.
* @param bound the outer exclusive bound; may be positive or negative
* @return a random long between 0 (inclusive) and bound (exclusive)
*/
public long nextLong(long bound) {
long rand = nextLong();
final long randLow = rand & 0xFFFFFFFFL;
final long boundLow = bound & 0xFFFFFFFFL;
rand >>>= 32;
bound >>= 32;
final long t = rand * boundLow + (randLow * boundLow >>> 32);
return rand * bound + (t >> 32) + (randLow * bound + (t & 0xFFFFFFFFL) >> 32);
}
/**
* Inclusive inner, exclusive outer; both inner and outer can be positive or negative.
* @param inner the inner bound, inclusive, can be positive or negative
* @param outer the outer bound, exclusive, can be positive or negative and may be greater than or less than inner
* @return a random long that may be equal to inner and will otherwise be between inner and outer
*/
public long nextLong(final long inner, final long outer) {
return inner + nextLong(outer - inner);
}
public double nextDouble() {
return (nextLong() & DOUBLE_MASK) * NORM_53;
}
public float nextFloat() {
return (float) ((nextLong() & FLOAT_MASK) * NORM_24);
}
public boolean nextBoolean() {
return nextLong() < 0L;
}
public void nextBytes(final byte[] bytes) {
int i = bytes.length, n;
while (i != 0) {
n = Math.min(i, 8);
for (long bits = nextLong(); n-- != 0; bits >>>= 8) {
bytes[--i] = (byte) bits;
}
}
}
/**
* Get the current internal state of the StatefulRandomness as a long.
*
* @return the current internal state of this object.
*/
@Override
public long getState() {
return state;
}
/**
* Sets the seed of this generator using one long, running that through LightRNG's algorithm twice to get the state.
* @param seed the number to use as the seed
*/
@Override
public void setState(final long seed) {
if(seed == 0)
state = -1L;
else
state = seed;
}
@Override
public String toString() {
return "LFSR with state 0x" + StringKit.hex(state) + 'L';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LFSR lfsr = (LFSR) o;
return (state == lfsr.state);
}
@Override
public int hashCode() {
return (int) (state ^ (state >>> 32));
}
/**
* Gets the next number that an LFSR would produce using {@link #nextLong()} if its state was {@code state}.
* Does not allow state to be 0. Strongly consider using the result of this and assigning it to state if you expect
* to call this again, such as with {@code (state = LFSR.determine(state))}, which will ensure the long-term
* properties of an LFSR hold up (such as having a period of ((2 to the 64) minus 1), or the guarantee that every
* number from 1 to ((2 to the 64) minus 1), inclusive on both, will be generated once per period).
* @param state any long other than 0
* @return the next long that a 64-bit LFSR would produce with the given state
*/
public static long determine(final long state)
{
return state >>> 1 ^ (-(state & 1L) & 0xD800000000000000L);
}
/**
* Gets the next number from 1 to 255 that a different kind of LFSR would produce if its state was {@code state}.
* Does not allow state to be 0. If given all byte values except 0 as arguments, will produce all ints 1-255.
* Strongly consider using the result of this and assigning it to state if you expect to call this again, such as
* with {@code (state = LFSR.determineByte(state))}, which will ensure the long-term properties of an LFSR hold up
* (such as having a period of 255, or the guarantee that every number from 1 to 255, inclusive on both, will be
* generated once per period).
* @param state any byte other than 0
* @return the next int between 1 and 255 that an 8-bit LFSR would produce with the given state
*/
public static int determineByte(final byte state)
{
return state >>> 1 ^ (-(state & 1) & 0xB8);
}
/**
* Gets the next number that a different kind of 32-bit LFSR would produce if its state was {@code state}.
* Does not allow state to be 0. If given all int values except 0 as arguments, will produce all ints except 0.
* Strongly consider using the result of this and assigning it to state if you expect to call this again, such as
* with {@code (state = LFSR.determineInt(state))}, which will ensure the long-term properties of an LFSR hold up
* (such as having a period of ((2 to the 32) minus 1), or the guarantee that every number from 1 to ((2 to the 32)
* minus 1), inclusive on both, will be generated once per period).
* @param state any long other than 0
* @return the next int that a 32-bit LFSR would produce with the given state
*/
public static int determineInt(final int state)
{
return state >>> 1 ^ (-(state & 1) & 0xA3000000);
}
/**
* Gets the next positive long that a different kind of 63-bit LFSR would produce if its state was {@code state}.
* Does not allow state to be 0 or negative. If given all positive long values (not including 0) as arguments, will
* produce all longs greater than 0. Strongly consider using the result of this and assigning it to state if you
* expect to call this again, such as with {@code (state = LFSR.determinePositiveLong(state))}, which will ensure
* the long-term properties of an LFSR hold up (such as having a period of ((2 to the 63) minus 1), or the guarantee
* that every number from 1 to ((2 to the 63) minus 1), inclusive on both, will be generated once per period).
* @param state any positive long, not including 0
* @return the next int that a 63-bit LFSR would produce with the given state
*/
public static long determinePositiveLong(final long state)
{
return state >>> 1 ^ (-(state & 1L) & 0x6000000000000000L);
}
/**
* Gets the next positive int that a different kind of 31-bit LFSR would produce if its state was {@code state}.
* Does not allow state to be 0 or negative. If given all positive int values (not including 0) as arguments, will
* produce all ints greater than 0. Strongly consider using the result of this and assigning it to state if you
* expect to call this again, such as with {@code (state = LFSR.determinePositiveInt(state))}, which will ensure the
* long-term properties of an LFSR hold up (such as having a period of ((2 to the 31) minus 1), or the guarantee
* that every number from 1 to ((2 to the 31) minus 1), inclusive on both, will be generated once per period).
* <br>
* A potential benefit of using this particular LFSR type is that the period is a prime number, 2147483647; this can
* sometimes be relevant if you simultaneously get pseudo-random numbers from sources of randomness with different
* periods that are "relatively co-prime" (that is, they share no common factors other than 1). This case lengthens
* the total period of the combined generators significantly, generally multiplying the periods together to get the
* combined period, as opposed to other cases that may simply add them together.
* @param state any positive int, not including 0
* @return the next int that a 31-bit LFSR would produce with the given state
*/
public static int determinePositiveInt(final int state)
{
return state >>> 1 ^ (-(state & 1) & 0x48000000);
}
/**
* Gets the next int that a different kind of LFSR would produce if its state was {@code state}.
* Does not allow state to be {@link Integer#MIN_VALUE}, nor will this produce a result of {@link Integer#MIN_VALUE}
* (as long as {@link Integer#MIN_VALUE} was not the input). If given all int values except
* {@link Integer#MIN_VALUE} as arguments, will produce all ints in the range {@code [-2147483647,2147483647]},
* including 0 but not -2147483648 (the minimum int). Strongly consider using the result of this and assigning it to
* state if you expect to call this again, such as with {@code (state = LFSR.determineIntSymmetrical(state))}, which
* will ensure the long-term properties of an LFSR hold up (such as having a period of ((2 to the 32) minus 1), or
* the guarantee that every int except {@link Integer#MIN_VALUE} will be generated once per period).
* <br>
* This is called Symmetrical because it produces the same amount of positive and negative numbers, instead of the
* normal generation of more negative ones (due to how ints are represented, the min value is always further from 0
* than the max value for any signed integer type).
* @param state any int other than -2147483648 (0x80000000), which is {@link Integer#MIN_VALUE}; can produce 0
* @return the next int other than -2147483648 that an LFSR would produce with the given state
*/
public static int determineIntSymmetrical(final int state)
{
return ((state ^ 0x80000000) >>> 1 ^ (-(state & 1) & 0xA3000000));
}
/**
* Gets the next number that an LFSR would produce using {@link #nextInt(int)} if its state was {@code state} and
* {@code bound} was passed to nextInt(). Does not allow state to be 0, but bound can be negative, which causes this
* not to produce positive numbers. This method is very predictable and its use is not encouraged; prefer using
* {@link #determineBounded(int, int)}.
* @param state any long other than 0
* @param bound the exclusive bound on the result as an int; does better if the bound is not too high (below 10000?)
* @return the next value that {@link LFSR#determine(long)} would produce with the given state, but limited to bound; can return 0
*/
public static int determineBounded(final long state, int bound)
{
return (bound = (int)((bound * (state >>> 1 & 0xFFFFFFFFL)) >> 32)) + (bound >>> 31);
}
/**
* Gets an int using {@link #determineInt(int)} and bounds it to fit between 0 (inclusive) and bound (exclusive).
* Does not allow state to be 0, but bound can be negative, which causes this not to produce positive numbers.
* @param state any int other than 0
* @param bound the exclusive bound on the result as an int; does better if the bound is not too high (below 10000?)
* @return the next int that {@link LFSR#determineInt(int)} would produce with the given state, but limited to bound; can return 0
*/
public static int determineBounded(final int state, int bound)
{
return (bound = (int)((bound * ((state >>> 1 ^ (-(state & 1) & 0xA3000000)) & 0xFFFFFFFFL)) >> 32)) + (bound >>> 31);
}
}
| 46.602524 | 134 | 0.662222 |
db7a5066591576fa295089fedc639f69e845044b | 4,973 | package co.matisses.bcs.rest;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
/**
*
* @author dbotero
*/
@ApplicationPath("res")
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new HashSet<>();
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method. It is automatically
* populated with all resources defined in the project. If required, comment
* out calling this method in getClasses().
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(co.matisses.bcs.b1ws.client.activities.ActivitiesREST.class);
resources.add(co.matisses.bcs.b1ws.client.binlocationattributes.BinLocationAttributesREST.class);
resources.add(co.matisses.bcs.b1ws.client.binlocations.BinLocationsREST.class);
resources.add(co.matisses.bcs.b1ws.client.businesspartners.BusinessPartnerREST.class);
resources.add(co.matisses.bcs.b1ws.client.creditnotes.CreditNotesREST.class);
resources.add(co.matisses.bcs.b1ws.client.employeesinfo.EmployeesInfoREST.class);
resources.add(co.matisses.bcs.b1ws.client.goodsissue.GoodsIssueREST.class);
resources.add(co.matisses.bcs.b1ws.client.goodsreceipt.GoodsReceiptREST.class);
resources.add(co.matisses.bcs.b1ws.client.invoices.InvoicesREST.class);
resources.add(co.matisses.bcs.b1ws.client.items.ItemsREST.class);
resources.add(co.matisses.bcs.b1ws.client.journalentries.JournalEntryREST.class);
resources.add(co.matisses.bcs.b1ws.client.orders.OrderREST.class);
resources.add(co.matisses.bcs.b1ws.client.payments.IncomingPaymentREST.class);
resources.add(co.matisses.bcs.b1ws.client.payments.IncomingPaymentServiceREST.class);
resources.add(co.matisses.bcs.b1ws.client.quotations.QuotationsREST.class);
resources.add(co.matisses.bcs.b1ws.client.serviceCalls.ServiceCallsREST.class);
resources.add(co.matisses.bcs.b1ws.client.stocktransfer.StockTransferREST.class);
resources.add(co.matisses.bcs.b1ws.client.warehousesublevelcodes.WarehouseSublevelCodesREST.class);
resources.add(co.matisses.bcs.google.URLShortener.class);
resources.add(co.matisses.bcs.mailchimp.MailChimpREST.class);
resources.add(co.matisses.bcs.mbean.BCSApplicationMBean.class);
resources.add(co.matisses.bcs.mbean.ImagenProductoMBean.class);
resources.add(co.matisses.bcs.rest.AlarmaREST.class);
resources.add(co.matisses.bcs.rest.CaptacionClientesREST.class);
resources.add(co.matisses.bcs.rest.CoordinadoraWSREST.class);
resources.add(co.matisses.bcs.rest.CotizacionWEBREST.class);
resources.add(co.matisses.bcs.rest.DigitoVerificacionREST.class);
resources.add(co.matisses.bcs.rest.EmailPatternValidatorREST.class);
resources.add(co.matisses.bcs.rest.Encode128REST.class);
resources.add(co.matisses.bcs.rest.FiltrosProductoREST.class);
resources.add(co.matisses.bcs.rest.InformeRotacionREST.class);
resources.add(co.matisses.bcs.rest.JWTTokenValidatorREST.class);
resources.add(co.matisses.bcs.rest.ListaRegalosREST.class);
resources.add(co.matisses.bcs.rest.ListaRegalosSessionValidatorREST.class);
resources.add(co.matisses.bcs.rest.MercadoLibreREST.class);
resources.add(co.matisses.bcs.rest.NotificacionesListaRegalosREST.class);
resources.add(co.matisses.bcs.rest.PlaceToPayREST.class);
resources.add(co.matisses.bcs.rest.PrintReportREST.class);
resources.add(co.matisses.bcs.rest.ProcesarDocumentoREST.class);
resources.add(co.matisses.bcs.rest.ProcesoPagosREST.class);
resources.add(co.matisses.bcs.rest.ProgramacionDescuentosREST.class);
resources.add(co.matisses.bcs.rest.SMSServiceREST.class);
resources.add(co.matisses.bcs.rest.SendHtmlEmailREST.class);
resources.add(co.matisses.bcs.rest.SessionUsuarioPaginaREST.class);
resources.add(co.matisses.bcs.rest.ShippingMethodsREST.class);
resources.add(co.matisses.bcs.rest.ShoppingCartValidatorREST.class);
resources.add(co.matisses.bcs.rest.SondaItemsREST.class);
resources.add(co.matisses.bcs.rest.SondaSolucionesLlamadaREST.class);
resources.add(co.matisses.bcs.rest.TiempoRotacionREST.class);
resources.add(co.matisses.bcs.rest.ValidarInventarioCompraWebREST.class);
resources.add(co.matisses.bcs.rest.ZebraPrintREST.class);
resources.add(co.matisses.bcs.sync.ItemDataBrandService.class);
resources.add(co.matisses.bcs.sync.ItemDataColorService.class);
resources.add(co.matisses.bcs.sync.ItemDataMaterialService.class);
resources.add(co.matisses.bcs.sync.ItemDataService.class);
}
}
| 58.505882 | 107 | 0.746833 |
5997170b146472ff5d68d88e8bd9675277f1b1de | 179 | package com.xdag.wallet.ui.activity;
import android.app.Activity;
/**
* Created by wangxuguo on 2018/6/21.
*/
public class ChangedWalletNameActivity extends BaseActivity {
}
| 16.272727 | 61 | 0.759777 |
5498d39452341da9329098a407532d0126cecd3f | 1,025 | package com.types;
import java.util.NoSuchElementException;
/**
* Interface to provide queue specific functionality to the implementing class
* This interface only defines the functionality which the queue implementing classes require.
* Any class having queue behaviour should implement this interface and override all of its methods
*
* @param <T>
*/
public interface Queue<T> extends DataStructure<T> {
/**
* Method to add element
*
* @param t element
* @return boolean
* @throws NullPointerException
*/
boolean offer(T t) throws NullPointerException;
/**
* Method to remove element
*
* @return element
*/
T poll();
/**
* Method to check element on head
*
* @return element
*/
T peek();
/**
* Method to check element on head. This throws exception on runtime if the queue is empty
*
* @return element
* @throws NoSuchElementException
*/
T element() throws NoSuchElementException;
}
| 22.282609 | 99 | 0.650732 |
3fdbc46de4215c77fadfc0745e1f0623428e4388 | 11,279 | package io.nuls.poc.utils.thread.process;
import io.nuls.base.data.Block;
import io.nuls.base.data.BlockExtendsData;
import io.nuls.base.data.BlockHeader;
import io.nuls.base.data.Transaction;
import io.nuls.poc.constant.ConsensusConstant;
import io.nuls.poc.constant.ConsensusErrorCode;
import io.nuls.poc.model.bo.BlockData;
import io.nuls.poc.model.bo.Chain;
import io.nuls.poc.model.bo.consensus.ConsensusStatus;
import io.nuls.poc.model.bo.round.MeetingMember;
import io.nuls.poc.model.bo.round.MeetingRound;
import io.nuls.poc.utils.manager.ConsensusManager;
import io.nuls.poc.utils.manager.RoundManager;
import io.nuls.tools.core.ioc.SpringLiteContext;
import io.nuls.tools.data.DateUtils;
import io.nuls.tools.exception.NulsException;
import io.nuls.tools.log.Log;
import io.nuls.tools.thread.TimeService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
* 共识处理器
* Consensus processor
*
* @author tag
* 2018/11/15
* */
public class ConsensusProcess {
private RoundManager roundManager = SpringLiteContext.getBean(RoundManager.class);
private boolean hasPacking;
public void process(Chain chain){
try {
boolean canPackage = checkCanPackage(chain);
if (!canPackage) {
return;
}
doWork(chain);
}catch (NulsException e){
Log.error(e.getMessage());
}
}
/**
* 检查节点打包状态
* Check node packing status
* */
private boolean checkCanPackage(Chain chain) throws NulsException{
if(chain == null ){
throw new NulsException(ConsensusErrorCode.CHAIN_NOT_EXIST);
}
/*
检查模块状态是否为运行中
Check whether the module status is in operation
*/
if (chain.getConsensusStatus().ordinal() <= ConsensusStatus.WAIT_RUNNING.ordinal()) {
return false;
}
/*todo
检查网络状态是否正常(调用网络模块接口获取当前链接节点数)
Check whether the network status is normal
*/
int availableNodes = 5;
if(availableNodes < ConsensusConstant.ALIVE_MIN_NODE_COUNT){
return false;
}
/*
检查节点状态是否可打包(区块管理模块同步完成之后设置该状态)
Check whether the node status can be packaged (set up after the block management module completes synchronization)
*/
if(!chain.isCanPacking()){
return false;
}
return true;
}
private void doWork(Chain chain)throws NulsException{
/*
检查节点状态
Check node status
*/
if (chain.getConsensusStatus().ordinal() < ConsensusStatus.RUNNING.ordinal()) {
return;
}
/*
获取当前轮次信息并验证轮次信息
Get current round information
*/
MeetingRound round = roundManager.getOrResetCurrentRound(chain,true);
if (round == null) {
return;
}
MeetingMember member = round.getMyMember();
if(member == null){
return;
}
/*
如果是共识节点则判断是否轮到自己出块
1.节点是否正在打包
2.当前时间是否处于节点打包开始时间和结束时间之间
If it's a consensus node, it's time to decide whether it's your turn to come out of the block.
1. Is the node packing?
2. Is the current time between the start and end of the node packing?
*/
if(!hasPacking && member.getPackStartTime() < TimeService.currentTimeMillis() && member.getPackEndTime() > TimeService.currentTimeMillis()){
hasPacking = true;
try {
if (Log.isDebugEnabled()) {
Log.debug("当前网络时间: " + DateUtils.convertDate(new Date(TimeService.currentTimeMillis())) + " , 我的打包开始时间: " +
DateUtils.convertDate(new Date(member.getPackStartTime())) + " , 我的打包结束时间: " +
DateUtils.convertDate(new Date(member.getPackEndTime())) + " , 当前轮开始时间: " +
DateUtils.convertDate(new Date(round.getStartTime())) + " , 当前轮结束开始时间: " +
DateUtils.convertDate(new Date(round.getEndTime())));
}
packing(chain, member, round);
} catch (Exception e) {
Log.error(e);
}
while (member.getPackEndTime() > TimeService.currentTimeMillis()) {
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
Log.error(e);
}
}
hasPacking = false;
}
}
private void packing(Chain chain,MeetingMember self, MeetingRound round) throws IOException, NulsException {
/*
等待出块
Wait for blocks
*/
waitReceiveNewestBlock(chain,self, round);
long start = System.currentTimeMillis();
Block block = doPacking(chain, self, round);
Log.info("doPacking use:" + (System.currentTimeMillis() - start) + "ms");
/*
* 打包完成之后,查看打包区块和主链最新区块是否连续,如果不连续表示打包过程中收到了上一个共识节点打包的区块,此时本地节点需要重新打包区块
* After packaging, check whether the packaged block and the latest block in the main chain are continuous. If the block is not continuous,
* the local node needs to repackage the block when it receives the packaged block from the previous consensus node in the packaging process.
*/
BlockHeader header =chain.getNewestHeader();
boolean rePacking = !block.getHeader().getPreHash().equals(header.getHash());
if(rePacking){
start = System.currentTimeMillis();
block=doPacking(chain, self, round);
Log.info("doPacking use:" + (System.currentTimeMillis() - start) + "ms");
}
if (null == block) {
Log.error("make a null block");
return;
}
//todo 打包成功后将区块传给区块管理模块广播
}
/**
* 是否到达节点出块的时间点,如果本地最新区块为本轮次中上一节点所出,则直接打包出块,否则等待一定时间之后如果还没有接收到上一节点出的块则直接打包出块
* Whether or not to arrive at the time point when the node is out of the block, if the latest local block is out of the previous node in this round, it will be packaged directly.
* Otherwise, if the block from the previous node has not been received after waiting for a certain time, it will be packed directly.
* */
private boolean waitReceiveNewestBlock(Chain chain,MeetingMember self, MeetingRound round){
long timeout = chain.getConfig().getPackingInterval()/2;
long endTime = self.getPackStartTime() + timeout;
boolean hasReceiveNewestBlock = false;
try {
while (!hasReceiveNewestBlock) {
/*
判断本地最新区块是否为轮次中上一个节点所出
Determine whether the latest local block is from the last node in the round
*/
hasReceiveNewestBlock = hasReceiveNewestBlock(chain, self, round);
if (hasReceiveNewestBlock) {
break;
}
Thread.sleep(100L);
if (TimeService.currentTimeMillis() >= endTime) {
break;
}
}
} catch (InterruptedException e) {
Log.error(e);
}
return !hasReceiveNewestBlock;
}
/**
* 判断本地最新区块是否为本轮次上一个区块所出
* Judging whether the latest block in this region is from the last block in this round
* */
private boolean hasReceiveNewestBlock(Chain chain,MeetingMember self, MeetingRound round){
int myIndex = self.getPackingIndexOfRound();
MeetingMember preMember;
MeetingRound preRound = round;
/*
如果当前节点为该轮次第一个出块节点,则本地最新区块应该是上一轮的最后一个出块节点所出
If the current node is the first out-of-block node in the round, the latest local block should be the last out-of-block node in the previous round.
*/
if(myIndex == 1){
preRound = round.getPreRound();
if(preRound == null){
Log.error("PreRound is null!");
return true;
}
preMember = preRound.getMember(preRound.getMemberCount());
}else{
preMember = round.getMember(self.getPackingIndexOfRound()-1);
}
if (preMember == null) {
return true;
}
/*
比较本地最新区块出块地址与上一节点的出块地址是否相等,如果相等则表示上一节点已出块,当前节点可以出块了
Comparing whether the block address of the latest local block is equal to that of the previous node, if equal,
it means that the previous node has already blocked, and the current node can blocked.
*/
BlockHeader bestBlockHeader = chain.getNewestHeader();
BlockExtendsData blockRoundData = new BlockExtendsData(bestBlockHeader.getExtend());
byte[] bestPackingAddress = bestBlockHeader.getPackingAddress();
long bestRoundIndex = blockRoundData.getRoundIndex();
int bestPackingIndex = blockRoundData.getPackingIndexOfRound();
byte[] prePackingAddress = preMember.getAgent().getPackingAddress();
long preRoundIndex = preRound.getIndex();
int prePackingIndex = preMember.getPackingIndexOfRound();
if (Arrays.equals(bestPackingAddress, prePackingAddress) && bestRoundIndex == preRoundIndex && bestPackingIndex == prePackingIndex) {
return true;
} else {
return false;
}
}
private Block doPacking(Chain chain, MeetingMember self, MeetingRound round) throws NulsException, IOException{
BlockHeader bestBlock = chain.getNewestHeader();
BlockData bd = new BlockData();
bd.setHeight(bestBlock.getHeight() + 1);
bd.setPreHash(bestBlock.getHash());
bd.setTime(self.getPackEndTime());
BlockExtendsData extendsData = new BlockExtendsData();
extendsData.setRoundIndex(round.getIndex());
extendsData.setConsensusMemberCount(round.getMemberCount());
extendsData.setPackingIndexOfRound(self.getPackingIndexOfRound());
extendsData.setRoundStartTime(round.getStartTime());
bd.setExtendsData(extendsData);
StringBuilder str = new StringBuilder();
str.append(self.getAgent().getPackingAddress());
str.append(" ,order:" + self.getPackingIndexOfRound());
str.append(",packTime:" + new Date(self.getPackEndTime()));
str.append("\n");
Log.debug("pack round:" + str);
//todo 从交易管理模块获取打包交易
List<Transaction> packingTxList = new ArrayList<>();
/*
组装系统交易(CoinBase/红牌/黄牌)+ 创建区块
Assembly System Transactions (CoinBase/Red/Yellow)+ Create blocks
*/
ConsensusManager consensusManager = SpringLiteContext.getBean(ConsensusManager.class);
consensusManager.addConsensusTx(chain,bestBlock,packingTxList,self,round);
bd.setTxList(packingTxList);
Block newBlock = consensusManager.createBlock(bd, self.getAgent().getPackingAddress());
Log.info("make block height:" + newBlock.getHeader().getHeight() + ",txCount: " + newBlock.getTxs().size() + " , block size: " + newBlock.size() + " , time:" + DateUtils.convertDate(new Date(newBlock.getHeader().getTime())) + ",packEndTime:" +
DateUtils.convertDate(new Date(self.getPackEndTime())));
return newBlock;
}
}
| 39.575439 | 251 | 0.625321 |
d649de348cc6f858b0ad1ec66ef5822a422449c8 | 237 | package com.codurance.katalyst.kickstart;
public class Calculator {
public int sum(int... numbers) {
int result = 0;
for (int number: numbers) {
result += number;
}
return result;
}
}
| 19.75 | 41 | 0.556962 |
24c534b1529888254b4bee123e0fe70372bd7831 | 351 | package haw.vs.superteam.gamesservice.api;
import haw.vs.superteam.gamesservice.model.Event;
import retrofit.Call;
import retrofit.http.Body;
import retrofit.http.POST;
/**
* Created by florian on 11.01.16.
*/
public interface PlayerAPI {
@POST("turn")
Call<Void> turn();
@POST("event")
Call<Void> event(@Body Event[] events);
}
| 18.473684 | 49 | 0.698006 |
2cec0c5e9221db048487ff28af88173e25b081c8 | 10,542 | package module;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import bouyomi.BouyomiProxy;
import bouyomi.DiscordAPI;
import bouyomi.IAutoSave;
import bouyomi.IModule;
import bouyomi.Tag;
import bouyomi.Util.JsonUtil;
public class NicoAlart implements IModule,IAutoSave, Runnable{
private Thread thread;
private int lastWriteHashCode,lastWriteHashCodeA;
public static final HashMap<String,String> shortcutDB=new HashMap<String,String>();
public static HashMap<String,String> alarted=new HashMap<String,String>();
public static class NicoLiveEvent implements BouyomiEvent{
public Live[] live;
public NicoLiveEvent(Live[] lv) {
live=lv;
}
}
public static class CheckLiveEvent implements BouyomiEvent{
public Live[] live;
private CheckLiveEvent(Live[] lv) {
live=lv;
}
}
public NicoAlart(){
thread=new Thread(this,"定期ニコニコ生放送コミュニティ検索");
thread.start();
}
@Override
public void call(Tag tag){
String s=tag.getTag("ニコニコ生放送コミュニティ検索");
if(s!=null) {
try{
int cid=Integer.parseInt(s);
DiscordAPI.chatDefaultHost("検索URL=https://api.search.nicovideo.jp/api/v2/live/contents/search"+getParm(null,cid));
Live[] lives=getLives(null,cid);
if(lives.length>0) {
StringBuilder sb=new StringBuilder();
for(Live lv:lives)sb.append(lv);
s=sb.toString();
}else s="放送されてません";
DiscordAPI.chatDefaultHost(s);
}catch(NumberFormatException|IOException e){
e.printStackTrace();
}
}
s=tag.getTag("ニコニコ生放送コミュニティ検索RAW","ニコニコ生放送コミュニティ検索raw");
if(s!=null) {
try{
int cid=Integer.parseInt(s);
String q="ゲーム OR 描いてみた OR リスナーは外部記憶装置 OR 通知用";
DiscordAPI.chatDefaultHost("検索URL=https://api.search.nicovideo.jp/api/v2/live/contents/search"+getParm(q,cid));
String js=getLiveJSON(q,cid);
DiscordAPI.chatDefaultHost(js);
}catch(NumberFormatException|IOException e){
e.printStackTrace();
chatException(e);
}
}
for(Entry<String, String> e:shortcutDB.entrySet()) {
if(tag.con.text.equals(e.getKey()+"放送してる?")) {
System.out.println(e.getKey()+"放送してる?");
try{
int id=Integer.parseInt(e.getValue());
try{
Live[] lives=getLives(null,id);
if(lives.length>0) {
DiscordAPI.chatDefaultHost("https://live2.nicovideo.jp/watch/"+lives[0].contentId+" でしてる");
}else DiscordAPI.chatDefaultHost("多分してない/*ニコニコの検索サーバが遅延してるかも");
}catch(IOException ex){
DiscordAPI.chatDefaultHost("わかんにゃい!");
chatException(ex);
}
}catch(NumberFormatException nfe) {
}
}
}
s=tag.getTag("放送チェックショートカット");
if(s!=null) {
int index=s.indexOf("=");
if(index>0){
try{
String key=s.substring(0,index);
String val=s.substring(index+1);
Matcher m=Pattern.compile("co[0-9]++").matcher(val);
if(m.find()) {
m=Pattern.compile("[0-9]++").matcher(m.group());
m.find();
try {
int co=Integer.parseInt(m.group());
shortcutDB.put(key,val=Integer.toString(co));
DiscordAPI.chatDefaultHost(val+"放送してる? に完全一致でco"+co+"が放送してるか取得できるように登録");
}catch(NumberFormatException nfe) {
DiscordAPI.chatDefaultHost("コミュID指定ミスってる");
}
}
}catch(Exception e) {
chatException(e);
}
}
}
/*
s=tag.getTag("おっさん放送してる?");
if(s!=null) {
try{
Live[] lives=getLives(null,1003067);
if(lives.length>0) {
DiscordAPI.chatDefaultHost("https://live2.nicovideo.jp/watch/"+lives[0].contentId+" でしてる");
}else DiscordAPI.chatDefaultHost("してない");
}catch(IOException e){
DiscordAPI.chatDefaultHost("わかんにゃい!");
}
}
*/
s=tag.getTag("このコミュ放送してる?","このコミュ放送してる?");
if(s!=null) {
Matcher m=Pattern.compile("co[0-9]++").matcher(s);
boolean miss=false;
if(m.find()) {
m=Pattern.compile("[0-9]++").matcher(m.group());
m.find();
try {
int co=Integer.parseInt(m.group());
try{
Live[] lives=getLives(null,co);
if(lives.length>0) {
DiscordAPI.chatDefaultHost("https://live2.nicovideo.jp/watch/"+lives[0].contentId+" でしてる");
}else DiscordAPI.chatDefaultHost("してない");
}catch(IOException e){
miss=true;
}
}catch(NumberFormatException nfe) {
DiscordAPI.chatDefaultHost("コミュID指定ミスってる");
}
}else miss=true;
if(miss)DiscordAPI.chatDefaultHost("わかんにゃい!");
}
}
public static int getCo(String org) {
Matcher m=Pattern.compile("co[0-9]++").matcher(org);
if(m.find()) {
m=Pattern.compile("[0-9]++").matcher(m.group());
m.find();
try {
return Integer.parseInt(m.group());
}catch(NumberFormatException nfe) {
}
}
return -1;
}
@Override
public void autoSave(){
int hc=shortcutDB.hashCode();
if(hc!=lastWriteHashCode) {
lastWriteHashCode=hc;
try{
BouyomiProxy.save(shortcutDB,"NicoShortCut.txt");
}catch(IOException e){
e.printStackTrace();
}
}
hc=alarted.hashCode();
if(hc!=lastWriteHashCodeA) {
lastWriteHashCodeA=hc;
try{
BouyomiProxy.save(alarted,"NicoAlart.txt");
}catch(IOException e){
e.printStackTrace();
}
}
}
@Override
public void shutdownHook(){
if(!shortcutDB.isEmpty())try{
BouyomiProxy.save(shortcutDB,"NicoShortCut.txt");
}catch(IOException e){
e.printStackTrace();
}
if(!alarted.isEmpty())try{
BouyomiProxy.save(alarted,"NicoAlart.txt");
}catch(IOException e){
e.printStackTrace();
}
}
public boolean chatException(Exception e) {
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
e.printStackTrace(pw);
pw.close();
return DiscordAPI.chatDefaultHost(sw.toString());
}
@Override
public void run(){
try{
BouyomiProxy.load(shortcutDB,"NicoShortCut.txt");
}catch(IOException e){
e.printStackTrace();
}
shortcutDB.put("おっさん","1003067");
try{
BouyomiProxy.load(alarted,"NicoAlart.txt");
}catch(IOException e){
e.printStackTrace();
}
lastWriteHashCode=shortcutDB.hashCode();
lastWriteHashCodeA=alarted.hashCode();
while(true) {
try{
check(1003067);
autoSave();
}catch(IOException e1){
e1.printStackTrace();
}
try{
Thread.sleep(5*60*1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void check(int id) throws IOException {
Live[] lives=getLives(null,id);
if(lives.length>0) {
String last=alarted.get(Integer.toString(id));
if(!(lives[0].contentId.equals(last))) {
BouyomiProxy.module.event(new NicoLiveEvent(lives));
StringBuilder sb=new StringBuilder("生放送 ");
sb.append(lives[0].title);
sb.append(" が開始されました/*");
for(Live lv:lives)sb.append(lv);
String s=sb.toString();
//System.out.println(s);
DiscordAPI.chatDefaultHost(s);
}
alarted.put(Integer.toString(id),lives[0].contentId);
}else {
alarted.put(Integer.toString(id),"");
}
}
public static void main(String[] args) throws IOException {
Live[] l=getLives(null,1124081);
for(Live lv:l)System.out.println(lv);
}
public static Live[] getLives(String q,int... id) throws IOException {
//System.out.print("q="+q+" コミュニティ="+id[0]+"で検索実行...");
String js=getLiveJSON(q,id);
Object[] o=JsonUtil.getAsArray(js,"data");
Live[] live=new Live[o.length];
if(o!=null)for(int i=0;i<o.length;i++){
@SuppressWarnings("unchecked")
Map<String, Object> map=(Map<String,Object>)o[i];
live[i]=new Live(map);
}
BouyomiProxy.module.event(new CheckLiveEvent(live));
//System.out.println(live.length+"件です");
return live;
}
public static class Live{
public String title;
public String contentId;
/**説明*/
public String description;
public String communityId;
public Live(Map<String,Object> map) {
description=map.get("description").toString();
contentId=map.get("contentId").toString();
title=map.get("title").toString();
communityId=map.get("communityId").toString();
//for(Entry<String, Object> e:map.entrySet())System.out.println(e.getKey()+"="+e.getValue());
}
@Override
public int hashCode() {
return title.hashCode()+contentId.hashCode()+description.hashCode();
}
@Override
public boolean equals(Object o) {
if(o instanceof Live);
else return false;
Live l=(Live) o;
return title.equals(l.title)&&contentId.equals(l.contentId)&&description.equals(l.description);
}
@Override
public String toString() {
StringBuilder sb=new StringBuilder("配信ID=").append(contentId).append("\n");
sb.append("配信URL=https://live2.nicovideo.jp/watch/").append(contentId).append("\n");
sb.append("配信タイトル=").append(title).append("\n");
//sb.append("説明文\n").append(description);
return sb.toString();
}
}
public static String getLiveJSON(String q,int... communityId) throws IOException {
String url=getParm(q,communityId);
URL url0=new URL("https://api.search.nicovideo.jp/api/v2/live/contents/search"+url);
URLConnection uc=url0.openConnection();
uc.setRequestProperty("User-Agent","Atuwa Bouyomi Proxy");
InputStream is=uc.getInputStream();//POSTした結果を取得
byte[] b=new byte[512];
int len;
ByteArrayOutputStream res=new ByteArrayOutputStream();
while(true) {
len=is.read(b);
if(len<1)break;
res.write(b,0,len);
}
return res.toString("utf-8");
}
private static String getParm(String q,int... communityId) {
if(q==null)q=" ゲーム OR 描いてみた OR リスナーは外部記憶装置 OR 通知用";
try{
q=URLEncoder.encode(q,"utf-8");
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}
StringBuilder sb=new StringBuilder("?q=");
sb.append(q);
sb.append("&targets=tags");
sb.append("&_sort=-viewCounter");
sb.append("&_context=AtuwaBouyomiProxy");
sb.append("&fields=contentId,title,description,communityId");
sb.append("&filters[liveStatus][0]=onair");
for(int i=0;i<communityId.length;i++) {
sb.append("&filters[communityId][");
sb.append(i).append("]=");
sb.append(communityId[i]);
}
//System.out.println(sb);
return sb.toString();
}
} | 30.293103 | 119 | 0.65424 |
acee182973dc16021d2b5a2cd87ba04a8a80f01d | 6,535 | package com.sap.ateam.wsl4cc.rfc;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.sap.conn.jco.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sap.ateam.wsl4cc.Wsl4ccDestination;
import com.sap.ateam.wsl4cc.Wsl4ccException;
import com.sap.ateam.wsl4cc.handler.ServiceHandler;
import com.sap.ateam.wsl4cc.io.OutputStatus;
import com.sap.ateam.wsl4cc.io.Wsl4ccError;
import com.sap.ateam.wsl4cc.io.Wsl4ccInput;
import com.sap.ateam.wsl4cc.io.Wsl4ccOutput;
import com.sap.ateam.wsl4cc.util.ConversionUtil;
import javax.ws.rs.HEAD;
public class RfcServiceHandler implements ServiceHandler {
@Override
public void initialize(String dest) {
this.dest = dest;
}
@Override
public Wsl4ccOutput execute(Wsl4ccInput input) throws Wsl4ccException {
JCoDestination destination = Wsl4ccDestination.getDestination(dest);
if (destination == null || !destination.isValid())
return new Wsl4ccError("Unrecognized RFC destination " + dest);
if (input.getName() == null || input.getName().isEmpty())
return new Wsl4ccError("Empty or null RFC function name not allowed");
JCoFunction func = Wsl4ccDestination.getFunction(destination, input.getName());
if (func == null)
return new Wsl4ccError("Unrecognized RFC function " + input.getName());
// Prepare input parameters
prepareImportsFromUserInput (func, input);
// Prepare input tables, if any
prepareTablesFromUserInput (func, input);
// Execute the function
Wsl4ccOutput output = executeFunction(func, destination, input);
// Return output variables
JCoParameterList exports = func.getExportParameterList();
output.setOutput(ConversionUtil.convertParameterListToMap(exports));
// Return tables
JCoParameterList tables = func.getTableParameterList();
output.setTables(ConversionUtil.convertParameterListToMap(tables));
return output;
}
/**
* Parse the user provided input and create the imports parameter to be used during invocation of RFC function.
*
* @param func JCoFunction that corresponds to the RFC
* @param input User provided input
* @throws Wsl4ccException
*/
private void prepareImportsFromUserInput(JCoFunction func, Wsl4ccInput input) throws Wsl4ccException {
JCoParameterList imports = func.getImportParameterList();
Map<String,Object> userInputMap = input.getInput();
List<String> paramNames = new ArrayList<>();
if (imports == null)
return;
JCoParameterFieldIterator iterator = imports.getParameterFieldIterator();
while (iterator.hasNextField()) {
JCoParameterField field = iterator.nextParameterField();
String name = field.getName();
paramNames.add(name);
if (userInputMap != null && userInputMap.containsKey(name)) {
logger.debug("Found input field name {} of type {} with value {}", name, field.getTypeAsString(), userInputMap.get(name));
ConversionUtil.convertPrimitiveToJCoField(imports, name, userInputMap.get(name));
} else {
// logger.debug("Setting default value for input field name {}", name);
imports.setValue(name, (String) null);
}
}
// Check validity of other parameters
if (userInputMap != null && userInputMap.size() > 0) {
for (Map.Entry<String,Object> i: input.getInput().entrySet()) {
String name = i.getKey();
if (!paramNames.contains(name)) {
throw new Wsl4ccException ("Unrecognized or invalid input parameter " + name);
}
}
}
}
/**
* Parse the user provided input table(s) and create the tables parameter to be used during invocation of RFC function.
*
* @param func JCoFunction that corresponds to the RFC
* @param input User provided input
* @throws Wsl4ccException
*/
private void prepareTablesFromUserInput(JCoFunction func, Wsl4ccInput input) throws Wsl4ccException {
JCoParameterList tables = func.getTableParameterList();
Map<String,Object> userTableMap = input.getTables();
List<String> tableNames = new ArrayList<>();
if (tables == null)
return;
JCoParameterFieldIterator iterator = tables.getParameterFieldIterator();
while (iterator.hasNextField()) {
JCoParameterField field = iterator.nextParameterField();
String name = field.getName();
tableNames.add(name);
if (userTableMap != null && userTableMap.containsKey(name)) {
logger.debug("Found input table name {} of type {} with value {}", name, field.getTypeAsString(), userTableMap.get(name));
JCoTable table = tables.getTable(name);
if (userTableMap.get(name) instanceof List<?>) {
ConversionUtil.convertToJCoTable(name, table, (List<?>) userTableMap.get(name));
tables.setValue(name, table);
} else {
throw new Wsl4ccException ("Table parameter " + name + " must be input as an array.");
}
}
}
// Check validity of other parameters
if (userTableMap != null && userTableMap.size() > 0) {
for (Map.Entry<String,Object> i: input.getTables().entrySet()) {
String name = i.getKey();
if (!tableNames.contains(name)) {
throw new Wsl4ccException ("Unrecognized or invalid table parameter " + name);
}
}
}
}
private Wsl4ccOutput executeFunction(JCoFunction function, JCoDestination destination, final Wsl4ccInput input) {
Wsl4ccOutput output = new Wsl4ccOutput();
boolean error = false;
String errorMessage = null;
try {
JCoContext.begin(destination);
function.execute(destination);
if (input.readBooleanOption("commit")) {
JCoFunction commitFunction = Wsl4ccDestination.getFunction(destination, "BAPI_TRANSACTION_COMMIT");
commitFunction.execute(destination);
}
output.setStatus(OutputStatus.OK);
} catch (JCoException e) {
error = true;
errorMessage = e.getMessage();
} finally {
try {
JCoContext.end(destination);
} catch (JCoException e) {
error = true;
errorMessage = e.getMessage();
}
}
if (error) {
output.setStatus(OutputStatus.ERROR);
output.setMessage(errorMessage == null ? "(null)" : errorMessage);
}
return output;
}
private String dest;
private Logger logger = LoggerFactory.getLogger(RfcServiceHandler.class);
}
| 34.57672 | 135 | 0.677429 |
629b4c6b41000e8fd0f4f821c22075c0194a529c | 528 | package pl.oucik.auth.listeners;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import pl.oucik.auth.OAuth;
public class PlayerChatMessageLisener implements Listener {
private final OAuth p;
public PlayerChatMessageLisener(OAuth p){ this.p = p;}
@EventHandler
public void onMessage(AsyncPlayerChatEvent e){
if(!p.manager().getUser(e.getPlayer().getName()).islogged()){
e.setCancelled(true);
}
}
}
| 25.142857 | 69 | 0.717803 |
0b1009c8a1cfae0dfd180a85f38f638b19ceb135 | 2,883 | package lkd.namsic.game.creator;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import lkd.namsic.game.config.Config;
import lkd.namsic.game.enums.object.SkillList;
import lkd.namsic.game.object.Skill;
import lkd.namsic.setting.Logger;
public class SkillCreator implements Creatable {
private void createSkill(@NonNull SkillList skillData, @Nullable String activeDes, @Nullable String passiveDes) {
Skill skill = new Skill(skillData, activeDes, passiveDes);
Config.unloadObject(skill);
}
@Override
public void start() {
createSkill(SkillList.MAGIC_BALL, "[1 마나] [회피 불가] [치명타 불가]\n" +
"(마법 공격력 * 1) 에 해당하는 마법 데미지를 가한다",null);
createSkill(SkillList.SMITE, "[5 마나]\n(공격력 * 0.5) 에 해당하는 물리 데미지 + (마법 공격력 * 0.5) 에 해당하는 " +
"마법 데미지 + ((공격력 + 마법 공격력) * 0.1) 에 해당하는 고정 데미지를 가한다",
"공격 전 마법 데미지가 0이면 물리 데미지의 5%에 해당하는 마법 데미지를 가한다");
createSkill(SkillList.LASER, "[10 마나] [1 턴]\n(마법 공격력 * 2.5) 에 해당하는 마법 데미지를 가한다", null);
createSkill(SkillList.SCAR, "[5 마나] [최대 3 대상]\n모든 대상에게 공격력의 10% 에 해당하는 데미지를 3번 가한다\n" +
"만약 3번의 공격 중 치명타가 터졌다면 대상에게 3턴간 공격력의 20%의 고정 데미지를 주는 출혈을 일으킨다", null);
createSkill(SkillList.CHARM, "[15 마나] [저항 가능]\n대상의 턴이 오면 턴을 강제로 빼앗고 " +
"해당 턴의 공격을 무조건 치명타로 만든다", null);
createSkill(SkillList.STRINGS_OF_LIFE, null,
"[전투 당 1회]\n체력이 최대 체력의 50% 이하일 때 죽음에 이르는 피해를 입을 시 체력을 1 남기고 생존한다");
createSkill(SkillList.RESIST, "[10 마나]\n3턴간 받는 모든 물리 피해를 60% 줄여 받는다", null);
createSkill(SkillList.RUSH, "[5 마나] [치명타 불가]\n" +
"대상의 위치까지 필드를 이동하고 이동한 거리와 공격력에 비례하여 데미지를 가한다", null);
createSkill(SkillList.ROAR, "[2 마나]\n모든 적의 공격속도를 레벨 차이에 비례하여 30초간 감소시킨다\n" +
"(1.5레벨 차이당 1%) (최대 30%)", null);
createSkill(SkillList.HOWLING_OF_WOLF, "[30 마나] [획득 불가]\n" +
"주변에 라이칸스로프 두 마리를 소환하여 전투에 난입시킨다", null);
createSkill(SkillList.CUTTING_MOONLIGHT, "[8 마나]\n" + "다른 타입의(n 설정 달빛 베기) 적 전체에게 " +
"(공격력 * 0.9) 또는 (마법 공격력 * 0.9) 중 더 높은 스텟으로 물리 또는 마법 데미지를 가한다",null);
createSkill(SkillList.SPAWN_IMP, "[50 마나] [획득 불가]\n" +
"주변에 임프 세 마리를 소환하여 전투에 난입시킨다", null);
createSkill(SkillList.ESSENCE_DRAIN, "[10 마나] [회피 불가] [치명타 불가]\n" +
"대상에게 (마법 공격력 * 1) 에 해당하는 마법 데미지를 가하고 그 데미지만큼 회복한다", null);
createSkill(SkillList.MAGIC_DRAIN, "[회피 불가]\n대상의 최대 마나의 10% 에 해당하는 " +
"마나를 없애고, 자신의 최대 마나의 10% 에 해당하는 마나를 회복한다", null);
createSkill(SkillList.MANA_EXPLOSION, "[50 마나] [회피 불가] [3 턴]\n필드 거리 16 내의 " +
"모든 대상에게 (마법 공격력 * 5) 에 해당하는 마법 데미지를 가한다", null);
Logger.i("ObjectMaker", "Skill making is done!");
}
}
| 42.397059 | 117 | 0.57787 |
a114bafa3e12fe9a7fb9a75a08d7e4be0b1ce6e7 | 1,292 | package com.bdoemu.gameserver.model.stats;
import com.bdoemu.commons.concurrent.CloseableReentrantLock;
import com.bdoemu.core.network.sendable.SMSetSubResourcePoints;
import com.bdoemu.gameserver.model.creature.Creature;
public class SubResourcePointStat extends Stat {
private long subResourcePointCacheCount;
public SubResourcePointStat(final Creature owner) {
super(owner);
}
public boolean addSubResourcePoints(final int points) {
double pointsDiff = points;
try (final CloseableReentrantLock closeableLock = this.lock.open()) {
final double newValue = pointsDiff + this.value;
if (newValue > this.maxValue) {
pointsDiff = this.maxValue - this.value;
} else if (newValue < 0.0) {
pointsDiff = -this.value;
}
this.value += pointsDiff;
if (this.owner.isPlayer()) {
this.owner.sendPacket(new SMSetSubResourcePoints(this.owner));
} else {
this.owner.getAi().HandleUpdateCombineWave(null, null);
}
++this.subResourcePointCacheCount;
}
return true;
}
public long getSubResourcePointCacheCount() {
return this.subResourcePointCacheCount;
}
} | 34.918919 | 78 | 0.642415 |
64ddaeda92c16ff066b72972e09dbd05a5aba2b3 | 11,980 | package org.dhallj.cbor;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/**
* An implementation of enough of the CBOR spec to cope with decoding the CBOR values we need for
* Dhall.
*/
public abstract class Reader {
/** Only allow symbols that correspond to entire encoded Dhall expressions. */
public final <R> R nextSymbol(Visitor<R> visitor) {
skip55799();
byte b = this.read();
switch (MajorType.fromByte(b)) {
case UNSIGNED_INTEGER:
return visitor.onUnsignedInteger(readUnsignedInteger(b));
case NEGATIVE_INTEGER:
return visitor.onNegativeInteger(readNegativeInteger(b));
case BYTE_STRING:
return visitor.onByteString(readByteString(b));
case TEXT_STRING:
return visitor.onTextString(readTextString(b));
case ARRAY:
return readArrayStart(b, visitor);
case MAP:
return visitor.onMap(readMapStart(b));
case SEMANTIC_TAG:
throw new CborException("We should have skipped semantic tags");
case PRIMITIVE:
return readPrimitive(b, visitor);
default:
throw new CborException("Invalid CBOR major type " + Byte.toString(b));
}
}
protected abstract byte read();
protected abstract byte peek();
protected abstract byte[] read(int count);
public final BigInteger readUnsignedInteger() {
skip55799();
return readUnsignedInteger(read());
}
public final BigInteger readPositiveBigNum() {
skip55799();
BigInteger result = readBigNum();
if (result.compareTo(BigInteger.ZERO) < 0) {
throw new CborException(result.toString() + " is not a positive big num");
} else {
return result;
}
}
public final BigInteger readBigNum() {
skip55799();
byte next = read();
switch (MajorType.fromByte(next)) {
case UNSIGNED_INTEGER:
return readUnsignedInteger(next);
case NEGATIVE_INTEGER:
return readNegativeInteger(next);
case SEMANTIC_TAG:
AdditionalInfo info = AdditionalInfo.fromByte(next);
BigInteger t = readBigInteger(info, next);
long tag = t.longValue();
BigInteger length = readUnsignedInteger();
long len = length.longValue(); // Don't handle Bignums larger than this
BigInteger result = readBigInteger(len);
if (tag == 2) {
return result;
} else if (tag == 3) {
return BigInteger.valueOf(-1).subtract(result);
} else {
throw new CborException(Long.toString(tag) + " is not a valid tag for a bignum");
}
default:
throw new CborException(
"Not a valid major type for an Unsigned Integer: "
+ MajorType.fromByte(next).toString());
}
}
public final String readNullableTextString() {
skip55799();
byte next = read();
switch (MajorType.fromByte(next)) {
case TEXT_STRING:
return readTextString(next);
case PRIMITIVE:
return readPrimitive(next, NullVisitor.instanceForString);
default:
throw new CborException("Next symbol is neither a text string or null");
}
}
public final byte[] readNullableByteString() {
skip55799();
byte next = read();
switch (MajorType.fromByte(next)) {
case BYTE_STRING:
return readByteString(next);
case PRIMITIVE:
return readPrimitive(next, NullVisitor.instanceForByteArray);
default:
throw new CborException("Next symbol is neither a byte string or null");
}
}
/**
* This is unfortunate and horrible.
*
* <p>A hack to support decoding record projections, which are the only expressions which have a
* CBOR representation where we don't know simply from the length of the array and the first
* element what type of expression we're decoding - could be projection or projection by type
*/
public final String tryReadTextString() {
skip55799();
byte next = peek();
switch (MajorType.fromByte(next)) {
case TEXT_STRING:
return readTextString(read());
default:
return null;
}
}
public final BigInteger readArrayStart() {
skip55799();
byte next = read();
switch (MajorType.fromByte(next)) {
case ARRAY:
AdditionalInfo info = AdditionalInfo.fromByte(next);
BigInteger length = readBigInteger(info, next);
if (length.compareTo(BigInteger.ZERO) < 0) {
throw new CborException("Indefinite array not needed for Dhall");
} else {
return length;
}
default:
throw new CborException("Next symbol is not an array");
}
}
public final <R> Map<String, R> readMap(Visitor<R> visitor) {
skip55799();
byte b = this.read();
switch (MajorType.fromByte(b)) {
case MAP:
int length = readMapStart(b).intValue();
Map<String, R> entries = new HashMap<>(length);
for (int i = 0; i < length; i++) {
String key = readNullableTextString();
R value = nextSymbol(visitor);
entries.put(key, value);
}
return entries;
default:
throw new CborException(
"Cannot read map - major type is " + MajorType.fromByte(b).toString());
}
}
private final BigInteger readUnsignedInteger(byte b) {
AdditionalInfo info = AdditionalInfo.fromByte(b);
return readBigInteger(info, b);
}
private final BigInteger readNegativeInteger(byte b) {
AdditionalInfo info = AdditionalInfo.fromByte(b);
return BigInteger.valueOf(-1).subtract(readBigInteger(info, b));
}
private final byte[] readByteString(byte b) {
AdditionalInfo info = AdditionalInfo.fromByte(b);
BigInteger length = readBigInteger(info, b);
if (length.compareTo(BigInteger.ZERO) < 0) {
throw new CborException("Indefinite byte string not needed for Dhall");
} else {
// We don't handle the case where the length is > Integer.MaxValue
return this.read(length.intValue());
}
}
private final String readTextString(byte b) {
AdditionalInfo info = AdditionalInfo.fromByte(b);
BigInteger length = readBigInteger(info, b);
if (length.compareTo(BigInteger.ZERO) < 0) {
// Indefinite length - do we need this for Dhall?
throw new CborException("Indefinite text string not needed for Dhall");
} else {
// We don't handle the case where the length is > Integer.MaxValue
return new String(this.read(length.intValue()), Charset.forName("UTF-8"));
}
}
private final <R> R readArrayStart(byte b, Visitor<R> visitor) {
AdditionalInfo info = AdditionalInfo.fromByte(b);
BigInteger length = readBigInteger(info, b);
if (length.compareTo(BigInteger.ZERO) < 0) {
throw new CborException("Indefinite array not needed for Dhall");
} else {
skip55799();
byte next = read();
switch (MajorType.fromByte(next)) {
case UNSIGNED_INTEGER:
return visitor.onArray(length, readUnsignedInteger(next));
case TEXT_STRING:
return visitor.onVariableArray(length, readTextString(next));
default:
throw new CborException(
"Invalid start to CBOR-encoded Dhall expression " + MajorType.fromByte(b).toString());
}
}
}
private final BigInteger readMapStart(byte b) {
AdditionalInfo info = AdditionalInfo.fromByte(b);
BigInteger length = readBigInteger(info, b);
if (length.compareTo(BigInteger.ZERO) < 0) {
throw new CborException("Indefinite array not needed for Dhall");
} else {
return length;
}
}
private static final String unassignedMessage(int v) {
StringBuilder builder = new StringBuilder("Primitive ");
builder.append(v);
builder.append(" is unassigned");
return builder.toString();
}
private static final String notValidMessage(int v) {
StringBuilder builder = new StringBuilder("Primitive ");
builder.append(v);
builder.append(" is not valid");
return builder.toString();
}
private final <R> R readPrimitive(byte b, Visitor<R> visitor) {
int value = b & 31;
if (0 <= value && value <= 19) {
throw new CborException(unassignedMessage(value));
} else if (value == 20) {
return visitor.onFalse();
} else if (value == 21) {
return visitor.onTrue();
} else if (value == 22) {
return visitor.onNull();
} else if (value == 23) {
throw new CborException(unassignedMessage(value));
} else if (value == 24) {
throw new CborException("Simple value not needed for Dhall");
} else if (value == 25) {
// https://github.com/c-rack/cbor-java/blob/master/src/main/java/co/nstant/in/cbor/decoder/HalfPrecisionFloatDecoder.java
int bits = 0;
for (int i = 0; i < 2; i++) {
int next = this.read() & 0xff;
bits <<= 8;
bits |= next;
}
return visitor.onHalfFloat(HalfFloat.toFloat(bits));
} else if (value == 26) {
int result = 0;
for (int i = 0; i < 4; i++) {
int next = this.read() & 0xff;
result <<= 8;
result |= next;
}
return visitor.onSingleFloat(Float.intBitsToFloat(result));
} else if (value == 27) {
long result = 0;
for (int i = 0; i < 8; i++) {
int next = this.read() & 0xff;
result <<= 8;
result |= next;
}
return visitor.onDoubleFloat(Double.longBitsToDouble(result));
} else if (28 <= value && value <= 30) {
throw new CborException(unassignedMessage(value));
} else if (value == 31) {
throw new CborException("Break stop code not needed for Dhall");
} else {
throw new CborException(notValidMessage(value));
}
}
private final void skip55799() {
byte next = peek();
switch (MajorType.fromByte(next)) {
case SEMANTIC_TAG:
AdditionalInfo info = AdditionalInfo.fromByte(next);
switch (info) {
case DIRECT:
return; // Don't advance pointer if it's a Bignum
default:
BigInteger tag = readBigInteger(info, read()); // Now advance pointer
int t = tag.intValue();
if (t != 55799) {
throw new CborException("Unrecognized CBOR semantic tag " + Integer.toString(t));
} else {
skip55799(); // Please tell me no encoders do this
}
}
default:
}
}
private final BigInteger readBigInteger(AdditionalInfo info, byte first) {
switch (info) {
case DIRECT:
return BigInteger.valueOf(first & 31);
case ONE_BYTE:
return readBigInteger(1);
case TWO_BYTES:
return readBigInteger(2);
case FOUR_BYTES:
return readBigInteger(4);
case EIGHT_BYTES:
return readBigInteger(8);
case RESERVED:
throw new CborException("Additional info RESERVED should not require reading a uintXX");
case INDEFINITE:
return BigInteger.valueOf(-1);
default:
throw new IllegalArgumentException("Invalid AdditionalInfo");
}
}
private final BigInteger readBigInteger(long numBytes) {
BigInteger result = BigInteger.ZERO;
for (long i = 0; i < numBytes; i++) {
int next = this.read() & 0xff;
result = result.shiftLeft(8).or(BigInteger.valueOf(next));
}
return result;
}
public static final class ByteArrayReader extends Reader {
private final byte[] bytes;
private int cursor = 0;
public ByteArrayReader(byte[] bytes) {
this.bytes = bytes;
}
@Override
protected byte read() {
return this.bytes[this.cursor++];
}
@Override
protected byte peek() {
return this.bytes[this.cursor];
}
@Override
protected byte[] read(int count) {
byte[] bs = new byte[count];
System.arraycopy(bytes, this.cursor, bs, 0, count);
this.cursor += count;
return bs;
}
}
}
| 31.861702 | 127 | 0.630384 |
00ac9acee407fbc6654f000174160770b290d49b | 519 | package cn.yuyangyang.weixin;
import cn.yuyangyang.weixin.service.PassiveReplyService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class WeixinCqmygApplicationTests {
@Autowired
private PassiveReplyService passiveReplyService;
@Test
void dbTest() {
String s = passiveReplyService.selectByKeyWord("abc", "dfg", "lxt");
System.out.println(s);
}
}
| 22.565217 | 76 | 0.755299 |
988f58413f404061d039d94c63d130755347bc28 | 2,284 | package org.finos.symphony.toolkit.spring.api.factories;
import java.util.List;
import javax.net.ssl.TrustManager;
import org.finos.symphony.toolkit.spring.api.builders.ApiBuilderFactory;
import org.finos.symphony.toolkit.spring.api.health.AgentHealthHelper;
import org.finos.symphony.toolkit.spring.api.properties.EndpointProperties;
import org.finos.symphony.toolkit.spring.api.properties.PodProperties;
import org.springframework.boot.actuate.health.HealthContributorRegistry;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.symphony.api.bindings.ApiBuilder;
import com.symphony.api.bindings.ApiWrapper;
import com.symphony.api.id.SymphonyIdentity;
import io.micrometer.core.instrument.MeterRegistry;
/**
* Creates ApiInstances with health endpoint and metrics, if a {@link HealthIndicatorRegistry} is defined.
*
* @author Rob Moffat
*/
public class DefaultApiInstanceFactory extends TokenManagingApiInstanceFactory {
protected HealthContributorRegistry registry;
protected MeterRegistry mr;
protected ObjectMapper om;
public DefaultApiInstanceFactory(ApiBuilderFactory apiBuilderFactory, HealthContributorRegistry registry, MeterRegistry meter, ObjectMapper om) {
super(apiBuilderFactory);
this.registry = registry;
this.mr = meter;
this.om = om;
}
@Override
protected List<ApiWrapper> buildApiWrappers(PodProperties pp, SymphonyIdentity id, EndpointProperties ep) {
List<ApiWrapper> out = super.buildApiWrappers(pp, id, ep);
out.add(new MetricsApiWrapper(mr, pp, id.getCommonName(), ep.getUrl()));
return out;
}
@Override
public ApiInstance createApiInstance(SymphonyIdentity id, PodProperties pp, TrustManager[] trustManagers) throws Exception {
ApiInstance parent = super.createApiInstance(id, pp, trustManagers);
ApiBuilder agentApiBuilder = ((BasicAPIInstance) parent).agentApiBuilder;
AgentHealthHelper agentHealth = new AgentHealthHelper(agentApiBuilder);
HealthCheckingApiInstance out = new HealthCheckingApiInstance(parent, agentHealth);
if (registry != null) {
String healthIndicatorName = "symphony-api-"+id.getCommonName()+"-"+pp.getId();
if (registry.getContributor(healthIndicatorName) == null) {
registry.registerContributor(healthIndicatorName, out);
}
}
return out;
}
}
| 36.83871 | 147 | 0.798161 |
e19555cb26a5a4582fb93cf64ee56dc3c874bdf3 | 5,091 | /*
* Copyright 2000-2020 Vaadin Ltd.
*
* 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.vaadin.flow.tutorial.theme;
import java.util.Arrays;
import java.util.List;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.textfield.TextFieldVariant;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouterLayout;
import com.vaadin.flow.theme.AbstractTheme;
import com.vaadin.flow.theme.NoTheme;
import com.vaadin.flow.theme.Theme;
import com.vaadin.flow.theme.lumo.Lumo;
import com.vaadin.flow.theme.material.Material;
import com.vaadin.flow.tutorial.annotations.CodeFor;
@CodeFor("../documentation-themes/theme-variants.asciidoc")
public class UsingComponentThemes {
@Route(value = "")
public class DefaultLumoApplication extends Div {
}
// tag::apptheme[]
@Theme("my-theme")
public class Application extends SpringBootServletInitializer implements AppShellConfigurator {
}
// end::apptheme[]
// tag::lumo[]
@Route(value = "")
@Theme(themeClass = Lumo.class)
public class LumoApplication extends Div {
}
// end::lumo[]
// tag::material[]
@Route(value = "")
@Theme(themeClass = Material.class)
public class MaterialApplication extends Div {
}
// end::material[]
//
@Route(value = "")
@Theme("my-theme")
public class MyApplication extends Div {
}
@Theme("my-theme")
public class MainLayout extends Div implements RouterLayout {
}
@Route(value = "", layout = MainLayout.class)
public class HomeView extends Div {
}
@Route(value = "blog", layout = MainLayout.class)
public class BlogPost extends Div {
}
// tag::notheme[]
@Route(value = "")
@NoTheme
public class UnThemedApplication extends Div {
}
// end::notheme[]
@Route(value = "")
@Theme(themeClass = Lumo.class, variant = "large")
public class LargeThemedApplication extends Div {
}
@Route(value = "")
// tag::lumo-dark[]
@Theme(themeClass = Lumo.class, variant = Lumo.DARK)
// end::lumo-dark[]
public class DarkApplication extends Div {
}
@Route(value = "")
// tag::material-dark[]
@Theme(value = Material.class, variant = Material.DARK)
// end::material-dark[]
public class DarkMaterialApplication extends Div {
}
public class Button extends Component {
public Button(String string) {
}
public void addThemeVariants(ButtonVariant... vars) {
}
public List<String> getThemeNames() {
return null;
}
}
{
// tag::themed-button[]
// Using the high-level HasTheme API
Button button = new Button("Themed button");
button.addThemeVariants(ButtonVariant.LUMO_PRIMARY,
ButtonVariant.LUMO_SMALL);
// end::themed-button[]
}
{
// tag::themed-button2[]
Button button = new Button("Themed button");
button.getThemeNames().addAll(Arrays.asList("primary", "small"));
// end::themed-button2[]
}
{
// tag::themed-button3[]
// Using the low-level Element API
Button button = new Button("Themed button");
String themeAttributeName = "theme";
String oldValue = button.getElement().getAttribute(themeAttributeName);
String variantsToAdd = "primary small";
button.getElement().setAttribute(themeAttributeName,
oldValue == null || oldValue.isEmpty() ? variantsToAdd
: ' ' + variantsToAdd);
// end::themed-button3[]
}
{
// tag::combobox-variant[]
ComboBox comboBox = new ComboBox();
comboBox.getElement().setAttribute("theme", TextFieldVariant.LUMO_SMALL.getVariantName());
// end::combobox-variant[]
}
// tag::lumo-compact[]
@JsModule("@vaadin/vaadin-lumo-styles/presets/compact.js")
@Theme(Lumo.class)
// end::lumo-compact[]
public class CompactMainLayout extends Div implements RouterLayout {
}
@JsModule("@vaadin/vaadin-lumo-styles/color.js")
public class MyTheme implements AbstractTheme {
@Override
public String getBaseUrl() {
return "/src/";
}
@Override
public String getThemeUrl() {
return "/theme/myTheme/";
}
}
}
| 29.598837 | 99 | 0.65056 |
d36697298f7623f652077fe0574910c2217472b5 | 875 | package linkedlist;
/**
* Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val,
* and return the new head.
* Example 1:
*
* Input: head = [1,2,6,3,4,5,6], val = 6
* Output: [1,2,3,4,5]
*/
public class RemoveLinkedListElements {
//use a pre node, we only make pre node point to next node when next node's value != val;
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
while(head != null) {
if(head.val != val) {
pre.next = head;
pre = pre.next;
}
head = head.next;
}
pre.next = null;//need make pre.next = null, in case we have 1-2-3-7-7-7 where target val is 7
return dummy.next;
}
}
| 31.25 | 120 | 0.572571 |
bc4ea365b7c3a4b2ec0e349d90dc51ec719dd83f | 299 | package com.reversecoder.git.api;
public class ConnectionException extends GitApiException {
public ConnectionException(final String message) {
super(message);
}
public ConnectionException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 21.357143 | 77 | 0.715719 |
2fd524c67ac6e6e4491bd12c3009492eb84701c3 | 6,461 | package com.rc.lock.services;
import android.app.IntentService;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.support.annotation.Nullable;
import com.rc.lock.base.AppConstants;
import com.rc.lock.db.CommLockInfoManager;
import com.rc.lock.model.CommLockInfo;
import com.rc.lock.model.FaviterInfo;
import com.rc.lock.utils.NotificationUtil;
import com.rc.lock.utils.SpUtil;
import org.litepal.crud.DataSupport;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class LoadAppListService extends IntentService {
public static final String ACTION_START_LOAD_APP = "rc.lock.service.action.LOADAPP";
long time = 0;
private PackageManager mPackageManager;
@Nullable
private CommLockInfoManager mLockInfoManager;
public LoadAppListService() {
super("LoadAppListService");
}
@Override
public void onCreate() {
super.onCreate();
mPackageManager = getPackageManager();
mLockInfoManager = new CommLockInfoManager(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationUtil.createNotification(this,"Stabilisers","Stabilisers is running in the background.");
}
}
@Override
protected void onHandleIntent(Intent handleIntent) {
time = System.currentTimeMillis();
boolean isInitFaviter = SpUtil.getInstance().getBoolean(AppConstants.LOCK_IS_INIT_FAVITER, false);
boolean isInitDb = SpUtil.getInstance().getBoolean(AppConstants.LOCK_IS_INIT_DB, false);
if (!isInitFaviter) {
SpUtil.getInstance().putBoolean(AppConstants.LOCK_IS_INIT_FAVITER, true);
initFavoriteApps();
}
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = mPackageManager.queryIntentActivities(intent, 0);
if (isInitDb) {
List<ResolveInfo> appList = new ArrayList<>();
List<CommLockInfo> dbList = null;
if (mLockInfoManager != null) {
dbList = mLockInfoManager.getAllCommLockInfos();
}
for (ResolveInfo resolveInfo : resolveInfos) {
if (!resolveInfo.activityInfo.packageName.equals(AppConstants.APP_PACKAGE_NAME)) {
appList.add(resolveInfo);
}
}
if (appList.size() > dbList.size()) {
List<ResolveInfo> reslist = new ArrayList<>();
HashMap<String, CommLockInfo> hashMap = new HashMap<>();
for (CommLockInfo info : dbList) {
hashMap.put(info.getPackageName(), info);
}
for (ResolveInfo info : appList) {
if (!hashMap.containsKey(info.activityInfo.packageName)) {
reslist.add(info);
}
}
try {
if (reslist.size() != 0)
mLockInfoManager.instanceCommLockInfoTable(reslist);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
} else if (appList.size() < dbList.size()) {
List<CommLockInfo> commlist = new ArrayList<>();
HashMap<String, ResolveInfo> hashMap = new HashMap<>();
for (ResolveInfo info : appList) {
hashMap.put(info.activityInfo.packageName, info);
}
for (CommLockInfo info : dbList) {
if (!hashMap.containsKey(info.getPackageName())) {
commlist.add(info);
}
}
if (commlist.size() != 0)
mLockInfoManager.deleteCommLockInfoTable(commlist);
}
} else {
SpUtil.getInstance().putBoolean(AppConstants.LOCK_IS_INIT_DB, true);
try {
if (mLockInfoManager != null) {
mLockInfoManager.instanceCommLockInfoTable(resolveInfos);
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
// Log.i("onHandleIntent", "time consuming = " + (System.currentTimeMillis() - time));
}
@Override
public void onDestroy() {
super.onDestroy();
mLockInfoManager = null;
}
public void initFavoriteApps() {
List<String> packageList = new ArrayList<>();
List<FaviterInfo> faviterInfos = new ArrayList<>();
//android
packageList.add("com.android.gallery3d");
packageList.add("com.android.mms");
packageList.add("com.android.contacts");
packageList.add("com.android.email");
packageList.add("com.android.vending");
//TODO:
// packageList.add("com.android.settings");
packageList.add("com.android.dialer");
packageList.add("com.android.camera");
//......
//google apps
packageList.add("com.google.android.apps.photos");
packageList.add("com.google.android.gm");
packageList.add("com.google.android.youtube");
packageList.add("com.google.android.apps.tachyon");//duo
//social app
packageList.add("org.thoughtcrime.securesms");//signal
packageList.add("org.telegram.messenger");
packageList.add("com.whatsapp");
packageList.add("com.twitter.android");
packageList.add("com.facebook.katana");
packageList.add("com.facebook.orca");
//etc
packageList.add("org.fdroid.fdroid");
packageList.add("org.mozilla.firefox");
packageList.add("org.schabi.newpipe");
packageList.add("eu.faircode.email");//fair mail
packageList.add("com.simplemobile.gallery.pro");// simple gallery
packageList.add("com.mediatek.filemanager");
packageList.add("com.sec.android.gallery3d");
packageList.add("com.sec.android.app.myfiles");
for (String packageName : packageList) {
FaviterInfo info = new FaviterInfo();
info.setPackageName(packageName);
faviterInfos.add(info);
}
DataSupport.deleteAll(FaviterInfo.class);
DataSupport.saveAll(faviterInfos);
}
}
| 36.297753 | 112 | 0.60486 |
aec835086a5485e255caefcc3eb92b12cfb15317 | 1,868 | package cn.jiuyoung;
/**
* AllPairsPath
*/
public class AllPairsPath {
public static void main(String[] args) {
int max = Integer.MAX_VALUE;
int[][] l = {
{ 0, -1, 3, max, max},
{max, 0, 3, 2, 2},
{max, max, 0, max, max},
{max, 1, 5, 0, max},
{max, max, max, -3, 0}
};
AllPairsPath ap = new AllPairsPath();
ap.floyd(l);
}
public void arraycopy(int[][] src, int[][] dest) {
int n = src.length;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
dest[i][j] = src[i][j];
}
}
}
public void floyd(int[][] w){
int n = w.length;
int[][] d = new int[n][n];
//print(w);
arraycopy(w, d);
for(int k = 0; k < n; k++) {
int[][] d1 = new int[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(d[i][k] != Integer.MAX_VALUE && d[k][j] != Integer.MAX_VALUE) {
d1[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]);
}else {
d1[i][j] = d[i][j];
}
}
}
System.out.println(k);
print(d1);
arraycopy(d1, d);
}
}
public void print(int[][] l) {
int n = l.length;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(l[i][j] != Integer.MAX_VALUE) {
System.out.printf("%2d ", l[i][j]);
}else {
System.out.print("**" + " ");
}
}
System.out.println();
}
System.out.println("________________________________________________");
}
} | 28.738462 | 86 | 0.361349 |
cd6f5855d7555f9f0c660fced70cb2f76aeb4d61 | 5,618 | package jaredbgreat.dldungeons.pieces.chests;
/*
* Doomlike Dungeons by is licensed the MIT License
* Copyright (c) 2014-2018 Jared Blackburn
*/
import static jaredbgreat.dldungeons.pieces.chests.LootType.GEAR;
import static jaredbgreat.dldungeons.pieces.chests.LootType.HEAL;
import static jaredbgreat.dldungeons.pieces.chests.LootType.LOOT;
import java.util.Random;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemBow;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.item.ItemTool;
/**
* A representation of all available loot by type and level. This class
* is actually primarily responsible for selecting specific items of
* the requested type and level rather than for storage, though it
* does store arrays of LootList for use in the selection process.
*
* @author Jared Blackburn
*
*/
public class LootCategory {
public static final int LEVELS = 7;
private final LootListSet lists;
public LootList[] gear;
public LootList[] heal;
public LootList[] loot;
public LootCategory(LootListSet listset) {
lists = listset;
gear = new LootList[]{lists.gear1, lists.gear2,
lists.gear3, lists.gear4, lists.gear5, lists.gear6, lists.gear7};
heal = new LootList[]{lists.heal1, lists.heal2,
lists.heal3, lists.heal4, lists.heal5, lists.heal6, lists.heal7};
loot = new LootList[]{lists.loot1, lists.loot2,
lists.loot3, lists.loot4, lists.loot5, lists.loot6, lists.loot7};
};
/**
* Takes the loots type and level and returns an item stack of a random
* item fitting the type and level supplied.
*
* @param type
* @param level
* @param random
* @return
*/
public LootResult getLoot(LootType type, int level, Random random) {
if(level <= 6) {
level = Math.min(6, (level + random.nextInt(2) - random.nextInt(2)));
}
if(level < 0) level = 0;
switch(type) {
case GEAR:
if(random.nextBoolean()) {
return getEnchantedGear(level, random);
} else {
int l = Math.min(6, level);
return enchantedLowerLevel(gear[Math.min(6, l)].getLoot(random), l, random);
}
case HEAL:
int l = Math.min(6, level);
return new LootResult(heal[Math.min(6, l)].getLoot(random).getStack(random), l);
case LOOT:
if(level > 6) {
if(level > random.nextInt(100)) {
return new LootResult(lists.special.getLoot(random).getStack(random), 7);
} else {
level = 6;
}
}
if(random.nextInt(10) == 0) {
return getEnchantedBook(level, random);
} else {
return new LootResult(loot[level].getLoot(random).getStack(random), level);
}
case RANDOM:
default:
switch(random.nextInt(3)) {
case 0:
return getLoot(GEAR, level, random);
case 1:
return getLoot(HEAL, level, random);
case 2:
default:
return getLoot(LOOT, level, random);
}
}
}
/**
* Returns an item stack from the gear list with some of the items value
* (in terms of loot level) possibly converted to random enchantments and
* the remained used as the loot level of the item itself.
*
* @param lootLevel
* @param random
* @return
*/
private LootResult getEnchantedGear(int lootLevel, Random random) {
ItemStack out;
float portion = random.nextFloat() / 2f;
int lootPart = Math.min(6, Math.max(0, (int)((((float)lootLevel) * (1f - portion)) + 0.5f)));
LootItem item = gear[lootPart].getLoot(random);
int diff = lootLevel - item.level + 1;
int enchPart =Math.min((5 + (diff * (diff + 1) / 2) * 5), diff * 10);
if(enchPart >= 1 && isEnchantable(item)) {
out = item.getStack(random);
out = EnchantmentHelper.addRandomEnchantment(random, out, enchPart, random.nextBoolean());
} else {
return enchantedLowerLevel(gear[Math.min(6, lootLevel)].getLoot(random), lootLevel, random);
}
return new LootResult(out, Math.min(lootLevel, 6));
}
/**
* Returns an item stack from the gear list with some of the items value
* (in terms of loot level) possibly converted to random enchantments and
* the remained used as the loot level of the item itself.
*
* @param lootLevel
* @param random
* @return
*/
private LootResult enchantedLowerLevel(LootItem item, int level, Random random) {
ItemStack out;
int diff = level - item.level;
if(isEnchantable(item) && (diff > random.nextInt(2))) {
int enchPart = Math.min((5 + (level * (level + 1) / 2) * 5), level * 10);
out = item.getStack(random);
out = EnchantmentHelper.addRandomEnchantment(random, out, enchPart, random.nextBoolean());
} else {
out = item.getStack(random);
}
return new LootResult(out, level);
}
/**
* True if the item is in a category that should be considered
* for possible enchantment.
*
* @param in
* @return
*/
private boolean isEnchantable(LootItem in) {
Item item = (Item)in.item;
return (((in.nbtData == null) || in.nbtData.isEmpty())
&& (item instanceof ItemSword
|| item instanceof ItemTool
|| item instanceof ItemArmor
|| item instanceof ItemBow));
}
/**
* Creates a random enchanted book and returns it as an ItemStack
*
* @param level
* @param random
* @return
*/
private LootResult getEnchantedBook(int level, Random random) {
ItemStack out = new ItemStack(Items.BOOK, 1);
out = EnchantmentHelper.addRandomEnchantment(random, out, Math.min(30, (int)(level * 7.5)), true);
return new LootResult(out, Math.min(level, 6));
}
public LootListSet getLists() {
return lists;
}
}
| 29.108808 | 100 | 0.683695 |
ddb4fdeb3def1b79da880c6e96bb7dde8105ec33 | 2,348 | /**
* Copyright (C) 2017 - present McLeod Moores Software Limited. All rights reserved.
*/
package com.mcleodmoores.analytics.financial.curve.interestrate.curvebuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.mcleodmoores.analytics.financial.index.IborTypeIndex;
import com.mcleodmoores.analytics.financial.index.OvernightIndex;
import com.opengamma.id.UniqueIdentifiable;
import com.opengamma.util.ArgumentChecker;
/**
* A builder that contains information about any pre-constructed curves that will be used by the {@link HullWhiteMethodCurveBuilder}.
*/
public class HullWhiteMethodPreConstructedCurveTypeSetUp extends HullWhiteMethodCurveSetUp implements PreConstructedCurveTypeSetUp {
private UniqueIdentifiable _discountingCurveId;
private List<IborTypeIndex> _iborCurveIndices;
private List<OvernightIndex> _overnightCurveIndices;
HullWhiteMethodPreConstructedCurveTypeSetUp(final HullWhiteMethodCurveSetUp builder) {
super(builder);
}
@Override
public HullWhiteMethodPreConstructedCurveTypeSetUp forDiscounting(final UniqueIdentifiable id) {
_discountingCurveId = ArgumentChecker.notNull(id, "id");
return this;
}
@Override
public HullWhiteMethodPreConstructedCurveTypeSetUp forIndex(final IborTypeIndex... indices) {
ArgumentChecker.notEmpty(indices, "indices");
if (_iborCurveIndices == null) {
_iborCurveIndices = new ArrayList<>();
}
_iborCurveIndices.addAll(Arrays.asList(indices));
return this;
}
@Override
public HullWhiteMethodPreConstructedCurveTypeSetUp forIndex(final OvernightIndex... indices) {
ArgumentChecker.notEmpty(indices, "indices");
if (_overnightCurveIndices == null) {
_overnightCurveIndices = new ArrayList<>();
}
_overnightCurveIndices.addAll(Arrays.asList(indices));
return this;
}
@Override
public UniqueIdentifiable getDiscountingCurveId() {
return _discountingCurveId;
}
@Override
public List<IborTypeIndex> getIborCurveIndices() {
return _iborCurveIndices == null ? null : Collections.unmodifiableList(_iborCurveIndices);
}
@Override
public List<OvernightIndex> getOvernightCurveIndices() {
return _overnightCurveIndices == null ? null : Collections.unmodifiableList(_overnightCurveIndices);
}
}
| 33.542857 | 133 | 0.783646 |
5540857ed2d562dcf1fb3dd0653c67f09c5c59e7 | 671 | package rero.dcc;
import java.net.ConnectException;
import java.net.Socket;
public class ConnectDCC extends GenericDCC {
protected String server;
protected int port;
public ConnectDCC(String _server, int _port) {
server = _server;
port = _port;
}
public int getPort() {
return port;
}
public String getHost() {
return server;
}
public Socket establishConnection() {
try {
Socket sock = new Socket(server, port);
return sock;
} catch (ConnectException cex) {
getImplementation().fireError(cex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
getImplementation().fireError(ex.getMessage());
}
return null;
}
}
| 18.135135 | 51 | 0.700447 |
7595e7611137ba36d4b6cb421153ac9bb3914dc8 | 14,153 | /*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.dts.v20180330.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class MigrateJobInfo extends AbstractModel{
/**
* 数据迁移任务ID
*/
@SerializedName("JobId")
@Expose
private String JobId;
/**
* 数据迁移任务名称
*/
@SerializedName("JobName")
@Expose
private String JobName;
/**
* 迁移任务配置选项
*/
@SerializedName("MigrateOption")
@Expose
private MigrateOption MigrateOption;
/**
* 源实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
*/
@SerializedName("SrcDatabaseType")
@Expose
private String SrcDatabaseType;
/**
* 源实例接入类型,值包括:extranet(外网),cvm(cvm自建实例),dcg(专线接入的实例),vpncloud(云vpn接入的实例),cdb(腾讯云数据库实例),ccn(云联网实例)
*/
@SerializedName("SrcAccessType")
@Expose
private String SrcAccessType;
/**
* 源实例信息,具体内容跟迁移任务类型相关
*/
@SerializedName("SrcInfo")
@Expose
private SrcInfo SrcInfo;
/**
* 目标实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
*/
@SerializedName("DstDatabaseType")
@Expose
private String DstDatabaseType;
/**
* 目标实例接入类型,目前支持:cdb(腾讯云数据库实例)
*/
@SerializedName("DstAccessType")
@Expose
private String DstAccessType;
/**
* 目标实例信息
*/
@SerializedName("DstInfo")
@Expose
private DstInfo DstInfo;
/**
* 需要迁移的源数据库表信息,如果需要迁移的是整个实例,该字段为[]
*/
@SerializedName("DatabaseInfo")
@Expose
private String DatabaseInfo;
/**
* 任务创建(提交)时间
*/
@SerializedName("CreateTime")
@Expose
private String CreateTime;
/**
* 任务开始执行时间
*/
@SerializedName("StartTime")
@Expose
private String StartTime;
/**
* 任务执行结束时间
*/
@SerializedName("EndTime")
@Expose
private String EndTime;
/**
* 任务状态,取值为:1-创建中(Creating),3-校验中(Checking)4-校验通过(CheckPass),5-校验不通过(CheckNotPass),7-任务运行(Running),8-准备完成(ReadyComplete),9-任务成功(Success),10-任务失败(Failed),11-撤销中(Stopping),12-完成中(Completing)
*/
@SerializedName("Status")
@Expose
private Long Status;
/**
* 任务详情
*/
@SerializedName("Detail")
@Expose
private MigrateDetailInfo Detail;
/**
* 任务错误信息提示,当任务发生错误时,不为null或者空值
*/
@SerializedName("ErrorInfo")
@Expose
private ErrorInfo [] ErrorInfo;
/**
* 标签
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("Tags")
@Expose
private TagItem [] Tags;
/**
* Get 数据迁移任务ID
* @return JobId 数据迁移任务ID
*/
public String getJobId() {
return this.JobId;
}
/**
* Set 数据迁移任务ID
* @param JobId 数据迁移任务ID
*/
public void setJobId(String JobId) {
this.JobId = JobId;
}
/**
* Get 数据迁移任务名称
* @return JobName 数据迁移任务名称
*/
public String getJobName() {
return this.JobName;
}
/**
* Set 数据迁移任务名称
* @param JobName 数据迁移任务名称
*/
public void setJobName(String JobName) {
this.JobName = JobName;
}
/**
* Get 迁移任务配置选项
* @return MigrateOption 迁移任务配置选项
*/
public MigrateOption getMigrateOption() {
return this.MigrateOption;
}
/**
* Set 迁移任务配置选项
* @param MigrateOption 迁移任务配置选项
*/
public void setMigrateOption(MigrateOption MigrateOption) {
this.MigrateOption = MigrateOption;
}
/**
* Get 源实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
* @return SrcDatabaseType 源实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
*/
public String getSrcDatabaseType() {
return this.SrcDatabaseType;
}
/**
* Set 源实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
* @param SrcDatabaseType 源实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
*/
public void setSrcDatabaseType(String SrcDatabaseType) {
this.SrcDatabaseType = SrcDatabaseType;
}
/**
* Get 源实例接入类型,值包括:extranet(外网),cvm(cvm自建实例),dcg(专线接入的实例),vpncloud(云vpn接入的实例),cdb(腾讯云数据库实例),ccn(云联网实例)
* @return SrcAccessType 源实例接入类型,值包括:extranet(外网),cvm(cvm自建实例),dcg(专线接入的实例),vpncloud(云vpn接入的实例),cdb(腾讯云数据库实例),ccn(云联网实例)
*/
public String getSrcAccessType() {
return this.SrcAccessType;
}
/**
* Set 源实例接入类型,值包括:extranet(外网),cvm(cvm自建实例),dcg(专线接入的实例),vpncloud(云vpn接入的实例),cdb(腾讯云数据库实例),ccn(云联网实例)
* @param SrcAccessType 源实例接入类型,值包括:extranet(外网),cvm(cvm自建实例),dcg(专线接入的实例),vpncloud(云vpn接入的实例),cdb(腾讯云数据库实例),ccn(云联网实例)
*/
public void setSrcAccessType(String SrcAccessType) {
this.SrcAccessType = SrcAccessType;
}
/**
* Get 源实例信息,具体内容跟迁移任务类型相关
* @return SrcInfo 源实例信息,具体内容跟迁移任务类型相关
*/
public SrcInfo getSrcInfo() {
return this.SrcInfo;
}
/**
* Set 源实例信息,具体内容跟迁移任务类型相关
* @param SrcInfo 源实例信息,具体内容跟迁移任务类型相关
*/
public void setSrcInfo(SrcInfo SrcInfo) {
this.SrcInfo = SrcInfo;
}
/**
* Get 目标实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
* @return DstDatabaseType 目标实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
*/
public String getDstDatabaseType() {
return this.DstDatabaseType;
}
/**
* Set 目标实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
* @param DstDatabaseType 目标实例数据库类型:mysql,redis,mongodb,postgresql,mariadb,percona
*/
public void setDstDatabaseType(String DstDatabaseType) {
this.DstDatabaseType = DstDatabaseType;
}
/**
* Get 目标实例接入类型,目前支持:cdb(腾讯云数据库实例)
* @return DstAccessType 目标实例接入类型,目前支持:cdb(腾讯云数据库实例)
*/
public String getDstAccessType() {
return this.DstAccessType;
}
/**
* Set 目标实例接入类型,目前支持:cdb(腾讯云数据库实例)
* @param DstAccessType 目标实例接入类型,目前支持:cdb(腾讯云数据库实例)
*/
public void setDstAccessType(String DstAccessType) {
this.DstAccessType = DstAccessType;
}
/**
* Get 目标实例信息
* @return DstInfo 目标实例信息
*/
public DstInfo getDstInfo() {
return this.DstInfo;
}
/**
* Set 目标实例信息
* @param DstInfo 目标实例信息
*/
public void setDstInfo(DstInfo DstInfo) {
this.DstInfo = DstInfo;
}
/**
* Get 需要迁移的源数据库表信息,如果需要迁移的是整个实例,该字段为[]
* @return DatabaseInfo 需要迁移的源数据库表信息,如果需要迁移的是整个实例,该字段为[]
*/
public String getDatabaseInfo() {
return this.DatabaseInfo;
}
/**
* Set 需要迁移的源数据库表信息,如果需要迁移的是整个实例,该字段为[]
* @param DatabaseInfo 需要迁移的源数据库表信息,如果需要迁移的是整个实例,该字段为[]
*/
public void setDatabaseInfo(String DatabaseInfo) {
this.DatabaseInfo = DatabaseInfo;
}
/**
* Get 任务创建(提交)时间
* @return CreateTime 任务创建(提交)时间
*/
public String getCreateTime() {
return this.CreateTime;
}
/**
* Set 任务创建(提交)时间
* @param CreateTime 任务创建(提交)时间
*/
public void setCreateTime(String CreateTime) {
this.CreateTime = CreateTime;
}
/**
* Get 任务开始执行时间
* @return StartTime 任务开始执行时间
*/
public String getStartTime() {
return this.StartTime;
}
/**
* Set 任务开始执行时间
* @param StartTime 任务开始执行时间
*/
public void setStartTime(String StartTime) {
this.StartTime = StartTime;
}
/**
* Get 任务执行结束时间
* @return EndTime 任务执行结束时间
*/
public String getEndTime() {
return this.EndTime;
}
/**
* Set 任务执行结束时间
* @param EndTime 任务执行结束时间
*/
public void setEndTime(String EndTime) {
this.EndTime = EndTime;
}
/**
* Get 任务状态,取值为:1-创建中(Creating),3-校验中(Checking)4-校验通过(CheckPass),5-校验不通过(CheckNotPass),7-任务运行(Running),8-准备完成(ReadyComplete),9-任务成功(Success),10-任务失败(Failed),11-撤销中(Stopping),12-完成中(Completing)
* @return Status 任务状态,取值为:1-创建中(Creating),3-校验中(Checking)4-校验通过(CheckPass),5-校验不通过(CheckNotPass),7-任务运行(Running),8-准备完成(ReadyComplete),9-任务成功(Success),10-任务失败(Failed),11-撤销中(Stopping),12-完成中(Completing)
*/
public Long getStatus() {
return this.Status;
}
/**
* Set 任务状态,取值为:1-创建中(Creating),3-校验中(Checking)4-校验通过(CheckPass),5-校验不通过(CheckNotPass),7-任务运行(Running),8-准备完成(ReadyComplete),9-任务成功(Success),10-任务失败(Failed),11-撤销中(Stopping),12-完成中(Completing)
* @param Status 任务状态,取值为:1-创建中(Creating),3-校验中(Checking)4-校验通过(CheckPass),5-校验不通过(CheckNotPass),7-任务运行(Running),8-准备完成(ReadyComplete),9-任务成功(Success),10-任务失败(Failed),11-撤销中(Stopping),12-完成中(Completing)
*/
public void setStatus(Long Status) {
this.Status = Status;
}
/**
* Get 任务详情
* @return Detail 任务详情
*/
public MigrateDetailInfo getDetail() {
return this.Detail;
}
/**
* Set 任务详情
* @param Detail 任务详情
*/
public void setDetail(MigrateDetailInfo Detail) {
this.Detail = Detail;
}
/**
* Get 任务错误信息提示,当任务发生错误时,不为null或者空值
* @return ErrorInfo 任务错误信息提示,当任务发生错误时,不为null或者空值
*/
public ErrorInfo [] getErrorInfo() {
return this.ErrorInfo;
}
/**
* Set 任务错误信息提示,当任务发生错误时,不为null或者空值
* @param ErrorInfo 任务错误信息提示,当任务发生错误时,不为null或者空值
*/
public void setErrorInfo(ErrorInfo [] ErrorInfo) {
this.ErrorInfo = ErrorInfo;
}
/**
* Get 标签
注意:此字段可能返回 null,表示取不到有效值。
* @return Tags 标签
注意:此字段可能返回 null,表示取不到有效值。
*/
public TagItem [] getTags() {
return this.Tags;
}
/**
* Set 标签
注意:此字段可能返回 null,表示取不到有效值。
* @param Tags 标签
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setTags(TagItem [] Tags) {
this.Tags = Tags;
}
public MigrateJobInfo() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public MigrateJobInfo(MigrateJobInfo source) {
if (source.JobId != null) {
this.JobId = new String(source.JobId);
}
if (source.JobName != null) {
this.JobName = new String(source.JobName);
}
if (source.MigrateOption != null) {
this.MigrateOption = new MigrateOption(source.MigrateOption);
}
if (source.SrcDatabaseType != null) {
this.SrcDatabaseType = new String(source.SrcDatabaseType);
}
if (source.SrcAccessType != null) {
this.SrcAccessType = new String(source.SrcAccessType);
}
if (source.SrcInfo != null) {
this.SrcInfo = new SrcInfo(source.SrcInfo);
}
if (source.DstDatabaseType != null) {
this.DstDatabaseType = new String(source.DstDatabaseType);
}
if (source.DstAccessType != null) {
this.DstAccessType = new String(source.DstAccessType);
}
if (source.DstInfo != null) {
this.DstInfo = new DstInfo(source.DstInfo);
}
if (source.DatabaseInfo != null) {
this.DatabaseInfo = new String(source.DatabaseInfo);
}
if (source.CreateTime != null) {
this.CreateTime = new String(source.CreateTime);
}
if (source.StartTime != null) {
this.StartTime = new String(source.StartTime);
}
if (source.EndTime != null) {
this.EndTime = new String(source.EndTime);
}
if (source.Status != null) {
this.Status = new Long(source.Status);
}
if (source.Detail != null) {
this.Detail = new MigrateDetailInfo(source.Detail);
}
if (source.ErrorInfo != null) {
this.ErrorInfo = new ErrorInfo[source.ErrorInfo.length];
for (int i = 0; i < source.ErrorInfo.length; i++) {
this.ErrorInfo[i] = new ErrorInfo(source.ErrorInfo[i]);
}
}
if (source.Tags != null) {
this.Tags = new TagItem[source.Tags.length];
for (int i = 0; i < source.Tags.length; i++) {
this.Tags[i] = new TagItem(source.Tags[i]);
}
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "JobId", this.JobId);
this.setParamSimple(map, prefix + "JobName", this.JobName);
this.setParamObj(map, prefix + "MigrateOption.", this.MigrateOption);
this.setParamSimple(map, prefix + "SrcDatabaseType", this.SrcDatabaseType);
this.setParamSimple(map, prefix + "SrcAccessType", this.SrcAccessType);
this.setParamObj(map, prefix + "SrcInfo.", this.SrcInfo);
this.setParamSimple(map, prefix + "DstDatabaseType", this.DstDatabaseType);
this.setParamSimple(map, prefix + "DstAccessType", this.DstAccessType);
this.setParamObj(map, prefix + "DstInfo.", this.DstInfo);
this.setParamSimple(map, prefix + "DatabaseInfo", this.DatabaseInfo);
this.setParamSimple(map, prefix + "CreateTime", this.CreateTime);
this.setParamSimple(map, prefix + "StartTime", this.StartTime);
this.setParamSimple(map, prefix + "EndTime", this.EndTime);
this.setParamSimple(map, prefix + "Status", this.Status);
this.setParamObj(map, prefix + "Detail.", this.Detail);
this.setParamArrayObj(map, prefix + "ErrorInfo.", this.ErrorInfo);
this.setParamArrayObj(map, prefix + "Tags.", this.Tags);
}
}
| 27.535019 | 207 | 0.619586 |
2b4aaf8e720a2af56b2f949aa25f5fa0c276b56a | 2,694 | package Model;
/**
* LoginManager
*
* Connects with the server of the bank using pin an cartnumber.
*/
import org.json.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.io.*;
public class LoginManager {
// Test method for loginManager
public static void main(String[] args) {
LoginManager loginManager = LoginManager.tryLogin(1, 1);
}
private final int acountid;
private final String accountname;
private final int balance;
// Private default constructor
private LoginManager(int acountid, String accountname, int balance) {
this.acountid = acountid;
this.accountname = accountname;
this.balance = balance;
}
// Returns an loginManager when succeeded, else null
public final static LoginManager tryLogin(int cardNumber, int pincode) {
try {
JSONObject obj = loadData("https://www.quickbanking.ml:64405//JSON_API/getbalance.php");
return new LoginManager(obj.getInt("id"), obj.getString("accountname"), obj.getInt("balance"));
} catch (Exception e) {
System.err.println("error while initialising login");
System.err.println(e.toString());
}
return null;
}
// Loads JSONobjest with a post request from the given url
private static JSONObject loadData(String urlStr) {
try {
URL url = new URL(urlStr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setDoOutput(true);
http.setRequestMethod("POST");
byte[] out = "pin=1&cartnumber=1".getBytes(StandardCharsets.UTF_8);
int length = out.length;
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
http.connect();
try (OutputStream os = http.getOutputStream()) {
os.write(out);
}
InputStream stream = http.getInputStream();
String str = new String(stream.readAllBytes());
System.out.println(str);
return new JSONObject(str);
} catch (MalformedURLException e) {
System.out.println("malformed URL");
} catch (Exception e) {
System.out.println(e.toString());
System.out.println(e.getMessage());
System.out.println("error with loading data");
}
return null;
}
// Returns balance
public int getBalance() {
return balance;
}
// returns account name
public String getAccountname() {
return accountname;
}
} | 31.325581 | 107 | 0.616555 |
55003bb66fbe1892345eb92d719b55b7aa333345 | 61 | package com.github.nyanyaww.client;
public class Client {
}
| 12.2 | 35 | 0.770492 |
c564505ad9398ffa94884ad4271579954fb99317 | 478 | package pay.one.faster.requester.domain.repository;
import pay.one.faster.requester.domain.Requester;
import pay.one.faster.requester.domain.data.RegisterRequester;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* @author claudioed on 2019-02-23.
* Project requester
*/
public interface RequesterDataRepository {
Flux<Requester> all();
Mono<Requester> find(String id);
Mono<Requester> register(RegisterRequester registerRequester);
}
| 22.761905 | 64 | 0.784519 |
68a8b01bc9095a10996893638c2871a7da43ac78 | 77 | public class MessagePrinter {
public native void printMsg(String msg);
}
| 19.25 | 44 | 0.753247 |
44bac020460cbd4cd4d68b54037592cb7dfbb032 | 2,167 | package org.educama.shipment.process.tasks;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.runtime.CaseExecution;
import org.camunda.bpm.engine.task.Task;
import org.educama.shipment.control.ShipmentControlService;
import org.educama.shipment.process.ShipmentCaseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/**
* Class representing an interface to the Complete Shipment Order Task.
*/
@Component
public class CompleteShipmentOrderTask {
private ProcessEngine processEngine;
private ShipmentControlService shipmentControlService;
@Autowired
public CompleteShipmentOrderTask(ProcessEngine processEngine,
ShipmentControlService shipmentControlService) {
this.processEngine = processEngine;
this.shipmentControlService = shipmentControlService;
}
public boolean isActive(String trackingId) {
return processEngine.getCaseService().createCaseExecutionQuery()
.activityId(ShipmentCaseConstants.PLAN_ITEM_HUMAN_TASK_COMPLETE_SHIPMENT_ORDER)
.caseInstanceBusinessKey(trackingId)
.active()
.singleResult() != null;
}
public boolean canBeCompleted(String trackingId) {
return shipmentControlService.isShipmentOrderComplete(trackingId);
}
public void complete(String trackingId) {
CaseExecution completeShipmentOrderCaseExecution = processEngine.getCaseService().createCaseExecutionQuery()
.activityId(ShipmentCaseConstants.PLAN_ITEM_HUMAN_TASK_COMPLETE_SHIPMENT_ORDER)
.caseInstanceBusinessKey(trackingId)
.active()
.singleResult();
Assert.notNull(completeShipmentOrderCaseExecution);
Task task = processEngine.getTaskService().createTaskQuery()
.caseExecutionId(completeShipmentOrderCaseExecution.getId())
.singleResult();
Assert.notNull(task);
processEngine.getTaskService().complete(task.getId());
}
}
| 37.362069 | 116 | 0.726811 |
120f646f49cadd0676bc0a1fb7c987845b6f8f63 | 1,271 | package br.eti.arthurgregorio.library.application.jobs;
import br.eti.arthurgregorio.library.domain.entities.administration.ActivationStatus;
import br.eti.arthurgregorio.library.domain.entities.administration.UserActivation;
import br.eti.arthurgregorio.library.domain.repositories.administration.UserActivationRepository;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author Arthur Gregorio
*
* @version 1.0.0
* @since 1.0.0, 06/05/2020
*/
@Component
public class UserActivationExpirationJob {
private UserActivationRepository userActivationRepository;
/**
*
* @param userActivationRepository
*/
public UserActivationExpirationJob(UserActivationRepository userActivationRepository) {
this.userActivationRepository = userActivationRepository;
}
/**
*
*/
@Scheduled(cron = "0 0/30 * * * ?")
public void updateExpiredActivations() {
final var activations = this.userActivationRepository.findByActivationStatus(ActivationStatus.WAITING);
activations.stream()
.filter(UserActivation::isExpired)
.forEach(activation -> this.userActivationRepository.save(activation.expire()));
}
} | 31.775 | 111 | 0.744296 |
179afebc3037239a9c8e65ac3d54d45d8bdb2b86 | 599 | /*
* 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 devman.gui;
import java.util.Date;
/**
*
* @author Sergio Flores
*/
public interface SGuiLogEntryMask {
public Date getDate();
public double getTime();
public String getType();
public String getUser();
public String getNotes();
public String getInsertUser();
public Date getInsertTimestamp();
public String getUpdateUser();
public Date getUpdateTimestamp();
}
| 23.038462 | 79 | 0.701169 |
00beb16e2c9c4cab2961d720aa23bce247b343f0 | 825 | package com.blackducksoftware.integration.hub.alert.channel.email.template;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
public class FreemarkerTargetTest {
@Test
public void testFreemarker() {
final FreemarkerTarget freemarkerTarget = new FreemarkerTarget();
final Map<String, String> target1 = new HashMap<>();
target1.put("key1", "value1");
final Map<String, String> target2 = new HashMap<>();
target2.put("key2", "value2");
freemarkerTarget.add(target1);
freemarkerTarget.add(target2);
final List<Map<String, String>> expected = Arrays.asList(target1, target2);
assertEquals(expected, freemarkerTarget);
}
}
| 25.78125 | 83 | 0.694545 |
827e91ab75a98126ec79c9b8025341daa014401b | 67 | /**
*
*/
package uk.ac.ox.ndph.mts.role_service.controller.dtos;
| 13.4 | 55 | 0.686567 |
87b73c3242dd1dad562ef827a11ab55ec5d21e56 | 1,121 | package ch.epfl.sweng.nodes;
import java.util.Objects;
/**
* Represents a variable in Teal.
* As Teal does not have variable declarations, only parameters are variables.
*/
public final class TealVariableNode extends TealNode {
/**
* The variable's name.
*/
public final String name;
/**
* Initializes a new variable node with the given name.
*
* @param name The name.
*/
public TealVariableNode(final String name) {
this.name = Objects.requireNonNull(name);
}
@Override
public <T> T accept(final TealNodeVisitor<T> visitor) {
return visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final TealVariableNode that = (TealVariableNode) o;
return Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public String toString() {
return name;
}
} | 21.150943 | 78 | 0.58876 |
a5731584b82b9a02bf2d8bb10d8c65f001e5ad69 | 4,803 | package com.microsoft.windowsazure.notifications;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
public class NotificationsManager {
/**
* Key for handler class name in local storage
*/
private static final String NOTIFICATIONS_HANDLER_CLASS = "WAMS_NotificationsHandlerClass";
/**
* Key for registration id in local storage
*/
private static final String GOOGLE_CLOUD_MESSAGING_REGISTRATION_ID = "WAMS_GoogleCloudMessagingRegistrationId";
/**
* NotificationsHandler instance
*/
private static NotificationsHandler mHandler;
/**
* Handles notifications with the provided NotificationsHandler class
* @param context Application Context
* @param gcmAppId Google Cloud Messaging Application ID
* @param notificationsHandlerClass NotificationHandler class used for handling notifications
*/
public static <T extends NotificationsHandler> void handleNotifications(final Context context, final String gcmAppId, final Class<T> notificationsHandlerClass) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
setHandler(notificationsHandlerClass, context);
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String registrationId = gcm.register(gcmAppId);
setRegistrationId(registrationId, context);
NotificationsHandler handler = getHandler(context);
if (handler != null && registrationId != null) {
getHandler(context).onRegistered(context, registrationId);
}
} catch (Exception e) {
Log.e("NotificationsManager", e.toString());
}
return null;
}
}.execute();
}
/**
* Stops handlind notifications
* @param context Application Context
*/
public static void stopHandlingNotifications(final Context context) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
gcm.unregister();
String registrationId = getRegistrationId(context);
setRegistrationId(null, context);
NotificationsHandler handler = getHandler(context);
if (handler != null && registrationId != null) {
handler.onUnregistered(context, registrationId);
}
} catch (Exception e) {
Log.e("NotificationsManager", e.toString());
}
return null;
}
}.execute();
}
/**
* Retrieves the NotificationsHandler from local storage
* @param context Application Context
*/
static NotificationsHandler getHandler(Context context) {
if (mHandler == null) {
SharedPreferences prefereneces = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
String className = prefereneces.getString(NOTIFICATIONS_HANDLER_CLASS, null);
if (className != null) {
try {
Class<?> notificationsHandlerClass = Class.forName(className);
mHandler = (NotificationsHandler) notificationsHandlerClass.newInstance();
} catch (Exception e) {
return null;
}
}
}
return mHandler;
}
/**
* Retrieves the RegistrationId from local storage
* @param context Application Context
*/
private static String getRegistrationId(Context context) {
SharedPreferences prefereneces = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
String registrationId = prefereneces.getString(GOOGLE_CLOUD_MESSAGING_REGISTRATION_ID, null);
return registrationId;
}
/**
* Stores the NotificationsHandler class in local storage
* @param notificationsHandlerClass NotificationsHandler class
* @param context Application Context
*/
private static <T extends NotificationsHandler> void setHandler(Class<T> notificationsHandlerClass, Context context) {
SharedPreferences prefereneces = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
Editor editor = prefereneces.edit();
editor.putString(NOTIFICATIONS_HANDLER_CLASS, notificationsHandlerClass.getName());
editor.commit();
}
/**
* Stores the RegistrationId in local storage
* @param registrationId RegistrationId to store
* @param context Application Context
*/
private static void setRegistrationId(String registrationId, Context context) {
SharedPreferences prefereneces = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
Editor editor = prefereneces.edit();
editor.putString(GOOGLE_CLOUD_MESSAGING_REGISTRATION_ID, registrationId);
editor.commit();
}
}
| 31.188312 | 162 | 0.746825 |
a73bcc61391489abd542accff48c160e959c9a77 | 2,337 | package Tests;
import Base.ExtentTestManager;
import Base.TestBase;
import Pages.NotifyCusp;
import Pages.SignInPage;
import Pages.TopBarSection;
import com.aventstack.extentreports.Status;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class NotifyCuspTest extends TestBase {
private WebDriver driver;
@BeforeMethod
public void setUp() {
driver = getDriver();
}
@Test /*C39253*/
public void FullNameFieldIsDisplayed() {
SignInPage login = new SignInPage(driver);
TopBarSection profileIcon = new TopBarSection(driver);
TopBarSection notifyOption = new TopBarSection(driver);
NotifyCusp dialog = new NotifyCusp(driver);
String error = "Notify CUSP dialog is not shown on click of the Notify Cusp";
String test = "Testcase C39253";
login.LoginGlobalAdmin();
profileIcon.clickMenuIcon();
notifyOption.clickNotifyOption();
if (dialog.NotifyCuspDialogIsDisplayed()) {
Assert.assertTrue(true);
} else {
System.out.println(error);
ExtentTestManager.getTest().log(Status.INFO, error);
Assert.fail();
}
ExtentTestManager.getTest().log(Status.INFO, test);
}
@Test /*C39255*/
public void SendButtonIsDisabledIfDescriptionIsEmpty() {
SignInPage login = new SignInPage(driver);
TopBarSection profileIcon = new TopBarSection(driver);
TopBarSection notifyOption = new TopBarSection(driver);
NotifyCusp field = new NotifyCusp(driver);
NotifyCusp button = new NotifyCusp(driver);
String text = "Autotest";
String error = "Send button is enabled even though the description field is empty";
String test = "Testcase C39255";
login.LoginGlobalAdmin();
profileIcon.clickMenuIcon();
notifyOption.clickNotifyOption();
field.putInTitle(text);
if (button.SendButtonIsDisabled()) {
Assert.assertTrue(true);
} else {
System.out.println(error);
ExtentTestManager.getTest().log(Status.INFO, error);
Assert.fail();
}
ExtentTestManager.getTest().log(Status.INFO, test);
}
} | 30.75 | 91 | 0.661104 |
002e2303e080823c764474c95dec21a17bfdcf40 | 983 | package org.data2semantics.mustard.kernels.data;
import java.util.List;
import org.nodes.DTGraph;
import org.nodes.DTNode;
/**
* Class to represent graph data that is as one (RDF) graph, with a list of instance nodes in that one graph.
* The graph used is a DTGraph, which is a directed multigraph with labels on the nodes and links.
*
* @author Gerben
*
*/
public class SingleDTGraph implements GraphData {
private DTGraph<String,String> graph;
private List<DTNode<String,String>> instances;
public SingleDTGraph(DTGraph<String, String> graph,
List<DTNode<String, String>> instances) {
super();
this.graph = graph;
this.instances = instances;
}
public DTGraph<String, String> getGraph() {
return graph;
}
public List<DTNode<String, String>> getInstances() {
return instances;
}
/**
* returns the size of the instances list.
*
*/
public int numInstances() {
return instances.size();
}
}
| 21.369565 | 110 | 0.68057 |
f6aa100626701c10f5b7b3671416288c3306e2f0 | 7,497 | package thredds.server.wfs;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import thredds.server.config.ThreddsConfig;
/**
* A writer for a WFS compliant Geospatial XML given a print writer.
* Specifically writes the XML for WFS GetCapabilities requests.
*
* @author wchen@usgs.gov
*
*/
public class WFSGetCapabilitiesWriter {
private PrintWriter response;
private String fileOutput;
private final String server;
private List<WFSRequestType> operationList;
private List<WFSFeature> featureList;
/**
* Writes the two service sections
*/
private void writeServiceInfo() {
fileOutput += "<ows:ServiceIdentification> "
+ "<ows:Title>WFS Server on THREDDS</ows:Title> "
+ "<ows:Abstract>ncWFS uses the NetCDF Java Library to handle WFS requests</ows:Abstract> "
+ "<ows:ServiceType codeSpace=\"OGC\">WFS</ows:ServiceType> "
+ "<ows:ServiceTypeVersion>2.0.0</ows:ServiceTypeVersion> "
+ "<ows:Fees/> "
+ "<ows:AccessConstraints/> "
+ "</ows:ServiceIdentification> ";
fileOutput += "<ows:ServiceProvider> "
+ "<ows:ProviderName>" + ThreddsConfig.get("serverInformation.hostInstitution.name", "hostInstitution") + "</ows:ProviderName> "
+ "<ows:ProviderSite xlink:href=\"" + ThreddsConfig.get("serverInformation.hostInstitution.webSite", "") + "\" xlink:type=\"simple\"/> "
+ "<ows:ServiceContact/> "
+ "</ows:ServiceProvider> ";
}
/**
* Given the parameter operation name, add the operation
* to the operations metadata section.
*/
private void writeAOperation(WFSRequestType rt) {
fileOutput += "<ows:Operation name=\"" + rt.toString() + "\"> "
+ "<ows:DCP> "
+ "<ows:HTTP> "
+ "<ows:Get xlink:href=\"" + server + "?\"/> "
+ "<ows:Post xlink:href=\"" + server + "\"/> "
+ "</ows:HTTP> "
+ "</ows:DCP>";
fileOutput += "</ows:Operation> ";
}
/**
* Writes a constraint OWS element out.
*
* @param name of the constraint
* @boolean isImplemented or not
*/
private void writeAConstraint(String name, boolean isImplemented) {
String defValue;
if(isImplemented) defValue = "TRUE"; else defValue = "FALSE";
fileOutput += "<ows:Constraint name=\"" + name + "\"> "
+ "<ows:NoValues/> "
+ "<ows:DefaultValue>" + defValue +"</ows:DefaultValue> "
+ "</ows:Constraint>";
}
/**
* Writes headers and service sections
*/
private void writeHeadersAndSS() {
fileOutput += "<wfs:WFS_Capabilities xsi:schemaLocation="
+ WFSXMLHelper.encQuotes("http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd ")
+ " xmlns:xsi=" + WFSXMLHelper.encQuotes("http://www.w3.org/2001/XMLSchema-instance")
+ " xmlns:xlink=" + WFSXMLHelper.encQuotes("http://www.w3.org/1999/xlink")
+ " xmlns:gml=" + WFSXMLHelper.encQuotes("http://opengis.net/gml")
+ " xmlns:fes=" + WFSXMLHelper.encQuotes("http://www.opengis.net/fes/2.0")
+ " xmlns:ogc=" + WFSXMLHelper.encQuotes("http://www.opengis.net/ogc")
+ " xmlns:ows=" + WFSXMLHelper.encQuotes("http://www.opengis.net/ows/1.1\" xmlns:wfs=\"http://opengis.net/wfs/2.0")
+ " xmlns=" + WFSXMLHelper.encQuotes("http://www.opengis.net/wfs/2.0")
+ " version=\"2.0.0\">";
writeServiceInfo();
}
/**
* Initiate the response with an XML file with an XML header.
*/
public void startXML() {
fileOutput += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
writeHeadersAndSS();
}
/**
* Finish writing the XML file, write the end tag for WFS_Capabilities and append it all to the PrintWriter.
*
* Once a XML is finished, the WFSDataWriter is no longer usable.
*/
public void finishXML() {
fileOutput += "</wfs:WFS_Capabilities>";
this.response.append(fileOutput);
response = null;
fileOutput = null;
}
/**
* Given the parameter operation name, add the operation
* to the operations metadata section.
*/
public void addOperation(WFSRequestType rt) {
this.operationList.add(rt);
}
/**
* Takes all added operations and writes an operations metadata section.
*/
public void writeOperations() {
fileOutput += "<ows:OperationsMetadata> ";
for(WFSRequestType rt : operationList) {
writeAOperation(rt);
}
// Write parameters
fileOutput += "<ows:Parameter name=\"AcceptVersions\"> "
+ "<ows:AllowedValues> "
+ "<ows:Value>2.0.0</ows:Value>"
+ "</ows:AllowedValues>"
+ "</ows:Parameter>";
fileOutput += "<ows:Parameter name=\"AcceptFormats\">"
+ "<ows:AllowedValues> "
+ "<ows:Value>text/xml</ows:Value>"
+ "</ows:AllowedValues>"
+ "</ows:Parameter>";
fileOutput += "<ows:Parameter name=\"Sections\"> "
+ "<ows:AllowedValues> "
+ "<ows:Value>ServiceIdentification</ows:Value> "
+ "<ows:Value>ServiceProvider</ows:Value> "
+ "<ows:Value>OperationsMetadata</ows:Value> "
+ "<ows:Value>FeatureTypeList</ows:Value> "
+ "</ows:AllowedValues>"
+ "</ows:Parameter>";
fileOutput += "<ows:Parameter name=\"version\"> "
+ "<ows:AllowedValues> "
+ "<ows:Value>2.0.0</ows:Value>"
+ "</ows:AllowedValues>"
+ "</ows:Parameter>";
// Write constraints
writeAConstraint("ImplementsBasicWFS", true);
writeAConstraint("ImplementsTransactionalWFS", false);
writeAConstraint("ImplementsLockingWFS", false);
writeAConstraint("KVPEncoding", false);
writeAConstraint("XMLEncoding", true);
writeAConstraint("SOAPEncoding", false);
writeAConstraint("ImplementsInheritance", false);
writeAConstraint("ImplementsRemoteResolve", false);
writeAConstraint("ImplementsResultPaging", false);
writeAConstraint("ImplementsStandardJoins", false);
writeAConstraint("ImplementsSpatialJoins", false);
writeAConstraint("ImplementsTemporalJoins", false);
writeAConstraint("ImplementsFeatureVersioning", false);
writeAConstraint("ManageStoredQueries", false);
writeAConstraint("PagingIsTransactionSafe", false);
writeAConstraint("QueryExpressions", false);
fileOutput += "</ows:OperationsMetadata>";
}
/**
*
*/
public void writeFeatureTypes() {
fileOutput += "<FeatureTypeList> ";
for(WFSFeature wf : featureList) {
fileOutput +=
"<FeatureType> "
+ "<Name>" + wf.getName() + "</Name> "
+ "<Title>" + wf.getTitle() + "</Title> "
+ "<DefaultCRS>" + "urn:ogc:def:crs:EPSG::4326" + "</DefaultCRS>"
+ "<OutputFormats> "
+ "<Format>text/xml; subtype=gml/3.2.1</Format> "
+ "</OutputFormats> "
+ "<ows:WGS84BoundingBox dimensions=\"2\"> "
+ "<ows:LowerCorner>-180 -90</ows:LowerCorner> <ows:UpperCorner>180 90</ows:UpperCorner>"
+ "</ows:WGS84BoundingBox>"
+ "</FeatureType> ";
}
fileOutput += "</FeatureTypeList> ";
}
/**
* Add a feature to the writer's feature list.
*
* @param feature to add
*/
public void addFeature(WFSFeature feature) {
this.featureList.add(feature);
}
/**
* Opens a WFSDataWriter, writes to the HttpResponse given.
*
* @param response to write to
* @param server URI
*/
public WFSGetCapabilitiesWriter(PrintWriter response, String server){
this.response = response;
this.fileOutput = "";
this.server = server;
this.operationList = new ArrayList<WFSRequestType>();
this.featureList = new ArrayList<WFSFeature>();
}
}
| 32.881579 | 142 | 0.638789 |
33e9b84a15f0b727ac2172c7c653058f67425d18 | 175 | package daikon.dcomp;
/**
* Classes implementing this interface have been instrumented by DynComp and have implemented a
* clone method.
*/
public interface DCompClone {}
| 21.875 | 95 | 0.765714 |
b9db9803ff7188dd46fc278b5e679d9f0ccaa3ba | 372 | package ultimatetictactoe.bll.game;
import ultimatetictactoe.bll.field.IField;
/**
*
* @author mjl
*/
public interface IGameState {
IField getField();
int getMoveNumber();
void setMoveNumber(int moveNumber);
int getRoundNumber();
void setRoundNumber(int roundNumber);
int getTimePerMove();
void setTimePerMove(int milliSeconds);
}
| 14.307692 | 42 | 0.701613 |
af75b0b56dbf6d4bf57f5344f24d5eb0c3d8dda7 | 592 | package interpreter;
/**
* Command class that, when executed, makes the Turtle visible
* @author Sarahbland
*
*/
class ShowTurtleCommand extends Command{
/**
* Creates new instance of command, which can be executed at the correct time
* @param turtle is turtle who should be made visible
*/
protected ShowTurtleCommand(Turtle turtles) {
setActiveTurtles(turtles);
}
/**
* Shows turtle's image to the user
* @return 1 always
*/
@Override
protected double execute() {
getActiveTurtles().showTurtle();
return 1;
}
}
| 20.413793 | 81 | 0.650338 |
704ee73961e83eaf99ea10aaf11cb0677dab339e | 309 | package com.platzi.market.domain.repository;
import com.platzi.market.domain.Purchase;
import java.util.List;
import java.util.Optional;
public interface IPurchaseRepository {
List<Purchase> getAll();
Optional<List<Purchase>> getByClientId(String clientId);
Purchase save(Purchase purchase);
}
| 23.769231 | 60 | 0.776699 |
828f1e8d1a03f0c4f03ecad177f7a5a411fe632e | 55,439 | package org.linlinjava.litemall.db.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class WxGzhUserExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public WxGzhUserExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria(this);
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_gzh_user
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public WxGzhUserExample orderBy(String orderByClause) {
this.setOrderByClause(orderByClause);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_gzh_user
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public WxGzhUserExample orderBy(String ... orderByClauses) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < orderByClauses.length; i++) {
sb.append(orderByClauses[i]);
if (i < orderByClauses.length - 1) {
sb.append(" , ");
}
}
this.setOrderByClause(sb.toString());
return this;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andSubscribeIsNull() {
addCriterion("subscribe is null");
return (Criteria) this;
}
public Criteria andSubscribeIsNotNull() {
addCriterion("subscribe is not null");
return (Criteria) this;
}
public Criteria andSubscribeEqualTo(Byte value) {
addCriterion("subscribe =", value, "subscribe");
return (Criteria) this;
}
public Criteria andSubscribeNotEqualTo(Byte value) {
addCriterion("subscribe <>", value, "subscribe");
return (Criteria) this;
}
public Criteria andSubscribeGreaterThan(Byte value) {
addCriterion("subscribe >", value, "subscribe");
return (Criteria) this;
}
public Criteria andSubscribeGreaterThanOrEqualTo(Byte value) {
addCriterion("subscribe >=", value, "subscribe");
return (Criteria) this;
}
public Criteria andSubscribeLessThan(Byte value) {
addCriterion("subscribe <", value, "subscribe");
return (Criteria) this;
}
public Criteria andSubscribeLessThanOrEqualTo(Byte value) {
addCriterion("subscribe <=", value, "subscribe");
return (Criteria) this;
}
public Criteria andSubscribeIn(List<Byte> values) {
addCriterion("subscribe in", values, "subscribe");
return (Criteria) this;
}
public Criteria andSubscribeNotIn(List<Byte> values) {
addCriterion("subscribe not in", values, "subscribe");
return (Criteria) this;
}
public Criteria andSubscribeBetween(Byte value1, Byte value2) {
addCriterion("subscribe between", value1, value2, "subscribe");
return (Criteria) this;
}
public Criteria andSubscribeNotBetween(Byte value1, Byte value2) {
addCriterion("subscribe not between", value1, value2, "subscribe");
return (Criteria) this;
}
public Criteria andOpenidIsNull() {
addCriterion("openid is null");
return (Criteria) this;
}
public Criteria andOpenidIsNotNull() {
addCriterion("openid is not null");
return (Criteria) this;
}
public Criteria andOpenidEqualTo(String value) {
addCriterion("openid =", value, "openid");
return (Criteria) this;
}
public Criteria andOpenidNotEqualTo(String value) {
addCriterion("openid <>", value, "openid");
return (Criteria) this;
}
public Criteria andOpenidGreaterThan(String value) {
addCriterion("openid >", value, "openid");
return (Criteria) this;
}
public Criteria andOpenidGreaterThanOrEqualTo(String value) {
addCriterion("openid >=", value, "openid");
return (Criteria) this;
}
public Criteria andOpenidLessThan(String value) {
addCriterion("openid <", value, "openid");
return (Criteria) this;
}
public Criteria andOpenidLessThanOrEqualTo(String value) {
addCriterion("openid <=", value, "openid");
return (Criteria) this;
}
public Criteria andOpenidLike(String value) {
addCriterion("openid like", value, "openid");
return (Criteria) this;
}
public Criteria andOpenidNotLike(String value) {
addCriterion("openid not like", value, "openid");
return (Criteria) this;
}
public Criteria andOpenidIn(List<String> values) {
addCriterion("openid in", values, "openid");
return (Criteria) this;
}
public Criteria andOpenidNotIn(List<String> values) {
addCriterion("openid not in", values, "openid");
return (Criteria) this;
}
public Criteria andOpenidBetween(String value1, String value2) {
addCriterion("openid between", value1, value2, "openid");
return (Criteria) this;
}
public Criteria andOpenidNotBetween(String value1, String value2) {
addCriterion("openid not between", value1, value2, "openid");
return (Criteria) this;
}
public Criteria andNicknameIsNull() {
addCriterion("nickname is null");
return (Criteria) this;
}
public Criteria andNicknameIsNotNull() {
addCriterion("nickname is not null");
return (Criteria) this;
}
public Criteria andNicknameEqualTo(String value) {
addCriterion("nickname =", value, "nickname");
return (Criteria) this;
}
public Criteria andNicknameNotEqualTo(String value) {
addCriterion("nickname <>", value, "nickname");
return (Criteria) this;
}
public Criteria andNicknameGreaterThan(String value) {
addCriterion("nickname >", value, "nickname");
return (Criteria) this;
}
public Criteria andNicknameGreaterThanOrEqualTo(String value) {
addCriterion("nickname >=", value, "nickname");
return (Criteria) this;
}
public Criteria andNicknameLessThan(String value) {
addCriterion("nickname <", value, "nickname");
return (Criteria) this;
}
public Criteria andNicknameLessThanOrEqualTo(String value) {
addCriterion("nickname <=", value, "nickname");
return (Criteria) this;
}
public Criteria andNicknameLike(String value) {
addCriterion("nickname like", value, "nickname");
return (Criteria) this;
}
public Criteria andNicknameNotLike(String value) {
addCriterion("nickname not like", value, "nickname");
return (Criteria) this;
}
public Criteria andNicknameIn(List<String> values) {
addCriterion("nickname in", values, "nickname");
return (Criteria) this;
}
public Criteria andNicknameNotIn(List<String> values) {
addCriterion("nickname not in", values, "nickname");
return (Criteria) this;
}
public Criteria andNicknameBetween(String value1, String value2) {
addCriterion("nickname between", value1, value2, "nickname");
return (Criteria) this;
}
public Criteria andNicknameNotBetween(String value1, String value2) {
addCriterion("nickname not between", value1, value2, "nickname");
return (Criteria) this;
}
public Criteria andSexIsNull() {
addCriterion("sex is null");
return (Criteria) this;
}
public Criteria andSexIsNotNull() {
addCriterion("sex is not null");
return (Criteria) this;
}
public Criteria andSexEqualTo(Integer value) {
addCriterion("sex =", value, "sex");
return (Criteria) this;
}
public Criteria andSexNotEqualTo(Integer value) {
addCriterion("sex <>", value, "sex");
return (Criteria) this;
}
public Criteria andSexGreaterThan(Integer value) {
addCriterion("sex >", value, "sex");
return (Criteria) this;
}
public Criteria andSexGreaterThanOrEqualTo(Integer value) {
addCriterion("sex >=", value, "sex");
return (Criteria) this;
}
public Criteria andSexLessThan(Integer value) {
addCriterion("sex <", value, "sex");
return (Criteria) this;
}
public Criteria andSexLessThanOrEqualTo(Integer value) {
addCriterion("sex <=", value, "sex");
return (Criteria) this;
}
public Criteria andSexIn(List<Integer> values) {
addCriterion("sex in", values, "sex");
return (Criteria) this;
}
public Criteria andSexNotIn(List<Integer> values) {
addCriterion("sex not in", values, "sex");
return (Criteria) this;
}
public Criteria andSexBetween(Integer value1, Integer value2) {
addCriterion("sex between", value1, value2, "sex");
return (Criteria) this;
}
public Criteria andSexNotBetween(Integer value1, Integer value2) {
addCriterion("sex not between", value1, value2, "sex");
return (Criteria) this;
}
public Criteria andCityIsNull() {
addCriterion("city is null");
return (Criteria) this;
}
public Criteria andCityIsNotNull() {
addCriterion("city is not null");
return (Criteria) this;
}
public Criteria andCityEqualTo(String value) {
addCriterion("city =", value, "city");
return (Criteria) this;
}
public Criteria andCityNotEqualTo(String value) {
addCriterion("city <>", value, "city");
return (Criteria) this;
}
public Criteria andCityGreaterThan(String value) {
addCriterion("city >", value, "city");
return (Criteria) this;
}
public Criteria andCityGreaterThanOrEqualTo(String value) {
addCriterion("city >=", value, "city");
return (Criteria) this;
}
public Criteria andCityLessThan(String value) {
addCriterion("city <", value, "city");
return (Criteria) this;
}
public Criteria andCityLessThanOrEqualTo(String value) {
addCriterion("city <=", value, "city");
return (Criteria) this;
}
public Criteria andCityLike(String value) {
addCriterion("city like", value, "city");
return (Criteria) this;
}
public Criteria andCityNotLike(String value) {
addCriterion("city not like", value, "city");
return (Criteria) this;
}
public Criteria andCityIn(List<String> values) {
addCriterion("city in", values, "city");
return (Criteria) this;
}
public Criteria andCityNotIn(List<String> values) {
addCriterion("city not in", values, "city");
return (Criteria) this;
}
public Criteria andCityBetween(String value1, String value2) {
addCriterion("city between", value1, value2, "city");
return (Criteria) this;
}
public Criteria andCityNotBetween(String value1, String value2) {
addCriterion("city not between", value1, value2, "city");
return (Criteria) this;
}
public Criteria andProvinceIsNull() {
addCriterion("province is null");
return (Criteria) this;
}
public Criteria andProvinceIsNotNull() {
addCriterion("province is not null");
return (Criteria) this;
}
public Criteria andProvinceEqualTo(String value) {
addCriterion("province =", value, "province");
return (Criteria) this;
}
public Criteria andProvinceNotEqualTo(String value) {
addCriterion("province <>", value, "province");
return (Criteria) this;
}
public Criteria andProvinceGreaterThan(String value) {
addCriterion("province >", value, "province");
return (Criteria) this;
}
public Criteria andProvinceGreaterThanOrEqualTo(String value) {
addCriterion("province >=", value, "province");
return (Criteria) this;
}
public Criteria andProvinceLessThan(String value) {
addCriterion("province <", value, "province");
return (Criteria) this;
}
public Criteria andProvinceLessThanOrEqualTo(String value) {
addCriterion("province <=", value, "province");
return (Criteria) this;
}
public Criteria andProvinceLike(String value) {
addCriterion("province like", value, "province");
return (Criteria) this;
}
public Criteria andProvinceNotLike(String value) {
addCriterion("province not like", value, "province");
return (Criteria) this;
}
public Criteria andProvinceIn(List<String> values) {
addCriterion("province in", values, "province");
return (Criteria) this;
}
public Criteria andProvinceNotIn(List<String> values) {
addCriterion("province not in", values, "province");
return (Criteria) this;
}
public Criteria andProvinceBetween(String value1, String value2) {
addCriterion("province between", value1, value2, "province");
return (Criteria) this;
}
public Criteria andProvinceNotBetween(String value1, String value2) {
addCriterion("province not between", value1, value2, "province");
return (Criteria) this;
}
public Criteria andCountryIsNull() {
addCriterion("country is null");
return (Criteria) this;
}
public Criteria andCountryIsNotNull() {
addCriterion("country is not null");
return (Criteria) this;
}
public Criteria andCountryEqualTo(String value) {
addCriterion("country =", value, "country");
return (Criteria) this;
}
public Criteria andCountryNotEqualTo(String value) {
addCriterion("country <>", value, "country");
return (Criteria) this;
}
public Criteria andCountryGreaterThan(String value) {
addCriterion("country >", value, "country");
return (Criteria) this;
}
public Criteria andCountryGreaterThanOrEqualTo(String value) {
addCriterion("country >=", value, "country");
return (Criteria) this;
}
public Criteria andCountryLessThan(String value) {
addCriterion("country <", value, "country");
return (Criteria) this;
}
public Criteria andCountryLessThanOrEqualTo(String value) {
addCriterion("country <=", value, "country");
return (Criteria) this;
}
public Criteria andCountryLike(String value) {
addCriterion("country like", value, "country");
return (Criteria) this;
}
public Criteria andCountryNotLike(String value) {
addCriterion("country not like", value, "country");
return (Criteria) this;
}
public Criteria andCountryIn(List<String> values) {
addCriterion("country in", values, "country");
return (Criteria) this;
}
public Criteria andCountryNotIn(List<String> values) {
addCriterion("country not in", values, "country");
return (Criteria) this;
}
public Criteria andCountryBetween(String value1, String value2) {
addCriterion("country between", value1, value2, "country");
return (Criteria) this;
}
public Criteria andCountryNotBetween(String value1, String value2) {
addCriterion("country not between", value1, value2, "country");
return (Criteria) this;
}
public Criteria andLanguageIsNull() {
addCriterion("`language` is null");
return (Criteria) this;
}
public Criteria andLanguageIsNotNull() {
addCriterion("`language` is not null");
return (Criteria) this;
}
public Criteria andLanguageEqualTo(String value) {
addCriterion("`language` =", value, "language");
return (Criteria) this;
}
public Criteria andLanguageNotEqualTo(String value) {
addCriterion("`language` <>", value, "language");
return (Criteria) this;
}
public Criteria andLanguageGreaterThan(String value) {
addCriterion("`language` >", value, "language");
return (Criteria) this;
}
public Criteria andLanguageGreaterThanOrEqualTo(String value) {
addCriterion("`language` >=", value, "language");
return (Criteria) this;
}
public Criteria andLanguageLessThan(String value) {
addCriterion("`language` <", value, "language");
return (Criteria) this;
}
public Criteria andLanguageLessThanOrEqualTo(String value) {
addCriterion("`language` <=", value, "language");
return (Criteria) this;
}
public Criteria andLanguageLike(String value) {
addCriterion("`language` like", value, "language");
return (Criteria) this;
}
public Criteria andLanguageNotLike(String value) {
addCriterion("`language` not like", value, "language");
return (Criteria) this;
}
public Criteria andLanguageIn(List<String> values) {
addCriterion("`language` in", values, "language");
return (Criteria) this;
}
public Criteria andLanguageNotIn(List<String> values) {
addCriterion("`language` not in", values, "language");
return (Criteria) this;
}
public Criteria andLanguageBetween(String value1, String value2) {
addCriterion("`language` between", value1, value2, "language");
return (Criteria) this;
}
public Criteria andLanguageNotBetween(String value1, String value2) {
addCriterion("`language` not between", value1, value2, "language");
return (Criteria) this;
}
public Criteria andHeadimgurlIsNull() {
addCriterion("headimgurl is null");
return (Criteria) this;
}
public Criteria andHeadimgurlIsNotNull() {
addCriterion("headimgurl is not null");
return (Criteria) this;
}
public Criteria andHeadimgurlEqualTo(String value) {
addCriterion("headimgurl =", value, "headimgurl");
return (Criteria) this;
}
public Criteria andHeadimgurlNotEqualTo(String value) {
addCriterion("headimgurl <>", value, "headimgurl");
return (Criteria) this;
}
public Criteria andHeadimgurlGreaterThan(String value) {
addCriterion("headimgurl >", value, "headimgurl");
return (Criteria) this;
}
public Criteria andHeadimgurlGreaterThanOrEqualTo(String value) {
addCriterion("headimgurl >=", value, "headimgurl");
return (Criteria) this;
}
public Criteria andHeadimgurlLessThan(String value) {
addCriterion("headimgurl <", value, "headimgurl");
return (Criteria) this;
}
public Criteria andHeadimgurlLessThanOrEqualTo(String value) {
addCriterion("headimgurl <=", value, "headimgurl");
return (Criteria) this;
}
public Criteria andHeadimgurlLike(String value) {
addCriterion("headimgurl like", value, "headimgurl");
return (Criteria) this;
}
public Criteria andHeadimgurlNotLike(String value) {
addCriterion("headimgurl not like", value, "headimgurl");
return (Criteria) this;
}
public Criteria andHeadimgurlIn(List<String> values) {
addCriterion("headimgurl in", values, "headimgurl");
return (Criteria) this;
}
public Criteria andHeadimgurlNotIn(List<String> values) {
addCriterion("headimgurl not in", values, "headimgurl");
return (Criteria) this;
}
public Criteria andHeadimgurlBetween(String value1, String value2) {
addCriterion("headimgurl between", value1, value2, "headimgurl");
return (Criteria) this;
}
public Criteria andHeadimgurlNotBetween(String value1, String value2) {
addCriterion("headimgurl not between", value1, value2, "headimgurl");
return (Criteria) this;
}
public Criteria andSubscribeTimeIsNull() {
addCriterion("subscribe_time is null");
return (Criteria) this;
}
public Criteria andSubscribeTimeIsNotNull() {
addCriterion("subscribe_time is not null");
return (Criteria) this;
}
public Criteria andSubscribeTimeEqualTo(Long value) {
addCriterion("subscribe_time =", value, "subscribeTime");
return (Criteria) this;
}
public Criteria andSubscribeTimeNotEqualTo(Long value) {
addCriterion("subscribe_time <>", value, "subscribeTime");
return (Criteria) this;
}
public Criteria andSubscribeTimeGreaterThan(Long value) {
addCriterion("subscribe_time >", value, "subscribeTime");
return (Criteria) this;
}
public Criteria andSubscribeTimeGreaterThanOrEqualTo(Long value) {
addCriterion("subscribe_time >=", value, "subscribeTime");
return (Criteria) this;
}
public Criteria andSubscribeTimeLessThan(Long value) {
addCriterion("subscribe_time <", value, "subscribeTime");
return (Criteria) this;
}
public Criteria andSubscribeTimeLessThanOrEqualTo(Long value) {
addCriterion("subscribe_time <=", value, "subscribeTime");
return (Criteria) this;
}
public Criteria andSubscribeTimeIn(List<Long> values) {
addCriterion("subscribe_time in", values, "subscribeTime");
return (Criteria) this;
}
public Criteria andSubscribeTimeNotIn(List<Long> values) {
addCriterion("subscribe_time not in", values, "subscribeTime");
return (Criteria) this;
}
public Criteria andSubscribeTimeBetween(Long value1, Long value2) {
addCriterion("subscribe_time between", value1, value2, "subscribeTime");
return (Criteria) this;
}
public Criteria andSubscribeTimeNotBetween(Long value1, Long value2) {
addCriterion("subscribe_time not between", value1, value2, "subscribeTime");
return (Criteria) this;
}
public Criteria andUnionidIsNull() {
addCriterion("unionid is null");
return (Criteria) this;
}
public Criteria andUnionidIsNotNull() {
addCriterion("unionid is not null");
return (Criteria) this;
}
public Criteria andUnionidEqualTo(String value) {
addCriterion("unionid =", value, "unionid");
return (Criteria) this;
}
public Criteria andUnionidNotEqualTo(String value) {
addCriterion("unionid <>", value, "unionid");
return (Criteria) this;
}
public Criteria andUnionidGreaterThan(String value) {
addCriterion("unionid >", value, "unionid");
return (Criteria) this;
}
public Criteria andUnionidGreaterThanOrEqualTo(String value) {
addCriterion("unionid >=", value, "unionid");
return (Criteria) this;
}
public Criteria andUnionidLessThan(String value) {
addCriterion("unionid <", value, "unionid");
return (Criteria) this;
}
public Criteria andUnionidLessThanOrEqualTo(String value) {
addCriterion("unionid <=", value, "unionid");
return (Criteria) this;
}
public Criteria andUnionidLike(String value) {
addCriterion("unionid like", value, "unionid");
return (Criteria) this;
}
public Criteria andUnionidNotLike(String value) {
addCriterion("unionid not like", value, "unionid");
return (Criteria) this;
}
public Criteria andUnionidIn(List<String> values) {
addCriterion("unionid in", values, "unionid");
return (Criteria) this;
}
public Criteria andUnionidNotIn(List<String> values) {
addCriterion("unionid not in", values, "unionid");
return (Criteria) this;
}
public Criteria andUnionidBetween(String value1, String value2) {
addCriterion("unionid between", value1, value2, "unionid");
return (Criteria) this;
}
public Criteria andUnionidNotBetween(String value1, String value2) {
addCriterion("unionid not between", value1, value2, "unionid");
return (Criteria) this;
}
public Criteria andRemarkIsNull() {
addCriterion("remark is null");
return (Criteria) this;
}
public Criteria andRemarkIsNotNull() {
addCriterion("remark is not null");
return (Criteria) this;
}
public Criteria andRemarkEqualTo(String value) {
addCriterion("remark =", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotEqualTo(String value) {
addCriterion("remark <>", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkGreaterThan(String value) {
addCriterion("remark >", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkGreaterThanOrEqualTo(String value) {
addCriterion("remark >=", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLessThan(String value) {
addCriterion("remark <", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLessThanOrEqualTo(String value) {
addCriterion("remark <=", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLike(String value) {
addCriterion("remark like", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotLike(String value) {
addCriterion("remark not like", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkIn(List<String> values) {
addCriterion("remark in", values, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotIn(List<String> values) {
addCriterion("remark not in", values, "remark");
return (Criteria) this;
}
public Criteria andRemarkBetween(String value1, String value2) {
addCriterion("remark between", value1, value2, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotBetween(String value1, String value2) {
addCriterion("remark not between", value1, value2, "remark");
return (Criteria) this;
}
public Criteria andGroupidIsNull() {
addCriterion("groupid is null");
return (Criteria) this;
}
public Criteria andGroupidIsNotNull() {
addCriterion("groupid is not null");
return (Criteria) this;
}
public Criteria andGroupidEqualTo(Integer value) {
addCriterion("groupid =", value, "groupid");
return (Criteria) this;
}
public Criteria andGroupidNotEqualTo(Integer value) {
addCriterion("groupid <>", value, "groupid");
return (Criteria) this;
}
public Criteria andGroupidGreaterThan(Integer value) {
addCriterion("groupid >", value, "groupid");
return (Criteria) this;
}
public Criteria andGroupidGreaterThanOrEqualTo(Integer value) {
addCriterion("groupid >=", value, "groupid");
return (Criteria) this;
}
public Criteria andGroupidLessThan(Integer value) {
addCriterion("groupid <", value, "groupid");
return (Criteria) this;
}
public Criteria andGroupidLessThanOrEqualTo(Integer value) {
addCriterion("groupid <=", value, "groupid");
return (Criteria) this;
}
public Criteria andGroupidIn(List<Integer> values) {
addCriterion("groupid in", values, "groupid");
return (Criteria) this;
}
public Criteria andGroupidNotIn(List<Integer> values) {
addCriterion("groupid not in", values, "groupid");
return (Criteria) this;
}
public Criteria andGroupidBetween(Integer value1, Integer value2) {
addCriterion("groupid between", value1, value2, "groupid");
return (Criteria) this;
}
public Criteria andGroupidNotBetween(Integer value1, Integer value2) {
addCriterion("groupid not between", value1, value2, "groupid");
return (Criteria) this;
}
public Criteria andTagidListIsNull() {
addCriterion("tagid_list is null");
return (Criteria) this;
}
public Criteria andTagidListIsNotNull() {
addCriterion("tagid_list is not null");
return (Criteria) this;
}
public Criteria andTagidListEqualTo(String value) {
addCriterion("tagid_list =", value, "tagidList");
return (Criteria) this;
}
public Criteria andTagidListNotEqualTo(String value) {
addCriterion("tagid_list <>", value, "tagidList");
return (Criteria) this;
}
public Criteria andTagidListGreaterThan(String value) {
addCriterion("tagid_list >", value, "tagidList");
return (Criteria) this;
}
public Criteria andTagidListGreaterThanOrEqualTo(String value) {
addCriterion("tagid_list >=", value, "tagidList");
return (Criteria) this;
}
public Criteria andTagidListLessThan(String value) {
addCriterion("tagid_list <", value, "tagidList");
return (Criteria) this;
}
public Criteria andTagidListLessThanOrEqualTo(String value) {
addCriterion("tagid_list <=", value, "tagidList");
return (Criteria) this;
}
public Criteria andTagidListLike(String value) {
addCriterion("tagid_list like", value, "tagidList");
return (Criteria) this;
}
public Criteria andTagidListNotLike(String value) {
addCriterion("tagid_list not like", value, "tagidList");
return (Criteria) this;
}
public Criteria andTagidListIn(List<String> values) {
addCriterion("tagid_list in", values, "tagidList");
return (Criteria) this;
}
public Criteria andTagidListNotIn(List<String> values) {
addCriterion("tagid_list not in", values, "tagidList");
return (Criteria) this;
}
public Criteria andTagidListBetween(String value1, String value2) {
addCriterion("tagid_list between", value1, value2, "tagidList");
return (Criteria) this;
}
public Criteria andTagidListNotBetween(String value1, String value2) {
addCriterion("tagid_list not between", value1, value2, "tagidList");
return (Criteria) this;
}
public Criteria andSubscribeSceneIsNull() {
addCriterion("subscribe_scene is null");
return (Criteria) this;
}
public Criteria andSubscribeSceneIsNotNull() {
addCriterion("subscribe_scene is not null");
return (Criteria) this;
}
public Criteria andSubscribeSceneEqualTo(String value) {
addCriterion("subscribe_scene =", value, "subscribeScene");
return (Criteria) this;
}
public Criteria andSubscribeSceneNotEqualTo(String value) {
addCriterion("subscribe_scene <>", value, "subscribeScene");
return (Criteria) this;
}
public Criteria andSubscribeSceneGreaterThan(String value) {
addCriterion("subscribe_scene >", value, "subscribeScene");
return (Criteria) this;
}
public Criteria andSubscribeSceneGreaterThanOrEqualTo(String value) {
addCriterion("subscribe_scene >=", value, "subscribeScene");
return (Criteria) this;
}
public Criteria andSubscribeSceneLessThan(String value) {
addCriterion("subscribe_scene <", value, "subscribeScene");
return (Criteria) this;
}
public Criteria andSubscribeSceneLessThanOrEqualTo(String value) {
addCriterion("subscribe_scene <=", value, "subscribeScene");
return (Criteria) this;
}
public Criteria andSubscribeSceneLike(String value) {
addCriterion("subscribe_scene like", value, "subscribeScene");
return (Criteria) this;
}
public Criteria andSubscribeSceneNotLike(String value) {
addCriterion("subscribe_scene not like", value, "subscribeScene");
return (Criteria) this;
}
public Criteria andSubscribeSceneIn(List<String> values) {
addCriterion("subscribe_scene in", values, "subscribeScene");
return (Criteria) this;
}
public Criteria andSubscribeSceneNotIn(List<String> values) {
addCriterion("subscribe_scene not in", values, "subscribeScene");
return (Criteria) this;
}
public Criteria andSubscribeSceneBetween(String value1, String value2) {
addCriterion("subscribe_scene between", value1, value2, "subscribeScene");
return (Criteria) this;
}
public Criteria andSubscribeSceneNotBetween(String value1, String value2) {
addCriterion("subscribe_scene not between", value1, value2, "subscribeScene");
return (Criteria) this;
}
public Criteria andQrSceneIsNull() {
addCriterion("qr_scene is null");
return (Criteria) this;
}
public Criteria andQrSceneIsNotNull() {
addCriterion("qr_scene is not null");
return (Criteria) this;
}
public Criteria andQrSceneEqualTo(Integer value) {
addCriterion("qr_scene =", value, "qrScene");
return (Criteria) this;
}
public Criteria andQrSceneNotEqualTo(Integer value) {
addCriterion("qr_scene <>", value, "qrScene");
return (Criteria) this;
}
public Criteria andQrSceneGreaterThan(Integer value) {
addCriterion("qr_scene >", value, "qrScene");
return (Criteria) this;
}
public Criteria andQrSceneGreaterThanOrEqualTo(Integer value) {
addCriterion("qr_scene >=", value, "qrScene");
return (Criteria) this;
}
public Criteria andQrSceneLessThan(Integer value) {
addCriterion("qr_scene <", value, "qrScene");
return (Criteria) this;
}
public Criteria andQrSceneLessThanOrEqualTo(Integer value) {
addCriterion("qr_scene <=", value, "qrScene");
return (Criteria) this;
}
public Criteria andQrSceneIn(List<Integer> values) {
addCriterion("qr_scene in", values, "qrScene");
return (Criteria) this;
}
public Criteria andQrSceneNotIn(List<Integer> values) {
addCriterion("qr_scene not in", values, "qrScene");
return (Criteria) this;
}
public Criteria andQrSceneBetween(Integer value1, Integer value2) {
addCriterion("qr_scene between", value1, value2, "qrScene");
return (Criteria) this;
}
public Criteria andQrSceneNotBetween(Integer value1, Integer value2) {
addCriterion("qr_scene not between", value1, value2, "qrScene");
return (Criteria) this;
}
public Criteria andQrSceneStrIsNull() {
addCriterion("qr_scene_str is null");
return (Criteria) this;
}
public Criteria andQrSceneStrIsNotNull() {
addCriterion("qr_scene_str is not null");
return (Criteria) this;
}
public Criteria andQrSceneStrEqualTo(String value) {
addCriterion("qr_scene_str =", value, "qrSceneStr");
return (Criteria) this;
}
public Criteria andQrSceneStrNotEqualTo(String value) {
addCriterion("qr_scene_str <>", value, "qrSceneStr");
return (Criteria) this;
}
public Criteria andQrSceneStrGreaterThan(String value) {
addCriterion("qr_scene_str >", value, "qrSceneStr");
return (Criteria) this;
}
public Criteria andQrSceneStrGreaterThanOrEqualTo(String value) {
addCriterion("qr_scene_str >=", value, "qrSceneStr");
return (Criteria) this;
}
public Criteria andQrSceneStrLessThan(String value) {
addCriterion("qr_scene_str <", value, "qrSceneStr");
return (Criteria) this;
}
public Criteria andQrSceneStrLessThanOrEqualTo(String value) {
addCriterion("qr_scene_str <=", value, "qrSceneStr");
return (Criteria) this;
}
public Criteria andQrSceneStrLike(String value) {
addCriterion("qr_scene_str like", value, "qrSceneStr");
return (Criteria) this;
}
public Criteria andQrSceneStrNotLike(String value) {
addCriterion("qr_scene_str not like", value, "qrSceneStr");
return (Criteria) this;
}
public Criteria andQrSceneStrIn(List<String> values) {
addCriterion("qr_scene_str in", values, "qrSceneStr");
return (Criteria) this;
}
public Criteria andQrSceneStrNotIn(List<String> values) {
addCriterion("qr_scene_str not in", values, "qrSceneStr");
return (Criteria) this;
}
public Criteria andQrSceneStrBetween(String value1, String value2) {
addCriterion("qr_scene_str between", value1, value2, "qrSceneStr");
return (Criteria) this;
}
public Criteria andQrSceneStrNotBetween(String value1, String value2) {
addCriterion("qr_scene_str not between", value1, value2, "qrSceneStr");
return (Criteria) this;
}
public Criteria andCreateDateIsNull() {
addCriterion("create_date is null");
return (Criteria) this;
}
public Criteria andCreateDateIsNotNull() {
addCriterion("create_date is not null");
return (Criteria) this;
}
public Criteria andCreateDateEqualTo(Date value) {
addCriterion("create_date =", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateNotEqualTo(Date value) {
addCriterion("create_date <>", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateGreaterThan(Date value) {
addCriterion("create_date >", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateGreaterThanOrEqualTo(Date value) {
addCriterion("create_date >=", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateLessThan(Date value) {
addCriterion("create_date <", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateLessThanOrEqualTo(Date value) {
addCriterion("create_date <=", value, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateIn(List<Date> values) {
addCriterion("create_date in", values, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateNotIn(List<Date> values) {
addCriterion("create_date not in", values, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateBetween(Date value1, Date value2) {
addCriterion("create_date between", value1, value2, "createDate");
return (Criteria) this;
}
public Criteria andCreateDateNotBetween(Date value1, Date value2) {
addCriterion("create_date not between", value1, value2, "createDate");
return (Criteria) this;
}
public Criteria andDeletedIsNull() {
addCriterion("deleted is null");
return (Criteria) this;
}
public Criteria andDeletedIsNotNull() {
addCriterion("deleted is not null");
return (Criteria) this;
}
public Criteria andDeletedEqualTo(Integer value) {
addCriterion("deleted =", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotEqualTo(Integer value) {
addCriterion("deleted <>", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedGreaterThan(Integer value) {
addCriterion("deleted >", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedGreaterThanOrEqualTo(Integer value) {
addCriterion("deleted >=", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedLessThan(Integer value) {
addCriterion("deleted <", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedLessThanOrEqualTo(Integer value) {
addCriterion("deleted <=", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedIn(List<Integer> values) {
addCriterion("deleted in", values, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotIn(List<Integer> values) {
addCriterion("deleted not in", values, "deleted");
return (Criteria) this;
}
public Criteria andDeletedBetween(Integer value1, Integer value2) {
addCriterion("deleted between", value1, value2, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotBetween(Integer value1, Integer value2) {
addCriterion("deleted not between", value1, value2, "deleted");
return (Criteria) this;
}
public Criteria andDemoIsNull() {
addCriterion("demo is null");
return (Criteria) this;
}
public Criteria andDemoIsNotNull() {
addCriterion("demo is not null");
return (Criteria) this;
}
public Criteria andDemoEqualTo(String value) {
addCriterion("demo =", value, "demo");
return (Criteria) this;
}
public Criteria andDemoNotEqualTo(String value) {
addCriterion("demo <>", value, "demo");
return (Criteria) this;
}
public Criteria andDemoGreaterThan(String value) {
addCriterion("demo >", value, "demo");
return (Criteria) this;
}
public Criteria andDemoGreaterThanOrEqualTo(String value) {
addCriterion("demo >=", value, "demo");
return (Criteria) this;
}
public Criteria andDemoLessThan(String value) {
addCriterion("demo <", value, "demo");
return (Criteria) this;
}
public Criteria andDemoLessThanOrEqualTo(String value) {
addCriterion("demo <=", value, "demo");
return (Criteria) this;
}
public Criteria andDemoLike(String value) {
addCriterion("demo like", value, "demo");
return (Criteria) this;
}
public Criteria andDemoNotLike(String value) {
addCriterion("demo not like", value, "demo");
return (Criteria) this;
}
public Criteria andDemoIn(List<String> values) {
addCriterion("demo in", values, "demo");
return (Criteria) this;
}
public Criteria andDemoNotIn(List<String> values) {
addCriterion("demo not in", values, "demo");
return (Criteria) this;
}
public Criteria andDemoBetween(String value1, String value2) {
addCriterion("demo between", value1, value2, "demo");
return (Criteria) this;
}
public Criteria andDemoNotBetween(String value1, String value2) {
addCriterion("demo not between", value1, value2, "demo");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table wx_gzh_user
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
private WxGzhUserExample example;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_gzh_user
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
protected Criteria(WxGzhUserExample example) {
super();
this.example = example;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_gzh_user
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public WxGzhUserExample example() {
return this.example;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_gzh_user
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public Criteria andIf(boolean ifAdd, ICriteriaAdd add) {
if (ifAdd) {
add.add(this);
}
return this;
}
/**
* This interface was generated by MyBatis Generator.
* This interface corresponds to the database table wx_gzh_user
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
public interface ICriteriaAdd {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_gzh_user
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
Criteria add(Criteria add);
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | 32.979774 | 102 | 0.580151 |
703c1d3fa35fe9b4cec94794af6ff59b4b254c28 | 39,757 | package com.yandex.metrica;
import java.io.IOException;
import java.util.Arrays;
public interface c {
public static final class a extends com.yandex.metrica.impl.ob.d {
public f b;
public d[] c;
public C0023a[] d;
public C0024c[] e;
public String[] f;
public e[] g;
public static final class f extends com.yandex.metrica.impl.ob.d {
public long b;
public int c;
public long d;
public f() {
d();
}
public f d() {
this.b = 0;
this.c = 0;
this.d = 0;
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
bVar.a(1, this.b);
bVar.c(2, this.c);
long j = this.d;
if (j != 0) {
bVar.b(3, j);
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c() + com.yandex.metrica.impl.ob.b.c(1, this.b) + com.yandex.metrica.impl.ob.b.f(2, this.c);
long j = this.d;
return j != 0 ? c2 + com.yandex.metrica.impl.ob.b.d(3, j) : c2;
}
}
public static final class b extends com.yandex.metrica.impl.ob.d {
public double b;
public double c;
public long d;
public int e;
public int f;
public int g;
public int h;
public int i;
public b() {
d();
}
public b d() {
this.b = 0.0d;
this.c = 0.0d;
this.d = 0;
this.e = 0;
this.f = 0;
this.g = 0;
this.h = 0;
this.i = 0;
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
bVar.a(1, this.b);
bVar.a(2, this.c);
long j = this.d;
if (j != 0) {
bVar.a(3, j);
}
int i2 = this.e;
if (i2 != 0) {
bVar.b(4, i2);
}
int i3 = this.f;
if (i3 != 0) {
bVar.b(5, i3);
}
int i4 = this.g;
if (i4 != 0) {
bVar.b(6, i4);
}
int i5 = this.h;
if (i5 != 0) {
bVar.a(7, i5);
}
int i6 = this.i;
if (i6 != 0) {
bVar.a(8, i6);
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c() + com.yandex.metrica.impl.ob.b.d(1) + com.yandex.metrica.impl.ob.b.d(2);
long j = this.d;
if (j != 0) {
c2 += com.yandex.metrica.impl.ob.b.c(3, j);
}
int i2 = this.e;
if (i2 != 0) {
c2 += com.yandex.metrica.impl.ob.b.e(4, i2);
}
int i3 = this.f;
if (i3 != 0) {
c2 += com.yandex.metrica.impl.ob.b.e(5, i3);
}
int i4 = this.g;
if (i4 != 0) {
c2 += com.yandex.metrica.impl.ob.b.e(6, i4);
}
int i5 = this.h;
if (i5 != 0) {
c2 += com.yandex.metrica.impl.ob.b.d(7, i5);
}
int i6 = this.i;
return i6 != 0 ? c2 + com.yandex.metrica.impl.ob.b.d(8, i6) : c2;
}
}
public static final class d extends com.yandex.metrica.impl.ob.d {
private static volatile d[] e;
public long b;
public b c;
public C0025a[] d;
/* renamed from: com.yandex.metrica.c$a$d$c reason: collision with other inner class name */
public static final class C0029c extends com.yandex.metrica.impl.ob.d {
private static volatile C0029c[] f;
public String b;
public int c;
public String d;
public boolean e;
public static C0029c[] d() {
if (f == null) {
synchronized (com.yandex.metrica.impl.ob.c.f813a) {
if (f == null) {
f = new C0029c[0];
}
}
}
return f;
}
public C0029c() {
e();
}
public C0029c e() {
this.b = "";
this.c = 0;
this.d = "";
this.e = false;
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
bVar.a(1, this.b);
int i = this.c;
if (i != 0) {
bVar.c(2, i);
}
if (!this.d.equals("")) {
bVar.a(3, this.d);
}
boolean z = this.e;
if (z) {
bVar.a(4, z);
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c() + com.yandex.metrica.impl.ob.b.b(1, this.b);
int i = this.c;
if (i != 0) {
c2 += com.yandex.metrica.impl.ob.b.f(2, i);
}
if (!this.d.equals("")) {
c2 += com.yandex.metrica.impl.ob.b.b(3, this.d);
}
return this.e ? c2 + com.yandex.metrica.impl.ob.b.e(4) : c2;
}
}
public static final class b extends com.yandex.metrica.impl.ob.d {
public f b;
public String c;
public int d;
public b() {
d();
}
public b d() {
this.b = null;
this.c = "";
this.d = 0;
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
f fVar = this.b;
if (fVar != null) {
bVar.a(1, (com.yandex.metrica.impl.ob.d) fVar);
}
bVar.a(2, this.c);
int i = this.d;
if (i != 0) {
bVar.a(5, i);
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c();
f fVar = this.b;
if (fVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(1, (com.yandex.metrica.impl.ob.d) fVar);
}
int b2 = c2 + com.yandex.metrica.impl.ob.b.b(2, this.c);
int i = this.d;
return i != 0 ? b2 + com.yandex.metrica.impl.ob.b.d(5, i) : b2;
}
}
/* renamed from: com.yandex.metrica.c$a$d$a reason: collision with other inner class name */
public static final class C0025a extends com.yandex.metrica.impl.ob.d {
private static volatile C0025a[] m;
public long b;
public long c;
public int d;
public String e;
public byte[] f;
public b g;
public b h;
public String i;
public C0026a j;
public int k;
public int l;
/* renamed from: com.yandex.metrica.c$a$d$a$b */
public static final class b extends com.yandex.metrica.impl.ob.d {
public C0027a[] b;
public C0029c[] c;
public int d;
public String e;
public C0028b f;
/* renamed from: com.yandex.metrica.c$a$d$a$b$a reason: collision with other inner class name */
public static final class C0027a extends com.yandex.metrica.impl.ob.d {
private static volatile C0027a[] k;
public int b;
public int c;
public int d;
public int e;
public int f;
public String g;
public boolean h;
public int i;
public int j;
public static C0027a[] d() {
if (k == null) {
synchronized (com.yandex.metrica.impl.ob.c.f813a) {
if (k == null) {
k = new C0027a[0];
}
}
}
return k;
}
public C0027a() {
e();
}
public C0027a e() {
this.b = -1;
this.c = 0;
this.d = -1;
this.e = -1;
this.f = -1;
this.g = "";
this.h = false;
this.i = 0;
this.j = -1;
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
int i2 = this.b;
if (i2 != -1) {
bVar.b(1, i2);
}
int i3 = this.c;
if (i3 != 0) {
bVar.c(2, i3);
}
int i4 = this.d;
if (i4 != -1) {
bVar.b(3, i4);
}
int i5 = this.e;
if (i5 != -1) {
bVar.b(4, i5);
}
int i6 = this.f;
if (i6 != -1) {
bVar.b(5, i6);
}
if (!this.g.equals("")) {
bVar.a(6, this.g);
}
boolean z = this.h;
if (z) {
bVar.a(7, z);
}
int i7 = this.i;
if (i7 != 0) {
bVar.a(8, i7);
}
int i8 = this.j;
if (i8 != -1) {
bVar.b(9, i8);
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c();
int i2 = this.b;
if (i2 != -1) {
c2 += com.yandex.metrica.impl.ob.b.e(1, i2);
}
int i3 = this.c;
if (i3 != 0) {
c2 += com.yandex.metrica.impl.ob.b.f(2, i3);
}
int i4 = this.d;
if (i4 != -1) {
c2 += com.yandex.metrica.impl.ob.b.e(3, i4);
}
int i5 = this.e;
if (i5 != -1) {
c2 += com.yandex.metrica.impl.ob.b.e(4, i5);
}
int i6 = this.f;
if (i6 != -1) {
c2 += com.yandex.metrica.impl.ob.b.e(5, i6);
}
if (!this.g.equals("")) {
c2 += com.yandex.metrica.impl.ob.b.b(6, this.g);
}
if (this.h) {
c2 += com.yandex.metrica.impl.ob.b.e(7);
}
int i7 = this.i;
if (i7 != 0) {
c2 += com.yandex.metrica.impl.ob.b.d(8, i7);
}
int i8 = this.j;
return i8 != -1 ? c2 + com.yandex.metrica.impl.ob.b.e(9, i8) : c2;
}
}
/* renamed from: com.yandex.metrica.c$a$d$a$b$b reason: collision with other inner class name */
public static final class C0028b extends com.yandex.metrica.impl.ob.d {
public String b;
public int c;
public C0028b() {
d();
}
public C0028b d() {
this.b = "";
this.c = 0;
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
bVar.a(1, this.b);
int i = this.c;
if (i != 0) {
bVar.a(2, i);
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c() + com.yandex.metrica.impl.ob.b.b(1, this.b);
int i = this.c;
return i != 0 ? c2 + com.yandex.metrica.impl.ob.b.d(2, i) : c2;
}
}
public b() {
d();
}
public b d() {
this.b = C0027a.d();
this.c = C0029c.d();
this.d = 2;
this.e = "";
this.f = null;
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
C0027a[] aVarArr = this.b;
int i = 0;
if (aVarArr != null && aVarArr.length > 0) {
int i2 = 0;
while (true) {
C0027a[] aVarArr2 = this.b;
if (i2 >= aVarArr2.length) {
break;
}
C0027a aVar = aVarArr2[i2];
if (aVar != null) {
bVar.a(1, (com.yandex.metrica.impl.ob.d) aVar);
}
i2++;
}
}
C0029c[] cVarArr = this.c;
if (cVarArr != null && cVarArr.length > 0) {
while (true) {
C0029c[] cVarArr2 = this.c;
if (i >= cVarArr2.length) {
break;
}
C0029c cVar = cVarArr2[i];
if (cVar != null) {
bVar.a(2, (com.yandex.metrica.impl.ob.d) cVar);
}
i++;
}
}
int i3 = this.d;
if (i3 != 2) {
bVar.a(3, i3);
}
if (!this.e.equals("")) {
bVar.a(4, this.e);
}
C0028b bVar2 = this.f;
if (bVar2 != null) {
bVar.a(5, (com.yandex.metrica.impl.ob.d) bVar2);
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c();
C0027a[] aVarArr = this.b;
int i = 0;
if (aVarArr != null && aVarArr.length > 0) {
int i2 = 0;
while (true) {
C0027a[] aVarArr2 = this.b;
if (i2 >= aVarArr2.length) {
break;
}
C0027a aVar = aVarArr2[i2];
if (aVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(1, (com.yandex.metrica.impl.ob.d) aVar);
}
i2++;
}
}
C0029c[] cVarArr = this.c;
if (cVarArr != null && cVarArr.length > 0) {
while (true) {
C0029c[] cVarArr2 = this.c;
if (i >= cVarArr2.length) {
break;
}
C0029c cVar = cVarArr2[i];
if (cVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(2, (com.yandex.metrica.impl.ob.d) cVar);
}
i++;
}
}
int i3 = this.d;
if (i3 != 2) {
c2 += com.yandex.metrica.impl.ob.b.d(3, i3);
}
if (!this.e.equals("")) {
c2 += com.yandex.metrica.impl.ob.b.b(4, this.e);
}
C0028b bVar = this.f;
return bVar != null ? c2 + com.yandex.metrica.impl.ob.b.b(5, (com.yandex.metrica.impl.ob.d) bVar) : c2;
}
}
/* renamed from: com.yandex.metrica.c$a$d$a$a reason: collision with other inner class name */
public static final class C0026a extends com.yandex.metrica.impl.ob.d {
public String b;
public String c;
public String d;
public C0026a() {
d();
}
public C0026a d() {
this.b = "";
this.c = "";
this.d = "";
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
bVar.a(1, this.b);
if (!this.c.equals("")) {
bVar.a(2, this.c);
}
if (!this.d.equals("")) {
bVar.a(3, this.d);
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c() + com.yandex.metrica.impl.ob.b.b(1, this.b);
if (!this.c.equals("")) {
c2 += com.yandex.metrica.impl.ob.b.b(2, this.c);
}
return !this.d.equals("") ? c2 + com.yandex.metrica.impl.ob.b.b(3, this.d) : c2;
}
}
public static C0025a[] d() {
if (m == null) {
synchronized (com.yandex.metrica.impl.ob.c.f813a) {
if (m == null) {
m = new C0025a[0];
}
}
}
return m;
}
public C0025a() {
e();
}
public C0025a e() {
this.b = 0;
this.c = 0;
this.d = 0;
this.e = "";
this.f = com.yandex.metrica.impl.ob.f.b;
this.g = null;
this.h = null;
this.i = "";
this.j = null;
this.k = 0;
this.l = 0;
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
bVar.a(1, this.b);
bVar.a(2, this.c);
bVar.b(3, this.d);
if (!this.e.equals("")) {
bVar.a(4, this.e);
}
if (!Arrays.equals(this.f, com.yandex.metrica.impl.ob.f.b)) {
bVar.a(5, this.f);
}
b bVar2 = this.g;
if (bVar2 != null) {
bVar.a(6, (com.yandex.metrica.impl.ob.d) bVar2);
}
b bVar3 = this.h;
if (bVar3 != null) {
bVar.a(7, (com.yandex.metrica.impl.ob.d) bVar3);
}
if (!this.i.equals("")) {
bVar.a(8, this.i);
}
C0026a aVar = this.j;
if (aVar != null) {
bVar.a(9, (com.yandex.metrica.impl.ob.d) aVar);
}
int i2 = this.k;
if (i2 != 0) {
bVar.b(10, i2);
}
int i3 = this.l;
if (i3 != 0) {
bVar.a(12, i3);
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c() + com.yandex.metrica.impl.ob.b.c(1, this.b) + com.yandex.metrica.impl.ob.b.c(2, this.c) + com.yandex.metrica.impl.ob.b.e(3, this.d);
if (!this.e.equals("")) {
c2 += com.yandex.metrica.impl.ob.b.b(4, this.e);
}
if (!Arrays.equals(this.f, com.yandex.metrica.impl.ob.f.b)) {
c2 += com.yandex.metrica.impl.ob.b.b(5, this.f);
}
b bVar = this.g;
if (bVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(6, (com.yandex.metrica.impl.ob.d) bVar);
}
b bVar2 = this.h;
if (bVar2 != null) {
c2 += com.yandex.metrica.impl.ob.b.b(7, (com.yandex.metrica.impl.ob.d) bVar2);
}
if (!this.i.equals("")) {
c2 += com.yandex.metrica.impl.ob.b.b(8, this.i);
}
C0026a aVar = this.j;
if (aVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(9, (com.yandex.metrica.impl.ob.d) aVar);
}
int i2 = this.k;
if (i2 != 0) {
c2 += com.yandex.metrica.impl.ob.b.e(10, i2);
}
int i3 = this.l;
return i3 != 0 ? c2 + com.yandex.metrica.impl.ob.b.d(12, i3) : c2;
}
}
public static d[] d() {
if (e == null) {
synchronized (com.yandex.metrica.impl.ob.c.f813a) {
if (e == null) {
e = new d[0];
}
}
}
return e;
}
public d() {
e();
}
public d e() {
this.b = 0;
this.c = null;
this.d = C0025a.d();
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
bVar.a(1, this.b);
b bVar2 = this.c;
if (bVar2 != null) {
bVar.a(2, (com.yandex.metrica.impl.ob.d) bVar2);
}
C0025a[] aVarArr = this.d;
if (aVarArr != null && aVarArr.length > 0) {
int i = 0;
while (true) {
C0025a[] aVarArr2 = this.d;
if (i >= aVarArr2.length) {
break;
}
C0025a aVar = aVarArr2[i];
if (aVar != null) {
bVar.a(3, (com.yandex.metrica.impl.ob.d) aVar);
}
i++;
}
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c() + com.yandex.metrica.impl.ob.b.c(1, this.b);
b bVar = this.c;
if (bVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(2, (com.yandex.metrica.impl.ob.d) bVar);
}
C0025a[] aVarArr = this.d;
if (aVarArr != null && aVarArr.length > 0) {
int i = 0;
while (true) {
C0025a[] aVarArr2 = this.d;
if (i >= aVarArr2.length) {
break;
}
C0025a aVar = aVarArr2[i];
if (aVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(3, (com.yandex.metrica.impl.ob.d) aVar);
}
i++;
}
}
return c2;
}
}
/* renamed from: com.yandex.metrica.c$a$a reason: collision with other inner class name */
public static final class C0023a extends com.yandex.metrica.impl.ob.d {
private static volatile C0023a[] d;
public String b;
public String c;
public static C0023a[] d() {
if (d == null) {
synchronized (com.yandex.metrica.impl.ob.c.f813a) {
if (d == null) {
d = new C0023a[0];
}
}
}
return d;
}
public C0023a() {
e();
}
public C0023a e() {
this.b = "";
this.c = "";
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
bVar.a(1, this.b);
bVar.a(2, this.c);
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
return super.c() + com.yandex.metrica.impl.ob.b.b(1, this.b) + com.yandex.metrica.impl.ob.b.b(2, this.c);
}
}
/* renamed from: com.yandex.metrica.c$a$c reason: collision with other inner class name */
public static final class C0024c extends com.yandex.metrica.impl.ob.d {
private static volatile C0024c[] d;
public String b;
public String c;
public static C0024c[] d() {
if (d == null) {
synchronized (com.yandex.metrica.impl.ob.c.f813a) {
if (d == null) {
d = new C0024c[0];
}
}
}
return d;
}
public C0024c() {
e();
}
public C0024c e() {
this.b = "";
this.c = "";
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
bVar.a(1, this.b);
bVar.a(2, this.c);
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
return super.c() + com.yandex.metrica.impl.ob.b.b(1, this.b) + com.yandex.metrica.impl.ob.b.b(2, this.c);
}
}
public static final class e extends com.yandex.metrica.impl.ob.d {
private static volatile e[] g;
public int b;
public int c;
public String d;
public boolean e;
public String f;
public static e[] d() {
if (g == null) {
synchronized (com.yandex.metrica.impl.ob.c.f813a) {
if (g == null) {
g = new e[0];
}
}
}
return g;
}
public e() {
e();
}
public e e() {
this.b = 0;
this.c = 0;
this.d = "";
this.e = false;
this.f = "";
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
int i = this.b;
if (i != 0) {
bVar.b(1, i);
}
int i2 = this.c;
if (i2 != 0) {
bVar.b(2, i2);
}
if (!this.d.equals("")) {
bVar.a(3, this.d);
}
boolean z = this.e;
if (z) {
bVar.a(4, z);
}
if (!this.f.equals("")) {
bVar.a(5, this.f);
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c();
int i = this.b;
if (i != 0) {
c2 += com.yandex.metrica.impl.ob.b.e(1, i);
}
int i2 = this.c;
if (i2 != 0) {
c2 += com.yandex.metrica.impl.ob.b.e(2, i2);
}
if (!this.d.equals("")) {
c2 += com.yandex.metrica.impl.ob.b.b(3, this.d);
}
if (this.e) {
c2 += com.yandex.metrica.impl.ob.b.e(4);
}
return !this.f.equals("") ? c2 + com.yandex.metrica.impl.ob.b.b(5, this.f) : c2;
}
}
public a() {
d();
}
public a d() {
this.b = null;
this.c = d.d();
this.d = C0023a.d();
this.e = C0024c.d();
this.f = com.yandex.metrica.impl.ob.f.f894a;
this.g = e.d();
this.f842a = -1;
return this;
}
public void a(com.yandex.metrica.impl.ob.b bVar) throws IOException {
f fVar = this.b;
if (fVar != null) {
bVar.a(1, (com.yandex.metrica.impl.ob.d) fVar);
}
d[] dVarArr = this.c;
int i = 0;
if (dVarArr != null && dVarArr.length > 0) {
int i2 = 0;
while (true) {
d[] dVarArr2 = this.c;
if (i2 >= dVarArr2.length) {
break;
}
d dVar = dVarArr2[i2];
if (dVar != null) {
bVar.a(3, (com.yandex.metrica.impl.ob.d) dVar);
}
i2++;
}
}
C0023a[] aVarArr = this.d;
if (aVarArr != null && aVarArr.length > 0) {
int i3 = 0;
while (true) {
C0023a[] aVarArr2 = this.d;
if (i3 >= aVarArr2.length) {
break;
}
C0023a aVar = aVarArr2[i3];
if (aVar != null) {
bVar.a(7, (com.yandex.metrica.impl.ob.d) aVar);
}
i3++;
}
}
C0024c[] cVarArr = this.e;
if (cVarArr != null && cVarArr.length > 0) {
int i4 = 0;
while (true) {
C0024c[] cVarArr2 = this.e;
if (i4 >= cVarArr2.length) {
break;
}
C0024c cVar = cVarArr2[i4];
if (cVar != null) {
bVar.a(8, (com.yandex.metrica.impl.ob.d) cVar);
}
i4++;
}
}
String[] strArr = this.f;
if (strArr != null && strArr.length > 0) {
int i5 = 0;
while (true) {
String[] strArr2 = this.f;
if (i5 >= strArr2.length) {
break;
}
String str = strArr2[i5];
if (str != null) {
bVar.a(9, str);
}
i5++;
}
}
e[] eVarArr = this.g;
if (eVarArr != null && eVarArr.length > 0) {
while (true) {
e[] eVarArr2 = this.g;
if (i >= eVarArr2.length) {
break;
}
e eVar = eVarArr2[i];
if (eVar != null) {
bVar.a(10, (com.yandex.metrica.impl.ob.d) eVar);
}
i++;
}
}
super.a(bVar);
}
/* access modifiers changed from: protected */
public int c() {
int c2 = super.c();
f fVar = this.b;
if (fVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(1, (com.yandex.metrica.impl.ob.d) fVar);
}
d[] dVarArr = this.c;
int i = 0;
if (dVarArr != null && dVarArr.length > 0) {
int i2 = 0;
while (true) {
d[] dVarArr2 = this.c;
if (i2 >= dVarArr2.length) {
break;
}
d dVar = dVarArr2[i2];
if (dVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(3, (com.yandex.metrica.impl.ob.d) dVar);
}
i2++;
}
}
C0023a[] aVarArr = this.d;
if (aVarArr != null && aVarArr.length > 0) {
int i3 = 0;
while (true) {
C0023a[] aVarArr2 = this.d;
if (i3 >= aVarArr2.length) {
break;
}
C0023a aVar = aVarArr2[i3];
if (aVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(7, (com.yandex.metrica.impl.ob.d) aVar);
}
i3++;
}
}
C0024c[] cVarArr = this.e;
if (cVarArr != null && cVarArr.length > 0) {
int i4 = 0;
while (true) {
C0024c[] cVarArr2 = this.e;
if (i4 >= cVarArr2.length) {
break;
}
C0024c cVar = cVarArr2[i4];
if (cVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(8, (com.yandex.metrica.impl.ob.d) cVar);
}
i4++;
}
}
String[] strArr = this.f;
if (strArr != null && strArr.length > 0) {
int i5 = 0;
int i6 = 0;
int i7 = 0;
while (true) {
String[] strArr2 = this.f;
if (i5 >= strArr2.length) {
break;
}
String str = strArr2[i5];
if (str != null) {
i7++;
i6 += com.yandex.metrica.impl.ob.b.b(str);
}
i5++;
}
c2 = c2 + i6 + (i7 * 1);
}
e[] eVarArr = this.g;
if (eVarArr != null && eVarArr.length > 0) {
while (true) {
e[] eVarArr2 = this.g;
if (i >= eVarArr2.length) {
break;
}
e eVar = eVarArr2[i];
if (eVar != null) {
c2 += com.yandex.metrica.impl.ob.b.b(10, (com.yandex.metrica.impl.ob.d) eVar);
}
i++;
}
}
return c2;
}
}
}
| 36.743993 | 171 | 0.312649 |
3281324c16dc058f385aac374ee3bbe2ab61e173 | 6,050 | /**
* Copyright (C) 2016 Hyphenate Inc. All rights reserved.
* <p>
* 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.elead.im.activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.elead.activity.BaseActivity;
import com.elead.eplatform.R;
import com.elead.im.util.EaseUserUtils;
import com.elead.utils.ToastUtil;
import com.elead.views.CircularImageView;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMGroupInfo;
import com.hyphenate.exceptions.HyphenateException;
public class GroupSimpleDetailActivity extends BaseActivity {
private Button btn_add_group;
private TextView tv_admin;
private TextView tv_name;
private TextView tv_introduction;
private EMGroup group;
private String groupid;
private CircularImageView avatar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.em_activity_group_simle_details);
tv_name = (TextView) findViewById(R.id.name);
tv_admin = (TextView) findViewById(R.id.tv_admin);
avatar = (CircularImageView) findViewById(R.id.avatar);
btn_add_group = (Button) findViewById(R.id.btn_add_to_group);
tv_introduction = (TextView) findViewById(R.id.tv_introduction);
EMGroupInfo groupInfo = (EMGroupInfo) getIntent().getSerializableExtra("groupinfo");
String groupname = null;
if (groupInfo != null) {
groupname = groupInfo.getGroupName();
groupid = groupInfo.getGroupId();
} else {
group = PublicGroupsSeachActivity.searchedGroup;
if (group == null)
return;
groupname = group.getGroupName();
groupid = group.getGroupId();
}
tv_name.setText(groupname);
if (group != null) {
showGroupDetail();
return;
}
new Thread(new Runnable() {
public void run() {
//get detail from server
try {
group = EMClient.getInstance().groupManager().getGroupFromServer(groupid);
runOnUiThread(new Runnable() {
public void run() {
showGroupDetail();
}
});
} catch (final HyphenateException e) {
e.printStackTrace();
final String st1 = getResources().getString(R.string.Failed_to_get_group_chat_information);
runOnUiThread(new Runnable() {
public void run() {
ToastUtil.showToast(GroupSimpleDetailActivity.this, st1 + e.getMessage(), 0).show();
}
});
}
}
}).start();
}
//join the group
public void addToGroup(View view) {
String st1 = getResources().getString(R.string.Is_sending_a_request);
final String st2 = getResources().getString(R.string.Request_to_join);
final String st3 = getResources().getString(R.string.send_the_request_is);
final String st4 = getResources().getString(R.string.Join_the_group_chat);
final String st5 = getResources().getString(R.string.Failed_to_join_the_group_chat);
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage(st1);
pd.setCanceledOnTouchOutside(false);
pd.show();
new Thread(new Runnable() {
public void run() {
try {
//if group is membersOnly,you need apply to join
if (group.isMembersOnly()) {
EMClient.getInstance().groupManager().applyJoinToGroup(groupid, st2);
} else {
EMClient.getInstance().groupManager().joinGroup(groupid);
}
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
if (group.isMembersOnly())
ToastUtil.showToast(GroupSimpleDetailActivity.this, st3, 0).show();
else
ToastUtil.showToast(GroupSimpleDetailActivity.this, st4, 0).show();
btn_add_group.setEnabled(false);
}
});
} catch (final HyphenateException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
ToastUtil.showToast(GroupSimpleDetailActivity.this, st5 + e.getMessage(), 0).show();
}
});
}
}
}).start();
}
private void showGroupDetail() {
//get group detail, and you are not in, then show join button
if (!group.getMembers().contains(EMClient.getInstance().getCurrentUser()))
btn_add_group.setEnabled(true);
tv_name.setText(group.getGroupName());
tv_admin.setText(EaseUserUtils.getUserInfo(group.getOwner()).getNickname());
tv_introduction.setText(group.getDescription());
}
public void back(View view) {
finish();
}
}
| 38.535032 | 112 | 0.585455 |
f6a699b3809bbb4dc0b98ccf5c6696c6dff243c9 | 149 | package domain.usecases.assistent;
import domain.entities.Assistent;
public interface AddAssistent {
void addAssistent(Assistent assistent);
}
| 18.625 | 43 | 0.805369 |
a9a0e14690b24b6cfc68007501ea631995021a39 | 3,348 | package com.github.hollykunge.serviceunitproject.serviceimpl;
import com.alibaba.fastjson.JSONObject;
import com.github.hollykunge.serviceunitproject.common.UserInfo;
import com.github.hollykunge.serviceunitproject.service.IUserService;
import com.github.hollykunge.serviceunitproject.service.UserPositionService;
import com.github.hollykunge.serviceunitproject.serviceimpl.servicebiz.Synchrodata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class UserPositionServiceImpl implements UserPositionService {
@Autowired
IUserService iUserService;
@Value("${spring.address}")
private String address;
/**
* 获取人员岗位信息
*
* @author guxq
*/
@Override
public UserInfo getUserPosition(String userID) {
Map p2 = new HashMap<>();
p2.put("userid",userID);
UserInfo userInfo = iUserService.getUserInfo(p2);
//开发使用
/* String templatefilePath = "D:\\jsonpersonpostion.json";
String s = readJsonFile(templatefilePath);
JSONObject json = JSONObject.parseObject(s);*/
//正式使用
String ss= getServiceJsonString(userID);
log.info("说明用户岗位接口访问成功");
JSONObject json = JSONObject.parseObject(ss);
if(json==null){
log.error("接口访问不到数据,两种");
return userInfo;
}
String org = (String) json.get("org");
String position = (String) json.get("position");
String responsyslist = (String) json.get("responsyslist");
String partsyslist = (String) json.get("partsyslist");
userInfo.setErbuorg(org);
userInfo.setPosition(position);
userInfo.setResponsyslist(responsyslist);
userInfo.setPartsyslist(partsyslist);
return userInfo;
}
/**
* 读取json文件,返回json串
* @param fileName
* @return
*/
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"gb2312");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private String getServiceJsonString(String userPid){
URL url = null;
String rtnStr="";
try {
url = new URL(address);
Synchrodata synchrodata = new Synchrodata(url);
rtnStr = synchrodata.getSynchrodataHttpSoap12Endpoint().getUserPosition(userPid);
} catch (Exception e) {
e.printStackTrace();
log.error("访问协同设计用户岗位主数据webservice出错",e);
return rtnStr;
}
return rtnStr;
}
}
| 29.892857 | 93 | 0.634409 |
257b9215bab3e42cf3ea9ab9331033d0ef71a7f5 | 1,825 | package bl4ckscor3.discord.bl4ckb0t.module.blackjack;
public class Card
{
private Rank rank;
private Suit suit;
private boolean cuttingCard = false;
/**
* Sets this card to be a cutting card
*/
public Card()
{
cuttingCard = true;
}
/**
* Initializes a new playing card
* @param r The rank of the card
* @param s The suit of the card
*/
public Card(Rank r, Suit s)
{
rank = r;
suit = s;
}
/**
* @return The card's rank
*/
public Rank getRank()
{
return rank;
}
/**
* @return The card's suit
*/
public Suit getSuit()
{
return suit;
}
/**
* @return True if this card is a cutting card, false otherwise
*/
public boolean isCuttingCard()
{
return cuttingCard;
}
/**
* @return This card's value
*/
public int value()
{
return rank.value;
}
@Override
public String toString()
{
return !isCuttingCard() ? suit.toString() + " " + rank.toString() : "Cutting Card";
}
public static enum Rank
{
TWO(2, "2"),
THREE(3, "3"),
FOUR(4, "4"),
FIVE(5, "5"),
SIX(6, "6"),
SEVEN(7, "7"),
EIGHT(8, "8"),
NINE(9, "9"),
TEN(10, "10"),
JACK(10, "J"),
QUEEN(10, "Q"),
KING(10, "K"),
ACE(11, "A"); //ace can also be 1, but that is handled in the game logic
private int value;
private String string;
Rank(int v, String r)
{
value = v;
string = r;
}
public int getValue()
{
return value;
}
@Override
public String toString()
{
return string;
}
}
public static enum Suit
{
HEARTS("♥️"),
CLUBS("♣️"),
DIAMONDS("♦️"),
SPADES("♠️");
private String string;
Suit(String r)
{
string = r;
}
@Override
public String toString()
{
return string;
}
}
}
| 14.717742 | 86 | 0.540274 |
2f0fccf20939c1c9ec93c476f5165909a24d2b02 | 4,529 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.hackprinceton.team9;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int activity_main=0x7f020000;
public static final int background=0x7f020001;
public static final int buttonjoincojoy=0x7f020002;
public static final int buttonjoincojoyp=0x7f020003;
public static final int buttonstartcojoy=0x7f020004;
public static final int end=0x7f020005;
public static final int final2=0x7f020006;
public static final int ic_launcher=0x7f020007;
public static final int play=0x7f020008;
public static final int rand=0x7f020009;
}
public static final class id {
public static final int action_end=0x7f08000a;
public static final int action_settings=0x7f080008;
public static final int action_shuffle=0x7f080009;
public static final int btn_join=0x7f080000;
public static final int btn_start=0x7f080001;
public static final int cur_play=0x7f080002;
public static final int current_artist=0x7f080004;
public static final int current_title=0x7f080003;
public static final int song_artist=0x7f080007;
public static final int song_list=0x7f080005;
public static final int song_title=0x7f080006;
}
public static final class layout {
public static final int activity_hosting_start=0x7f030000;
public static final int activity_join=0x7f030001;
public static final int activity_main=0x7f030002;
public static final int activity_music_player=0x7f030003;
public static final int song=0x7f030004;
}
public static final class menu {
public static final int hosting_start=0x7f070000;
public static final int join=0x7f070001;
public static final int main=0x7f070002;
public static final int music_player=0x7f070003;
}
public static final class string {
public static final int action_settings=0x7f050001;
public static final int app_name=0x7f050000;
public static final int btn_join_cojoy=0x7f050004;
public static final int btn_start_cojoy=0x7f050003;
public static final int currently_playing=0x7f050008;
public static final int hello_world=0x7f050002;
public static final int homepage=0x7f050005;
public static final int title_activity_join=0x7f050007;
public static final int title_activity_music_player=0x7f050006;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
| 42.726415 | 91 | 0.705233 |
76d75ddc57192c1ea92dbf21057fb2a827cec4fd | 13,871 | package com.amily.tycoon.login;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.amily.tycoon.R;
import com.amily.tycoon.home.HomeActivity;
import com.amily.tycoon.models.User;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthInvalidUserException;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.iid.FirebaseInstanceId;
import com.muddzdev.styleabletoastlibrary.StyleableToast;
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private Context mContext = LoginActivity.this;
// firebase
private FirebaseAuth mAuth;
private DatabaseReference mRootRef;
// widgets
private Button mLoginBtn, mSignupBtn;
private EditText mEmail, mPassword;
private TextView mForgotPassword;
private ProgressBar mProgressBar;
private AlertDialog alertDialog;
private Dialog mDialog;
private EditText mEnteredEmailDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Log.e(TAG, "onCreate: Login activity started gracefully" );
mContext = LoginActivity.this;
mDialog = new Dialog(this);
mDialog.setContentView(R.layout.layout_forgot_password);
mAuth = FirebaseAuth.getInstance();
mRootRef = FirebaseDatabase.getInstance().getReference();
mLoginBtn = findViewById(R.id.login_btn);
mSignupBtn = findViewById(R.id.sign_up_btn);
mEmail = findViewById(R.id.email_login_activity);
mPassword = findViewById(R.id.password_login_activity);
mForgotPassword = findViewById(R.id.forgotPassword_tv);
mProgressBar = findViewById(R.id.progressbar);
mProgressBar.setVisibility(View.GONE);
alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
mLoginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: attempting to login" );
if(checkInputs(mEmail.getText().toString(), mPassword.getText().toString())) {
// checking internet connection
try {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()) {
mProgressBar.setVisibility(View.VISIBLE);
mLoginBtn.setEnabled(false);
mSignupBtn.setEnabled(false);
mEmail.setEnabled(false);
mPassword.setEnabled(false);
loginTheUser(mEmail.getText().toString().toLowerCase(), mPassword.getText().toString());
}
else {
mProgressBar.setVisibility(View.GONE);
Toast.makeText(mContext, "Check your internet connection", Toast.LENGTH_SHORT).show();
mProgressBar.setVisibility(View.GONE);
mLoginBtn.setEnabled(true);
mSignupBtn.setEnabled(true);
mEmail.setEnabled(true);
mPassword.setEnabled(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
else
Toast.makeText(mContext, "All the text fields should not be empty", Toast.LENGTH_SHORT).show();
}
});
mSignupBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: navigating to sign up activity" );
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
mForgotPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popUpDialog();
}
});
}
private void popUpDialog() {
TextView txtclose;
Button cancelBtn, submitBtn;
final ProgressBar progressBarDialog;
txtclose = mDialog.findViewById(R.id.txtclose);
cancelBtn = mDialog.findViewById(R.id.cancel_btn_dialog);
mEnteredEmailDialog = mDialog.findViewById(R.id.send_offer_btn_dialog_et);
submitBtn = mDialog.findViewById(R.id.send_offer_btn_dialog);
progressBarDialog = mDialog.findViewById(R.id.progressbarDialog);
progressBarDialog.setVisibility(View.GONE);
cancelBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
}
});
txtclose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
}
});
submitBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!mEnteredEmailDialog.getText().toString().equals("")) {
progressBarDialog.setVisibility(View.VISIBLE);
getEmail(mEnteredEmailDialog.getText().toString(), progressBarDialog);
}
else {
StyleableToast.makeText(mContext, "Enter your email please", R.style.customToast).show();
}
}
});
mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mDialog.show();
}
private void getEmail(final String email, final ProgressBar progressBarDialog) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_users))
.orderByChild(getString(R.string.field_email))
.equalTo(email.toLowerCase());
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
try {
progressBarDialog.setVisibility(View.GONE);
String string = dataSnapshot.getValue().toString();
String stringWithPassword = string.substring(string.lastIndexOf("psw=") + 4); // we added 4 to skip 4 characters which are (psw=)
int iend = stringWithPassword.indexOf(",");
String password = null;
if (iend != -1) {
password = stringWithPassword.substring(0, iend); //this will give abc
}
alertDialog.setTitle("Tinny");
alertDialog.setMessage("The password hint is : " + password.substring(0, password.length() - 2) + "**");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
mDialog.dismiss();
}catch (Exception e) {
Log.e(TAG, "onDataChange: THERE IS AN EXCEPTION : " + e.getMessage());
}
}
else {
alertDialog.setTitle("Tinny");
alertDialog.setMessage("Invalid email, check your email and try again.");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
progressBarDialog.setVisibility(View.GONE);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private boolean checkInputs(String email, String password) {
if(TextUtils.isEmpty(email) || TextUtils.isEmpty(password) ) {
Toast.makeText(mContext, "All the text fields should not be empty", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void loginTheUser(String email, String password) {
FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
String devicetoken = FirebaseInstanceId.getInstance().getToken();
mRootRef.child(getString(R.string.dbname_users))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(getString(R.string.field_device_token))
.setValue(devicetoken).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()) {
try {
Log.e(TAG, "onComplete: The login the user" );
Intent loginIntent = new Intent(mContext, HomeActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
catch (Exception e) {
Log.e(TAG, "onComplete: " + e.getMessage() );
}
}
else {
Toast.makeText(LoginActivity.this, "There is a problem in regarding log in", Toast.LENGTH_SHORT).show();
}
}
});
}
else if(task.getException() instanceof FirebaseAuthInvalidUserException){ // If a user is already registered
alertDialog.setTitle("Tinny");
alertDialog.setMessage("Invalid email, check your email and try again.");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}else if(task.getException() instanceof FirebaseAuthInvalidCredentialsException){ // If the password is weak
alertDialog.setTitle("Tinny");
alertDialog.setMessage("Invalid password, check your password and try again.");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
mProgressBar.setVisibility(View.GONE);
mLoginBtn.setEnabled(true);
mSignupBtn.setEnabled(true);
mEmail.setEnabled(true);
mPassword.setEnabled(true);
}
});
}
}
| 42.289634 | 153 | 0.56492 |
b715ec2429ec199a981f6f3663ceb7faced31d44 | 4,437 | package p000ai.api.util;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Set;
/* renamed from: ai.api.util.PartialDate */
public class PartialDate {
private static final String UNSPECIFIED_DATE = "uu";
private static final String UNSPECIFIED_HOUR = "uu";
private static final String UNSPECIFIED_MINUTE = "uu";
private static final String UNSPECIFIED_MONTH = "uu";
public static final Integer UNSPECIFIED_VALUE = null;
private static final String UNSPECIFIED_YEAR = "uuuu";
/* renamed from: c */
private final Calendar f2c;
private final Set<Integer> unspecifiedFields;
public PartialDate() {
this.unspecifiedFields = new HashSet();
this.f2c = Calendar.getInstance();
}
public PartialDate(Calendar calendar) {
this.unspecifiedFields = new HashSet();
this.f2c = calendar;
}
public PartialDate(Date date) {
this.unspecifiedFields = new HashSet();
GregorianCalendar gregorianCalendar = new GregorianCalendar();
this.f2c = gregorianCalendar;
gregorianCalendar.setTime(date);
}
public void set(int i, Integer num) {
if (num != UNSPECIFIED_VALUE) {
this.unspecifiedFields.remove(Integer.valueOf(i));
this.f2c.set(i, num.intValue());
} else if (i == 1) {
this.unspecifiedFields.add(1);
} else if (i == 2) {
this.unspecifiedFields.add(2);
} else if (i >= 3 && i <= 8) {
this.unspecifiedFields.add(5);
} else if (i >= 10 && i <= 11) {
this.unspecifiedFields.add(11);
} else if (i == 12) {
this.unspecifiedFields.add(12);
}
}
public Integer get(int i) {
if (i == 1) {
if (!this.unspecifiedFields.contains(1)) {
return Integer.valueOf(this.f2c.get(i));
}
return UNSPECIFIED_VALUE;
} else if (i == 2) {
if (!this.unspecifiedFields.contains(2)) {
return Integer.valueOf(this.f2c.get(i));
}
return UNSPECIFIED_VALUE;
} else if (i < 3 || i > 8) {
if (i < 10 || i > 11) {
if (i != 12) {
return Integer.valueOf(this.f2c.get(i));
}
if (!this.unspecifiedFields.contains(12)) {
return Integer.valueOf(this.f2c.get(12));
}
return UNSPECIFIED_VALUE;
} else if (!this.unspecifiedFields.contains(11)) {
return Integer.valueOf(this.f2c.get(i));
} else {
return UNSPECIFIED_VALUE;
}
} else if (!this.unspecifiedFields.contains(5)) {
return Integer.valueOf(this.f2c.get(i));
} else {
return UNSPECIFIED_VALUE;
}
}
private String getFieldAsString(int i) {
if (i == 1) {
if (this.unspecifiedFields.contains(1)) {
return UNSPECIFIED_YEAR;
}
return String.format("%4d", new Object[]{Integer.valueOf(this.f2c.get(i))});
} else if (i == 2) {
if (this.unspecifiedFields.contains(2)) {
return "uu";
}
return String.format("%02d", new Object[]{Integer.valueOf(this.f2c.get(i))});
} else if (i < 3 || i > 8) {
if (i < 10 || i > 11) {
if (i != 12) {
return String.format("%s", new Object[]{Integer.valueOf(this.f2c.get(i))});
} else if (this.unspecifiedFields.contains(12)) {
return "uu";
} else {
return String.format("%02d", new Object[]{Integer.valueOf(this.f2c.get(i))});
}
} else if (this.unspecifiedFields.contains(11)) {
return "uu";
} else {
return String.format("%02d", new Object[]{Integer.valueOf(this.f2c.get(i))});
}
} else if (this.unspecifiedFields.contains(5)) {
return "uu";
} else {
return String.format("%02d", new Object[]{Integer.valueOf(this.f2c.get(i))});
}
}
public String toString() {
return String.format("%s-%s-%s", new Object[]{getFieldAsString(1), getFieldAsString(2), getFieldAsString(5)});
}
}
| 35.782258 | 118 | 0.538427 |
d3d97ba1259ecb4128676ff11d81f90ca6c31bf9 | 16,872 | /*
* Copyright (c) 2008-2016, GigaSpaces Technologies, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gigaspaces.internal.metadata;
import com.gigaspaces.document.DocumentProperties;
import com.gigaspaces.internal.io.IOUtils;
import com.gigaspaces.internal.metadata.converter.ConversionException;
import com.gigaspaces.internal.reflection.IConstructor;
import com.gigaspaces.internal.reflection.IParamsConstructor;
import com.gigaspaces.internal.server.space.SpaceUidFactory;
import com.gigaspaces.internal.version.PlatformLogicalVersion;
import com.gigaspaces.metadata.SpaceMetadataException;
import com.gigaspaces.metadata.SpaceMetadataValidationException;
import com.gigaspaces.time.SystemTime;
import com.j_spaces.core.IGSEntry;
import net.jini.core.lease.Lease;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Map.Entry;
/**
* Pojo introspector for all the pojo implementations.
*
* @author Niv Ingberg
* @since 7.0
*/
@com.gigaspaces.api.InternalApi
public class PojoIntrospector<T> extends AbstractTypeIntrospector<T> {
// serialVersionUID should never be changed.
private static final long serialVersionUID = 1L;
public static final byte EXTERNALIZABLE_CODE = 1;
private SpaceTypeInfo _typeInfo;
private transient IConstructor<T> _constructor;
private transient SpacePropertyInfo _idProperty;
private transient SpacePropertyInfo _versionProperty;
private transient SpacePropertyInfo _timeToLiveProperty;
private transient SpacePropertyInfo _transientProperty;
private transient SpacePropertyInfo _dynamicPropertiesProperty;
private transient boolean _isAutoPkGen;
private transient boolean _transient;
private transient Class<T> _pojoClass;
/**
* Default constructor for Externalizable.
*/
public PojoIntrospector() {
}
public PojoIntrospector(ITypeDesc typeDesc) {
super(typeDesc);
SpaceTypeInfo typeInfo = SpaceTypeInfoRepository.getTypeInfo(typeDesc.getObjectClass());
init(typeInfo);
}
public Class<T> getType() {
return _pojoClass;
}
public T newInstance() {
return _constructor.newInstance();
}
@Override
public T toObject(IGSEntry entry, ITypeDesc typeDesc) {
if (!_typeInfo.hasConstructorProperties())
return super.toObject(entry, typeDesc);
try {
return instantiateObjectByConstructor(entry.getFieldsValues(),
null /* dynamicProperties */,
entry.getUID(),
entry.getVersion(),
entry.getTimeToLive(),
entry.isTransient());
} catch (Exception e) {
throw new ConversionException(e);
}
}
@Override
protected T instantiateObject(
Object[] values,
Map<String, Object> dynamicProperties,
String uid,
int version,
long timeToLive,
boolean isTransient) {
if (!_typeInfo.hasConstructorProperties()) {
return super.instantiateObject(values, dynamicProperties, uid, version, timeToLive, isTransient);
}
return instantiateObjectByConstructor(values, dynamicProperties, uid, version, timeToLive, isTransient);
}
@SuppressWarnings("unchecked")
private T instantiateObjectByConstructor(
Object[] values,
Map<String, Object> dynamicProperties,
String uid,
int version,
long timeToLive,
boolean isTransient) {
return (T) _typeInfo.createConstructorBasedInstance(values,
dynamicProperties,
uid,
version,
calculateLease(timeToLive),
!isTransient);
}
@Override
protected Object[] processDocumentObjectInterop(Object[] values, EntryType entryType, boolean cloneOnChange) {
return entryType.isVirtual() ? fromDocumentIfNeeded(values, cloneOnChange) : values;
}
public int getVersion(T target) {
if (_versionProperty == null)
return 0;
Integer version = (Integer) _versionProperty.getValue(target);
return version == null ? 0 : version.intValue();
}
public boolean setVersion(T target, int version) {
if (_versionProperty == null)
return false;
try {
_versionProperty.setValue(target, version);
return true;
} catch (Throwable e) {
throw new ConversionException("Failed to set pojo version", e);
}
}
public long getTimeToLive(T target) {
if (_timeToLiveProperty == null)
return Lease.FOREVER;
Long ttl = (Long) _timeToLiveProperty.getValue(target);
long realTTL = (ttl == null ? 0 : ttl.longValue());
return realTTL - SystemTime.timeMillis();
}
public boolean setTimeToLive(T target, long ttl) {
if (_timeToLiveProperty == null)
return false;
try {
_timeToLiveProperty.setValue(target, calculateLease(ttl));
return true;
} catch (Throwable e) {
throw new ConversionException("Failed to set pojo lease.", e);
}
}
private static long calculateLease(long ttl) {
return ttl == Long.MAX_VALUE ? ttl : ttl + SystemTime.timeMillis();
}
public boolean isTransient(T target) {
if (_transientProperty == null || target == null)
return _transient;
try {
Boolean persistent = (Boolean) getValue(target, _transientProperty);
return persistent == null ? true : !persistent;
} catch (Exception e) {
throw new ConversionException("Failed to get pojo transient", e);
}
}
public boolean setTransient(T target, boolean isTransient) {
if (_transientProperty == null)
return false;
try {
_transientProperty.setValue(target, !isTransient);
return true;
} catch (Exception e) {
throw new ConversionException("Failed to set pojo transient", e);
}
}
public boolean hasDynamicProperties() {
return _dynamicPropertiesProperty != null;
}
public Map<String, Object> getDynamicProperties(T target) {
if (_dynamicPropertiesProperty == null)
return null;
Map<String, Object> properties = (Map<String, Object>) _dynamicPropertiesProperty.getValue(target);
if (properties == null)
return null;
DocumentProperties dynamicProperties = new DocumentProperties(properties.size());
for (Entry<String, Object> entry : properties.entrySet()) {
if (_typeDesc.getFixedPropertyPosition(entry.getKey()) != -1)
throw new SpaceMetadataException("Illegal dynamic property '" + entry.getKey() + "' in type '" + _typeDesc.getTypeName() + "' - this property is defined as a fixed property.");
dynamicProperties.put(entry.getKey(), entry.getValue());
}
return dynamicProperties;
}
public void setDynamicProperties(T target, Map<String, Object> dynamicProperties) {
if (_dynamicPropertiesProperty == null)
return;
if (dynamicProperties == null)
_dynamicPropertiesProperty.setValue(target, null);
else {
Map<String, Object> properties = (Map<String, Object>) _dynamicPropertiesProperty.getValue(target);
if (properties == null) {
properties = new DocumentProperties();
_dynamicPropertiesProperty.setValue(target, properties);
}
properties.putAll(dynamicProperties);
}
}
public Object[] getValues(T target) {
try {
final Object[] values = _typeInfo.getSpacePropertiesValues(target, false);
for (int i = 0; i < values.length; i++) {
SpacePropertyInfo property = _typeInfo.getProperty(i);
if (_isAutoPkGen && property == _idProperty)
values[i] = null;
else
values[i] = property.convertToNullIfNeeded(values[i]);
}
return values;
} catch (Exception e) {
throw new ConversionException(e);
}
}
public void setValues(T target, Object[] values) {
try {
_typeInfo.setSpacePropertiesValues(target, values);
} catch (Exception e) {
throw new ConversionException(e);
}
}
public Object getValue(T target, int index) {
try {
return getValue(target, _typeInfo.getProperty(index));
} catch (Exception e) {
throw new ConversionException(e);
}
}
private Object getValue(T target, SpacePropertyInfo property) {
Object value = property.getValue(target);
return property.convertToNullIfNeeded(value);
}
public void setValue(T target, Object value, int index) {
try {
setValue(target, _typeInfo.getProperty(index), value);
} catch (Exception e) {
throw new ConversionException(e);
}
}
private void setValue(T target, SpacePropertyInfo property, Object value) {
value = property.convertFromNullIfNeeded(value);
property.setValue(target, value);
}
protected Object getDynamicProperty(T target, String name) {
if (_dynamicPropertiesProperty == null)
return null;
Map<String, Object> properties = (Map<String, Object>) _dynamicPropertiesProperty.getValue(target);
if (properties == null)
return null;
return properties.get(name);
}
public void setDynamicProperty(T target, String name, Object value) {
if (_dynamicPropertiesProperty != null) {
Map<String, Object> properties = (Map<String, Object>) _dynamicPropertiesProperty.getValue(target);
if (properties == null) {
properties = new DocumentProperties();
_dynamicPropertiesProperty.setValue(target, properties);
}
properties.put(name, value);
}
}
@Override
public void unsetDynamicProperty(T target, String name) {
if (_dynamicPropertiesProperty != null) {
Map<String, Object> properties = (Map<String, Object>) _dynamicPropertiesProperty.getValue(target);
if (properties != null)
properties.remove(name);
}
}
private void init(SpaceTypeInfo typeInfo) {
this._typeInfo = typeInfo;
this._pojoClass = (Class<T>) typeInfo.getType();
if (typeInfo.hasConstructorProperties()) {
// validation only, the instantiation logic exists in typeInfo
IParamsConstructor<?> paramsConstructor = typeInfo.getParamsConstructor();
if (paramsConstructor == null)
throw new SpaceMetadataValidationException(_pojoClass, "Missing expected constructor");
} else {
this._constructor = (IConstructor<T>) typeInfo.getDefaultConstructor();
if (_constructor == null)
throw new SpaceMetadataValidationException(_pojoClass, "Must be a public static class and have a default constructor.");
}
_idProperty = typeInfo.getIdProperty();
_versionProperty = typeInfo.getVersionProperty();
_timeToLiveProperty = typeInfo.getLeaseExpirationProperty();
_transientProperty = typeInfo.getPersistProperty();
_dynamicPropertiesProperty = typeInfo.getDynamicPropertiesProperty();
_isAutoPkGen = typeInfo.getIdAutoGenerate();
_transient = !typeInfo.isPersist();
}
public String getUID(T target, boolean isTemplate, boolean ignoreIdIfNotExists) {
// If no SpaceId property:
if (_idProperty == null) {
if (ignoreIdIfNotExists)
return null;
throw new SpaceMetadataException("Cannot get uid - SpaceId property is not defined.");
}
final Object id = getValue(target, _idProperty);
// If SpaceId(autoGenerate=true):
if (_isAutoPkGen) {
if (id != null)
return id.toString();
if (ignoreIdIfNotExists)
return null;
throw new SpaceMetadataException("SpaceId(autoGenerate=true) property value cannot be null.");
}
// If SpaceId(autoGenerate=false):
// Do not generate uid for templates - required to support inheritance and SQLQuery.
if (isTemplate)
return null;
// generate the uid from the id property and the type's name:
if (id != null)
return SpaceUidFactory.createUidFromTypeAndId(getTypeDesc(), id);
throw new SpaceMetadataException("SpaceId(autoGenerate=false) property value cannot be null.");
}
public boolean setUID(T target, String uid) {
try {
// If no id property cannot set uid:
if (_idProperty == null)
return false;
// If id property is autoGenerate false cannot set uid:
if (!_isAutoPkGen)
return false;
// if id is already set do not override it:
String fieldValue = (String) getValue(target, _idProperty);
if (fieldValue != null && fieldValue.length() != 0)
return false;
// Set uid:
setValue(target, _idProperty, uid);
return true;
} catch (Exception e) {
throw new SpaceMetadataException("Failed to set uid for type " + getType().getName(), e);
}
}
public void setEntryInfo(T target, String uid, int version, long ttl) {
setUID(target, uid);
setVersion(target, version);
}
public boolean hasTimeToLiveProperty(T target) {
return _timeToLiveProperty != null;
}
public boolean hasTransientProperty(T target) {
return _transientProperty != null;
}
public boolean hasUID(T target) {
return _idProperty != null && _isAutoPkGen && getValue(target, _idProperty) != null;
}
public boolean hasVersionProperty(T target) {
return _versionProperty != null;
}
@Override
public boolean propertyHasNullValue(int position) {
return _typeInfo.getProperty(position).hasNullValue();
}
@Override
public boolean hasConstructorProperties() {
return _typeInfo.hasConstructorProperties();
}
@Override
public byte getExternalizableCode() {
return EXTERNALIZABLE_CODE;
}
@Override
public void readExternal(ObjectInput in, PlatformLogicalVersion version)
throws IOException, ClassNotFoundException {
super.readExternal(in, version);
if (version.greaterOrEquals(PlatformLogicalVersion.v10_1_0))
readExternalV10_1(in, version);
else
readExternalV7_1(in);
}
private void readExternalV10_1(ObjectInput in, PlatformLogicalVersion version) throws IOException, ClassNotFoundException {
SpaceTypeInfo typeInfo = new SpaceTypeInfo();
typeInfo.readExternal(in, version);
init(typeInfo);
}
private void readExternalV7_1(ObjectInput in) throws IOException, ClassNotFoundException {
SpaceTypeInfo typeInfo = IOUtils.readObject(in);
init(typeInfo);
}
/**
* NOTE: if you change this method, you need to make this class ISwapExternalizable
*/
@Override
public void writeExternal(ObjectOutput out, PlatformLogicalVersion version)
throws IOException {
super.writeExternal(out, version);
if (version.greaterOrEquals(PlatformLogicalVersion.v10_1_0))
writeExternalV10_1(out, version);
else
writeExternalV7_1(out);
}
private void writeExternalV10_1(ObjectOutput out, PlatformLogicalVersion version) throws IOException {
_typeInfo.writeExternal(out, version);
}
private void writeExternalV7_1(ObjectOutput out) throws IOException {
IOUtils.writeObject(out, _typeInfo);
}
}
| 34.859504 | 192 | 0.641358 |
3ddb97583d4d22cfd98336acd4efef5b9a8867a3 | 8,610 | /*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.mmaico.shared.libraries;
import java.util.Arrays;
/**
* Miscellaneous object utility methods.
* Mainly for internal use within the framework.
*
* <p>Thanks to Alex Ruiz for contributing several enhancements to this class!
*
* @author Juergen Hoeller
* @author Keith Donald
* @author Rod Johnson
* @author Rob Harrop
* @author Chris Beams
* @since 19.03.2004
*/
public abstract class ObjectUtils {
private static final int INITIAL_HASH = 7;
private static final int MULTIPLIER = 31;
//---------------------------------------------------------------------
// Convenience methods for content-based equality/hash-code handling
//---------------------------------------------------------------------
/**
* Determine if the given objects are equal, returning {@code true}
* if both are {@code null} or {@code false} if only one is
* {@code null}.
* <p>Compares arrays with {@code Arrays.equals}, performing an equality
* check based on the array elements rather than the array reference.
* @param o1 first Object to compare
* @param o2 second Object to compare
* @return whether the given objects are equal
* @see java.util.Arrays#equals
*/
public static boolean nullSafeEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
if (o1.getClass().isArray() && o2.getClass().isArray()) {
if (o1 instanceof Object[] && o2 instanceof Object[]) {
return Arrays.equals((Object[]) o1, (Object[]) o2);
}
if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
return Arrays.equals((boolean[]) o1, (boolean[]) o2);
}
if (o1 instanceof byte[] && o2 instanceof byte[]) {
return Arrays.equals((byte[]) o1, (byte[]) o2);
}
if (o1 instanceof char[] && o2 instanceof char[]) {
return Arrays.equals((char[]) o1, (char[]) o2);
}
if (o1 instanceof double[] && o2 instanceof double[]) {
return Arrays.equals((double[]) o1, (double[]) o2);
}
if (o1 instanceof float[] && o2 instanceof float[]) {
return Arrays.equals((float[]) o1, (float[]) o2);
}
if (o1 instanceof int[] && o2 instanceof int[]) {
return Arrays.equals((int[]) o1, (int[]) o2);
}
if (o1 instanceof long[] && o2 instanceof long[]) {
return Arrays.equals((long[]) o1, (long[]) o2);
}
if (o1 instanceof short[] && o2 instanceof short[]) {
return Arrays.equals((short[]) o1, (short[]) o2);
}
}
return false;
}
/**
* Return as hash code for the given object; typically the value of
* {@code Object#hashCode()}}. If the object is an array,
* this method will delegate to any of the {@code nullSafeHashCode}
* methods for arrays in this class. If the object is {@code null},
* this method returns 0.
* @see #nullSafeHashCode(Object[])
* @see #nullSafeHashCode(boolean[])
* @see #nullSafeHashCode(byte[])
* @see #nullSafeHashCode(char[])
* @see #nullSafeHashCode(double[])
* @see #nullSafeHashCode(float[])
* @see #nullSafeHashCode(int[])
* @see #nullSafeHashCode(long[])
* @see #nullSafeHashCode(short[])
*/
public static int nullSafeHashCode(Object obj) {
if (obj == null) {
return 0;
}
if (obj.getClass().isArray()) {
if (obj instanceof Object[]) {
return nullSafeHashCode((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeHashCode((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeHashCode((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeHashCode((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeHashCode((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeHashCode((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeHashCode((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeHashCode((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeHashCode((short[]) obj);
}
}
return obj.hashCode();
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(Object[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (Object element : array) {
hash = MULTIPLIER * hash + nullSafeHashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(boolean[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (boolean element : array) {
hash = MULTIPLIER * hash + hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(byte[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (byte element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(char[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (char element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(double[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (double element : array) {
hash = MULTIPLIER * hash + hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(float[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (float element : array) {
hash = MULTIPLIER * hash + hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(int[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (int element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(long[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (long element : array) {
hash = MULTIPLIER * hash + hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(short[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (short element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
/**
* Return the same value as {@link Boolean#hashCode()}}.
* @see Boolean#hashCode()
*/
public static int hashCode(boolean bool) {
return (bool ? 1231 : 1237);
}
/**
* Return the same value as {@link Double#hashCode()}}.
* @see Double#hashCode()
*/
public static int hashCode(double dbl) {
return hashCode(Double.doubleToLongBits(dbl));
}
/**
* Return the same value as {@link Float#hashCode()}}.
* @see Float#hashCode()
*/
public static int hashCode(float flt) {
return Float.floatToIntBits(flt);
}
/**
* Return the same value as {@link Long#hashCode()}}.
* @see Long#hashCode()
*/
public static int hashCode(long lng) {
return (int) (lng ^ (lng >>> 32));
}
}
| 27.246835 | 78 | 0.634146 |
525cfcdc877c5d266c37364b7f57a811ef2031d8 | 687 | package com.dmi.gradle.ndkclassic.sample;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class HelloActivity extends Activity {
static {
System.loadLibrary("hello");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(getMessage());
Toast.makeText(getApplicationContext(), HelloUniverse.getMessage(), Toast.LENGTH_LONG).show();
}
private native String getMessage();
}
| 28.625 | 102 | 0.720524 |
b150fb96c21289fed00e14777bf044081209d92f | 12,597 | package {service.namespace}.utils.sap.netweaver;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.NotImplementedException;
import {service.namespace}.auth.IApplicationUser;
import {service.namespace}.auth.IApplicationUserChangeBuilder;
import {service.namespace}.auth.IApplicationUserProvider;
import {service.namespace}.auth.IPrincipalSearchRequest;
import com.sap.security.api.IGroup;
import com.sap.security.api.IGroupFactory;
import com.sap.security.api.ISearchResult;
import com.sap.security.api.IUser;
import com.sap.security.api.IUserFactory;
import com.sap.security.api.IUserMaint;
import com.sap.security.api.UMException;
import com.sap.security.api.UMFactory;
import com.sap.tc.logging.Location;
import com.sap.tc.logging.Severity;
public class UMEApplicationUserProvider extends AbstractUMEApplicationPrincipalProvider implements IApplicationUserProvider {
private static Location LOC = Location.getLocation(UMEApplicationUserProvider.class);
private static final int MAX_SEARCH_RESULT_SIZE_USERS = 20;
@Override
public int countUsers(IPrincipalSearchRequest searchRequest) {
boolean isJokerSearch = UMEHelper.hasNoSearchTermOrOnlyJoker(searchRequest.getSearchTerm());
TimedSection timedSection = null;
int count = 0;
try {
if (searchRequest.getHide().isEmpty() && searchRequest.getContainedInGroups().isEmpty() && isJokerSearch) {
// IF We have no group and hide restrictions AND a joker search, we have to return the count for all
// users
timedSection = TimedSection.start(LOC, "countUsers(all with joker)",
"isJokerSearch=" + isJokerSearch + " searchRequest=" + searchRequest);
IUserFactory userFactory = UMFactory.getUserFactory();
ISearchResult uniqueIDsSearchResult = userFactory.getUniqueIDs();
count = uniqueIDsSearchResult.size();
} else if (searchRequest.getHide().isEmpty() && searchRequest.getContainedInGroups().isEmpty()
&& !isJokerSearch) {
// IF We have no group and hide restrictions BUT NOT a joker search, we have to check ALL users based on
// names
timedSection = TimedSection.start(LOC, "countUsers(noHides,noGroups)",
"isJokerSearch=" + isJokerSearch + " searchRequest=" + searchRequest);
count = UMEHelper.countUsersWithName(searchRequest.getSearchTerm(), MAX_SEARCH_RESULT_SIZE_USERS);
} else if (!searchRequest.getContainedInGroups().isEmpty()) {
// IF We have Group Search Request, we collect all members by groups
timedSection = TimedSection.start(LOC,
"countUsers(withGroups,hide=" + !searchRequest.getHide().isEmpty() + ")",
"isJokerSearch=" + isJokerSearch + " searchRequest=" + searchRequest);
List<IApplicationUser> foundUsers = new ArrayList<>();
addUserMembersFromGivenGroups(searchRequest, foundUsers);
count = foundUsers.size();
} else {
timedSection = TimedSection.start(LOC, "countUsers(noOptimization)",
"isJokerSearch=" + isJokerSearch + " searchRequest=" + searchRequest);
count = getUsers(searchRequest).length;
}
} catch (UMException e) {
LOC.traceThrowableT(Severity.ERROR,
"Error in countUsers() isJokerSearch=" + isJokerSearch + " searchRequest=" + searchRequest, e);
} finally {
if (timedSection != null) {
timedSection.finish("count=" + count);
}
}
return count;
}
@Override
public IApplicationUser[] getUsers(IPrincipalSearchRequest searchRequest) {
boolean isJokerSearch = UMEHelper.hasNoSearchTermOrOnlyJoker(searchRequest.getSearchTerm());
TimedSection timedSection = null;
List<IApplicationUser> foundUsers = new ArrayList<>();
try {
IUserFactory userFactory = UMFactory.getUserFactory();
if (searchRequest.getHide().isEmpty() && searchRequest.getContainedInGroups().isEmpty() && isJokerSearch) {
// IF We have no group and hide restrictions AND a joker search, we have to return the all
// users (restricted to maximum requested)
timedSection = TimedSection.start(LOC, "getUsers(all with joker)",
"isJokerSearch=" + isJokerSearch + " searchRequest=" + searchRequest);
addUsersIfMatchesSearch(userFactory.getUniqueIDs(), searchRequest, foundUsers);
} else if (searchRequest.getHide().isEmpty() && searchRequest.getContainedInGroups().isEmpty()
&& !isJokerSearch) {
// IF We have no group and hide restrictions BUT NOT a joker search, we have to check ALL users based on
// names
timedSection = TimedSection.start(LOC, "getUsers(noHides,noGroups)",
"isJokerSearch=" + isJokerSearch + " searchRequest=" + searchRequest);
addUsersIfMatchesSearch(
UMEHelper.searchUsersWithName(searchRequest.getSearchTerm(), MAX_SEARCH_RESULT_SIZE_USERS),
searchRequest, foundUsers);
} else if (!searchRequest.getContainedInGroups().isEmpty()) {
// IF We have Group Search Request, we collect all members by groups
timedSection = TimedSection.start(LOC,
"getUsers(withGroups,hide=" + !searchRequest.getHide().isEmpty() + ")",
"isJokerSearch=" + isJokerSearch + " searchRequest=" + searchRequest);
addUserMembersFromGivenGroups(searchRequest, foundUsers);
} else {
timedSection = TimedSection.start(LOC, "getUsers(noOptimization)",
"isJokerSearch=" + isJokerSearch + " searchRequest=" + searchRequest);
addUsersIfMatchesSearch(
UMEHelper.searchUsersWithName(searchRequest.getSearchTerm(), MAX_SEARCH_RESULT_SIZE_USERS),
searchRequest, foundUsers);
}
} catch (Exception e) {
LOC.traceThrowableT(Severity.ERROR,
"Error in getUsers() isJokerSearch=" + isJokerSearch + " searchRequest=" + searchRequest, e);
} finally {
if (timedSection != null) {
timedSection.finish("foundUsers.size=" + foundUsers.size());
}
}
return foundUsers.toArray(new IApplicationUser[] {});
}
@Override
public IApplicationUser getLoggedInUser(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
IUser user = UMFactory.getAuthenticator().getLoggedInUser(servletRequest, servletResponse);
IApplicationUser applicationUser = null;
if (user != null) {
applicationUser = new UMEUser(user);
}
return applicationUser;
}
@Override
public IApplicationUser getLoggedInUser() {
IUser user = UMFactory.getAuthenticator().getLoggedInUser();
IApplicationUser applicationUser = null;
if (user != null) {
applicationUser = new UMEUser(user);
}
return applicationUser;
}
@Override
public IApplicationUser getUserByUniqueName(String userUniqueName) {
try {
// @TODO make error tolerant, think about NotFoundException
IUserFactory userFactory = UMFactory.getUserFactory();
return new UMEUser(userFactory.getUserByUniqueName(userUniqueName));
} catch (Exception e) {
LOC.traceThrowableT(Severity.ERROR, "Error in search of user [" + userUniqueName + "]", e);
}
return null;
}
@Override
public void updateUser(IApplicationUserChangeBuilder changeBuilder) throws Exception {
// Retrieve the modifiable user object.
IUserMaint userMaint = (IUserMaint) changeBuilder.getChangeData();
// Write the changes to the user store.
userMaint.save();
userMaint.commit();
}
private void addUserMembersFromGivenGroups(IPrincipalSearchRequest searchRequest, List<IApplicationUser> foundUsers)
throws UMException {
Set<String> containedInGroups = searchRequest.getContainedInGroups();
IGroupFactory groupFactory = UMFactory.getGroupFactory();
for (String groupUniqueName : containedInGroups) {
try {
IGroup group = groupFactory.getGroupByUniqueName(groupUniqueName);
if (group != null) {
addUserMembersFromIGroup(group, searchRequest, foundUsers);
}
} catch (Exception e) {
LOC.traceThrowableT(Severity.ERROR,
"Error in addUserMembersFromGivenGroups() [groupUniqueName=" + groupUniqueName + "]", e);
}
}
}
private void addUserMembersFromIGroup(IGroup group, IPrincipalSearchRequest searchRequest,
List<IApplicationUser> foundUsers) throws UMException {
IGroupFactory groupFactory = UMFactory.getGroupFactory();
Iterator<String> userSearchResult = group.getUserMembers(false);
addUsersIfMatches(userSearchResult, searchRequest, foundUsers);
Iterator<String> subGroupSearchResult = group.getGroupMembers(false);
while (subGroupSearchResult != null && subGroupSearchResult.hasNext()
&& foundUsers.size() < MAX_SEARCH_RESULT_SIZE_USERS) {
String subGroupId = subGroupSearchResult.next();
try {
IGroup subGroup = groupFactory.getGroup(subGroupId);
addUserMembersFromIGroup(subGroup, searchRequest, foundUsers);
} catch (Exception e) {
LOC.traceThrowableT(Severity.ERROR,
"Error in addUserMembersFromIGroup() [subGroupId=" + subGroupId + "]", e);
}
}
}
private void addUsersIfMatchesSearch(ISearchResult userSearchResult, IPrincipalSearchRequest searchRequest,
List<IApplicationUser> foundUsers) throws UMException {
IUserFactory userFactory = UMFactory.getUserFactory();
if (userSearchResult != null) {
int state = userSearchResult.getState();
if (state == ISearchResult.SEARCH_RESULT_OK || state == ISearchResult.SIZE_LIMIT_EXCEEDED) {
while (userSearchResult != null && userSearchResult.hasNext()
&& foundUsers.size() < MAX_SEARCH_RESULT_SIZE_USERS) {
UMEUser appUser = new UMEUser(userFactory.getUser((String) userSearchResult.next()));
addUserIfMatches(appUser, searchRequest, foundUsers);
}
}
if (state != ISearchResult.SEARCH_RESULT_OK) {
String msg = "Error State " + searchResultStateAsTest(state) + " in search of user with searchRequest='"
+ searchRequest + "'";
if (ISearchResult.SIZE_LIMIT_EXCEEDED == state) {
LOC.warningT(msg);
} else {
LOC.errorT(msg);
}
}
}
}
private void addUsersIfMatches(Iterator<String> userSearchResult, IPrincipalSearchRequest searchRequest,
List<IApplicationUser> foundUsers) throws UMException {
IUserFactory userFactory = UMFactory.getUserFactory();
while (userSearchResult != null && userSearchResult.hasNext()
&& foundUsers.size() < MAX_SEARCH_RESULT_SIZE_USERS) {
UMEUser appUser = new UMEUser(userFactory.getUser(userSearchResult.next()));
addUserIfMatches(appUser, searchRequest, foundUsers);
}
}
/**
* Add User to foundUsers group, if he matched search Request
*
* @param appUser
* @param searchRequest
* @param foundUsers
*/
private void addUserIfMatches(IApplicationUser appUser, IPrincipalSearchRequest searchRequest,
List<IApplicationUser> foundUsers) {
boolean addUser = false;
if (!searchRequest.getHide().contains(appUser.getUniqueName())
&& (searchRequest.getContainedInGroups().isEmpty()
|| CollectionUtils.containsAny(appUser.getGroupUniqueNames(), searchRequest.getContainedInGroups()))) {
addUser = UMEHelper.matchesUserSearchTerm(appUser, searchRequest.getSearchTerm());
}
//LOC.debugT((addUser ? "Adding" : "Skipping") + " appUser " + appUser.getUniqueName() + " for searchRequest=" + searchRequest);
if (addUser) {
foundUsers.add(appUser);
}
}
}
| 48.825581 | 134 | 0.664761 |
c1014305a2321ebf8ca2aa8508f6eba943f72226 | 671 | package ca.bc.gov.open.jag.aireviewermockapi.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@Controller
public class ParentController {
Logger logger = LoggerFactory.getLogger(ParentController.class);
@PostMapping("/airsavejsondata")
public ResponseEntity documentReady(@RequestBody Object documentReady) {
logger.info("Request received");
return ResponseEntity.ok("Something Happened");
}
}
| 27.958333 | 76 | 0.789866 |
1e99ff929e795f29f16a28840f79b77a14ff4b75 | 5,453 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.log4j.lf5.viewer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* LogTableColumn
*
* @author Michael J. Sikorsky
* @author Brad Marlborough
*/
// Contributed by ThoughtWorks Inc.
public class LogTableColumn implements java.io.Serializable {
private static final long serialVersionUID = -4275827753626456547L;
// log4j table columns.
public final static LogTableColumn DATE = new LogTableColumn("Date");
public final static LogTableColumn THREAD = new LogTableColumn("Thread");
public final static LogTableColumn MESSAGE_NUM = new LogTableColumn("Message #");
public final static LogTableColumn LEVEL = new LogTableColumn("Level");
public final static LogTableColumn NDC = new LogTableColumn("NDC");
public final static LogTableColumn CATEGORY = new LogTableColumn("Category");
public final static LogTableColumn MESSAGE = new LogTableColumn("Message");
public final static LogTableColumn LOCATION = new LogTableColumn("Location");
public final static LogTableColumn THROWN = new LogTableColumn("Thrown");
//--------------------------------------------------------------------------
// Protected Variables:
//--------------------------------------------------------------------------
protected String _label;
//--------------------------------------------------------------------------
// Private Variables:
//--------------------------------------------------------------------------
private static LogTableColumn[] _log4JColumns;
private static Map _logTableColumnMap;
//--------------------------------------------------------------------------
// Constructors:
//--------------------------------------------------------------------------
static {
_log4JColumns = new LogTableColumn[]{DATE, THREAD, MESSAGE_NUM, LEVEL, NDC, CATEGORY,
MESSAGE, LOCATION, THROWN};
_logTableColumnMap = new HashMap();
for (int i = 0; i < _log4JColumns.length; i++) {
_logTableColumnMap.put(_log4JColumns[i].getLabel(), _log4JColumns[i]);
}
}
public LogTableColumn(String label) {
_label = label;
}
//--------------------------------------------------------------------------
// Public Methods:
//--------------------------------------------------------------------------
/**
* Return the Label of the LogLevel.
*/
public String getLabel() {
return _label;
}
/**
* Convert a column label into a LogTableColumn object.
*
* @param column The label of a level to be converted into a LogTableColumn.
* @return LogTableColumn The LogTableColumn with a label equal to column.
* @throws LogTableColumnFormatException Is thrown when the column can not be
* converted into a LogTableColumn.
*/
public static LogTableColumn valueOf(String column)
throws LogTableColumnFormatException {
LogTableColumn tableColumn = null;
if (column != null) {
column = column.trim();
tableColumn = (LogTableColumn) _logTableColumnMap.get(column);
}
if (tableColumn == null) {
StringBuffer buf = new StringBuffer();
buf.append("Error while trying to parse (" + column + ") into");
buf.append(" a LogTableColumn.");
throw new LogTableColumnFormatException(buf.toString());
}
return tableColumn;
}
public boolean equals(Object o) {
boolean equals = false;
if (o instanceof LogTableColumn) {
if (this.getLabel() ==
((LogTableColumn) o).getLabel()) {
equals = true;
}
}
return equals;
}
public int hashCode() {
return _label.hashCode();
}
public String toString() {
return _label;
}
/**
* @return A <code>List</code> of <code>LogTableColumn/code> objects that map
* to log4j <code>Column</code> objects.
*/
public static List getLogTableColumns() {
return Arrays.asList(_log4JColumns);
}
public static LogTableColumn[] getLogTableColumnArray() {
return _log4JColumns;
}
//--------------------------------------------------------------------------
// Protected Methods:
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Private Methods:
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Nested Top-Level Classes or Interfaces:
//--------------------------------------------------------------------------
}
| 32.652695 | 89 | 0.556391 |
2a113ae915437958111c70af5616cb64aa20981d | 1,216 | package com.rc.portal.service;
import java.sql.SQLException;
import java.util.List;
import com.rc.portal.vo.CPaymentWay;
import com.rc.portal.vo.CPaymentWayExample;
import com.rc.portal.vo.TMemberReceiverLatLon;
public interface CPaymentWayManager {
int countByExample(CPaymentWayExample example) throws SQLException;
int deleteByExample(CPaymentWayExample example) throws SQLException;
int deleteByPrimaryKey(Long id) throws SQLException;
Long insert(CPaymentWay record) throws SQLException;
Long insertSelective(CPaymentWay record) throws SQLException;
List selectByExample(CPaymentWayExample example) throws SQLException;
List<CPaymentWay> selectByExampleAndReceiverId(CPaymentWayExample example,TMemberReceiverLatLon receiverLatLon) throws SQLException;
CPaymentWay selectByPrimaryKey(Long id) throws SQLException;
int updateByExampleSelective(CPaymentWay record, CPaymentWayExample example) throws SQLException;
int updateByExample(CPaymentWay record, CPaymentWayExample example) throws SQLException;
int updateByPrimaryKeySelective(CPaymentWay record) throws SQLException;
int updateByPrimaryKey(CPaymentWay record) throws SQLException;
}
| 30.4 | 136 | 0.818257 |
fb102c4e50b0b1db3f7b0b4eff11c0935d5300be | 797 | package com.demkom58.springram.controller.method.result;
import com.demkom58.springram.controller.config.SpringramConfigurer;
import com.demkom58.springram.controller.message.SpringramMessage;
import org.springframework.core.MethodParameter;
import org.telegram.telegrambots.meta.bots.AbsSender;
import java.util.List;
/**
* Handler interface for handling results of handler
* methods. For creating custom handler implement it,
* then specify it in your
* {@link SpringramConfigurer#configureReturnValueHandlers(List)}
*
* @author Max Demydenko
* @since 0.1
*/
public interface HandlerMethodReturnValueHandler {
boolean isSupported(MethodParameter returnType);
void handle(MethodParameter returnType, SpringramMessage message, AbsSender bot, Object result) throws Exception;
}
| 33.208333 | 117 | 0.81054 |
58dbfa312e941f6e7949545f4edab2681a76cb82 | 362 | package de.sfn_kassel.FourierPaint;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* Created by robin on 19.07.15.
*/
public interface IBrush {
void applyTo(BufferedImage img, int x, int y);
void applyTo(BufferedImage img, int x1, int y1, int x2, int y2);
int getSize();
void setSize(int size);
void setColor(Color c);
}
| 18.1 | 68 | 0.679558 |
476dc199e04d1f26888c146d546b58761b768bc3 | 2,467 | package controller;
import static org.junit.Assert.*;
import java.awt.Point;
import org.junit.Test;
import controller.flightZone.ConvertDecimalDegreesToXYCoords;
import controller.flightZone.ZoneBounds;
// Add a new test which transforms in both directions accurately!
public class CoordinateTransformationTest {
@Test
public void testOriginTransform() {
ZoneBounds zoneBounds;
long latNorth = 42720000;
long latSouth = 42500000;
long lonWest = -86200000;
long lonEast = -85000000;
int leftPanel = 180;
int alt = 100;
zoneBounds = ZoneBounds.getInstance();
zoneBounds.setZoneBounds(latNorth, lonWest, latSouth, lonEast, alt);
long xRange = 1600;
long yRange = 960;
ConvertDecimalDegreesToXYCoords coordTransformation = new ConvertDecimalDegreesToXYCoords(xRange,yRange,180);
Point pnt = coordTransformation.getPoint(latNorth,lonWest);
System.out.println(pnt);
assert(pnt.x == leftPanel);
assert(pnt.y == 0);
}
@Test
public void TestOriginTransform2(){
ZoneBounds zoneBounds;
long latNorth = -42720000;
long latSouth = -42500000;
long lonWest = 86200000;
long lonEast = 85000000;
int alt = 100;
int leftPanel = 180;
zoneBounds = ZoneBounds.getInstance();
zoneBounds.setZoneBounds(latNorth, lonWest, latSouth, lonEast, alt);
long xRange = 1600;
long yRange = 960;
ConvertDecimalDegreesToXYCoords coordTransformation = new ConvertDecimalDegreesToXYCoords(xRange,yRange,180);
Point pnt = coordTransformation.getPoint(latNorth,lonWest);
System.out.println(pnt);
assert(pnt.x == leftPanel);
// Note this only works because the zone is square. If it is not square, then y and x are scaled according to the x fit.
assert(pnt.y == 0);
}
@Test
public void testDiaganolCornerTransform() {
ZoneBounds zoneBounds;
long latNorth = 42720000;
long latSouth = 42500000;
long lonWest = -86200000;
long lonEast = -85000000;
int alt = 100;
zoneBounds = ZoneBounds.getInstance();
zoneBounds.setZoneBounds(latNorth, lonWest, latSouth, lonEast, alt);
long xRange = 1600;
long yRange = 960;
ConvertDecimalDegreesToXYCoords coordTransformation = new ConvertDecimalDegreesToXYCoords(xRange,yRange,180);
Point pnt = coordTransformation.getPoint(latSouth,lonEast);
System.out.println(pnt);
assert(pnt.x == xRange);
// y uses x scaling so we check for y coordinate scal
assert(pnt.y == 260);
}
}
| 32.893333 | 124 | 0.724362 |
3f994c0344a02fcfa5fecf09a7887baeae2a9208 | 3,510 | /*
Derby - Class org.apache.derbyTesting.functionTests.util.Triggers
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.derbyTesting.functionTests.util;
import java.sql.*;
/**
* Methods for testing triggers
*/
public class Triggers
{
private static final String RESULT_SET_NOT_OPEN = "XCL16";
private Triggers()
{
}
public static int doNothingInt() throws Throwable
{
return 1;
}
public static void doNothing() throws Throwable
{}
public static int doConnCommitInt() throws Throwable
{
Connection conn = DriverManager.getConnection("jdbc:default:connection");
conn.commit();
return 1;
}
public static void doConnCommit() throws Throwable
{
Connection conn = DriverManager.getConnection("jdbc:default:connection");
conn.commit();
}
public static void doConnRollback() throws Throwable
{
Connection conn = DriverManager.getConnection("jdbc:default:connection");
conn.rollback();
}
public static void doConnectionSetIsolation() throws Throwable
{
Connection conn = DriverManager.getConnection("jdbc:default:connection");
conn.setTransactionIsolation(conn.TRANSACTION_SERIALIZABLE);
}
public static int doConnStmtIntNoRS(String text) throws Throwable
{
doConnStmtNoRS(text);
return 1;
}
public static void doConnStmtNoRS(String text) throws Throwable
{
Connection conn = DriverManager.getConnection("jdbc:default:connection");
Statement stmt = conn.createStatement();
stmt.execute(text);
}
public static int doConnStmtInt(String text) throws Throwable
{
doConnStmt(text);
return 1;
}
public static void doConnStmt(String text) throws Throwable
{
Connection conn = DriverManager.getConnection("jdbc:default:connection");
Statement stmt = conn.createStatement();
if (stmt.execute(text))
{
ResultSet rs = stmt.getResultSet();
try {
while (rs.next()) {}
} catch (SQLException e) {
if (RESULT_SET_NOT_OPEN.equals(e.getSQLState())) {
// Some side effect (stored proc?) made the rs close,
// bail out
} else {
throw e;
}
} finally {
rs.close();
}
}
stmt.close();
conn.close();
}
public static void getConnection() throws Throwable
{
Connection conn = DriverManager.getConnection("jdbc:default:connection");
conn.close();
System.out.println("getConnection() called");
}
// used for performance numbers
static void zipThroughRs(ResultSet s) throws SQLException
{
if (s == null)
return;
while (s.next()) ;
}
public static long returnPrimLong(long x)
{
return x;
}
public static Long returnLong(Long x)
{
return x;
}
} | 25.251799 | 75 | 0.693732 |
67ddc9c4581e1052a072bd57162fa0d1bb8639fc | 3,909 | // Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.messaging.cpp;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.flatbuffers.FlatBufferBuilder;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileLock;
/**
* A class that manages Registration Token generation and passes the generated tokens to the native
* OnTokenReceived function.
*/
public class RegistrationIntentService extends IntentService {
private static final String TAG = "FirebaseRegService";
public RegistrationIntentService() {
// The tag here is used only to name the worker thread; it's important only for debugging.
// http://developer.android.com/reference/android/app/IntentService.html#IntentService(java.lang.String)
super(TAG);
}
// Fetch the latest registration token and notify the C++ layer.
@Override
protected void onHandleIntent(Intent intent) {
String token = FirebaseInstanceId.getInstance().getToken();
DebugLogging.log(TAG, String.format("onHandleIntent token=%s", token));
if (token != null) {
writeTokenToInternalStorage(this, token);
}
}
/** Write token to internal storage so it can be accessed by the C++ layer. */
public static void writeTokenToInternalStorage(Context context, String token) {
byte[] buffer = generateTokenByteBuffer(token);
ByteBuffer sizeBuffer = ByteBuffer.allocate(4);
// Write out the buffer length into the first four bytes.
sizeBuffer.order(ByteOrder.LITTLE_ENDIAN);
sizeBuffer.putInt(buffer.length);
FileLock lock = null;
try {
// Acquire lock. This prevents the C++ code from consuming and clearing the file while we
// append to it.
FileOutputStream lockFileStream = context.openFileOutput(MessageWriter.LOCK_FILE, 0);
lock = lockFileStream.getChannel().lock();
FileOutputStream outputStream =
context.openFileOutput(MessageWriter.STORAGE_FILE, Context.MODE_APPEND);
// We send both the buffer length and the buffer itself so that we can potentially process
// more than one event in the case where they get queued up.
outputStream.write(sizeBuffer.array());
outputStream.write(buffer);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Release the lock.
try {
if (lock != null) {
lock.release();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static byte[] generateTokenByteBuffer(String token) {
FlatBufferBuilder builder = new FlatBufferBuilder(0);
int tokenOffset = builder.createString(token != null ? token : "");
SerializedTokenReceived.startSerializedTokenReceived(builder);
SerializedTokenReceived.addToken(builder, tokenOffset);
int tokenReceivedOffset = SerializedTokenReceived.endSerializedTokenReceived(builder);
SerializedEvent.startSerializedEvent(builder);
SerializedEvent.addEventType(builder, SerializedEventUnion.SerializedTokenReceived);
SerializedEvent.addEvent(builder, tokenReceivedOffset);
builder.finish(SerializedEvent.endSerializedEvent(builder));
return builder.sizedByteArray();
}
}
| 38.323529 | 108 | 0.733691 |
0d5c3aba8d6cc68c65b75ea242777c727b592afc | 8,852 | /**
* Copyright Indra Soluciones Tecnologías de la Información, S.L.U.
* 2013-2019 SPAIN
*
* 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.minsait.onesait.platform.business.services.cache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hazelcast.config.EvictionPolicy;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MaxSizeConfig;
import com.hazelcast.core.DistributedObject;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.minsait.onesait.platform.config.model.Cache;
import com.minsait.onesait.platform.config.model.Cache.Type;
import com.minsait.onesait.platform.config.model.User;
import com.minsait.onesait.platform.config.repository.CacheRepository;
import com.minsait.onesait.platform.config.services.cache.CacheService;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class CacheBusinessServiceImpl implements CacheBusinessService {
@Autowired
private CacheService cacheService;
@Autowired
private HazelcastInstance hazelcastInstance;
@Autowired
private CacheRepository cacheRepository;
private static final String HZ_MAP_SERVICE = "hz:impl:mapService";
private static final String MSG_NOT_EXIST_HEADER = "Cache with identification ";
private static final String MSG_NOT_EXIST_FOOTER = " does not exist or user does not have authorization";
@Override
public boolean cacheExists(String identification) {
boolean cacheEx = false;
if (cacheRepository.findCacheByIdentification(identification) != null)
cacheEx = true;
return cacheEx;
}
@Override
@Transactional
public <K, V> Cache createCache(Cache cacheData) throws CacheBusinessServiceException {
Cache cache = cacheService.createMap(cacheData);
if (cache != null) {
if (existCacheObject(cache)) {
throw new CacheBusinessServiceException(CacheBusinessServiceException.Error.NAME_OF_MAP_ALREADY_USED,
"Error creating map");
}
if (cache.getType() == Type.MAP) {
return createMap(cache);
}
else {
throw new CacheBusinessServiceException(CacheBusinessServiceException.Error.UNSUPPORTED_TYPE,
"The cache type is not supported");
}
} else {
throw new CacheBusinessServiceException(CacheBusinessServiceException.Error.CACHE_WAS_NOT_CREATED,
"Error creating map");
}
}
private <K, V> Cache createMap(Cache cache) {
createCacheObject(cache);
hazelcastInstance.<K, V>getMap(cache.getIdentification());
return cache;
}
public List<String> findCachesWithIdentification(String identification) {
List<Cache> caches;
List<String> identifications = new ArrayList<>();
caches = cacheRepository.findAllByOrderByIdentificationAsc();
for (final Cache cache : caches) {
identifications.add(cache.getIdentification());
}
return identifications;
}
public Cache getCacheWithId(String identification) {
Cache cache;
identification = identification == null ? "" : identification;
cache = cacheRepository.findCacheByIdentification(identification);
return cache;
}
public void deleteCacheById(String identification) {
final Cache cache = cacheRepository.findCacheByIdentification(identification);
cacheRepository.delete(cache);
}
private boolean existCacheObject(Cache cache) {
// check if the map already exists to avoid random access to previously created
// maps
Collection<DistributedObject> distributedObjects = hazelcastInstance.getDistributedObjects();
for (DistributedObject obj : distributedObjects) {
log.trace("name: {}, serviceName: {}", obj.getName(), obj.getServiceName());
if (obj.getName().equals(cache.getIdentification()) && obj.getServiceName().equals(HZ_MAP_SERVICE)) {
return true;
}
}
return false;
}
private void createCacheObject(Cache cache) {
MapConfig mapConfig = createMapConfig(cache);
hazelcastInstance.getConfig().addMapConfig(mapConfig);
}
private MapConfig createMapConfig(Cache cache) {
MaxSizeConfig maxSizeConfig = new MaxSizeConfig();
maxSizeConfig.setSize(cache.getSize());
maxSizeConfig.setMaxSizePolicy(MaxSizeConfig.MaxSizePolicy.valueOf(cache.getMaxSizePolicy().toString()));
MapConfig mapConfig = new MapConfig(cache.getIdentification());
mapConfig.setMaxSizeConfig(maxSizeConfig);
mapConfig.setEvictionPolicy(EvictionPolicy.valueOf(cache.getEvictionPolicy().toString()));
return mapConfig;
}
@Override
@Transactional
public <K, V> void deleteMap(String identification, User user) throws CacheBusinessServiceException {
cacheService.deleteByIdentificationAndUser(identification, user);
hazelcastInstance.<K, V>getMap(identification).destroy();
}
@Override
public <K, V> void putIntoMap(String identification, K key, V value, User user)
throws CacheBusinessServiceException {
Cache cacheCnf = cacheService.getCacheConfiguration(identification, user);
if (cacheCnf != null) {
hazelcastInstance.<K, V>getMap(cacheCnf.getIdentification()).put(key, value);
} else {
throw new CacheBusinessServiceException(CacheBusinessServiceException.Error.CACHE_DOES_NOT_EXIST,
MSG_NOT_EXIST_HEADER + identification + MSG_NOT_EXIST_FOOTER);
}
}
@Override
public <K, V> void putAllIntoMap(String identification, Map<K, V> map, User user)
throws CacheBusinessServiceException {
Cache cacheCnf = cacheService.getCacheConfiguration(identification, user);
if (cacheCnf != null) {
hazelcastInstance.<K, V>getMap(cacheCnf.getIdentification()).putAll(map);
} else {
throw new CacheBusinessServiceException(CacheBusinessServiceException.Error.CACHE_DOES_NOT_EXIST,
MSG_NOT_EXIST_HEADER + identification + MSG_NOT_EXIST_FOOTER);
}
}
@Override
public <K, V> V getFromMap(String identification, User user, K key) throws CacheBusinessServiceException {
Cache cacheCnf = cacheService.getCacheConfiguration(identification, user);
if (cacheCnf != null) {
return hazelcastInstance.<K, V>getMap(cacheCnf.getIdentification()).get(key);
} else {
throw new CacheBusinessServiceException(CacheBusinessServiceException.Error.CACHE_DOES_NOT_EXIST,
MSG_NOT_EXIST_HEADER + identification + MSG_NOT_EXIST_FOOTER);
}
}
@Override
public <K, V> Map<K, V> getAllFromMap(String identification, User user) throws CacheBusinessServiceException {
Cache cacheCnf = cacheService.getCacheConfiguration(identification, user);
if (cacheCnf != null) {
IMap<K, V> map = hazelcastInstance.<K, V>getMap(identification);
return map.getAll(map.keySet());
} else {
throw new CacheBusinessServiceException(CacheBusinessServiceException.Error.CACHE_DOES_NOT_EXIST,
MSG_NOT_EXIST_HEADER + identification + MSG_NOT_EXIST_FOOTER);
}
}
@Override
public <K, V> Map<K, V> getManyFromMap(String identification, User user, Set<K> keys)
throws CacheBusinessServiceException {
Cache cacheCnf = cacheService.getCacheConfiguration(identification, user);
if (cacheCnf != null) {
IMap<K, V> map = hazelcastInstance.<K, V>getMap(identification);
return map.getAll(keys);
} else {
throw new CacheBusinessServiceException(CacheBusinessServiceException.Error.CACHE_DOES_NOT_EXIST,
MSG_NOT_EXIST_HEADER + identification + MSG_NOT_EXIST_FOOTER);
}
}
@Override
public void updateCache(String identification, Cache editCache) {
final Cache cache = cacheRepository.findCacheByIdentification(identification);
if (cache != null) {
cache.setType(editCache.getType());
cache.setEvictionPolicy(editCache.getEvictionPolicy());
cache.setMaxSizePolicy(editCache.getMaxSizePolicy());
cache.setSize(editCache.getSize());
cacheRepository.save(cache);
}
}
@Override
public List<String> getCachesIdentifications(String userId) {
List<Cache> caches;
final List<String> identifications = new ArrayList<>();
caches = cacheRepository.findAllByOrderByIdentificationAsc();
for (final Cache cache : caches) {
identifications.add(cache.getIdentification());
}
return identifications;
}
@Override
public void initializeAll() {
List<Cache> caches = cacheService.findAll();
for (Cache cache : caches) {
createCacheObject(cache);
}
}
}
| 33.78626 | 111 | 0.772594 |
e3c1e448a9b78116c5eb099d18b0a0c2ec9be4f8 | 7,562 | /** FourthRatings class contains various methods that can be used to get average ratings
* (with/without filters) as well as additional helper methods:
*
* * getAverageRatings and getAverageRatingsByFilter are used to find movies that have required
* * number of ratings, and in case with getAverageRatingsByFilter can be filtered using a range
* * of filters provided in this program.
*
* * getSimilarRatings and getSimilarRatingsByFilter work similarly to the methods mentioned
* * above but additionally ratings are provided using weighted averages. A user will get more
* * personalized recommendations because movies that were highly rated by only similar raters
* * will be returned. numSimilarRaters method parameter can be changed in order to modify
* * the precision of the provided recommendations.
*/
import java.util.*;
public class FourthRatings
{
public FourthRatings ()
{
// default constructor
this("ratings.csv");
}
public FourthRatings (String ratingsfile)
{
RaterDatabase.initialize(ratingsfile);
}
private double getAverageByID (String id, int minimalRaters)
{
double sum = 0.0;
int count = 0;
for (Rater rater : RaterDatabase.getRaters())
{
if (rater.hasRating(id))
{
sum += rater.getRating(id);
count += 1;
}
}
if (count >= minimalRaters)
{
return sum / count;
} else {
return 0.0;
}
}
public ArrayList<Rating> getAverageRatings (int minimalRaters)
{
ArrayList<Rating> averageRatings = new ArrayList<Rating> ();
ArrayList<String> movies = MovieDatabase.filterBy(new TrueFilter());
for (String movieID : movies)
{
double average = Math.round(getAverageByID(movieID, minimalRaters) * 100.0) / 100.0;
if (average != 0.0)
{
Rating rating = new Rating (movieID, average);
averageRatings.add(rating);
}
}
return averageRatings;
}
public ArrayList<Rating> getAverageRatingsByFilter (int minimalRaters, Filter filterCriteria) {
ArrayList<Rating> averageRatings = new ArrayList<Rating> ();
ArrayList<String> filteredMovies = MovieDatabase.filterBy(filterCriteria);
for (String movieID : filteredMovies)
{
double average = Math.round(getAverageByID(movieID, minimalRaters) * 100.0) / 100.0;
if (average != 0.0)
{
Rating rating = new Rating (movieID, average);
averageRatings.add(rating);
}
}
return averageRatings;
}
private double dotProduct (Rater me, Rater r)
{
double dotProduct = 0.0;
ArrayList<String> itemsRatedMe = me.getItemsRated();
for (String item : itemsRatedMe)
{
if (r.getItemsRated().contains(item))
{
double currRatingR = r.getRating(item);
double currRatingMe = me.getRating(item);
dotProduct += (currRatingR - 5.0) * (currRatingMe - 5.0);
}
}
return dotProduct;
}
private ArrayList<Rating> getSimilarities (String id)
{
ArrayList<Rating> similarities = new ArrayList<Rating> ();
Rater me = RaterDatabase.getRater(id);
for (Rater currRater : RaterDatabase.getRaters())
{
if (! currRater.getID().equals(id))
{
double dotProduct = dotProduct(me, currRater);
if (dotProduct >= 0)
{
similarities.add(new Rating(currRater.getID(), dotProduct));
}
}
}
Collections.sort(similarities, Collections.reverseOrder());
return similarities;
}
public ArrayList<Rating> getSimilarRatings (String id, int numSimilarRaters, int minimalRaters) {
ArrayList<Rating> weightedRatings = new ArrayList<Rating> ();
ArrayList<Rating> similarRaters = getSimilarities(id);
ArrayList<String> movies = MovieDatabase.filterBy(new TrueFilter());
HashMap<String,Double> accumulatedRating = new HashMap<String,Double> ();
HashMap<String,Integer> accumulatedCount = new HashMap<String,Integer> ();
for (String movieID : movies) {
double currRating = 0.0;
int currCount = 0;
for (int k=0; k < numSimilarRaters; k++) {
Rating r = similarRaters.get(k);
String raterID = r.getItem();
double weight = r.getValue();
Rater rater = RaterDatabase.getRater(raterID);
if (rater.hasRating(movieID)) {
double rating = rater.getRating(movieID) * weight;
currRating += rating;
currCount += 1;
}
}
if (currCount >= minimalRaters) {
accumulatedRating.put(movieID, currRating);
accumulatedCount.put(movieID, currCount);
}
}
for (String movieID : accumulatedRating.keySet()) {
double weightedRating = Math.round((accumulatedRating.get(movieID) / accumulatedCount.get(movieID)) * 100.0) / 100.0;
Rating rating = new Rating (movieID, weightedRating);
weightedRatings.add(rating);
}
Collections.sort(weightedRatings, Collections.reverseOrder());
return weightedRatings;
}
public ArrayList<Rating> getSimilarRatingsByFilter
(String id, int numSimilarRaters, int minimalRaters, Filter filterCriteria) {
ArrayList<Rating> weightedRatings = new ArrayList<Rating> ();
ArrayList<Rating> similarRaters = getSimilarities(id);
ArrayList<String> filteredMovies = MovieDatabase.filterBy(filterCriteria);
HashMap<String,Double> accumulatedRating = new HashMap<String,Double> ();
HashMap<String,Integer> accumulatedCount = new HashMap<String,Integer> ();
for (String movieID : filteredMovies) {
double currRating = 0.0;
int currCount = 0;
for (int k=0; k < numSimilarRaters; k++) {
Rating r = similarRaters.get(k);
String raterID = r.getItem();
double weight = r.getValue();
Rater rater = RaterDatabase.getRater(raterID);
if (rater.hasRating(movieID)) {
double rating = rater.getRating(movieID) * weight;
currRating += rating;
currCount += 1;
}
}
if (currCount >= minimalRaters) {
accumulatedRating.put(movieID, currRating);
accumulatedCount.put(movieID, currCount);
}
}
for (String movieID : accumulatedRating.keySet()) {
double weightedRating = Math.round((accumulatedRating.get(movieID) / accumulatedCount.get(movieID)) * 100.0) / 100.0;
Rating rating = new Rating (movieID, weightedRating);
weightedRatings.add(rating);
}
Collections.sort(weightedRatings, Collections.reverseOrder());
return weightedRatings;
}
}
| 35.838863 | 130 | 0.573526 |
095565f055e785f907b11e4a2be5c2d411c3d5e5 | 192 | package com.omnicrola.pixelblaster.gui.fx;
import com.omnicrola.pixelblaster.gui.IScreenElement;
public interface IElementAffector {
void update(IScreenElement screenElement);
}
| 19.2 | 54 | 0.786458 |
a8b59fa94a52876cf28574e8185418d20321fad1 | 8,217 | package com.github.simonpercic.oklog.core;
import java.util.ArrayList;
import java.util.List;
/**
* Log data builder.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class LogDataBuilder {
// region BodyState
public enum BodyState {
PLAIN_BODY(1),
NO_BODY(2),
ENCODED_BODY(3),
BINARY_BODY(4),
CHARSET_MALFORMED(5);
private final int intValue;
BodyState(int intValue) {
this.intValue = intValue;
}
int getIntValue() {
return intValue;
}
}
// endregion BodyState
private String requestMethod;
private String requestUrl;
private String requestUrlPath;
private String protocol;
private String requestContentType;
private long requestContentLength;
private List<HeaderDataBuilder> requestHeaders;
private String requestBody;
private BodyState requestBodyState;
private boolean requestFailed;
private int responseCode;
private String responseMessage;
private String responseUrl;
private long responseDurationMs;
private long responseContentLength;
private List<HeaderDataBuilder> responseHeaders;
private BodyState responseBodyState;
private long responseBodySize;
private String responseBody;
LogDataBuilder() {
this.requestBodyState = BodyState.PLAIN_BODY;
this.responseBodyState = BodyState.PLAIN_BODY;
}
LogDataBuilder requestMethod(String requestMethod) {
this.requestMethod = requestMethod;
return this;
}
LogDataBuilder requestUrl(String requestUrl) {
this.requestUrl = requestUrl;
return this;
}
LogDataBuilder requestUrlPath(String requestUrlPath) {
this.requestUrlPath = requestUrlPath;
return this;
}
LogDataBuilder protocol(String protocol) {
this.protocol = protocol;
return this;
}
LogDataBuilder requestContentType(String contentType) {
this.requestContentType = contentType;
return this;
}
LogDataBuilder requestContentLength(long contentLength) {
this.requestContentLength = contentLength;
return this;
}
LogDataBuilder addRequestHeader(String name, String value) {
if (this.requestHeaders == null) {
this.requestHeaders = new ArrayList<>();
}
this.requestHeaders.add(new HeaderDataBuilder(name, value));
return this;
}
LogDataBuilder requestBody(String requestBody) {
this.requestBody = requestBody;
return this;
}
LogDataBuilder requestBodyState(BodyState requestBodyState) {
this.requestBodyState = requestBodyState;
return this;
}
public LogDataBuilder requestFailed() {
this.requestFailed = true;
return this;
}
LogDataBuilder responseCode(int responseCode) {
this.responseCode = responseCode;
return this;
}
LogDataBuilder responseMessage(String responseMessage) {
this.responseMessage = responseMessage;
return this;
}
LogDataBuilder responseUrl(String responseUrl) {
this.responseUrl = responseUrl;
return this;
}
public LogDataBuilder responseDurationMs(long responseDurationMs) {
this.responseDurationMs = responseDurationMs;
return this;
}
LogDataBuilder responseContentLength(long responseContentLength) {
this.responseContentLength = responseContentLength;
return this;
}
LogDataBuilder addResponseHeader(String name, String value) {
if (this.responseHeaders == null) {
this.responseHeaders = new ArrayList<>();
}
this.responseHeaders.add(new HeaderDataBuilder(name, value));
return this;
}
LogDataBuilder responseBodyState(BodyState responseBodyState) {
this.responseBodyState = responseBodyState;
return this;
}
LogDataBuilder responseBodySize(long responseBodySize) {
this.responseBodySize = responseBodySize;
return this;
}
LogDataBuilder responseBody(String responseBody) {
this.responseBody = responseBody;
return this;
}
// region Getters
String getRequestMethod() {
return requestMethod;
}
String getRequestUrl() {
return requestUrl;
}
String getRequestUrlPath() {
return requestUrlPath;
}
String getProtocol() {
return protocol;
}
String getRequestContentType() {
return requestContentType;
}
long getRequestContentLength() {
return requestContentLength;
}
List<HeaderDataBuilder> getRequestHeaders() {
return requestHeaders;
}
String getRequestBody() {
return requestBody;
}
BodyState getRequestBodyState() {
return requestBodyState;
}
boolean isRequestFailed() {
return requestFailed;
}
int getResponseCode() {
return responseCode;
}
String getResponseMessage() {
return responseMessage;
}
String getResponseUrl() {
return responseUrl;
}
long getResponseDurationMs() {
return responseDurationMs;
}
long getResponseContentLength() {
return responseContentLength;
}
List<HeaderDataBuilder> getResponseHeaders() {
return responseHeaders;
}
BodyState getResponseBodyState() {
return responseBodyState;
}
long getResponseBodySize() {
return responseBodySize;
}
String getResponseBody() {
return responseBody;
}
// endregion Getters
@Override public String toString() {
String requestHeadersString = "";
if (requestHeaders != null) {
for (HeaderDataBuilder requestHeader : requestHeaders) {
requestHeadersString += requestHeader.toString() + " ";
}
}
String responseHeadersString = "";
if (responseHeaders != null) {
for (HeaderDataBuilder responseHeader : responseHeaders) {
responseHeadersString += responseHeader.toString() + " ";
}
}
return "LogDataBuilder{"
+ "\n" + "requestMethod='" + requestMethod + '\''
+ "\n" + ", requestUrl='" + requestUrl + '\''
+ "\n" + ", requestUrlPath='" + requestUrlPath + '\''
+ "\n" + ", protocol='" + protocol + '\''
+ "\n" + ", requestContentType='" + requestContentType + '\''
+ "\n" + ", requestContentLength=" + requestContentLength
+ "\n" + ", requestHeaders=" + requestHeadersString
+ "\n" + ", requestBody='" + requestBody + '\''
+ "\n" + ", requestBodyState=" + requestBodyState
+ "\n" + ", requestFailed=" + requestFailed
+ "\n" + ", responseCode=" + responseCode
+ "\n" + ", responseMessage='" + responseMessage + '\''
+ "\n" + ", responseUrl='" + responseUrl + '\''
+ "\n" + ", responseDurationMs=" + responseDurationMs
+ "\n" + ", responseContentLength=" + responseContentLength
+ "\n" + ", responseHeaders=" + responseHeadersString
+ "\n" + ", responseBodyState=" + responseBodyState
+ "\n" + ", responseBodySize=" + responseBodySize
+ "\n" + ", responseBody='" + responseBody + '\''
+ "\n" + '}';
}
static final class HeaderDataBuilder {
private final String name;
private final String value;
private HeaderDataBuilder(String name, String value) {
this.name = name;
this.value = value;
}
String getName() {
return name;
}
String getValue() {
return value;
}
@Override public String toString() {
return "HeaderDataBuilder{"
+ "name='" + name + '\''
+ ", value='" + value + '\''
+ '}';
}
}
}
| 26.592233 | 99 | 0.600219 |
0c4047f45b8cd5114d87c3de6274e0154542d720 | 5,576 | package monitor.azkaban.checker;
import monitor.azkaban.sender.BaseEvent;
import monitor.azkaban.sender.SenderEvent;
import monitor.azkaban.util.AzkabanMetaUtil;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class JobStatusChecker extends ArrayList<JobStatusChecker.JobStatusCheckEvent> implements Runnable {
private static Logger LOG = Logger.getLogger(JobStatusChecker.class);
private LinkedBlockingQueue<SenderEvent> queue;
private BasicDataSource bds;
private int interval;
public static void setLogger(Logger logger) {
LOG = logger;
}
public JobStatusChecker(HierarchicalConfiguration conf, LinkedBlockingQueue<SenderEvent> queue, BasicDataSource bds, int interval) {
this.queue = queue;
this.bds = bds;
this.interval = interval;
initCheckList(conf);
}
private void initCheckList(HierarchicalConfiguration conf) {
conf.getList("");
ConfigurationNode cNode = conf.getRootNode();
for (ConfigurationNode check : cNode.getChildren()) {
String status = conf.getString(check.getName() + ".status");
if (status == null) continue;
this.add(new JobStatusCheckEvent(conf.getString(check.getName() + ".project", "%")
, conf.getString(check.getName() + ".flow", "%")
, conf.getString(check.getName() + ".job", "%")
, status
, conf.getInt(check.getName() + ".attempt", 0)
, conf.getString(check.getName() + ".sender")));
}
StringBuilder sb = new StringBuilder();
sb.append("JobStatusChecker initialized ").append(this.size()).append(" checkEvents : [");
for (JobStatusCheckEvent ce : this) {
sb.append(ce.toString()).append(",");
}
sb.append("]");
LOG.info(sb.toString());
}
@Override
public void run() {
long lastCheckTime = System.currentTimeMillis();
long currentCheckTime;
while (!Thread.interrupted()) {
currentCheckTime = System.currentTimeMillis();
for (JobStatusCheckEvent ce : this) {
if (ce.shouldCheck(lastCheckTime, currentCheckTime)) {
try {
List<SenderEvent> list = AzkabanMetaUtil.checkJobStatus(bds.getConnection()
, lastCheckTime
, currentCheckTime
, ce.getAttempt()
, ce.getStatus()
, ce.getProject()
, ce.getFlow()
, ce.getJob());
LOG.debug(String.format("JobStatusChecker run time range [%s, %s] on event %s, found %d events.",
lastCheckTime, currentCheckTime, ce.toString(), list.size()));
for (SenderEvent se : list) {
se.setType(SenderEvent.Type.JOBSTATUS);
se.setMsg(String.format("Job in status, execId=%d, project=%s, flow=%s, job=%s, attempt=%d, status=%s, start=%s, end=%s."
, se.getExecId(), se.getProject(), se.getFlow(), se.getJob(), se.getAttempt(), se.getStatus()
, new Date(se.getStartTime()), new Date(se.getEndTime())));
while (!queue.offer(se, interval, TimeUnit.MILLISECONDS)) {
LOG.warn(String.format("SenderEvent offer to dispacher failed, retry... %s", se));
}
LOG.info(String.format("Offer event to dispacher succ: %s", se));
}
} catch (InterruptedException e) {
LOG.warn("JobStatusChecker interrupted.", e);
Thread.currentThread().interrupt();
} catch (Exception e) {
LOG.warn(null, e);
}
}
}
lastCheckTime = currentCheckTime;
try {
TimeUnit.MILLISECONDS.sleep(interval);
} catch (InterruptedException e) {
LOG.warn("JobStatusChecker interrupted.", e);
Thread.currentThread().interrupt();
}
}
LOG.info("JobStatusChecker stopped.");
}
protected class JobStatusCheckEvent extends BaseEvent implements ShouldCheckable {
private JobStatusCheckEvent(String project, String flow, String job, String status, int attempt, String sender) {
setProject(project);
setFlow(flow);
setJob(job);
setStatus(status);
setAttempt(attempt);
setSender(sender);
}
@Override
public boolean shouldCheck(long start, long end) {
return true;
}
@Override
public String toString() {
return String.format("CheckEvent: project=%s, flow=%s, job=%s, status=%s, attempt=%s, sender=%s"
, getProject(), getFlow(), getJob(), getStatus(), getAttempt(), getSender());
}
}
}
| 43.224806 | 149 | 0.556313 |
5129a5e71257ce2f372d8f934e9f0c359bcaadc1 | 4,787 | /*
*
* Coadaptive Heterogeneous simulation Engine for Combat Kill-webs and
* Multi-Agent Training Environment (CHECKMATE)
*
* Copyright 2007 Jeff Ridder
*
* 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.ridderware.checkmate.rotations.quaternion;
import com.ridderware.checkmate.rotations.IRotationOperator;
import org.apache.logging.log4j.*;
/**
* A quaternion rotation operator is a special quaternion that has properties of rotating
* vectors in fixed frames, or frames relative to fixed vectors. A quaternion rotation operator
* must have a norm of 1 (i.e., be a unit quaternion), and operates on a vector which can be
* represented as a pure quaternion (vector in R3). This class provides rotation operators that require
* these two conditions to be true.
*
* @author Jeff Ridder
*/
public class QuaternionRotationOperator extends Quaternion implements IRotationOperator
{
private static Logger logger =
LogManager.getLogger(QuaternionRotationOperator.class);
/** Creates a new instance of QuaternionRotationOperator
* @param q0 scalar part.
* @param q1 i part.
* @param q2 j part.
* @param q3 k part.
*/
public QuaternionRotationOperator(double q0, double q1, double q2,
double q3)
{
super(q0, q1, q2, q3);
double norm = this.norm();
if (norm < 1. - 1e8 || norm > 1. + 1e8)
{
logger.error("Rotation operators must be unit quaternions! Not a unit quaternion: norm = " +
norm);
}
}
/**
* Creates a new instance of QuaternionRotationOperator that is a duplicate of q.
* @param q the quaternion to be duplicated.
*/
public QuaternionRotationOperator(Quaternion q)
{
this(q.q0, q.q1, q.q2, q.q3);
}
/**
* Returns the input vector rotated in a fixed frame.
* @param v vector to be rotated.
* @return the rotated vector.
*/
@Override
public final double[] rotateVector(double[] v)
{
if (v.length != 3)
{
logger.error("Rotation operators operate on pure quaterions (vector in R3). Not operating on a pure quaternion: length = " +
v.length);
}
final double[] w = new double[3];
final double p = 2 * q0 * q0 - 1;
final double Q11 = p + 2 * q1 * q1;
final double Q12 = 2 * q1 * q2 - 2 * q0 * q3;
final double Q13 = 2 * q1 * q3 + 2 * q0 * q2;
final double Q21 = Q12 + 4 * q0 * q3;
final double Q22 = p + 2 * q2 * q2;
final double Q23 = 2 * q2 * q3 - 2 * q0 * q1;
final double Q31 = Q13 - 4 * q0 * q2;
final double Q32 = Q23 + 4 * q0 * q1;
final double Q33 = p + 2 * q3 * q3;
w[0] = Q11 * v[0] + Q12 * v[1] + Q13 * v[2];
w[1] = Q21 * v[0] + Q22 * v[1] + Q23 * v[2];
w[2] = Q31 * v[0] + Q32 * v[1] + Q33 * v[2];
return w;
}
/**
* Rotates the frame about the input vector.
* @param v vector about which the frame is rotated.
* @return the vector in the rotated frame.
*/
@Override
public final double[] rotateFrame(double[] v)
{
if (v.length != 3)
{
logger.error("Rotation operators operate on pure quaterions (vector in R3). Not operating on a pure quaternion: length = " +
v.length);
}
final double[] w = new double[3];
final double p = 2 * q0 * q0 - 1;
final double Q11 = p + 2 * q1 * q1;
final double Q12 = 2 * q1 * q2 + 2 * q0 * q3;
final double Q13 = 2 * q1 * q3 - 2 * q0 * q2;
final double Q21 = Q12 - 4 * q0 * q3;
final double Q22 = p + 2 * q2 * q2;
final double Q23 = 2 * q2 * q3 + 2 * q0 * q1;
final double Q31 = Q13 + 4 * q0 * q2;
final double Q32 = Q23 - 4 * q0 * q1;
final double Q33 = p + 2 * q3 * q3;
w[0] = Q11 * v[0] + Q12 * v[1] + Q13 * v[2];
w[1] = Q21 * v[0] + Q22 * v[1] + Q23 * v[2];
w[2] = Q31 * v[0] + Q32 * v[1] + Q33 * v[2];
return w;
}
}
| 30.106918 | 137 | 0.564863 |
46d3240f73bd0f6deef51434a92a2840c26ded48 | 12,039 | package es.upm.fi.oeg.rider.domain;
import java.util.LinkedList;
import Jama.Matrix;
import es.upm.fi.oeg.rider.dataservice.DataService;
import es.upm.fi.oeg.rider.domain.mapping.MappingItem;
import es.upm.fi.oeg.rider.domain.mapping.MatrixMapping;
import es.upm.fi.oeg.rider.domain.ontology.qualitymodel.IntervalScale;
import es.upm.fi.oeg.rider.domain.ontology.qualitymodel.QualityMeasure;
import es.upm.fi.oeg.rider.domain.ontology.qualitymodel.RankingFunction;
import es.upm.fi.oeg.rider.domain.ontology.qualitymodel.RatioScale;
import es.upm.fi.oeg.rider.domain.recommendation.Alternative;
import es.upm.fi.oeg.rider.domain.recommendation.Requirement;
public class SupermatrixService {
// public static DataService service = new DataService();
// fills the supermatrix with alternatives comparisons
public static ANPMatrix fillSupermatrixWithAlternatives(ANPMatrix supermatrix,
LinkedList<Requirement> requirements, LinkedList<Alternative> alternatives,
DataService service, boolean onlyRequirement) {
if(onlyRequirement)
return fillSupermatrixWithAlternativesOnlyRequirementsComparison(supermatrix, requirements, alternatives, service);
else
return fillSupermatrixWithAlternativesALLComparisons(supermatrix, requirements, alternatives, service);
}
// fills the supermatrix with alternatives comparisons
public static ANPMatrix fillSupermatrixWithAlternativesOnlyRequirementsComparison(ANPMatrix supermatrix,
LinkedList<Requirement> requirements, LinkedList<Alternative> alternatives,
DataService service) {
int k = supermatrix.getRowDimension();
ANPMatrix extendedSupermatrix = supermatrix.extend(alternatives);
//--------------------------------
// adds comparisons of alternatives w.r.t. characteristics
//--------------------------------
for (Requirement requirement : requirements) {
Matrix mat = compareAlternatives(requirement,alternatives, service);
// columnIndex to put the comparison
int columnIndex = extendedSupermatrix.getMapping().
getRowNumber(requirement.getMeasure().getUri().toString());
extendedSupermatrix.setMatrixColumn(k, k+alternatives.size()-1, columnIndex, mat);
}
//--------------------------------
// adds comparisons of characteristics w.r.t. alternatives
//--------------------------------
LinkedList<String> alreadyCompared = new LinkedList<String>();
for (int i = 0; i < requirements.size(); i++) {
Requirement r = requirements.get(i);
LinkedList<Requirement> cluster = new LinkedList<Requirement>();
cluster.add(r);
if(alreadyCompared.contains(r.getMeasure().getQualityCharacteristic().getUri().toString()))
continue;
alreadyCompared.add(r.getMeasure().getQualityCharacteristic().getUri().toString());
for (int j = i+1; j < requirements.size(); j++) {
if(r.getMeasure().getQualityCharacteristic().getUri().
equals(requirements.get(j).getMeasure().getQualityCharacteristic().getUri()))
cluster.add(requirements.get(j));
}
if(cluster.size() == 1){
Matrix ones = new Matrix(1,alternatives.size(),1);
extendedSupermatrix.setMatrixRow(extendedSupermatrix.getMapping().getRowNumber(cluster.get(0).
getMeasure().getUri().toString()), k, k+alternatives.size()-1, ones);
}
else{
for (Alternative alternative : alternatives) {
Matrix mat = compareCharacteristics(cluster,alternative, service);
extendedSupermatrix.setMatrixColumn(getPositionsForClusterRequirements(extendedSupermatrix, cluster),
extendedSupermatrix.getMapping().getRowNumber(alternative.getId()),mat);
}
}
}
return extendedSupermatrix;
}
// compares the contribution of characteristics w.r.t an alternative and returns weights
public static Matrix compareCharacteristics(LinkedList<Requirement> requirements,
Alternative alternative, DataService service) {
int size = requirements.size();
ComparisonMatrix comparison = new ComparisonMatrix(size,size);
for (int i = 0; i < size; i++) {
for (int j = i; j < size; j++) {
if(i == j){
comparison.set(i, j, 1);
continue;
}
double result = ComparisonService.compareCharacteristics(alternative,
requirements.get(i), requirements.get(j));
comparison.set(i, j, result);
comparison.set(j, i, 1/result);
}
}
Matrix weights = comparison.getWeights();
return weights;
}
// compares alternatives w.r.t characteristic and returns weights
public static Matrix compareAlternatives(Requirement requirement,
LinkedList<Alternative> alternatives, DataService service) {
int size = alternatives.size();
ComparisonMatrix comparison = new ComparisonMatrix(size,size);
for (int i = 0; i < size; i++) {
for (int j = i; j < size; j++) {
if(i == j){
comparison.set(i, j, 1);
continue;
}
double result = ComparisonService.compareAlternatives(alternatives.get(i),
alternatives.get(j),requirement);
comparison.set(i, j, result);
comparison.set(j, i, 1/result);
}
}
Matrix weights = comparison.getWeights();
return weights;
}
// compares alternatives w.r.t characteristic and returns weights
public static Matrix compareAlternatives(QualityMeasure measure,
LinkedList<Alternative> alternatives, DataService service) {
int size = alternatives.size();
ComparisonMatrix comparison = new ComparisonMatrix(size, size);
for (int i = 0; i < size; i++) {
for (int j = i; j < size; j++) {
if (i == j) {
comparison.set(i, j, 1);
continue;
}
double result = ComparisonService.compareAlternatives(
alternatives.get(i), alternatives.get(j), measure);
comparison.set(i, j, result);
comparison.set(j, i, 1 / result);
}
}
Matrix weights = comparison.getWeights();
return weights;
}
// returns the array of row indexes that corresponds to the list of requirements
private static int[] getPositionsForClusterRequirements(ANPMatrix supermatrix,
LinkedList<Requirement> cluster) {
int[] indexes = new int[cluster.size()];
int k = 0;
for (Requirement requirement : cluster) {
indexes[k++] = supermatrix.getMapping().getRowNumber(requirement.getMeasure().
getUri().toString());
}
return indexes;
}
public static LinkedList<String> getRequirementsCriteriaUris(LinkedList<Requirement> requirements){
LinkedList<String> requirementsCharacteristicsUris = new LinkedList<String>();
for (Requirement req : requirements) {
String uri = req.getMeasure().getQualityCharacteristic().getUri().toString();
if(!requirementsCharacteristicsUris.contains(uri))
requirementsCharacteristicsUris.add(uri);
}
return requirementsCharacteristicsUris;
}
public static LinkedList<String> getCriteriaUris(MatrixMapping
supermatrixMapping, DataService service){
LinkedList<String> requirementsCharacteristicsUris = new LinkedList<String>();
for (MappingItem item : supermatrixMapping.getMappingItems()) {
if(item.getCriterionId().contains("Alternatives"))
continue;
String uri = service.getCharacteristicUriOfMeasure(
item.getCriterionId());
if(!requirementsCharacteristicsUris.contains(uri))
requirementsCharacteristicsUris.add(uri);
}
return requirementsCharacteristicsUris;
}
/**
* Fills the supermatrix with alternatives, which are compared not only to requirements but to
* all measures in the supermatrix
* @param supermatrix
* @param requirements
* @param alternatives
* @param service
* @return
*/
public static ANPMatrix fillSupermatrixWithAlternativesALLComparisons(ANPMatrix supermatrix,
LinkedList<Requirement> requirements, LinkedList<Alternative> alternatives,
DataService service) {
int k = supermatrix.getRowDimension();
ANPMatrix extendedSupermatrix = supermatrix.extend(alternatives);
for (int i = 0; i<k; i++) {
String measureUri = extendedSupermatrix.getMapping().getCriterionId(i);
Requirement requirement = getRequirement(requirements, measureUri, service);
AlternativesFactory.addMeasureToAlternatives(alternatives,measureUri, service);
Matrix mat = compareAlternatives(requirement,alternatives, service);
// columnIndex to put the comparison
int columnIndex = extendedSupermatrix.getMapping().
getRowNumber(requirement.getMeasure().getUri().toString());
extendedSupermatrix.setMatrixColumn(k, k+alternatives.size()-1, columnIndex, mat);
}
//--------------------------------
// adds comparisons of characteristics w.r.t. alternatives
//--------------------------------
LinkedList<String> alreadyCompared = new LinkedList<String>();
for (int i = 0; i < k; i++) {
String measureUri = extendedSupermatrix.getMapping().getCriterionId(i);
Requirement r = getRequirement(requirements, measureUri, service);
LinkedList<Requirement> cluster = new LinkedList<Requirement>();
cluster.add(r);
if(alreadyCompared.contains(r.getMeasure().getQualityCharacteristic().getUri().toString()))
continue;
alreadyCompared.add(r.getMeasure().getQualityCharacteristic().getUri().toString());
for (int j = i+1; j < k; j++) {
String measureUri2 = extendedSupermatrix.getMapping().getCriterionId(j);
Requirement r2 = getRequirement(requirements, measureUri2, service);
if(r.getMeasure().getQualityCharacteristic().getUri().
equals(r2.getMeasure().getQualityCharacteristic().getUri()))
cluster.add(r2);
}
if(cluster.size() == 1){
Matrix ones = new Matrix(1,alternatives.size(),1);
extendedSupermatrix.setMatrixRow(extendedSupermatrix.getMapping().getRowNumber(cluster.get(0).
getMeasure().getUri().toString()), k, k+alternatives.size()-1, ones);
}
else{
for (Alternative alternative : alternatives) {
Matrix mat = compareCharacteristics(cluster,alternative, service);
extendedSupermatrix.setMatrixColumn(getPositionsForClusterRequirements(extendedSupermatrix, cluster),
extendedSupermatrix.getMapping().getRowNumber(alternative.getId()),mat);
}
}
}
return extendedSupermatrix;
}
/**
* Returns the requirement that is related to a given measure. If the measure is not in the requirements list
* a new requirement is created for that measure with the threshold equals to the best value,
* so that a comparison can be performed.
* @param requirements
* @param measureUri
* @param service
* @return
*/
private static Requirement getRequirement(LinkedList<Requirement> requirements, String measureUri, DataService service){
for (Requirement requirement : requirements) {
if(requirement.getMeasure().getUri().toString().equals(measureUri))
return requirement;
}
QualityMeasure measure = service.getQualityMeasureObject(measureUri);
if(measure.getScale().getClass().getSimpleName().equalsIgnoreCase("RatioScale")){
RatioScale scale = (RatioScale) measure.getScale();
String threshold = "";
if(scale.getRankingFunction().equals(RankingFunction.HIGHER_BEST))
threshold = "1";
if(scale.getRankingFunction().equals(RankingFunction.LOWER_BEST))
threshold = "0";
return new Requirement(measure,threshold);
}
if(measure.getScale().getClass().getSimpleName().equalsIgnoreCase("IntervalScale")){
IntervalScale scale = (IntervalScale) measure.getScale();
String threshold = "";
if(scale.getRankingFunction().equals(RankingFunction.HIGHER_BEST))
threshold = String.valueOf(scale.getUpperBoundry());
if(scale.getRankingFunction().equals(RankingFunction.LOWER_BEST))
threshold = String.valueOf(scale.getLowerBoundry());
return new Requirement(measure,threshold);
}
return null;
}
}
| 38.340764 | 122 | 0.699975 |
2eae5e496b97a811d8987adb3239c19fadab0146 | 1,507 | package ua.com.zno.online.controllers.utils.error;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import ua.com.zno.online.exceptions.ZnoServerException;
import ua.com.zno.online.exceptions.ZnoUserException;
/**
* Created by quento on 26.03.17.
*/
@ControllerAdvice
public class GlobalErrorHandler {
private static final Logger LOG = LoggerFactory.getLogger(GlobalErrorHandler.class.getName());
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(value = ZnoServerException.class)
@ResponseBody
public String handleConflict(ZnoServerException e) {
LOG.debug("Handling ZnoServerException in GlobalErrorHandler", e);
return e.getMessage();
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = ZnoUserException.class)
@ResponseBody
public String handleConflict(ZnoUserException e) {
LOG.debug("Handling ZnoUserException in GlobalErrorHandler", e);
return e.getMessage();
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = Exception.class)
public void handleConflict(Exception e) {
LOG.error("Handling Exception in GlobalErrorHandler", e);
}
}
| 32.76087 | 98 | 0.769741 |
ffcb470b5427d43d5c487e07b266d73c78fb69b8 | 1,929 | package com.feng.webmagic.urlDataConfig;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class BlogUrlData {
public static final String baseUrl = "https://blog.csdn.net/";
public static final String accountName = "csdnnews";
public static final String detailUrlReg = "https://blog\\.csdn\\.net/\\S+/article/details/\\d+";
public static final String listUrlReg = "https://blog\\.csdn\\.net/\\S+/article/list/\\d+?";
public static final String detailUrl = baseUrl + accountName + "/article/details/\\d+";
public static final String listUrl = baseUrl + accountName + "/article/list/\\d+?";
private static String[] accountNames = SpiderBlogUserConfig.SpiderBlogUser;
public static String[] getSpiderUrl(String accountName) {
int pageNum = getPageNum(accountName);
String spiderUrls[] = new String[pageNum];
String startUrl = baseUrl + accountName + "/article/list/1?";
for (int i = 0; i < pageNum; i++) {
String url = startUrl.replaceAll("1\\?", i + 1 + "?");
log.info(url);
spiderUrls[i] = url;
}
return spiderUrls;
}
//todo 根据账号获取爬虫页面
public static int getPageNum(String accountName) {
return 10;
}
public static String[] getSpiderUrl() {
return getSpiderUrl(accountName);
}
public static List<String> getSpiderUrlList() {
List<String> blogUrlList = new ArrayList<>();
for (String account : accountNames) {
String[] url = getSpiderUrl(account);
List<String> urlList = Arrays.asList(url);
blogUrlList.addAll(urlList);
}
return blogUrlList;
}
public static String[] getSpiderUrls() {
List<String> blogUrlList = getSpiderUrlList();
return blogUrlList.toArray(new String[blogUrlList.size()]);
}
}
| 33.842105 | 100 | 0.641783 |
Subsets and Splits