hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 5
1.02k
| max_stars_repo_name
stringlengths 4
126
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequence | max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 5
1.02k
| max_issues_repo_name
stringlengths 4
114
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequence | max_issues_count
float64 1
92.2k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 5
1.02k
| max_forks_repo_name
stringlengths 4
136
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequence | max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2.55
99.9
| max_line_length
int64 3
1k
| alphanum_fraction
float64 0.25
1
| index
int64 0
1M
| content
stringlengths 3
1.05M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e00bd5d0c1252c33c6431a5c1691f986d0b5dfc | 567 | java | Java | src/test/java/com/googlecode/transloader/test/fixture/WithArrayFields.java | fmunch/transloader | d6c756feca97fac4c4a449791ca13fa5d6ee1e7c | [
"Apache-2.0"
] | 7 | 2017-12-19T10:06:20.000Z | 2021-03-14T04:02:09.000Z | src/test/java/com/googlecode/transloader/test/fixture/WithArrayFields.java | fmunch/transloader | d6c756feca97fac4c4a449791ca13fa5d6ee1e7c | [
"Apache-2.0"
] | null | null | null | src/test/java/com/googlecode/transloader/test/fixture/WithArrayFields.java | fmunch/transloader | d6c756feca97fac4c4a449791ca13fa5d6ee1e7c | [
"Apache-2.0"
] | 8 | 2017-06-13T22:34:27.000Z | 2021-03-14T04:36:06.000Z | 47.25 | 107 | 0.777778 | 301 | package com.googlecode.transloader.test.fixture;
import com.googlecode.transloader.test.Triangulate;
public class WithArrayFields extends NonCommonJavaObject {
private int[] ints = {Triangulate.anyInt(), Triangulate.anyInt()};
private Object[] objects = {Triangulate.anyString(), new WithPrimitiveFields(), Triangulate.anyString()};
private boolean[] noBooleans = {};
private NonCommonJavaObject[] nonCommonJavaObjects = {new WithStringField(Triangulate.anyString())};
private NonCommonJavaType[] nonCommonJavaTypes = {new WithPrimitiveFields()};
}
|
3e00bd5e5db219a4ec18931900b2b84e0eb74764 | 5,572 | java | Java | examples/engine/src/main/java/org/apache/qpid/proton/examples/Server.java | jdanekrh/qpid-proton-j | 1a5e1936944c11bae64244a3223e3be98b2d6d18 | [
"Apache-2.0"
] | 32 | 2017-05-10T14:06:13.000Z | 2022-03-08T17:49:04.000Z | examples/engine/java/src/main/java/org/apache/qpid/proton/examples/Server.java | astitcher/qpid-proton-old | e65525192f1852c1106b41d914dcdb6080a9edf4 | [
"Apache-2.0"
] | 28 | 2017-01-25T15:59:58.000Z | 2022-01-28T00:29:24.000Z | examples/engine/java/src/main/java/org/apache/qpid/proton/examples/Server.java | astitcher/qpid-proton-old | e65525192f1852c1106b41d914dcdb6080a9edf4 | [
"Apache-2.0"
] | 59 | 2016-12-18T22:50:42.000Z | 2022-01-28T00:25:57.000Z | 30.955556 | 95 | 0.570352 | 302 | /*
*
* 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.qpid.proton.examples;
import org.apache.qpid.proton.amqp.messaging.Accepted;
import org.apache.qpid.proton.engine.BaseHandler;
import org.apache.qpid.proton.engine.Collector;
import org.apache.qpid.proton.engine.Delivery;
import org.apache.qpid.proton.engine.Event;
import org.apache.qpid.proton.engine.Link;
import org.apache.qpid.proton.engine.Receiver;
import org.apache.qpid.proton.engine.Sender;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Server
*
*/
public class Server extends BaseHandler
{
private class MessageStore {
Map<String,Deque<Message>> messages = new HashMap<String,Deque<Message>>();
void put(String address, Message message) {
Deque<Message> queue = messages.get(address);
if (queue == null) {
queue = new ArrayDeque<Message>();
messages.put(address, queue);
}
queue.add(message);
}
Message get(String address) {
Deque<Message> queue = messages.get(address);
if (queue == null) { return null; }
Message msg = queue.remove();
if (queue.isEmpty()) {
messages.remove(address);
}
return msg;
}
}
final private MessageStore messages = new MessageStore();
final private Router router;
private boolean quiet;
private int tag = 0;
public Server(Router router, boolean quiet) {
this.router = router;
this.quiet = quiet;
}
private byte[] nextTag() {
return String.format("%s", tag++).getBytes();
}
private int send(String address) {
return send(address, null);
}
private int send(String address, Sender snd) {
if (snd == null) {
Router.Routes<Sender> routes = router.getOutgoing(address);
snd = routes.choose();
if (snd == null) {
return 0;
}
}
int count = 0;
while (snd.getCredit() > 0 && snd.getQueued() < 1024) {
Message msg = messages.get(address);
if (msg == null) {
snd.drained();
return count;
}
Delivery dlv = snd.delivery(nextTag());
byte[] bytes = msg.getBytes();
snd.send(bytes, 0, bytes.length);
dlv.settle();
count++;
if (!quiet) {
System.out.println(String.format("Sent message(%s): %s", address, msg));
}
}
return count;
}
@Override
public void onLinkFlow(Event evt) {
Link link = evt.getLink();
if (link instanceof Sender) {
Sender snd = (Sender) link;
send(router.getAddress(snd), snd);
}
}
@Override
public void onDelivery(Event evt) {
Delivery dlv = evt.getDelivery();
Link link = dlv.getLink();
if (link instanceof Sender) {
dlv.settle();
} else {
Receiver rcv = (Receiver) link;
if (!dlv.isPartial()) {
byte[] bytes = new byte[dlv.pending()];
rcv.recv(bytes, 0, bytes.length);
String address = router.getAddress(rcv);
Message message = new Message(bytes);
messages.put(address, message);
dlv.disposition(Accepted.getInstance());
dlv.settle();
if (!quiet) {
System.out.println(String.format("Got message(%s): %s", address, message));
}
send(address);
}
}
}
public static final void main(String[] argv) throws IOException {
List<String> switches = new ArrayList<String>();
List<String> args = new ArrayList<String>();
for (String s : argv) {
if (s.startsWith("-")) {
switches.add(s);
} else {
args.add(s);
}
}
boolean quiet = switches.contains("-q");
String host = !args.isEmpty() && !Character.isDigit(args.get(0).charAt(0)) ?
args.remove(0) : "localhost";
int port = !args.isEmpty() ? Integer.parseInt(args.remove(0)) : 5672;
Collector collector = Collector.Factory.create();
Router router = new Router();
Driver driver = new Driver(collector, new Handshaker(),
new FlowController(1024), router,
new Server(router, quiet));
driver.listen(host, port);
driver.run();
}
}
|
3e00bd7f3dc1fd29f632d00d46af727e31e84094 | 2,213 | java | Java | tracerj/src/main/java/tracer/profiles/ConvexProfile.java | Flash3388/Tracer | 26f5ecd5fa7b6a0e55ce81a5aa409492e0e21643 | [
"Apache-2.0"
] | 2 | 2019-08-30T20:51:45.000Z | 2019-12-29T11:56:04.000Z | src/main/java/tracer/profiles/ConvexProfile.java | DanielTheCUPMaker/Tracer | 728da680fe4db8cde0d7cdf041f77893c79e4dd8 | [
"Apache-2.0"
] | 97 | 2019-09-03T19:56:17.000Z | 2021-12-10T02:52:35.000Z | tracerj/src/main/java/tracer/profiles/ConvexProfile.java | Flash3388/Tracer | 26f5ecd5fa7b6a0e55ce81a5aa409492e0e21643 | [
"Apache-2.0"
] | null | null | null | 32.544118 | 115 | 0.729779 | 303 | package tracer.profiles;
import calculus.functions.polynomial.Linear;
import calculus.functions.polynomial.PolynomialFunction;
import com.flash3388.flashlib.time.Time;
import tracer.motion.MotionState;
import tracer.profiles.base.BaseProfile;
import tracer.profiles.base.BasicProfile;
import tracer.profiles.base.Profile;
import util.TimeConversion;
public class ConvexProfile extends BasicProfile {
private final PolynomialFunction distance;
private final PolynomialFunction velocity;
private final PolynomialFunction acceleration;
private final MotionState target;
public ConvexProfile(MotionState target) {
this(new ProfileState(), target);
}
public ConvexProfile(Profile prevProfile, MotionState target) {
this(prevProfile.finalState(), target);
}
public ConvexProfile(ProfileState initialState, MotionState target) {
super(initialState);
this.target = target;
acceleration = new Linear(-target.jerk(), 0);
velocity = new PolynomialFunction(-target.jerk()/2, target.acceleration(), 0.0);
distance = new PolynomialFunction(-target.jerk()/6, target.acceleration()/2, initialState.velocity(), 0.0);
}
@Override
public Time duration() {
return Time.seconds(target.acceleration()/target.jerk());
}
@Override
public BaseProfile repositionProfile(ProfileState newInitialState) {
return new ConvexProfile(newInitialState, target);
}
@Override
protected double relativeDistanceAt(Time relativeTime) {
double timeInSeconds = TimeConversion.toSeconds(relativeTime);
return distance.applyAsDouble(timeInSeconds);
}
@Override
protected double relativeVelocityAt(Time relativeTime) {
double timeInSeconds = TimeConversion.toSeconds(relativeTime);
return velocity.applyAsDouble(timeInSeconds);
}
@Override
protected double relativeAccelerationAt(Time relativeTime) {
double timeInSeconds = TimeConversion.toSeconds(relativeTime);
return acceleration.applyAsDouble(timeInSeconds);
}
@Override
protected double relativeJerkAt(Time relativeTime) {
return -target.jerk();
}
}
|
3e00bdc816e1ddaf61d18d9aeb4cda201fb8e4b6 | 562 | java | Java | lab-padroes-projetos-java/src/main/java/com/digitalInnovation/padroesprojetosjava/PadraoSingleton.java | lucasmarcuzo/Projeto-DIO-Padroes-Projetos-Java | 175eb82f4cd0c4824b4383b08de438b7faffab5a | [
"MIT"
] | null | null | null | lab-padroes-projetos-java/src/main/java/com/digitalInnovation/padroesprojetosjava/PadraoSingleton.java | lucasmarcuzo/Projeto-DIO-Padroes-Projetos-Java | 175eb82f4cd0c4824b4383b08de438b7faffab5a | [
"MIT"
] | null | null | null | lab-padroes-projetos-java/src/main/java/com/digitalInnovation/padroesprojetosjava/PadraoSingleton.java | lucasmarcuzo/Projeto-DIO-Padroes-Projetos-Java | 175eb82f4cd0c4824b4383b08de438b7faffab5a | [
"MIT"
] | null | null | null | 23.416667 | 61 | 0.617438 | 304 | package com.digitalInnovation.padroesprojetosjava;
public final class PadraoSingleton {
private static PadraoSingleton instance;
public String value;
private PadraoSingleton(String value) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
this.value = value;
}
public static PadraoSingleton getInstance(String value) {
if (instance == null) {
instance = new PadraoSingleton(value);
}
return instance;
}
} |
3e00be6b68027c192ef17f5efe80707ccd7db4f4 | 3,349 | java | Java | app/services/Email.java | douglasjd1/ArkansasPetPages | 882476eae01c633b4e09aed6fa2fefde6a88a526 | [
"CC0-1.0"
] | 1 | 2019-09-25T18:20:31.000Z | 2019-09-25T18:20:31.000Z | app/services/Email.java | douglasjd1/ArkansasPetPages | 882476eae01c633b4e09aed6fa2fefde6a88a526 | [
"CC0-1.0"
] | null | null | null | app/services/Email.java | douglasjd1/ArkansasPetPages | 882476eae01c633b4e09aed6fa2fefde6a88a526 | [
"CC0-1.0"
] | null | null | null | 34.255102 | 88 | 0.530533 | 305 | package services;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.*;
import java.security.SecureRandom;
import java.util.Random;
public class Email
{
public static void sendForgotPasswordEmail(String contents, String destinationEmail)
{
String sender = "efpyi@example.com";
String subject = "Arkansas Pet Pages - Password Reset";
try
{
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder
.standard()
.withRegion(Regions.US_WEST_2)
//.withRegion(Regions.US_EAST_1)
.build();
SendEmailRequest request = new SendEmailRequest()
.withDestination(
new Destination().withToAddresses(destinationEmail))
.withMessage(new Message()
.withBody(new Body()
.withHtml(new Content()
.withCharset("UTF-8").withData(contents)))
.withSubject(new Content()
.withCharset("UTF-8").withData(subject)))
.withSource(sender);
client.sendEmail(request);
System.out.println("Sent email!");
}
catch (Exception e)
{
System.out.println("Unable to send email " + e.getMessage());
}
}
public static void sendWelcomeEmail(String contents, String destinationEmail)
{
String sender = "efpyi@example.com";
String subject = "Arkansas Pet Pages - Welcome!";
try
{
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder
.standard()
.withRegion(Regions.US_WEST_2)
//.withRegion(Regions.US_EAST_1)
.build();
SendEmailRequest request = new SendEmailRequest()
.withDestination(
new Destination().withToAddresses(destinationEmail))
.withMessage(new Message()
.withBody(new Body()
.withHtml(new Content()
.withCharset("UTF-8").withData(contents)))
.withSubject(new Content()
.withCharset("UTF-8").withData(subject)))
.withSource(sender);
client.sendEmail(request);
System.out.println("Sent email!");
}
catch (Exception e)
{
System.out.println("Unable to send email " + e.getMessage());
}
}
public static String generateRandomPassword()
{
Random random = new SecureRandom();
String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"0123456789!@#$%^&*_=+-/";
String password = "";
for(int i = 0; i < 8; i++)
{
password += charSet.charAt(random.nextInt(74));
}
return password;
}
}
|
3e00bed76d4ee4c60d1a3e3e9116fa21bc20e75d | 742 | java | Java | plumelog-rest/src/main/java/com/plumelog/config/InterceptorConfig.java | CaiJian0834/plumelog | f5c72934bd77eb805c40965f8676b641a7831bf3 | [
"Apache-2.0"
] | 1 | 2021-03-01T01:00:10.000Z | 2021-03-01T01:00:10.000Z | plumelog-rest/src/main/java/com/plumelog/config/InterceptorConfig.java | jiangbin216/plumelog | f5c72934bd77eb805c40965f8676b641a7831bf3 | [
"Apache-2.0"
] | null | null | null | plumelog-rest/src/main/java/com/plumelog/config/InterceptorConfig.java | jiangbin216/plumelog | f5c72934bd77eb805c40965f8676b641a7831bf3 | [
"Apache-2.0"
] | 1 | 2021-03-01T01:02:19.000Z | 2021-03-01T01:02:19.000Z | 26.5 | 84 | 0.783019 | 306 | package com.plumelog.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* className:InterceptorConfig
* description: TODO
* time:2020-05-29.16:19
*
* @author Tank
* @version 1.0.0
*/
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
@Autowired
Interceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor);
super.addInterceptors(registry);
}
}
|
3e00bf37c4b9a5be3b2cb3bce72f7163c46c0f12 | 2,416 | java | Java | src/com/hb/lovebaby/adapter/VideoNewCutAdapter.java | zxxqc/LoveBaby | 5368176d16f0532301ba79b4b322bf6d90138a5d | [
"Apache-2.0"
] | null | null | null | src/com/hb/lovebaby/adapter/VideoNewCutAdapter.java | zxxqc/LoveBaby | 5368176d16f0532301ba79b4b322bf6d90138a5d | [
"Apache-2.0"
] | null | null | null | src/com/hb/lovebaby/adapter/VideoNewCutAdapter.java | zxxqc/LoveBaby | 5368176d16f0532301ba79b4b322bf6d90138a5d | [
"Apache-2.0"
] | null | null | null | 25.702128 | 93 | 0.762417 | 307 | package com.hb.lovebaby.adapter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import com.hb.lovebaby.R;
public class VideoNewCutAdapter extends RecyclerView.Adapter<VideoNewCutAdapter.ViewHolder> {
/** 数据�?*/
private ArrayList<String> list;
/** 点击事件 */
private MyItemClickListener onClickListener;
public VideoNewCutAdapter(ArrayList<String> list) {
this.list = list;
}
public MyItemClickListener getOnClickListener() {
return onClickListener;
}
public void setOnClickListener(MyItemClickListener onClickListener) {
this.onClickListener = onClickListener;
}
@Override
public int getItemCount() {
return list.size();
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
Bitmap bitmap = getLoacalBitmap(list.get(position));
if (bitmap != null) {
viewHolder.img.setScaleType(ScaleType.CENTER_CROP);
viewHolder.img.setImageBitmap(bitmap);
}
}
public Bitmap getLoacalBitmap(String url) {
try {
FileInputStream fis = new FileInputStream(url);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
// 创建�?��View,简单起见直接使用系统提供的布局,就是一个TextView
View view = View.inflate(viewGroup.getContext(), R.layout.item_video_new_cut, null);
// 创建�?��ViewHolder
ViewHolder holder = new ViewHolder(view, onClickListener);
return holder;
}
public class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
public ImageView img;
private MyItemClickListener listener;
public ViewHolder(View itemView, MyItemClickListener listener) {
super(itemView);
this.listener = listener;
img = (ImageView) itemView.findViewById(R.id.item_video_new_img);
img.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (listener != null) {
listener.onItemClick(img, getPosition());
}
}
}
public interface MyItemClickListener {
public void onItemClick(View view, int position);
}
}
|
3e00bf477cfcf3c44e6ae642d952b053e61538e7 | 2,146 | java | Java | ClasseNumero/src/TesteClasseNumero.java | Paludeto/JavaPOOUnifil | e6218cbe0433834245d09c98a028be9503650440 | [
"MIT"
] | 1 | 2021-10-01T01:44:57.000Z | 2021-10-01T01:44:57.000Z | ClasseNumero/src/TesteClasseNumero.java | Paludeto/JavaPOOUnifil | e6218cbe0433834245d09c98a028be9503650440 | [
"MIT"
] | null | null | null | ClasseNumero/src/TesteClasseNumero.java | Paludeto/JavaPOOUnifil | e6218cbe0433834245d09c98a028be9503650440 | [
"MIT"
] | null | null | null | 40.490566 | 93 | 0.407269 | 308 | import java.util.InputMismatchException;
import java.util.Scanner;
public class TesteClasseNumero {
public static void main(String[] args) throws ParImparException {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Defina o número de elementos do array");
Numeros num = new Numeros(sc.nextInt());
int opcao = 0;
do {
try {
System.out.println(("\n" + """
Escolha um:
1. Definir valores.
2. Mostrar valores.
3. Mostrar maior número.
4. Mostrar se é par ou ímpar.
5. Sair.
"""));
opcao = sc.nextInt();
switch (opcao) {
case 1:
System.out.println("Defina os valores.");
num.carregaNumeros();
break;
case 2:
System.out.println(num.mostraNumeros());
break;
case 3:
System.out.println(num.maiorNumero());
break;
case 4:
System.out.println("Digite 1 para par e 2 para ímpares");
System.out.println(num.mostraParImpar(sc.nextInt()));
break;
}
} catch (InputMismatchException e) {
System.out.println("Especifique um inteiro válido.");
sc.nextLine();
} catch (ParImparException e) {
System.out.println("Utilize 1 ou 2.");
sc.nextLine();
}
} while (opcao != 5);
} catch (InputMismatchException e) {
System.out.println("Especifique apenas inteiros. Execute o programa novamente.");
sc.nextLine();
}
}
} |
3e00bfa025686b691adad9bd2d2f941f9308eed5 | 3,126 | java | Java | contrib/websvc.wsitconf/src/org/netbeans/modules/websvc/wsitconf/ui/service/PanelFactory.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | contrib/websvc.wsitconf/src/org/netbeans/modules/websvc/wsitconf/ui/service/PanelFactory.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | contrib/websvc.wsitconf/src/org/netbeans/modules/websvc/wsitconf/ui/service/PanelFactory.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 40.076923 | 118 | 0.725528 | 309 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.websvc.wsitconf.ui.service;
import javax.swing.undo.UndoManager;
import org.netbeans.api.project.Project;
import org.netbeans.modules.websvc.api.jaxws.project.config.JaxWsModel;
import org.netbeans.modules.xml.multiview.ui.SectionInnerPanel;
import org.netbeans.modules.xml.multiview.ui.SectionView;
import org.netbeans.modules.xml.multiview.ui.ToolBarDesignEditor;
import org.netbeans.modules.xml.wsdl.model.Binding;
import org.netbeans.modules.xml.wsdl.model.BindingFault;
import org.netbeans.modules.xml.wsdl.model.BindingInput;
import org.netbeans.modules.xml.wsdl.model.BindingOperation;
import org.netbeans.modules.xml.wsdl.model.BindingOutput;
import org.netbeans.modules.xml.wsdl.model.WSDLComponent;
import org.openide.nodes.Node;
/**
*
* @author Martin Grebac
*/
public class PanelFactory implements org.netbeans.modules.xml.multiview.ui.InnerPanelFactory {
private ToolBarDesignEditor editor;
private Node node;
private UndoManager undoManager;
private Project project;
private JaxWsModel jaxwsmodel;
/**
* Creates a new instance of PanelFactory
*/
PanelFactory(ToolBarDesignEditor editor, Node node, UndoManager undoManager, Project p, JaxWsModel jxwsmodel) {
this.editor=editor;
this.node = node;
this.project = p;
this.jaxwsmodel = jxwsmodel;
this.undoManager = undoManager;
}
public SectionInnerPanel createInnerPanel(Object key) {
if (key instanceof Binding) {
Binding b = (Binding)key;
return new BindingPanel((SectionView) editor.getContentView(), node, project, b, undoManager, jaxwsmodel);
}
if (key instanceof BindingOperation) {
BindingOperation o = (BindingOperation)key;
return new OperationPanel((SectionView) editor.getContentView(), node, project, o);
}
if (key instanceof BindingInput) {
BindingInput i = (BindingInput)key;
return new InputPanel((SectionView) editor.getContentView(), i, undoManager);
}
if ((key instanceof BindingOutput) || (key instanceof BindingFault)) {
return new GenericElementPanel((SectionView) editor.getContentView(),(WSDLComponent) key, undoManager);
}
return null;
}
}
|
3e00bfff221f02ce6007efafe8fef6ae226edd1d | 1,091 | java | Java | leetcode/src/main/java/com/my/CanThreePartsEqualSum.java | EmiyaXzero/study | 9ad867c3f77a148d699dbec49b1fbb195d57b0ec | [
"Apache-2.0"
] | null | null | null | leetcode/src/main/java/com/my/CanThreePartsEqualSum.java | EmiyaXzero/study | 9ad867c3f77a148d699dbec49b1fbb195d57b0ec | [
"Apache-2.0"
] | 2 | 2021-12-10T01:30:01.000Z | 2021-12-14T21:39:16.000Z | leetcode/src/main/java/com/my/CanThreePartsEqualSum.java | EmiyaXzero/study | 9ad867c3f77a148d699dbec49b1fbb195d57b0ec | [
"Apache-2.0"
] | null | null | null | 25.372093 | 92 | 0.493126 | 310 | package com.my;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: shanghang
* @Project:study
* @description:1013. 将数组分成和相等的三个部分
* @Date: 2020/5/4 18:54
**/
public class CanThreePartsEqualSum {
public boolean canThreePartsEqualSum(int[] A) {
int allSum = 0;
for (int i : A) {
allSum+=i;
}
if(allSum%3!=0){
return false;
}else {
int target = allSum/3;
int sum = 0;
List<Integer> allIdx = new ArrayList<>();
for (int i = 0;i<A.length;i++){
sum+=A[i];
if(sum == target && A[i] != 0){
sum = 0;
allIdx.add(i);
}
}
if(allIdx.size()<3){
return false;
}
}
return true;
}
public static void main(String[] args) {
CanThreePartsEqualSum canThreePartsEqualSum = new CanThreePartsEqualSum();
canThreePartsEqualSum.canThreePartsEqualSum(new int[]{10,-10,10,-10,10,-10,10,-10});
}
}
|
3e00c15fef9decc450af981f7a86a59f6511c5a8 | 768 | java | Java | src/main/java/ma/ensias/projetjee2_0/Responses/GetHomeResponse.java | AJOthmane/projet-spring | 5b976b7dd1d77009a85bcd01b041b7720a13cddb | [
"MIT"
] | 1 | 2021-06-03T21:12:52.000Z | 2021-06-03T21:12:52.000Z | src/main/java/ma/ensias/projetjee2_0/Responses/GetHomeResponse.java | AJOthmane/Projet-jee-2.0- | 5b976b7dd1d77009a85bcd01b041b7720a13cddb | [
"MIT"
] | 6 | 2021-06-07T00:01:01.000Z | 2021-06-08T16:27:47.000Z | src/main/java/ma/ensias/projetjee2_0/Responses/GetHomeResponse.java | AJOthmane/Projet-jee-2.0- | 5b976b7dd1d77009a85bcd01b041b7720a13cddb | [
"MIT"
] | 1 | 2021-06-09T11:39:13.000Z | 2021-06-09T11:39:13.000Z | 21.942857 | 73 | 0.674479 | 311 | package ma.ensias.projetjee2_0.Responses;
import java.util.ArrayList;
import ma.ensias.projetjee2_0.entites.Post;
public class GetHomeResponse {
private boolean success;
ArrayList<Post> listOfPosts = new ArrayList<>();
public GetHomeResponse(){
}
public GetHomeResponse(boolean success, ArrayList<Post> listOfPosts){
this.success = success;
this.listOfPosts = listOfPosts;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public ArrayList<Post> getListOfPosts() {
return this.listOfPosts;
}
public void setListOfPosts(ArrayList<Post> listOfPosts) {
this.listOfPosts = listOfPosts;
}
}
|
3e00c2d74a3c3e52a13217eff37e2fe184f6a222 | 1,988 | java | Java | src/test/java/org/tests/cache/TestL2CacheWithSharedBean.java | mrmx/ebean | 88429c6a7e4b5257787200693a2dd186233e6930 | [
"Apache-2.0"
] | 1 | 2017-02-28T17:32:39.000Z | 2017-02-28T17:32:39.000Z | src/test/java/org/tests/cache/TestL2CacheWithSharedBean.java | mrmx/ebean | 88429c6a7e4b5257787200693a2dd186233e6930 | [
"Apache-2.0"
] | 11 | 2017-11-07T18:32:56.000Z | 2022-03-08T16:39:45.000Z | src/test/java/org/tests/cache/TestL2CacheWithSharedBean.java | mrmx/ebean | 88429c6a7e4b5257787200693a2dd186233e6930 | [
"Apache-2.0"
] | 1 | 2020-09-02T08:54:43.000Z | 2020-09-02T08:54:43.000Z | 31.555556 | 97 | 0.757042 | 312 | package org.tests.cache;
import io.ebean.BaseTestCase;
import io.ebean.Ebean;
import io.ebean.Query;
import io.ebean.cache.ServerCache;
import io.ebeaninternal.api.SpiQuery;
import io.ebeaninternal.server.autotune.model.Origin;
import io.ebeaninternal.server.autotune.service.TunedQueryInfo;
import io.ebeaninternal.server.querydefn.OrmQueryDetail;
import org.tests.model.basic.FeatureDescription;
import org.junit.Assert;
import org.junit.Test;
public class TestL2CacheWithSharedBean extends BaseTestCase {
private TunedQueryInfo createTunedQueryInfo(OrmQueryDetail tunedDetail) {
Origin origin = new Origin();
origin.setDetail(tunedDetail.toString());
return new TunedQueryInfo(origin);
}
@Test
public void test() {
FeatureDescription f1 = new FeatureDescription();
f1.setName("one");
f1.setDescription(null);
Ebean.save(f1);
ServerCache beanCache = Ebean.getServerCacheManager().getBeanCache(FeatureDescription.class);
beanCache.getStatistics(true);
OrmQueryDetail tunedDetail = new OrmQueryDetail();
tunedDetail.select("name");
TunedQueryInfo tunedInfo = createTunedQueryInfo(tunedDetail);
Query<FeatureDescription> query = Ebean.find(FeatureDescription.class).setId(f1.getId());
tunedInfo.tuneQuery((SpiQuery<?>) query);
query.findOne(); // PUT into cache
FeatureDescription fd2 = query.findOne(); // LOAD cache
fd2.getDescription(); // invoke lazy load (this fails)
// load the cache
FeatureDescription fetchOne = Ebean.find(FeatureDescription.class, f1.getId());
Assert.assertNotNull(fetchOne);
Assert.assertEquals(1, beanCache.getStatistics(false).getSize());
FeatureDescription fetchTwo = Ebean.find(FeatureDescription.class, f1.getId());
FeatureDescription fetchThree = Ebean.find(FeatureDescription.class, f1.getId());
Assert.assertSame(fetchTwo, fetchThree);
String description = fetchThree.getDescription();
Assert.assertNull(description);
}
}
|
3e00c4571e2e2ad881d816adac73cb13ff7049a7 | 892 | java | Java | src/main/java/org/hebrbot/bot/model/HebrewPreposition.java | imvladikon/telegram-bot-hebrew | 01c1870308851a54fee4daec23c920f7bdd3eec4 | [
"MIT"
] | null | null | null | src/main/java/org/hebrbot/bot/model/HebrewPreposition.java | imvladikon/telegram-bot-hebrew | 01c1870308851a54fee4daec23c920f7bdd3eec4 | [
"MIT"
] | null | null | null | src/main/java/org/hebrbot/bot/model/HebrewPreposition.java | imvladikon/telegram-bot-hebrew | 01c1870308851a54fee4daec23c920f7bdd3eec4 | [
"MIT"
] | null | null | null | 22.3 | 66 | 0.674888 | 313 | package org.hebrbot.bot.model;
import lombok.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class HebrewPreposition implements HebrewWord {
String name;
String nameNekudot;
String root;
String meaning;
GrammaticalNumber number;
GrammaticalGender gender;
GrammaticalPerson person;
PartOfSpeech partOfSpeech;
@Override
public PartOfSpeech getPartOfSpeech() {
return PartOfSpeech.PREPOSITION;
}
@AllArgsConstructor
@NoArgsConstructor
@Getter
public enum PrepositionsChars {
BET("ב", HebrewPreposition.builder().name("ב").build()),
MEM("מ", HebrewPreposition.builder().name("מ").build()),
LAMED("ל", HebrewPreposition.builder().name("ל").build()),
KAF("כ", HebrewPreposition.builder().name("כ").build());
String he;
HebrewPreposition preposition;
}
}
|
3e00c49fa1e1bd27c5acf883d1faedd17c9c1f34 | 799 | java | Java | mercury/src/main/java/org/suggs/apps/mercury/model/util/xml/IDomParserUtil.java | suggitpe/java-gui | 349d716736020d8af0561161e08bfe993210afec | [
"Apache-2.0"
] | null | null | null | mercury/src/main/java/org/suggs/apps/mercury/model/util/xml/IDomParserUtil.java | suggitpe/java-gui | 349d716736020d8af0561161e08bfe993210afec | [
"Apache-2.0"
] | null | null | null | mercury/src/main/java/org/suggs/apps/mercury/model/util/xml/IDomParserUtil.java | suggitpe/java-gui | 349d716736020d8af0561161e08bfe993210afec | [
"Apache-2.0"
] | null | null | null | 27.551724 | 110 | 0.685857 | 314 | /*
* IDomParserUtil.java created on 9 Dec 2008 08:57:38 by suggitpe for project GUI - Mercury
*
*/
package org.suggs.apps.mercury.model.util.xml;
import org.suggs.apps.mercury.model.util.MercuryUtilityException;
import org.w3c.dom.Document;
/**
* This util is used for all DOM parser based activities.
*
* @author suggitpe
* @version 1.0 9 Dec 2008
*/
public interface IDomParserUtil {
/**
* @param aFilename
* @param aSchemaLocation
* @return a document created from the filname and a schema
* @throws MercuryUtilityException
* if there is an issue in parsing the file contents into a document
*/
Document createDocFromXmlFile( String aFilename, String aSchemaLocation ) throws MercuryUtilityException;
}
|
3e00c65514f7212f7582aded9ef2e2f2d1142b45 | 4,668 | java | Java | iBistuByDreamFactory/src/main/java/org/iflab/ibistubydreamfactory/activities/YellowPageDetailsActivity.java | ahtcfg24/New-iBistu-Android | 7fadef9b107eae039b780b07c17543a5e5108fcb | [
"Apache-2.0"
] | 20 | 2016-10-16T05:27:54.000Z | 2021-07-09T15:10:53.000Z | iBistuByDreamFactory/src/main/java/org/iflab/ibistubydreamfactory/activities/YellowPageDetailsActivity.java | ahtcfg24/iBistuByDreamFactory | 7fadef9b107eae039b780b07c17543a5e5108fcb | [
"Apache-2.0"
] | 1 | 2016-12-04T01:04:42.000Z | 2016-12-04T01:04:42.000Z | iBistuByDreamFactory/src/main/java/org/iflab/ibistubydreamfactory/activities/YellowPageDetailsActivity.java | ahtcfg24/iBistuByDreamFactory | 7fadef9b107eae039b780b07c17543a5e5108fcb | [
"Apache-2.0"
] | 8 | 2016-10-16T05:27:56.000Z | 2021-07-09T15:10:31.000Z | 37.95122 | 146 | 0.706512 | 315 | package org.iflab.ibistubydreamfactory.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.iflab.ibistubydreamfactory.MyApplication;
import org.iflab.ibistubydreamfactory.R;
import org.iflab.ibistubydreamfactory.adapters.yellowPageDetailsAdapter;
import org.iflab.ibistubydreamfactory.apis.APISource;
import org.iflab.ibistubydreamfactory.apis.YellowPageAPI;
import org.iflab.ibistubydreamfactory.customviews.YellowPageDialog;
import org.iflab.ibistubydreamfactory.models.ErrorMessage;
import org.iflab.ibistubydreamfactory.models.Resource;
import org.iflab.ibistubydreamfactory.models.YellowPageDepartment;
import org.iflab.ibistubydreamfactory.utils.ACache;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class YellowPageDetailsActivity extends AppCompatActivity {
@BindView(R.id.progressBar_yellowPageDepartDetails)
ProgressBar progressBar;
@BindView(R.id.listView_yellowPageDepartDetails)
ListView listViewYellowPageDepartDetails;
private List<YellowPageDepartment> yellowPageDepartmentDetailsList;
private Resource<YellowPageDepartment> yellowPageDepartDetailsResource;
private ACache aCache;
private String branchName;//部门下分支的名字
private String telephoneNumber;//部门下分支的号码
private String department;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yellow_page_depart_details);
ButterKnife.bind(this);
init();//初始化
if (yellowPageDepartDetailsResource == null) {
/*如果缓存没有就从网络获取*/
getYellowPageDepartResource();
} else {
loadData();
}
listViewYellowPageDepartDetails.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
branchName = yellowPageDepartmentDetailsList.get(position).getName();
telephoneNumber = yellowPageDepartmentDetailsList.get(position).getTelephone();
new YellowPageDialog(YellowPageDetailsActivity.this, branchName, telephoneNumber, yellowPageDepartmentDetailsList, position);
}
});
}
/**
* 初始化
*/
private void init() {
Intent intent = getIntent();
department = intent.getStringExtra("department");
setTitle(intent.getStringExtra("name"));
aCache = ACache.get(MyApplication.getAppContext());
yellowPageDepartDetailsResource = (Resource<YellowPageDepartment>) aCache.getAsObject(department);
}
/**
* 获得学校部门信息
*/
private void getYellowPageDepartResource() {
YellowPageAPI departmentService = APISource.getInstance().getAPIObject(YellowPageAPI.class);
String filter = "department=";
Call<Resource<YellowPageDepartment>> call = departmentService.getYellowPageDetails(filter + department);
call.enqueue(new Callback<Resource<YellowPageDepartment>>() {
@Override
public void onResponse(Call<Resource<YellowPageDepartment>> call, Response<Resource<YellowPageDepartment>> response) {
if (response.isSuccessful()) {
yellowPageDepartDetailsResource = response.body();
aCache.put(department, yellowPageDepartDetailsResource);
loadData();
} else {
ErrorMessage e = APISource.getErrorMessage(response);//解析错误信息
onFailure(call, e.toException());
}
}
@Override
public void onFailure(Call<Resource<YellowPageDepartment>> call, Throwable t) {
System.out.println("error:" + t.toString());
Toast.makeText(YellowPageDetailsActivity.this, "错误:" + t.getMessage(), Toast.LENGTH_LONG)
.show();
}
});
}
/**
* 加载部门下的详情数据到listview中
*/
private void loadData() {
yellowPageDepartmentDetailsList = yellowPageDepartDetailsResource.getResource();
progressBar.setVisibility(View.GONE);
listViewYellowPageDepartDetails.setAdapter(new yellowPageDetailsAdapter(YellowPageDetailsActivity.this, yellowPageDepartmentDetailsList));
}
}
|
3e00c7df3d72b005e0d277550a726dd9f1777799 | 1,283 | java | Java | src/main/java/no/kantega/polltibot/ai/pipeline/Dl4jUtils.java | kantega/polltibot-workshop | 0957f0bba8ce635a92e533c35204427c23e1125d | [
"Apache-2.0"
] | null | null | null | src/main/java/no/kantega/polltibot/ai/pipeline/Dl4jUtils.java | kantega/polltibot-workshop | 0957f0bba8ce635a92e533c35204427c23e1125d | [
"Apache-2.0"
] | null | null | null | src/main/java/no/kantega/polltibot/ai/pipeline/Dl4jUtils.java | kantega/polltibot-workshop | 0957f0bba8ce635a92e533c35204427c23e1125d | [
"Apache-2.0"
] | null | null | null | 25.66 | 85 | 0.619641 | 316 | package no.kantega.polltibot.ai.pipeline;
import fj.Unit;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.INDArrayIndex;
import org.nd4j.linalg.util.ArrayUtil;
import org.slf4j.Logger;
import java.util.Arrays;
import java.util.function.Function;
public class Dl4jUtils {
public static int[] atIndex(int a, int ... as){
return ArrayUtil.consArray(a,as);
}
public static INDArrayIndex[] atIndex(INDArrayIndex idx, INDArrayIndex ... idxs){
int len = idxs.length;
INDArrayIndex[] nas = new INDArrayIndex[len + 1];
nas[0] = idx;
System.arraycopy(idxs, 0, nas, 1, len);
return nas;
}
public static INDArray array(double... vals) {
return Nd4j.create(vals);
}
public static INDArray array(INDArray... rows) {
return Nd4j.concat(0, rows);
}
public static MLTask<Unit> log(String msg, Logger logger) {
return MLTask.supplier(() -> {
logger.info(msg);
return Unit.unit();
});
}
public static <A> Function<A, MLTask<A>> logK(String msg, Logger logger) {
return a -> MLTask.supplier(() -> {
logger.info(msg);
return a;
});
}
}
|
3e00c8188f948d8a93ba548157834c1cfa4fca5d | 1,626 | java | Java | JavaEnvir/src/com/gwm/commons/csrf/CsrfTokenRepository.java | hunhun1122/javaEnvir | 4ceb4443cb8f0c1f73c286195a42f607d6e7ce06 | [
"Apache-2.0"
] | null | null | null | JavaEnvir/src/com/gwm/commons/csrf/CsrfTokenRepository.java | hunhun1122/javaEnvir | 4ceb4443cb8f0c1f73c286195a42f607d6e7ce06 | [
"Apache-2.0"
] | null | null | null | JavaEnvir/src/com/gwm/commons/csrf/CsrfTokenRepository.java | hunhun1122/javaEnvir | 4ceb4443cb8f0c1f73c286195a42f607d6e7ce06 | [
"Apache-2.0"
] | null | null | null | 31.882353 | 88 | 0.742312 | 317 | package com.gwm.commons.csrf;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface CsrfTokenRepository {
/**
* Generates a {@link CsrfTokenBean}
*
* @param request the {@link HttpServletRequest} to use
* @return the {@link CsrfTokenBean} that was generated. Cannot be null.
*/
CsrfTokenBean generateToken(HttpServletRequest request);
/**
* Saves the {@link CsrfTokenBean} using the {@link HttpServletRequest} and
* {@link HttpServletResponse}. If the {@link CsrfTokenBean} is null, it is the same as
* deleting it.
*
* @param token the {@link CsrfTokenBean} to save or null to delete
* @param request the {@link HttpServletRequest} to use
* @param response the {@link HttpServletResponse} to use
*/
void saveToken(CsrfTokenBean token, HttpServletRequest request,
HttpServletResponse response);
/**
* Loads the expected {@link CsrfTokenBean} from the {@link HttpServletRequest}
*
* @param request the {@link HttpServletRequest} to use
* @return the {@link CsrfTokenBean} or null if none exists
*/
CsrfTokenBean loadToken(HttpServletRequest request);
/**
* 缓存来源的url
* @param request request the {@link HttpServletRequest} to use
* @param response the {@link HttpServletResponse} to use
*/
void cacheUrl(HttpServletRequest request, HttpServletResponse response);
/**
* 获取并清理来源的url
* @param request the {@link HttpServletRequest} to use
* @param response the {@link HttpServletResponse} to use
* @return 来源url
*/
String getRemoveCacheUrl(HttpServletRequest request, HttpServletResponse response);
}
|
3e00c81d6cc01f4749e4236b96eace12da4a216c | 721 | java | Java | tupl-support/src/main/java/com/truward/tupl/support/index/TuplIndexSupport.java | truward/tupl-support | 5d651aff08f860ba611207a7760e36dee6ecf7b3 | [
"Apache-2.0"
] | 1 | 2016-06-16T04:24:11.000Z | 2016-06-16T04:24:11.000Z | tupl-support/src/main/java/com/truward/tupl/support/index/TuplIndexSupport.java | truward/tupl-support | 5d651aff08f860ba611207a7760e36dee6ecf7b3 | [
"Apache-2.0"
] | 6 | 2016-06-07T05:41:05.000Z | 2016-06-13T03:38:32.000Z | tupl-support/src/main/java/com/truward/tupl/support/index/TuplIndexSupport.java | truward/tupl-support | 5d651aff08f860ba611207a7760e36dee6ecf7b3 | [
"Apache-2.0"
] | null | null | null | 27.730769 | 76 | 0.732316 | 318 | package com.truward.tupl.support.index;
import com.truward.tupl.support.TuplDatabaseProvider;
import com.truward.tupl.support.exception.InternalErrorDaoException;
import org.cojen.tupl.Index;
import javax.annotation.Nonnull;
import java.io.IOException;
/**
* Support mixin for Tupl operations.
*
* @author Alexander Shabanov
*/
public interface TuplIndexSupport extends TuplDatabaseProvider {
default <T> T withIndex(@Nonnull String indexName,
@Nonnull TuplIndexOperationCallback<T> callback) {
try (final Index index = getDatabase().openIndex(indexName)) {
return callback.call(index);
} catch (IOException e) {
throw new InternalErrorDaoException(e);
}
}
}
|
3e00c90176dc8dff7c6aceba771818bfd97b6691 | 866 | java | Java | src/server/main/MainServer.java | vince-stri/Chess-Project | f20e2b336ef10948e50ed3f86ca73d796c714a5c | [
"MIT"
] | null | null | null | src/server/main/MainServer.java | vince-stri/Chess-Project | f20e2b336ef10948e50ed3f86ca73d796c714a5c | [
"MIT"
] | null | null | null | src/server/main/MainServer.java | vince-stri/Chess-Project | f20e2b336ef10948e50ed3f86ca73d796c714a5c | [
"MIT"
] | null | null | null | 26.242424 | 89 | 0.714781 | 319 | package server.main;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import shared.ServerImpl;
public class MainServer {
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(1099);
ServerImpl server = new ServerImpl();
String url = "rmi://" + InetAddress.getLocalHost().getHostAddress() + "/ChessProject";
System.out.println("Registry with : " + url);
Naming.rebind(url, server);
System.out.println("Server launched");
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
3e00ca98fe8f1f08598ba509ebca9e85bef3ccff | 3,205 | java | Java | common/src/test/java/com/amazonaws/services/schemaregistry/common/AWSCompressionFactoryTest.java | burakkose/aws-glue-schema-registry | 8f7ca83710254d7ed77cc7665c734f96e64b81ba | [
"Apache-2.0"
] | null | null | null | common/src/test/java/com/amazonaws/services/schemaregistry/common/AWSCompressionFactoryTest.java | burakkose/aws-glue-schema-registry | 8f7ca83710254d7ed77cc7665c734f96e64b81ba | [
"Apache-2.0"
] | null | null | null | common/src/test/java/com/amazonaws/services/schemaregistry/common/AWSCompressionFactoryTest.java | burakkose/aws-glue-schema-registry | 8f7ca83710254d7ed77cc7665c734f96e64b81ba | [
"Apache-2.0"
] | null | null | null | 44.513889 | 165 | 0.797192 | 320 | package com.amazonaws.services.schemaregistry.common;
import com.amazonaws.services.schemaregistry.common.configs.GlueSchemaRegistryConfiguration;
import com.amazonaws.services.schemaregistry.utils.AWSSchemaRegistryConstants;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class AWSCompressionFactoryTest {
private final Map<String, Object> configs = new HashMap<>();
private GlueSchemaRegistryConfiguration glueSchemaRegistryConfiguration;
AWSCompressionFactory awsCompressionFactory;
@BeforeEach
public void setup() {
configs.put(AWSSchemaRegistryConstants.AWS_ENDPOINT, "https://test");
configs.put(AWSSchemaRegistryConstants.AWS_REGION, "us-west-2");
configs.put(AWSSchemaRegistryConstants.SCHEMA_NAME, "User-Topic");
configs.put(AWSSchemaRegistryConstants.REGISTRY_NAME, "User-Registry");
glueSchemaRegistryConfiguration = new GlueSchemaRegistryConfiguration(configs);
awsCompressionFactory = new AWSCompressionFactory();
}
@Test
public void testConstructor_validSerdeConfigs_succeeds() {
assertDoesNotThrow(() -> new AWSCompressionFactory());
}
@Test
public void testGetCompressionHandler_nullCompressionType_returnsNull() {
assertNull(awsCompressionFactory.getCompressionHandler(null));
}
@Test
public void testGetCompressionHandler_noneCompressionType_returnsNull() {
assertNull(awsCompressionFactory.getCompressionHandler(AWSSchemaRegistryConstants.COMPRESSION.NONE));
}
@Test
public void testGetCompressionHandler_zlibCompressionTypeWithZLibCompressionNotInitialized_initializesUsingDefaultCompression() {
AWSCompressionHandler awsCompressionHandler = awsCompressionFactory.getCompressionHandler(AWSSchemaRegistryConstants.COMPRESSION.ZLIB);
assertEquals(AWSSchemaRegistryDefaultCompression.class, awsCompressionHandler.getClass());
}
@Test
public void testGetCompressionHandler_zlibCompressionTypeWithZLibCompressionInitialized_initializesUsingDefaultCompression() {
//Initialize call
AWSCompressionHandler instance1 = awsCompressionFactory.getCompressionHandler(AWSSchemaRegistryConstants.COMPRESSION.ZLIB);
//Return initialized instance.
AWSCompressionHandler instance2 = awsCompressionFactory.getCompressionHandler(AWSSchemaRegistryConstants.COMPRESSION.ZLIB);
assertEquals(instance1, instance2);
}
@Test
public void testGetCompressionHandler_unknownCompressionByte_returnsNull() {
byte compressionBytes = Byte.parseByte("1");
assertNull(awsCompressionFactory.getCompressionHandler(compressionBytes));
}
@Test
public void testGetCompressionHandler_knownCompressionByte_returnsNull() {
assertEquals(AWSSchemaRegistryDefaultCompression.class, awsCompressionFactory.getCompressionHandler(AWSSchemaRegistryConstants.COMPRESSION_BYTE).getClass());
}
}
|
3e00cb028e487b3b061fabfa76dca98298724ec7 | 2,575 | java | Java | ExtractedJars/iRobot_com.irobot.home/javafiles/com/google/android/gms/tagmanager/zzgg.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | 3 | 2019-05-01T09:22:08.000Z | 2019-07-06T22:21:59.000Z | ExtractedJars/iRobot_com.irobot.home/javafiles/com/google/android/gms/tagmanager/zzgg.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | null | null | null | ExtractedJars/iRobot_com.irobot.home/javafiles/com/google/android/gms/tagmanager/zzgg.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | 1 | 2020-11-26T12:22:02.000Z | 2020-11-26T12:22:02.000Z | 24.065421 | 113 | 0.512233 | 321 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.tagmanager;
import com.google.android.gms.analytics.Logger;
// Referenced classes of package com.google.android.gms.tagmanager:
// zzdi
final class zzgg
implements Logger
{
zzgg()
{
// 0 0:aload_0
// 1 1:invokespecial #10 <Method void Object()>
// 2 4:return
}
public final void error(Exception exception)
{
zzdi.zza("", ((Throwable) (exception)));
// 0 0:ldc1 #15 <String "">
// 1 2:aload_1
// 2 3:invokestatic #21 <Method void zzdi.zza(String, Throwable)>
// 3 6:return
}
public final void error(String s)
{
zzdi.e(s);
// 0 0:aload_1
// 1 1:invokestatic #25 <Method void zzdi.e(String)>
// 2 4:return
}
public final int getLogLevel()
{
switch(zzdi.zzyn)
//* 0 0:getstatic #31 <Field int zzdi.zzyn>
{
//* 1 3:tableswitch 2 6: default 36
// 2 42
// 3 40
// 4 40
// 5 38
// 6 36
case 6: // '\006'
default:
return 3;
// 2 36:iconst_3
// 3 37:ireturn
case 5: // '\005'
return 2;
// 4 38:iconst_2
// 5 39:ireturn
case 3: // '\003'
case 4: // '\004'
return 1;
// 6 40:iconst_1
// 7 41:ireturn
case 2: // '\002'
return 0;
// 8 42:iconst_0
// 9 43:ireturn
}
}
public final void info(String s)
{
zzdi.zzdm(s);
// 0 0:aload_1
// 1 1:invokestatic #35 <Method void zzdi.zzdm(String)>
// 2 4:return
}
public final void setLogLevel(int i)
{
zzdi.zzab("GA uses GTM logger. Please use TagManager.setLogLevel(int) instead.");
// 0 0:ldc1 #39 <String "GA uses GTM logger. Please use TagManager.setLogLevel(int) instead.">
// 1 2:invokestatic #42 <Method void zzdi.zzab(String)>
// 2 5:return
}
public final void verbose(String s)
{
zzdi.v(s);
// 0 0:aload_1
// 1 1:invokestatic #46 <Method void zzdi.v(String)>
// 2 4:return
}
public final void warn(String s)
{
zzdi.zzab(s);
// 0 0:aload_1
// 1 1:invokestatic #42 <Method void zzdi.zzab(String)>
// 2 4:return
}
}
|
3e00cc4f93aac642729e281a5a5f083f7cb8a468 | 1,456 | java | Java | library/src/main/java/com/daohen/netease/library/NimLogin.java | daohen/neteaseLibrary | b0dd2e203fafdc8e110fbbce254ad27ed53ec8a9 | [
"Apache-2.0"
] | null | null | null | library/src/main/java/com/daohen/netease/library/NimLogin.java | daohen/neteaseLibrary | b0dd2e203fafdc8e110fbbce254ad27ed53ec8a9 | [
"Apache-2.0"
] | null | null | null | library/src/main/java/com/daohen/netease/library/NimLogin.java | daohen/neteaseLibrary | b0dd2e203fafdc8e110fbbce254ad27ed53ec8a9 | [
"Apache-2.0"
] | null | null | null | 29.12 | 97 | 0.710165 | 322 | package com.daohen.netease.library;
import com.daohen.netease.library.callback.NeteaseCallback;
import com.daohen.netease.library.manager.AuthServiceManager;
import com.daohen.netease.library.tool.NimPreferences;
import com.daohen.personal.toolbox.library.Singleton;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.auth.OnlineClient;
/**
* Created by alun on 17/7/18.
*/
public class NimLogin {
public static NimLogin get(){
return gDefault.get();
}
public void login(LoginInfo info, final NeteaseCallback<LoginInfo> callback){
AuthServiceManager.get().login(info, callback);
}
public LoginInfo getLoginInfo(){
return new LoginInfo(NimPreferences.get().getAccount(), NimPreferences.get().getToken());
}
public void logout(){
AuthServiceManager.get().getAuthService().logout();
NimPreferences.get().clear();
}
public StatusCode getCurrentStatus(){
return NIMClient.getStatus();
}
public void kickOtherClient(OnlineClient onlineClient, NeteaseCallback<Void> callback){
AuthServiceManager.get().kickOtherClient(onlineClient, callback);
}
private static final Singleton<NimLogin> gDefault = new Singleton<NimLogin>() {
@Override
protected NimLogin create() {
return new NimLogin();
}
};
}
|
3e00ccf2e37d330d0827040ea5ec19071e245f3b | 1,079 | java | Java | src/model/CD.java | taciossbr/tb-POO-JavaComBancoDeDados | 13fa1201663512c71f0d8e55566d72d7cda5b5ad | [
"MIT"
] | null | null | null | src/model/CD.java | taciossbr/tb-POO-JavaComBancoDeDados | 13fa1201663512c71f0d8e55566d72d7cda5b5ad | [
"MIT"
] | null | null | null | src/model/CD.java | taciossbr/tb-POO-JavaComBancoDeDados | 13fa1201663512c71f0d8e55566d72d7cda5b5ad | [
"MIT"
] | null | null | null | 18.929825 | 96 | 0.568119 | 323 | package model;
import java.util.ArrayList;
/**
*
* @author tacioss
*/
public class CD {
private int codigo;
private String titulo;
private ArrayList<Musica> musicas;
public CD(String titulo, ArrayList musicas) {
this.titulo = titulo;
this.musicas = musicas;
}
public CD(int codigo, String titulo, ArrayList musicas) {
this.codigo = codigo;
this.titulo = titulo;
this.musicas = musicas;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public ArrayList<Musica> getMusicas() {
return musicas;
}
public void addMusica(Musica musica) {
this.musicas.add(musica);
}
@Override
public String toString() {
return "CD{" + "codigo=" + codigo + ", titulo=" + titulo + ", musicas=" + musicas + '}';
}
}
|
3e00cd30db62b19cbe5e897d2acd4f535ee426ef | 347 | java | Java | src/main/java/com/project/EStore/service/domain/user/UserService.java | Nikolay-Daskalov/E-Store | 49bb23fb378348e54ee5ac0bd7772b60325bedce | [
"MIT"
] | null | null | null | src/main/java/com/project/EStore/service/domain/user/UserService.java | Nikolay-Daskalov/E-Store | 49bb23fb378348e54ee5ac0bd7772b60325bedce | [
"MIT"
] | null | null | null | src/main/java/com/project/EStore/service/domain/user/UserService.java | Nikolay-Daskalov/E-Store | 49bb23fb378348e54ee5ac0bd7772b60325bedce | [
"MIT"
] | null | null | null | 26.692308 | 62 | 0.795389 | 324 | package com.project.EStore.service.domain.user;
import com.project.EStore.model.service.user.UserServiceModel;
import com.project.EStore.service.domain.init.Init;
public interface UserService extends Init {
boolean isUsernameUnique(String username);
//TODO: add boolean and exception
void add(UserServiceModel userServiceModel);
}
|
3e00cdd6bccf4a2d842c83bd110661434d009749 | 221 | java | Java | src/main/java/mounderfod/fabricforfabric/recipe/WorktableRecipeJsonFormat.java | redcreeper14385/fabric-for-fabric | e86030683fc0c49bffe583891ed4bee4f02c87da | [
"MIT"
] | 3 | 2020-06-25T19:57:58.000Z | 2020-09-21T14:27:03.000Z | src/main/java/mounderfod/fabricforfabric/recipe/WorktableRecipeJsonFormat.java | redcreeper14385/fabric-for-fabric | e86030683fc0c49bffe583891ed4bee4f02c87da | [
"MIT"
] | 15 | 2020-06-25T22:53:18.000Z | 2021-07-01T19:16:36.000Z | src/main/java/mounderfod/fabricforfabric/recipe/WorktableRecipeJsonFormat.java | redcreeper14385/fabric-for-fabric | e86030683fc0c49bffe583891ed4bee4f02c87da | [
"MIT"
] | 4 | 2020-09-02T10:12:11.000Z | 2020-10-21T13:59:01.000Z | 20.090909 | 42 | 0.773756 | 325 | package mounderfod.fabricforfabric.recipe;
import com.google.gson.JsonObject;
public class WorktableRecipeJsonFormat {
public JsonObject input;
public JsonObject tool;
String output;
int outputAmount;
}
|
3e00ce91792f85e59f37588b80e812fac0f8ee42 | 2,251 | java | Java | app/src/main/java/com/example/parstagram/SignupActivity.java | sangokey/parstagram | ad9e9c59593ed3302eb864ba5a12146344f5e676 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/parstagram/SignupActivity.java | sangokey/parstagram | ad9e9c59593ed3302eb864ba5a12146344f5e676 | [
"Apache-2.0"
] | 3 | 2021-03-20T08:48:58.000Z | 2021-03-27T07:59:02.000Z | app/src/main/java/com/example/parstagram/SignupActivity.java | sangokey/parstagram | ad9e9c59593ed3302eb864ba5a12146344f5e676 | [
"Apache-2.0"
] | null | null | null | 33.102941 | 114 | 0.600178 | 326 | package com.example.parstagram;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class SignupActivity extends AppCompatActivity {
public static final String TAG = "SignupActivity";
private EditText etUsernames;
private EditText etPasswords;
private Button btnSignups;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
etUsernames = findViewById(R.id.etUsernames);
etPasswords = findViewById(R.id.etPasswords);
btnSignups = findViewById(R.id.btnSignup);
// Create the ParseUser
ParseUser user = new ParseUser();
btnSignups.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Set core properties
user.setUsername(etUsernames.getText().toString());
user.setPassword(etPasswords.getText().toString());
// Invoke signUpInBackground
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
goLoginActivity();
Toast.makeText(SignupActivity.this, "Sign Up Successful!", Toast.LENGTH_SHORT).show();
} else {
Log.e(TAG, "Issue with sign up", e);
Toast.makeText(SignupActivity.this, "Issue with sign up!", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
});
}
private void goLoginActivity() {
ParseUser.logOut();
ParseUser currentUser = ParseUser.getCurrentUser();
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
finish();
}
} |
3e00cf16025b2603f76a21a3fdb0b20ead6fc75c | 2,357 | java | Java | src/jp/gr/java_conf/neko_daisuki/photonote/RemoveNoteFragment.java | SumiTomohiko/PhotoNote | 013637f0869f61ea82a197dd7b183c4de0dfb8d5 | [
"MIT"
] | 1 | 2016-04-18T08:46:48.000Z | 2016-04-18T08:46:48.000Z | src/jp/gr/java_conf/neko_daisuki/photonote/RemoveNoteFragment.java | SumiTomohiko/PhotoNote | 013637f0869f61ea82a197dd7b183c4de0dfb8d5 | [
"MIT"
] | null | null | null | src/jp/gr/java_conf/neko_daisuki/photonote/RemoveNoteFragment.java | SumiTomohiko/PhotoNote | 013637f0869f61ea82a197dd7b183c4de0dfb8d5 | [
"MIT"
] | null | null | null | 33.197183 | 79 | 0.693254 | 327 | package jp.gr.java_conf.neko_daisuki.photonote;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class RemoveNoteFragment extends DialogFragment {
public interface RemoveNoteFragmentListener {
public void onRemoveNote(RemoveNoteFragment fragment,
Database.Note.Key note);
}
private class OnClickListener implements DialogInterface.OnClickListener {
private Database.Note.Key mNote;
public OnClickListener(Database.Note.Key note) {
mNote = note;
}
@Override
public void onClick(DialogInterface dialog, int which) {
mListener.onRemoveNote(RemoveNoteFragment.this, mNote);
}
}
private static final String KEY_KEY = "key";
private static final String KEY_NAME = "name";
private RemoveNoteFragmentListener mListener;
public static DialogFragment newInstance(Database.Note note) {
RemoveNoteFragment fragment = new RemoveNoteFragment();
Bundle args = new Bundle();
args.putString(KEY_KEY, note.getKey().toString());
args.putString(KEY_NAME, note.getName());
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mListener = (RemoveNoteFragmentListener)activity;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Resources res = getResources();
String fmt = res.getString(R.string.delete_entry_dialog_message);
String positive = res.getString(R.string.positive);
String negative = res.getString(R.string.negative);
Bundle args = getArguments();
String name = args.getString(KEY_NAME);
Database.Note.Key key = new Database.Note.Key(args.getString(KEY_KEY));
builder.setMessage(String.format(fmt, name, positive, negative));
builder.setPositiveButton(positive, new OnClickListener(key));
builder.setNegativeButton(negative, null);
return builder.create();
}
} |
3e00cf2762458fb059782c140e6d1498bfefd972 | 1,607 | java | Java | src/main/java/com/jdon/jivejdon/presentation/servlet/upload/strutsplugin/MonitoredDiskFileItemFactory.java | zhaoning999/jivejdon | 344ec14c0060f224607dced47097641d31863260 | [
"Apache-2.0"
] | 436 | 2018-09-04T00:47:49.000Z | 2022-03-29T09:36:40.000Z | src/main/java/com/jdon/jivejdon/presentation/servlet/upload/strutsplugin/MonitoredDiskFileItemFactory.java | yilizidan/jivejdon | 93b7a769c28b60e39118ba06c5e5301dffdc2714 | [
"Apache-2.0"
] | 15 | 2018-09-10T13:43:35.000Z | 2022-02-16T05:32:43.000Z | src/main/java/com/jdon/jivejdon/presentation/servlet/upload/strutsplugin/MonitoredDiskFileItemFactory.java | yilizidan/jivejdon | 93b7a769c28b60e39118ba06c5e5301dffdc2714 | [
"Apache-2.0"
] | 138 | 2018-09-04T00:47:53.000Z | 2022-03-17T20:21:52.000Z | 33.040816 | 135 | 0.735639 | 328 | /* Licence:
* Use this however/wherever you like, just don't blame me if it breaks anything.
*
* Credit:
* If you're nice, you'll leave this bit:
*
* Class by Pierre-Alexandre Losson -- http://www.telio.be/blog
* email : hzdkv@example.com
*/
/*
* Changed for Part 2, by Ken Cochrane
* http://KenCochrane.net , http://CampRate.com , http://PopcornMonsters.com
*/
package com.jdon.jivejdon.presentation.servlet.upload.strutsplugin;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.logging.log4j.*;
import java.io.File;
/**
*/
public class MonitoredDiskFileItemFactory extends DiskFileItemFactory
{
Logger log = LogManager.getLogger(this.getClass());
private OutputStreamListener listener = null;
public MonitoredDiskFileItemFactory(OutputStreamListener listener)
{
super();
log.debug("inside MonitoredDiskFileItemFactory constructor (listener) ");
this.listener = listener;
}
public MonitoredDiskFileItemFactory(int sizeThreshold, File repository, OutputStreamListener listener)
{
super(sizeThreshold, repository);
log.debug("inside MonitoredDiskFileItemFactory constructor ");
this.listener = listener;
}
public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName)
{
log.debug("inside MonitoredDiskFileItemFactory createItem ");
return new MonitoredDiskFileItem(fieldName, contentType, isFormField, fileName, getSizeThreshold(), getRepository(), listener);
}
}
|
3e00cf75eb4dae560a1b3906527a511572e3d934 | 654 | java | Java | app/src/main/java/me/saket/dank/utils/markdown/markwon/SpoilerLabelSpan.java | Sanjay15693/Dank | deed7953dd47d069bf88583a59c96ff8d19cf463 | [
"Apache-2.0"
] | 837 | 2018-12-15T18:43:56.000Z | 2022-03-21T20:34:37.000Z | app/src/main/java/me/saket/dank/utils/markdown/markwon/SpoilerLabelSpan.java | Sanjay15693/Dank | deed7953dd47d069bf88583a59c96ff8d19cf463 | [
"Apache-2.0"
] | 14 | 2018-12-16T00:48:50.000Z | 2020-08-02T16:16:31.000Z | app/src/main/java/me/saket/dank/utils/markdown/markwon/SpoilerLabelSpan.java | Sanjay15693/Dank | deed7953dd47d069bf88583a59c96ff8d19cf463 | [
"Apache-2.0"
] | 141 | 2018-12-15T19:32:50.000Z | 2022-01-26T09:41:01.000Z | 21.8 | 58 | 0.743119 | 329 | package me.saket.dank.utils.markdown.markwon;
import android.support.annotation.ColorInt;
import android.text.TextPaint;
import android.text.style.CharacterStyle;
public class SpoilerLabelSpan extends CharacterStyle {
private final @ColorInt int backgroundColor;
private boolean isHidden;
public SpoilerLabelSpan(@ColorInt int backgroundColor) {
super();
this.backgroundColor = backgroundColor;
}
public void setHidden(boolean hidden) {
this.isHidden = hidden;
}
@Override
public void updateDrawState(TextPaint ds) {
if (isHidden) {
ds.setColor(backgroundColor);
}
ds.bgColor = backgroundColor;
}
}
|
3e00d01fc44419fd644afc0b24d1419762a025b5 | 255 | java | Java | src/main/java/com/alibaba/dchain/inner/utils/StringUtil.java | aliyun/alibaba-dchain-open-api-sdk | 368f4223b06113c5a75e3ec8a420937299646e8c | [
"Apache-2.0"
] | 2 | 2022-03-18T09:14:42.000Z | 2022-03-21T02:46:44.000Z | src/main/java/com/alibaba/dchain/inner/utils/StringUtil.java | aliyun/alibaba-dchain-open-api-sdk | 368f4223b06113c5a75e3ec8a420937299646e8c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alibaba/dchain/inner/utils/StringUtil.java | aliyun/alibaba-dchain-open-api-sdk | 368f4223b06113c5a75e3ec8a420937299646e8c | [
"Apache-2.0"
] | null | null | null | 15.9375 | 48 | 0.603922 | 330 | package com.alibaba.dchain.inner.utils;
/**
* @author 开帆
* @date 2022/02/17
*/
public final class StringUtil {
private StringUtil() {
}
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
}
|
3e00d0468ad47fc8110ef170049028294236011d | 482 | java | Java | com.ur.urcap.examples.driver.gripper.advancedgripper/src/main/java/com/ur/urcap/examples/driver/gripper/advancedgripper/Activator.java | UniversalRobots/AdvancedGripper | 1d218e7e41a0cf33be56e8849be5337b2806636e | [
"Apache-2.0"
] | 1 | 2021-01-30T21:43:09.000Z | 2021-01-30T21:43:09.000Z | com.ur.urcap.examples.driver.gripper.advancedgripper/src/main/java/com/ur/urcap/examples/driver/gripper/advancedgripper/Activator.java | UniversalRobots/AdvancedGripper | 1d218e7e41a0cf33be56e8849be5337b2806636e | [
"Apache-2.0"
] | 13 | 2021-03-08T10:10:46.000Z | 2021-03-17T15:24:02.000Z | UR CAPS/Info (form sdk)/driver (From sdk)/gripper/com.ur.urcap.examples.driver.gripper.advancedgripper/src/main/java/com/ur/urcap/examples/driver/gripper/advancedgripper/Activator.java | Andreasgdp/Robot-hand-semester-2 | 8304c02e9f2d413826564996c35aa4b7b6ef7a7f | [
"MIT",
"Unlicense"
] | 1 | 2022-01-22T13:42:34.000Z | 2022-01-22T13:42:34.000Z | 25.368421 | 82 | 0.811203 | 331 | package com.ur.urcap.examples.driver.gripper.advancedgripper;
import com.ur.urcap.api.contribution.driver.gripper.GripperContribution;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
@Override
public void start(final BundleContext context) {
context.registerService(GripperContribution.class, new AdvancedGripper(), null);
}
@Override
public void stop(BundleContext context) {
}
}
|
3e00d057e9d91facf26f94eb03b3b2f0e8c5fb95 | 692 | java | Java | src/main/java/parameter/SegmentType.java | JianlanZhu/Carcassonne | fa322d1d50417e8bc5aada13e4ea20f64736456d | [
"Apache-2.0"
] | null | null | null | src/main/java/parameter/SegmentType.java | JianlanZhu/Carcassonne | fa322d1d50417e8bc5aada13e4ea20f64736456d | [
"Apache-2.0"
] | null | null | null | src/main/java/parameter/SegmentType.java | JianlanZhu/Carcassonne | fa322d1d50417e8bc5aada13e4ea20f64736456d | [
"Apache-2.0"
] | null | null | null | 26.615385 | 93 | 0.677746 | 332 | package edu.cmu.cs.cs214.hw4.parameter;
/**
* All the possible features.
*/
public enum SegmentType {
CITY("city", 2, 1), ROAD("road", 1, 1), FIELD("field", 0, 0), CLOISTER("cloister", 1, 1);
private String segmentTypeName;
private int completePoints;
private int incompletePoints;
SegmentType(String segmentTypeName, int completePoints, int incompletePoints) {
this.segmentTypeName = segmentTypeName;
this.completePoints = completePoints;
this.incompletePoints = incompletePoints;
}
public int getCompletePoints() {
return completePoints;
}
public int getIncompletePoints() {
return incompletePoints;
}
}
|
3e00d0c29040723bd89f0f0ee973e97dd3bca474 | 202 | java | Java | java_log/src/main/java/site/uuyy/log/JUL.java | wanghaizhang/blogproject | e14104430c764ec7185c787976e4ead042b07e0c | [
"Apache-2.0"
] | null | null | null | java_log/src/main/java/site/uuyy/log/JUL.java | wanghaizhang/blogproject | e14104430c764ec7185c787976e4ead042b07e0c | [
"Apache-2.0"
] | null | null | null | java_log/src/main/java/site/uuyy/log/JUL.java | wanghaizhang/blogproject | e14104430c764ec7185c787976e4ead042b07e0c | [
"Apache-2.0"
] | null | null | null | 16.833333 | 45 | 0.623762 | 333 | package site.uuyy.log;
import java.util.logging.Logger;
public class JUL {
public static void main(String[] args) {
Logger log = Logger.getLogger("jul");
log.info("123");
}
}
|
3e00d115b0fb421a7bc68346e0723f209a3ba22c | 5,579 | java | Java | thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/client/diffsummary/MultiDimensionalSummary.java | newsummit/incubator-pinot | 3fee99dcf2bcce9a5d292519cdfced30e726056b | [
"Apache-2.0"
] | null | null | null | thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/client/diffsummary/MultiDimensionalSummary.java | newsummit/incubator-pinot | 3fee99dcf2bcce9a5d292519cdfced30e726056b | [
"Apache-2.0"
] | null | null | null | thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/client/diffsummary/MultiDimensionalSummary.java | newsummit/incubator-pinot | 3fee99dcf2bcce9a5d292519cdfced30e726056b | [
"Apache-2.0"
] | null | null | null | 49.424779 | 120 | 0.76598 | 334 | /**
* Copyright (C) 2014-2018 LinkedIn Corp. (hzdkv@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.thirdeye.client.diffsummary;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Multimap;
import com.linkedin.thirdeye.client.diffsummary.costfunctions.CostFunction;
import com.linkedin.thirdeye.constant.MetricAggFunction;
import com.linkedin.thirdeye.dashboard.Utils;
import com.linkedin.thirdeye.dashboard.views.diffsummary.Summary;
import com.linkedin.thirdeye.dashboard.views.diffsummary.SummaryResponse;
import com.linkedin.thirdeye.datasource.MetricExpression;
import java.util.List;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
/**
* A portal class that is used to trigger the multi-dimensional summary algorithm and to get the summary response.
*/
public class MultiDimensionalSummary {
private OLAPDataBaseClient olapClient;
private CostFunction costFunction;
private DateTimeZone dateTimeZone;
public MultiDimensionalSummary(OLAPDataBaseClient olapClient, CostFunction costFunction,
DateTimeZone dateTimeZone) {
Preconditions.checkNotNull(olapClient);
Preconditions.checkNotNull(dateTimeZone);
Preconditions.checkNotNull(costFunction);
this.olapClient = olapClient;
this.costFunction = costFunction;
this.dateTimeZone = dateTimeZone;
}
/**
* Builds the summary given the given metric information.
*
* @param dataset the dataset of the metric.
* @param metric the name of the metric.
* @param currentStartInclusive the start time of current data cube, inclusive.
* @param currentEndExclusive the end time of the current data cube, exclusive.
* @param baselineStartInclusive the start of the baseline data cube, inclusive.
* @param baselineEndExclusive the end of the baseline data cube, exclusive.
* @param dimensions the dimensions to be considered in the summary. If the variable depth is zero, then the order
* of the dimension is used; otherwise, this method will determine the order of the dimensions
* depending on their cost. After the order is determined, the first 'depth' dimensions are used
* the generated the summary.
* @param dataFilters the filter to be applied on the data cube.
* @param summarySize the number of entries to be put in the summary.
* @param depth the number of dimensions to be drilled down when analyzing the summary.
* @param hierarchies the hierarchy among the dimensions. The order will always be honored when determining the order
* of dimensions.
* @param doOneSideError if the summary should only consider one side error.
*
* @return the multi-dimensional summary.
*/
public SummaryResponse buildSummary(String dataset, String metric, long currentStartInclusive,
long currentEndExclusive, long baselineStartInclusive, long baselineEndExclusive, Dimensions dimensions,
Multimap<String, String> dataFilters, int summarySize, int depth, List<List<String>> hierarchies,
boolean doOneSideError) throws Exception {
Preconditions.checkArgument(!Strings.isNullOrEmpty(dataset));
Preconditions.checkArgument(!Strings.isNullOrEmpty(metric));
Preconditions.checkArgument(currentStartInclusive < currentEndExclusive);
Preconditions.checkArgument(baselineStartInclusive < baselineEndExclusive);
Preconditions.checkNotNull(dimensions);
Preconditions.checkArgument(dimensions.size() > 0);
Preconditions.checkNotNull(dataFilters);
Preconditions.checkArgument(summarySize > 1);
Preconditions.checkNotNull(hierarchies);
Preconditions.checkArgument(depth >= 0);
olapClient.setCollection(dataset);
List<MetricExpression> metricExpressions = Utils.convertToMetricExpressions(metric, MetricAggFunction.SUM, dataset);
olapClient.setMetricExpression(metricExpressions.get(0));
olapClient.setCurrentStartInclusive(new DateTime(currentStartInclusive, dateTimeZone));
olapClient.setCurrentEndExclusive(new DateTime(currentEndExclusive, dateTimeZone));
olapClient.setBaselineStartInclusive(new DateTime(baselineStartInclusive, dateTimeZone));
olapClient.setBaselineEndExclusive(new DateTime(baselineEndExclusive, dateTimeZone));
Cube cube = new Cube(costFunction);
SummaryResponse response;
if (depth > 0) { // depth != 0 means manual dimension order
cube.buildWithAutoDimensionOrder(olapClient, dimensions, dataFilters, depth, hierarchies);
Summary summary = new Summary(cube, costFunction);
response = summary.computeSummary(summarySize, doOneSideError, depth);
} else { // manual dimension order
cube.buildWithManualDimensionOrder(olapClient, dimensions, dataFilters);
Summary summary = new Summary(cube, costFunction);
response = summary.computeSummary(summarySize, doOneSideError);
}
response.setDataset(dataset);
response.setMetricName(metric);
return response;
}
}
|
3e00d163e1e28403e1146918a4a8600c30e77dd7 | 5,815 | java | Java | server/src/main/java/org/uiautomation/ios/grid/StoppableRegisteringRemote.java | krmahadevan/ios-driver | b85f7e63d53ea23e041b9b06520d75df50a3349a | [
"Apache-2.0"
] | 207 | 2015-01-06T16:41:55.000Z | 2021-11-16T10:55:23.000Z | server/src/main/java/org/uiautomation/ios/grid/StoppableRegisteringRemote.java | krmahadevan/ios-driver | b85f7e63d53ea23e041b9b06520d75df50a3349a | [
"Apache-2.0"
] | 85 | 2015-01-06T18:42:44.000Z | 2018-03-22T21:13:04.000Z | server/src/main/java/org/uiautomation/ios/grid/StoppableRegisteringRemote.java | krmahadevan/ios-driver | b85f7e63d53ea23e041b9b06520d75df50a3349a | [
"Apache-2.0"
] | 90 | 2015-01-02T04:01:07.000Z | 2022-02-22T09:02:53.000Z | 37.516129 | 145 | 0.667928 | 335 | package org.uiautomation.ios.grid;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.json.JSONObject;
import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.common.exception.GridConfigurationException;
import org.openqa.selenium.remote.internal.HttpClientFactory;
import org.openqa.selenium.remote.server.log.LoggingManager;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import static org.uiautomation.ios.communication.Helper.extractObject;
public class StoppableRegisteringRemote {
private static final Logger log = Logger.getLogger(StoppableRegisteringRemote.class.getName());
private RegistrationRequest nodeConfig;
private final HttpClientFactory httpClientFactory;
private boolean run = true;
public StoppableRegisteringRemote(RegistrationRequest config) {
this.nodeConfig = config;
this.httpClientFactory = new HttpClientFactory();
}
public URL getRemoteURL() {
String host = (String) nodeConfig.getConfiguration().get(RegistrationRequest.HOST);
String port = (String) nodeConfig.getConfiguration().get(RegistrationRequest.PORT);
String url = "http://" + host + ":" + port;
try {
return new URL(url);
} catch (MalformedURLException e) {
throw new GridConfigurationException("error building the node url " + e.getMessage(), e);
}
}
/**
* register the hub following the configuration : <p/> - check if the proxy is already registered before sending a reg request. <p/> - register
* again every X ms is specified in the config of the node.
*/
public void startRegistrationProcess() {
log.info("using the json request : " + nodeConfig.toJSON());
final int registerCycleInterval = nodeConfig.getConfigAsInt(RegistrationRequest.REGISTER_CYCLE, 0);
if (registerCycleInterval > 0) {
new Thread(new Runnable() { // Thread safety reviewed
public void run() {
boolean first = true;
log.info("Starting auto register thread. Will try to register every " + registerCycleInterval + " ms.");
synchronized (this) {
while (run) {
try {
boolean checkForPresence = true;
if (first) {
first = false;
checkForPresence = false;
}
registerToHub(checkForPresence);
} catch (org.openqa.grid.common.exception.GridException e) {
log.info("couldn't register this node : " + e.getMessage());
}
try {
Thread.sleep(registerCycleInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
// While we wait for someone to rewrite server logging.
LoggingManager.perSessionLogHandler().clearThreadTempLogs();
}
}
}
}).start();
}
LoggingManager.perSessionLogHandler().clearThreadTempLogs();
}
public void stopRegistrationProcess() {
synchronized (this) {
run = false;
}
}
private void registerToHub(boolean checkPresenceFirst) {
if (!checkPresenceFirst || !isAlreadyRegistered(nodeConfig)) {
String tmp =
"http://" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":"
+ nodeConfig.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/register";
HttpClient client = httpClientFactory.getHttpClient();
try {
URL registration = new URL(tmp);
log.info("Registering the node to hub :" + registration);
BasicHttpEntityEnclosingRequest r =
new BasicHttpEntityEnclosingRequest("POST", registration.toExternalForm());
String json = nodeConfig.toJSON();
r.setEntity(new StringEntity(json, "UTF-8"));
HttpHost host = new HttpHost(registration.getHost(), registration.getPort());
HttpResponse response = client.execute(host, r);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Error sending the registration request.");
}
} catch (Exception e) {
throw new org.openqa.grid.common.exception.GridException("Error sending the registration request.", e);
}
} else {
log.fine("The node is already present on the hub. Skipping registration.");
}
}
private boolean isAlreadyRegistered(RegistrationRequest node) {
HttpClient client = httpClientFactory.getHttpClient();
try {
String tmp =
"http://" + node.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":"
+ node.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/api/proxy";
URL api = new URL(tmp);
HttpHost host = new HttpHost(api.getHost(), api.getPort());
String id = (String) node.getConfiguration().get(RegistrationRequest.ID);
if (id == null) {
id = (String) node.getConfiguration().get(RegistrationRequest.REMOTE_HOST);
}
BasicHttpRequest r = new BasicHttpRequest("GET", api.toExternalForm() + "?id=" + id);
HttpResponse response = client.execute(host, r);
if (response.getStatusLine().getStatusCode() != 200) {
throw new org.openqa.grid.common.exception.GridException("Hub is down or not responding.");
}
JSONObject o = extractObject(response);
return (Boolean) o.get("success");
} catch (Exception e) {
throw new org.openqa.grid.common.exception.GridException("Hub is down or not responding: " + e.getMessage());
}
}
}
|
3e00d1756960c18c735770b4e5d24b20e9a4bfbb | 1,951 | java | Java | src/main/java/SwapActionGroup.java | morgankdavis/tabs-suck | 9f6cdfbaec4c9659916cd4c4880beb51b9fb4d82 | [
"MIT"
] | null | null | null | src/main/java/SwapActionGroup.java | morgankdavis/tabs-suck | 9f6cdfbaec4c9659916cd4c4880beb51b9fb4d82 | [
"MIT"
] | null | null | null | src/main/java/SwapActionGroup.java | morgankdavis/tabs-suck | 9f6cdfbaec4c9659916cd4c4880beb51b9fb4d82 | [
"MIT"
] | null | null | null | 30.968254 | 99 | 0.549974 | 336 |
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
public class SwapActionGroup extends DefaultActionGroup {
private static final Logger log = Logger.getInstance("net.mkd.TabsSuck.OpenActionGroup");
public SwapActionGroup() {
super("Swap With", true);
}
@Override
public void update(AnActionEvent event) {
Project project = event.getProject();
TabsSuckProject projectComponent = project.getComponent(TabsSuckProject.class);
TabsSuckApplication applicationComponent = project.getComponent(TabsSuckApplication.class);
if (projectComponent != null) {
if (applicationComponent != null) {
Editor editor = event.getData(CommonDataKeys.EDITOR);
if (editor != null) {
Presentation presentation = event.getPresentation();
if (projectComponent.isEditorAttachedToProjectWindow(editor)) {
// rebuild the menu
removeAll();
int numEditors = projectComponent.numEditors();
for (int i = 0; i < numEditors; ++i) {
add(applicationComponent.swapAction(i));
}
presentation.setVisible(true);
}
else {
presentation.setVisible(false);
}
}
else {
log.warn("Editor in SwapActionGroup.update() is null.");
}
}
else {
log.warn("ApplicationComponent in SwapActionGroup.update() is null.");
}
}
else {
log.warn("ProductComponent in SwapActionGroup.update() is null.");
}
}
}
|
3e00d1f60484f3634de9ca22bd17cf9b0d8d751b | 4,869 | java | Java | plugin-core/src/main/java/org/ligoj/app/resource/node/EventResource.java | ligoj/plugin-api | a150ab2afb8c32b8b9f075e40513cdd8f01552cf | [
"MIT"
] | 4 | 2017-03-20T09:35:15.000Z | 2017-12-19T15:39:18.000Z | plugin-core/src/main/java/org/ligoj/app/resource/node/EventResource.java | ligoj/plugin-api | a150ab2afb8c32b8b9f075e40513cdd8f01552cf | [
"MIT"
] | 16 | 2017-03-20T09:37:00.000Z | 2020-09-17T11:20:27.000Z | plugin-core/src/main/java/org/ligoj/app/resource/node/EventResource.java | ligoj/plugin-api | a150ab2afb8c32b8b9f075e40513cdd8f01552cf | [
"MIT"
] | 9 | 2017-11-08T10:57:20.000Z | 2020-05-28T02:08:20.000Z | 32.032895 | 111 | 0.720682 | 337 | /*
* Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
*/
package org.ligoj.app.resource.node;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.transaction.Transactional;
import org.ligoj.app.dao.EventRepository;
import org.ligoj.app.model.Event;
import org.ligoj.app.model.EventType;
import org.ligoj.app.model.Node;
import org.ligoj.app.model.Subscription;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* {@link Event} resource.
*/
@Service
@Transactional
public class EventResource {
@Autowired
private EventRepository repository;
/**
* Register an event on a node. The event will be registered only if the value is new.
*
* @param node node
* @param eventType event type
* @param value new value
* @return <code>true</code> if the event has been registered in database.
*/
public boolean registerEvent(final Node node, final EventType eventType, final String value) {
final var lastEvent = repository.findFirstByNodeAndTypeOrderByIdDesc(node, eventType);
// Register event if it is a discovered node, or a status change
if (lastEvent == null || !value.equals(lastEvent.getValue())) {
final var newEvent = new Event();
newEvent.setNode(node);
saveEvent(newEvent, eventType, value);
return true;
}
// No change, no persisted event
return false;
}
/**
* register an event on a subscription. The event will be registered only if the value is new.
*
* @param subscription The related subscription.
* @param eventType The new event type.
* @param value The new event value.
* @return <code>true</code> if an event has been saved in database.
*/
public boolean registerEvent(final Subscription subscription, final EventType eventType, final String value) {
final var lastEvent = repository.findFirstBySubscriptionAndTypeOrderByIdDesc(subscription, eventType);
if (lastEvent == null || !value.equals(lastEvent.getValue())) {
final var newEvent = new Event();
newEvent.setSubscription(subscription);
saveEvent(newEvent, eventType, value);
return true;
}
return false;
}
/**
* save an event
*
* @param event event
* @param eventType event Type
* @param value value
*/
private void saveEvent(final Event event, final EventType eventType, final String value) {
event.setValue(value);
event.setType(eventType);
event.setDate(new Date());
repository.save(event);
}
/**
* {@link Event} JPA to VO object transformer without refined information.
*
* @param entity Source entity.
* @return The corresponding VO object with node/subscription reference.
*/
public static EventVo toVo(final Event entity) {
final var vo = new EventVo();
vo.setValue(entity.getValue());
vo.setType(entity.getType());
if (entity.getNode() == null) {
vo.setSubscription(entity.getSubscription().getId());
vo.setNode(NodeResource.toVoLight(entity.getSubscription().getNode()));
} else {
vo.setNode(NodeResource.toVoLight(entity.getNode()));
}
return vo;
}
/**
* Return the last known event related to a visible node of given user.
*
* @param user The principal user requesting these events.
* @param node The related node.
* @return Event related to a visible {@link Node}. May be <code>null</code>.
*/
public EventVo findByNode(final String user, final String node) {
return Optional.ofNullable(repository.findLastEvent(user, node)).map(EventResource::toVo).orElse(null);
}
/**
* Return all events related to a visible node of given user.
*
* @param user The principal user requesting these events.
* @return Events related to a visible {@link Node}.
*/
public List<EventVo> findAll(final String user) {
final var events = repository.findLastEvents(user);
final var services = new HashMap<String, EventVo>();
final var tools = new HashMap<String, EventVo>();
for (final var event : events) {
final var parent = event.getNode().getRefined();
fillParentEvents(tools, parent, EventResource.toVo(event), event.getValue());
fillParentEvents(services, parent.getRefined(), tools.get(parent.getId()), event.getValue());
}
return new ArrayList<>(services.values());
}
private void fillParentEvents(final Map<String, EventVo> parents, final Node parent, final EventVo eventVo,
final String eventValue) {
final var service = parents.computeIfAbsent(parent.getId(), key -> {
final var result = new EventVo();
result.setNode(NodeResource.toVoLight(parent));
result.setValue(eventValue);
result.setType(eventVo.getType());
return result;
});
service.getSpecifics().add(eventVo);
if ("DOWN".equals(eventValue)) {
service.setValue(eventValue);
}
}
}
|
3e00d2609a9447aa1f21a78ad3658d28741dc549 | 1,469 | java | Java | AccountingApp/app/src/main/java/com/example/accountingapp/MainViewPagerAdapter.java | 2375622526/AccountingApp | 0efc1980c4cb8f5debb91958fb7e5c57794b2163 | [
"Apache-2.0"
] | 3 | 2019-06-26T15:56:41.000Z | 2019-08-12T18:23:27.000Z | AccountingApp/app/src/main/java/com/example/accountingapp/MainViewPagerAdapter.java | 2375622526/AccountingApp | 0efc1980c4cb8f5debb91958fb7e5c57794b2163 | [
"Apache-2.0"
] | null | null | null | AccountingApp/app/src/main/java/com/example/accountingapp/MainViewPagerAdapter.java | 2375622526/AccountingApp | 0efc1980c4cb8f5debb91958fb7e5c57794b2163 | [
"Apache-2.0"
] | null | null | null | 24.898305 | 81 | 0.646698 | 338 | package com.example.accountingapp;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.LinkedList;
public class MainViewPagerAdapter extends FragmentPagerAdapter {
LinkedList<MainFragment> fragments = new LinkedList<>();
LinkedList<String> dates = new LinkedList<>();
public MainViewPagerAdapter(FragmentManager fm) {
super(fm);
initFraments();
}
private void initFraments(){
dates = GlodalUtil.getInstance().recordBatabaseHelper.getAvaliableDate();
if (!dates.contains(DateUtil.getFormattedDate())){
dates.addLast(DateUtil.getFormattedDate());
}
//根据数据区拿到多的数据,生成多少也的ViewPager
for (String date:dates){
MainFragment fragment = new MainFragment(date);
fragments.add(fragment);
}
}
public void reload(){
for (MainFragment mainFragment : fragments){
mainFragment.reload();
}
}
public int getLastIndex(){
return fragments.size()-1;
}
@Override
public Fragment getItem(int i) {
return fragments.get(i);
}
@Override
public int getCount() {
return fragments.size();
}
public String getDateStr(int index){
return dates.get(index);
}
public double getTotalCost(int i){
return fragments.get(i).getTodayAmount();
}
}
|
3e00d37398d5510e590c1c562cc9ac16d89e1a80 | 5,906 | java | Java | sns/deployment/src/main/java/io/quarkus/amazon/sns/deployment/SnsProcessor.java | emattheis/quarkus-amazon-services | 75b0764e967f2e7cf284539c0a5ff9129871ece5 | [
"Apache-2.0"
] | 87 | 2021-12-08T05:02:42.000Z | 2022-03-31T05:02:05.000Z | sns/deployment/src/main/java/io/quarkus/amazon/sns/deployment/SnsProcessor.java | emattheis/quarkus-amazon-services | 75b0764e967f2e7cf284539c0a5ff9129871ece5 | [
"Apache-2.0"
] | 69 | 2021-12-06T06:25:45.000Z | 2022-03-31T06:26:44.000Z | sns/deployment/src/main/java/io/quarkus/amazon/sns/deployment/SnsProcessor.java | emattheis/quarkus-amazon-services | 75b0764e967f2e7cf284539c0a5ff9129871ece5 | [
"Apache-2.0"
] | 7 | 2021-12-08T16:23:33.000Z | 2022-03-23T02:51:22.000Z | 41.300699 | 111 | 0.749915 | 339 | package io.quarkus.amazon.sns.deployment;
import java.util.List;
import org.jboss.jandex.DotName;
import io.quarkus.amazon.common.deployment.AbstractAmazonServiceProcessor;
import io.quarkus.amazon.common.deployment.AmazonClientAsyncTransportBuildItem;
import io.quarkus.amazon.common.deployment.AmazonClientBuildItem;
import io.quarkus.amazon.common.deployment.AmazonClientInterceptorsPathBuildItem;
import io.quarkus.amazon.common.deployment.AmazonClientSyncTransportBuildItem;
import io.quarkus.amazon.common.deployment.AmazonHttpClients;
import io.quarkus.amazon.common.runtime.AmazonClientApacheTransportRecorder;
import io.quarkus.amazon.common.runtime.AmazonClientNettyTransportRecorder;
import io.quarkus.amazon.common.runtime.AmazonClientRecorder;
import io.quarkus.amazon.common.runtime.AmazonClientUrlConnectionTransportRecorder;
import io.quarkus.amazon.sns.runtime.SnsBuildTimeConfig;
import io.quarkus.amazon.sns.runtime.SnsClientProducer;
import io.quarkus.amazon.sns.runtime.SnsRecorder;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.arc.deployment.BeanRegistrationPhaseBuildItem;
import io.quarkus.arc.deployment.SyntheticBeanBuildItem;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.ExtensionSslNativeSupportBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import software.amazon.awssdk.services.sns.SnsAsyncClient;
import software.amazon.awssdk.services.sns.SnsAsyncClientBuilder;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.SnsClientBuilder;
public class SnsProcessor extends AbstractAmazonServiceProcessor {
private static final String AMAZON_SNS = "amazon-sns";
SnsBuildTimeConfig buildTimeConfig;
@Override
protected String amazonServiceClientName() {
return AMAZON_SNS;
}
@Override
protected String configName() {
return "sns";
}
@Override
protected DotName syncClientName() {
return DotName.createSimple(SnsClient.class.getName());
}
@Override
protected DotName asyncClientName() {
return DotName.createSimple(SnsAsyncClient.class.getName());
}
@Override
protected String builtinInterceptorsPath() {
return "software/amazon/awssdk/services/sns/execution.interceptors";
}
@BuildStep
AdditionalBeanBuildItem producer() {
return AdditionalBeanBuildItem.unremovableOf(SnsClientProducer.class);
}
@BuildStep
void setup(BeanRegistrationPhaseBuildItem beanRegistrationPhase,
BuildProducer<ExtensionSslNativeSupportBuildItem> extensionSslNativeSupport,
BuildProducer<FeatureBuildItem> feature,
BuildProducer<AmazonClientInterceptorsPathBuildItem> interceptors,
BuildProducer<AmazonClientBuildItem> clientProducer) {
setupExtension(beanRegistrationPhase, extensionSslNativeSupport, feature, interceptors, clientProducer,
buildTimeConfig.sdk,
buildTimeConfig.syncClient);
}
@BuildStep(onlyIf = AmazonHttpClients.IsAmazonApacheHttpServicePresent.class)
@Record(ExecutionTime.RUNTIME_INIT)
void setupApacheSyncTransport(List<AmazonClientBuildItem> amazonClients, SnsRecorder recorder,
AmazonClientApacheTransportRecorder transportRecorder,
BuildProducer<AmazonClientSyncTransportBuildItem> syncTransports) {
createApacheSyncTransportBuilder(amazonClients,
transportRecorder,
buildTimeConfig.syncClient,
recorder.getSyncConfig(),
syncTransports);
}
@BuildStep(onlyIf = AmazonHttpClients.IsAmazonUrlConnectionHttpServicePresent.class)
@Record(ExecutionTime.RUNTIME_INIT)
void setupUrlConnectionSyncTransport(List<AmazonClientBuildItem> amazonClients, SnsRecorder recorder,
AmazonClientUrlConnectionTransportRecorder transportRecorder,
BuildProducer<AmazonClientSyncTransportBuildItem> syncTransports) {
createUrlConnectionSyncTransportBuilder(amazonClients,
transportRecorder,
buildTimeConfig.syncClient,
recorder.getSyncConfig(),
syncTransports);
}
@BuildStep(onlyIf = AmazonHttpClients.IsAmazonNettyHttpServicePresent.class)
@Record(ExecutionTime.RUNTIME_INIT)
void setupNettyAsyncTransport(List<AmazonClientBuildItem> amazonClients, SnsRecorder recorder,
AmazonClientNettyTransportRecorder transportRecorder,
BuildProducer<AmazonClientAsyncTransportBuildItem> asyncTransports) {
createNettyAsyncTransportBuilder(amazonClients,
transportRecorder,
recorder.getAsyncConfig(),
asyncTransports);
}
@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
void createClientBuilders(SnsRecorder recorder,
AmazonClientRecorder commonRecorder,
List<AmazonClientSyncTransportBuildItem> syncTransports,
List<AmazonClientAsyncTransportBuildItem> asyncTransports,
BuildProducer<SyntheticBeanBuildItem> syntheticBeans) {
createClientBuilders(commonRecorder,
recorder.getAwsConfig(),
recorder.getSdkConfig(),
buildTimeConfig.sdk,
syncTransports,
asyncTransports,
SnsClientBuilder.class,
(syncTransport) -> recorder.createSyncBuilder(syncTransport),
SnsAsyncClientBuilder.class,
(asyncTransport) -> recorder.createAsyncBuilder(asyncTransport),
null,
null,
syntheticBeans);
}
}
|
3e00d3e28e2d0646e3307281b2cfba6f055cba10 | 8,803 | java | Java | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/main/java/org/kie/workbench/common/stunner/core/client/canvas/controls/actions/CanvasNameEditionControlImpl.java | hasys/kie-wb-common | 117f2450eb86581952ab99f17c517b777ae3b2ed | [
"Apache-2.0"
] | null | null | null | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/main/java/org/kie/workbench/common/stunner/core/client/canvas/controls/actions/CanvasNameEditionControlImpl.java | hasys/kie-wb-common | 117f2450eb86581952ab99f17c517b777ae3b2ed | [
"Apache-2.0"
] | null | null | null | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/main/java/org/kie/workbench/common/stunner/core/client/canvas/controls/actions/CanvasNameEditionControlImpl.java | hasys/kie-wb-common | 117f2450eb86581952ab99f17c517b777ae3b2ed | [
"Apache-2.0"
] | null | null | null | 40.944186 | 129 | 0.64603 | 340 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.core.client.canvas.controls.actions;
import com.google.gwt.user.client.ui.IsWidget;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvas;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.Canvas;
import org.kie.workbench.common.stunner.core.client.canvas.controls.AbstractCanvasHandlerRegistrationControl;
import org.kie.workbench.common.stunner.core.client.canvas.event.CanvasFocusedEvent;
import org.kie.workbench.common.stunner.core.client.canvas.event.keyboard.KeyDownEvent;
import org.kie.workbench.common.stunner.core.client.canvas.event.keyboard.KeyboardEvent;
import org.kie.workbench.common.stunner.core.client.canvas.event.selection.CanvasElementSelectedEvent;
import org.kie.workbench.common.stunner.core.client.components.actions.NameEditBox;
import org.kie.workbench.common.stunner.core.client.components.views.FloatingView;
import org.kie.workbench.common.stunner.core.client.shape.Shape;
import org.kie.workbench.common.stunner.core.client.shape.view.HasEventHandlers;
import org.kie.workbench.common.stunner.core.client.shape.view.HasTitle;
import org.kie.workbench.common.stunner.core.client.shape.view.ShapeView;
import org.kie.workbench.common.stunner.core.client.shape.view.event.*;
import org.kie.workbench.common.stunner.core.graph.Element;
import org.kie.workbench.common.stunner.core.graph.content.view.View;
import org.kie.workbench.common.stunner.core.graph.util.GraphUtils;
import org.uberfire.mvp.Command;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import static org.uberfire.commons.validation.PortablePreconditions.checkNotNull;
@Dependent
public class CanvasNameEditionControlImpl
extends AbstractCanvasHandlerRegistrationControl
implements CanvasNameEditionControl<AbstractCanvasHandler, Element> {
private static final int FLOATING_VIEW_TIMEOUT = 3000;
private static final double SHAPE_EDIT_ALPH = 0.2d;
FloatingView<IsWidget> floatingView;
NameEditBox<AbstractCanvasHandler, Element> nameEditBox;
Event<CanvasElementSelectedEvent> elementSelectedEvent;
private String uuid;
private final Command floatingHideCallback = CanvasNameEditionControlImpl.this::hide;
@Inject
public CanvasNameEditionControlImpl( final FloatingView<IsWidget> floatingView,
final NameEditBox<AbstractCanvasHandler, Element> nameEditBox,
final Event<CanvasElementSelectedEvent> elementSelectedEvent ) {
this.floatingView = floatingView;
this.nameEditBox = nameEditBox;
this.elementSelectedEvent = elementSelectedEvent;
this.uuid = null;
}
@Override
public void enable( final AbstractCanvasHandler canvasHandler ) {
super.enable( canvasHandler );
nameEditBox.initialize( canvasHandler, () -> {
CanvasNameEditionControlImpl.this.hide();
elementSelectedEvent.fire( new CanvasElementSelectedEvent( canvasHandler, CanvasNameEditionControlImpl.this.uuid ) );
} );
floatingView
.hide()
.setHideCallback( floatingHideCallback )
.setTimeOut( FLOATING_VIEW_TIMEOUT )
.add( nameEditBox.asWidget() );
}
@Override
public void register( final Element element ) {
final Shape<?> shape = getShape( element.getUUID() );
if ( null != shape ) {
final ShapeView shapeView = shape.getShapeView();
if ( shapeView instanceof HasEventHandlers ) {
final HasEventHandlers hasEventHandlers = ( HasEventHandlers ) shapeView;
// Double click event.
final MouseDoubleClickHandler doubleClickHandler = new MouseDoubleClickHandler() {
@Override
public void handle( final MouseDoubleClickEvent event ) {
CanvasNameEditionControlImpl.this.show( element, event.getClientX(), event.getClientY() );
}
};
hasEventHandlers.addHandler( ViewEventType.MOUSE_DBL_CLICK, doubleClickHandler );
registerHandler( shape.getUUID(), doubleClickHandler );
// TODO: Not firing - Text over event.
final TextOverHandler overHandler = new TextOverHandler() {
@Override
public void handle( TextOverEvent event ) {
canvasHandler.getCanvas().getView().setCursor( AbstractCanvas.Cursors.TEXT );
}
};
hasEventHandlers.addHandler( ViewEventType.TEXT_OVER, overHandler );
registerHandler( shape.getUUID(), overHandler );
// TODO: Not firing - Text out event.
final TextOutHandler outHandler = new TextOutHandler() {
@Override
public void handle( TextOutEvent event ) {
canvasHandler.getCanvas().getView().setCursor( AbstractCanvas.Cursors.AUTO );
}
};
hasEventHandlers.addHandler( ViewEventType.TEXT_OUT, outHandler );
registerHandler( shape.getUUID(), outHandler );
}
}
}
@Override
public CanvasNameEditionControl<AbstractCanvasHandler, Element> show( final Element item,
final double x,
final double y ) {
this.uuid = item.getUUID();
enableShapeEdit();
nameEditBox.show( item );
Double[] size;
try {
size = GraphUtils.getSize( ( View ) item.getContent() );
} catch ( final ClassCastException e ) {
size = null;
}
final double rx = null != size ? size[0] / 2 : 0d;
floatingView
.setX( x - rx )
.setY( y )
.show();
return this;
}
@Override
public CanvasNameEditionControl<AbstractCanvasHandler, Element> hide() {
if ( isVisible() ) {
disableShapeEdit();
this.uuid = null;
nameEditBox.hide();
floatingView.hide();
}
return this;
}
@Override
protected void doDisable() {
super.doDisable();
disableShapeEdit();
this.uuid = null;
nameEditBox.hide();
nameEditBox = null;
floatingView.destroy();
floatingView = null;
}
private boolean enableShapeEdit() {
return setShapeEditMode( true );
}
private boolean disableShapeEdit() {
return setShapeEditMode( false );
}
private boolean setShapeEditMode( final boolean editMode ) {
final Shape<?> shape = getShape( this.uuid );
if ( null != shape ) {
final HasTitle hasTitle = ( HasTitle ) shape.getShapeView();
final double alpha = editMode ? SHAPE_EDIT_ALPH : 1d;
shape.getShapeView().setFillAlpha( alpha );
hasTitle.setTitleAlpha( alpha );
getCanvas().draw();
return true;
}
return false;
}
private Shape<?> getShape( final String uuid ) {
return null != uuid ? getCanvas().getShape( uuid ) : null;
}
private boolean isVisible() {
return null != this.uuid;
}
private Canvas getCanvas() {
return canvasHandler.getCanvas();
}
void onKeyDownEvent( @Observes KeyDownEvent keyDownEvent ) {
checkNotNull( "keyDownEvent", keyDownEvent );
final KeyboardEvent.Key key = keyDownEvent.getKey();
if ( null != key && KeyboardEvent.Key.ESC.equals( key ) ) {
hide();
}
}
void onCanvasFocusedEvent( @Observes CanvasFocusedEvent canvasFocusedEvent ) {
checkNotNull( "canvasFocusedEvent", canvasFocusedEvent );
hide();
}
}
|
3e00d3f57b88fb592470368c0cea750f8ea66a07 | 677 | java | Java | src/main/java/pl/sdacademy/java14poz/petle/petlawhile/PetlaWhile.java | jakub-olszewski/java14poz | cffb0119a9eb4ac2994e20b0ba5c52733844a360 | [
"MIT"
] | 1 | 2019-01-31T14:35:01.000Z | 2019-01-31T14:35:01.000Z | src/main/java/pl/sdacademy/java14poz/petle/petlawhile/PetlaWhile.java | jakub-olszewski/java14poz | cffb0119a9eb4ac2994e20b0ba5c52733844a360 | [
"MIT"
] | null | null | null | src/main/java/pl/sdacademy/java14poz/petle/petlawhile/PetlaWhile.java | jakub-olszewski/java14poz | cffb0119a9eb4ac2994e20b0ba5c52733844a360 | [
"MIT"
] | null | null | null | 23.344828 | 68 | 0.5613 | 341 | package pl.sdacademy.java14poz.petle.petlawhile;
/**
* PetlaWhile
*
* @author: Jakub Olszewski [http://github.com/jakub-olszewski]
* @date: 28.10.2018 14:13
**/
public class PetlaWhile {
public static void main(String[] args) {
boolean czyDzieckoPlacze = true;
int czas = 0;
while (czyDzieckoPlacze){
// wykonuje się od dopóki warunek w while jest spełniony
System.out.println("Dziecko płacze...");
if(czas==120){
czyDzieckoPlacze = false;
}
czas++;
}
if(!czyDzieckoPlacze){
System.out.println("Dziecko nie płacze.");
}
}
}
|
3e00d44ebf0b0efd31429ea6271852837689bb61 | 815 | java | Java | platform/src/main/java/org/pradeep/platform/hibernate/BaseServiceImpl.java | psingarakannan/home-acc-mngmt | c13176327bea7114c571bdeff46110af7bd5178f | [
"Apache-2.0"
] | 1 | 2018-12-28T06:30:04.000Z | 2018-12-28T06:30:04.000Z | platform/src/main/java/org/pradeep/platform/hibernate/BaseServiceImpl.java | psingarakannan/home-acc-mngmt | c13176327bea7114c571bdeff46110af7bd5178f | [
"Apache-2.0"
] | null | null | null | platform/src/main/java/org/pradeep/platform/hibernate/BaseServiceImpl.java | psingarakannan/home-acc-mngmt | c13176327bea7114c571bdeff46110af7bd5178f | [
"Apache-2.0"
] | null | null | null | 23.970588 | 65 | 0.716564 | 342 | package org.pradeep.platform.hibernate;
import org.hibernate.Session;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Date;
/**
* @author psingarakannan on 30/12/18
**/
@Service
public class BaseServiceImpl {
@PersistenceContext
private EntityManager entityManager;
public void saveOrUpdate(AuditedEntity entity) {
saveOrUpdateInTransaction ( entity );
}
public void saveOrUpdateInTransaction(AuditedEntity entity) {
entity.setCreatedBy ( "system" );
entity.setModifiedBy ( "system" );
entity.setCreatedTime ( new Date ( ) );
entity.setModifiedTime ( new Date ( ) );
entityManager.unwrap(Session.class).saveOrUpdate(entity);
}
}
|
3e00d4a653ab2f0fdc9a5411be993525f3bf7e11 | 1,875 | java | Java | app/src/main/java/com/the3rocks/advertscreen/domain/InteractorRX.java | luis-ibanez/advert-screen | 5cea54c560181b0eeaec683ad9250526387641c8 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/the3rocks/advertscreen/domain/InteractorRX.java | luis-ibanez/advert-screen | 5cea54c560181b0eeaec683ad9250526387641c8 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/the3rocks/advertscreen/domain/InteractorRX.java | luis-ibanez/advert-screen | 5cea54c560181b0eeaec683ad9250526387641c8 | [
"Apache-2.0"
] | null | null | null | 30.737705 | 106 | 0.701333 | 343 | package com.the3rocks.advertscreen.domain;
import com.the3rocks.advertscreen.executor.PostExecutionThread;
import com.the3rocks.advertscreen.executor.ThreadExecutor;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.schedulers.Schedulers;
import rx.subscriptions.Subscriptions;
public abstract class InteractorRX<R extends InteractorRX.RequestValues> {
private final ThreadExecutor threadExecutor;
private final PostExecutionThread postExecutionThread;
private Subscription subscription = Subscriptions.empty();
protected InteractorRX(ThreadExecutor threadExecutor,
PostExecutionThread postExecutionThread) {
this.threadExecutor = threadExecutor;
this.postExecutionThread = postExecutionThread;
}
/**
* Builds an {@link rx.Observable} which will be used when executing the current {@link InteractorRX}.
*/
protected abstract Observable buildUseCaseObservable(R requestValues);
/**
* Executes the current use case.
*
* @param useCaseSubscriber The guy who will be listen to the observable build
* with {@link #buildUseCaseObservable(R requestValues)}.
*/
@SuppressWarnings("unchecked")
public void execute(R requestValues, Subscriber useCaseSubscriber) {
this.subscription = this.buildUseCaseObservable(requestValues)
.subscribeOn(Schedulers.from(threadExecutor))
.observeOn(postExecutionThread.getScheduler())
.subscribe(useCaseSubscriber);
}
/**
* Unsubscribes from current {@link rx.Subscription}.
*/
public void unsubscribe() {
if (!subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
/**
* Data passed to a request.
*/
public static abstract class RequestValues {
}
}
|
3e00d570d1be28d36fc857224c9ea4bf1019bec7 | 1,796 | java | Java | app/src/main/java/miage/parisnanterre/fr/mynanterre2/fragment/SupportFragment.java | assane-sakho/myNanterreM2 | 44b73cc02769440f25b99ad40436a73591400fb5 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/miage/parisnanterre/fr/mynanterre2/fragment/SupportFragment.java | assane-sakho/myNanterreM2 | 44b73cc02769440f25b99ad40436a73591400fb5 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/miage/parisnanterre/fr/mynanterre2/fragment/SupportFragment.java | assane-sakho/myNanterreM2 | 44b73cc02769440f25b99ad40436a73591400fb5 | [
"Apache-2.0"
] | null | null | null | 35.45098 | 112 | 0.722345 | 344 | package miage.parisnanterre.fr.mynanterre2.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import miage.parisnanterre.fr.mynanterre2.R;
import miage.parisnanterre.fr.mynanterre2.implem.Cgu;
import miage.parisnanterre.fr.mynanterre2.implem.LiveTweet;
import miage.parisnanterre.fr.mynanterre2.implem.PlanBatiments;
import miage.parisnanterre.fr.mynanterre2.implem.library.ListeEspacesBu;
public class SupportFragment extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.support, container, false);
EditText SupportMessage = v.findViewById(R.id.SupportMessage);
Button Valider = v.findViewById(R.id.Valider);
Valider.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Envoyer mail
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{"nnheo@example.com"});
email.putExtra(Intent.EXTRA_SUBJECT, "Message de support MyNanterre");
email.putExtra(Intent.EXTRA_TEXT, SupportMessage.getText());
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choisissez votre application de messagerie :"));
}
});
return v;
}
}
|
3e00d67f55d8d4b7fc59ee6d5145b900cca15597 | 9,078 | java | Java | joglframework-gl/src/main/java/com/github/dabasan/joglf/gl/drawer/DynamicCapsulesDrawer.java | daba-backup/JOGLFramework | 3b4748554e460b0e41e14b3a0bd8b46b4342608d | [
"MIT"
] | null | null | null | joglframework-gl/src/main/java/com/github/dabasan/joglf/gl/drawer/DynamicCapsulesDrawer.java | daba-backup/JOGLFramework | 3b4748554e460b0e41e14b3a0bd8b46b4342608d | [
"MIT"
] | null | null | null | joglframework-gl/src/main/java/com/github/dabasan/joglf/gl/drawer/DynamicCapsulesDrawer.java | daba-backup/JOGLFramework | 3b4748554e460b0e41e14b3a0bd8b46b4342608d | [
"MIT"
] | null | null | null | 29.378641 | 91 | 0.702578 | 345 | package com.github.dabasan.joglf.gl.drawer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.dabasan.basis.coloru8.ColorU8;
import com.github.dabasan.basis.matrix.Matrix;
import com.github.dabasan.basis.matrix.MatrixFunctions;
import com.github.dabasan.basis.vector.Vector;
import com.github.dabasan.basis.vector.VectorFunctions;
import com.github.dabasan.joglf.gl.shader.ShaderProgram;
import com.github.dabasan.joglf.gl.shape.Capsule;
import com.github.dabasan.joglf.gl.wrapper.GLWrapper;
import com.jogamp.common.nio.Buffers;
import com.jogamp.opengl.GL;
/**
* Draws capsules.
*
* @author Daba
*
*/
public class DynamicCapsulesDrawer extends Dynamic3DDrawer {
private final Logger logger = LoggerFactory.getLogger(DynamicCapsulesDrawer.class);
private final Map<Integer, Capsule> capsules_map;
private final Map<Integer, Integer> indices_sizes_map;
private int buffer_num;
private IntBuffer indices_vbo;
private IntBuffer pos_vbo;
private IntBuffer dif_vbo;
private IntBuffer vao;
public DynamicCapsulesDrawer() {
capsules_map = new TreeMap<>();
indices_sizes_map = new HashMap<>();
buffer_num = 0;
}
@Override
public void SetDefaultProgram() {
final ShaderProgram program = new ShaderProgram("color");
this.AddProgram(program);
}
@Override
public void UpdateBuffers() {
final int capsule_num = capsules_map.size();
if (buffer_num != 0) {
this.DeleteBuffers();
}
indices_vbo = Buffers.newDirectIntBuffer(capsule_num);
pos_vbo = Buffers.newDirectIntBuffer(capsule_num);
dif_vbo = Buffers.newDirectIntBuffer(capsule_num);
vao = Buffers.newDirectIntBuffer(capsule_num);
GLWrapper.glGenBuffers(capsule_num, indices_vbo);
GLWrapper.glGenBuffers(capsule_num, pos_vbo);
GLWrapper.glGenBuffers(capsule_num, dif_vbo);
GLWrapper.glGenVertexArrays(capsule_num, vao);
buffer_num = capsule_num;
int buffer_count = 0;
for (final Capsule capsule : capsules_map.values()) {
final Vector capsule_pos_1 = capsule.GetCapsulePos1();
final Vector capsule_pos_2 = capsule.GetCapsulePos2();
final float radius = capsule.GetRadius();
final int slice_num = capsule.GetSliceNum();
final int stack_num = capsule.GetStackNum();
final ColorU8 color = capsule.GetColor();
final Vector capsule_axis = VectorFunctions.VSub(capsule_pos_2, capsule_pos_1);
final float d = VectorFunctions.VSize(capsule_axis);
final float half_d = d / 2.0f;
final float th_v = VectorFunctions.VAngleV(capsule_axis);
final float th_h = VectorFunctions.VAngleH(capsule_axis);
Vector center_pos = VectorFunctions.VAdd(capsule_pos_1, capsule_pos_2);
center_pos = VectorFunctions.VScale(center_pos, 0.5f);
final List<Vector> vertices = new ArrayList<>();
final List<Integer> indices = new ArrayList<>();
final int vertex_num = slice_num * (stack_num - 1) + 2;
// North pole
vertices.add(VectorFunctions.VGet(0.0f, radius + half_d, 0.0f));
// Middle
for (int i = 1; i < stack_num / 2; i++) {
final float ph = (float) Math.PI * i / stack_num;
final float y = radius * (float) Math.cos(ph) + half_d;
final float r = radius * (float) Math.sin(ph);
for (int j = 0; j < slice_num; j++) {
final float th = 2.0f * (float) Math.PI * j / slice_num;
final float x = r * (float) Math.cos(th);
final float z = r * (float) Math.sin(th);
vertices.add(VectorFunctions.VGet(x, y, z));
}
}
for (int i = stack_num / 2; i < stack_num; i++) {
final float ph = (float) Math.PI * i / stack_num;
final float y = radius * (float) Math.cos(ph) - half_d;
final float r = radius * (float) Math.sin(ph);
for (int j = 0; j < slice_num; j++) {
final float th = 2.0f * (float) Math.PI * j / slice_num;
final float x = r * (float) Math.cos(th);
final float z = r * (float) Math.sin(th);
vertices.add(VectorFunctions.VGet(x, y, z));
}
}
// South pole
vertices.add(VectorFunctions.VGet(0.0f, -radius - half_d, 0.0f));
final Matrix rot_z = MatrixFunctions.MGetRotZ(th_v - (float) Math.PI / 2.0f);
final Matrix rot_y = MatrixFunctions.MGetRotY(-th_h);
for (int i = 0; i < vertex_num; i++) {
Vector vertex = vertices.get(i);
vertex = MatrixFunctions.VTransform(vertex, rot_z);
vertex = MatrixFunctions.VTransform(vertex, rot_y);
vertex = VectorFunctions.VAdd(vertex, center_pos);
vertices.set(i, vertex);
}
// Ridgelines around the north pole
for (int i = 1; i <= slice_num; i++) {
indices.add(0);
indices.add(i);
}
// Ridgelines in the middle
int count = 1;
for (int i = 2; i < stack_num; i++) {
for (int j = 1; j < slice_num; j++) {
indices.add(count);
indices.add(count + 1);
indices.add(count);
indices.add(count + slice_num);
count++;
}
indices.add(count);
indices.add(count - slice_num + 1);
indices.add(count);
indices.add(count + slice_num);
count++;
}
// Ridgelines in the bottom
for (int i = 1; i < slice_num; i++) {
indices.add(count);
indices.add(count + 1);
indices.add(count);
indices.add(vertex_num - 1);
count++;
}
indices.add(count);
indices.add(count - slice_num + 1);
indices.add(count);
indices.add(vertex_num - 1);
final IntBuffer indices_buffer = Buffers.newDirectIntBuffer(indices.size());
final FloatBuffer pos_buffer = Buffers.newDirectFloatBuffer(vertices.size() * 3);
final FloatBuffer dif_buffer = Buffers.newDirectFloatBuffer(indices.size() * 4);
final int indices_size = indices.size();
for (int i = 0; i < indices_size; i++) {
indices_buffer.put(indices.get(i));
}
for (int i = 0; i < vertex_num; i++) {
final Vector vertex = vertices.get(i);
pos_buffer.put(vertex.GetX());
pos_buffer.put(vertex.GetY());
pos_buffer.put(vertex.GetZ());
}
final float color_r = color.GetR();
final float color_g = color.GetG();
final float color_b = color.GetB();
final float color_a = color.GetA();
for (int i = 0; i < indices_size; i++) {
dif_buffer.put(color_r);
dif_buffer.put(color_g);
dif_buffer.put(color_b);
dif_buffer.put(color_a);
}
indices_buffer.flip();
pos_buffer.flip();
dif_buffer.flip();
GLWrapper.glBindBuffer(GL.GL_ARRAY_BUFFER, pos_vbo.get(buffer_count));
GLWrapper.glBufferData(GL.GL_ARRAY_BUFFER, Buffers.SIZEOF_FLOAT * pos_buffer.capacity(),
pos_buffer, GL.GL_DYNAMIC_DRAW);
GLWrapper.glBindBuffer(GL.GL_ARRAY_BUFFER, dif_vbo.get(buffer_count));
GLWrapper.glBufferData(GL.GL_ARRAY_BUFFER, Buffers.SIZEOF_FLOAT * dif_buffer.capacity(),
dif_buffer, GL.GL_DYNAMIC_DRAW);
GLWrapper.glBindVertexArray(vao.get(buffer_count));
// Indices
GLWrapper.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, indices_vbo.get(buffer_count));
GLWrapper.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER,
Buffers.SIZEOF_INT * indices_buffer.capacity(), indices_buffer,
GL.GL_DYNAMIC_DRAW);
// Position attribute
GLWrapper.glBindBuffer(GL.GL_ARRAY_BUFFER, pos_vbo.get(buffer_count));
GLWrapper.glEnableVertexAttribArray(0);
GLWrapper.glVertexAttribPointer(0, 3, GL.GL_FLOAT, false, Buffers.SIZEOF_FLOAT * 3, 0);
// Color attribute
GLWrapper.glBindBuffer(GL.GL_ARRAY_BUFFER, dif_vbo.get(buffer_count));
GLWrapper.glEnableVertexAttribArray(1);
GLWrapper.glVertexAttribPointer(1, 4, GL.GL_FLOAT, false, Buffers.SIZEOF_FLOAT * 4, 0);
GLWrapper.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);
GLWrapper.glBindVertexArray(0);
indices_sizes_map.put(buffer_count, indices_size);
buffer_count++;
}
}
@Override
public void DeleteBuffers() {
GLWrapper.glDeleteBuffers(buffer_num, indices_vbo);
GLWrapper.glDeleteBuffers(buffer_num, pos_vbo);
GLWrapper.glDeleteBuffers(buffer_num, dif_vbo);
GLWrapper.glDeleteVertexArrays(buffer_num, vao);
buffer_num = 0;
}
public void AddCapsule(int capsule_id, Capsule capsule) {
capsules_map.put(capsule_id, capsule);
}
public int DeleteCapsule(int capsule_id) {
if (capsules_map.containsKey(capsule_id) == false) {
logger.warn("No such capsule. capsule_id={}", capsule_id);
return -1;
}
capsules_map.remove(capsule_id);
return 0;
}
public void DeleteAllCapsules() {
capsules_map.clear();
}
public Capsule GetCapsule(int capsule_id) {
return capsules_map.get(capsule_id);
}
@Override
public void Draw() {
final List<ShaderProgram> programs = this.GetPrograms();
for (final ShaderProgram program : programs) {
program.Enable();
for (int i = 0; i < buffer_num; i++) {
GLWrapper.glBindVertexArray(vao.get(i));
final int indices_size = indices_sizes_map.get(i);
GLWrapper.glEnable(GL.GL_BLEND);
GLWrapper.glDrawElements(GL.GL_LINES, indices_size, GL.GL_UNSIGNED_INT, 0);
GLWrapper.glDisable(GL.GL_BLEND);
GLWrapper.glBindVertexArray(0);
}
program.Disable();
}
}
}
|
3e00d697f2c88da8e7f88138145f52524a027a41 | 1,102 | java | Java | bootx-services/service-order/src/main/java/cn/bootx/order/param/order/OrderDetailParam.java | xxm1995/bootx-platform | 45aa11011fb142dbfad5e741d30fec6b0a1f2052 | [
"Apache-2.0"
] | null | null | null | bootx-services/service-order/src/main/java/cn/bootx/order/param/order/OrderDetailParam.java | xxm1995/bootx-platform | 45aa11011fb142dbfad5e741d30fec6b0a1f2052 | [
"Apache-2.0"
] | null | null | null | bootx-services/service-order/src/main/java/cn/bootx/order/param/order/OrderDetailParam.java | xxm1995/bootx-platform | 45aa11011fb142dbfad5e741d30fec6b0a1f2052 | [
"Apache-2.0"
] | 1 | 2022-03-19T13:44:47.000Z | 2022-03-19T13:44:47.000Z | 22.489796 | 70 | 0.720508 | 346 | package cn.bootx.order.param.order;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.media.Schema;;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
@Data
@Accessors(chain = true)
@Schema(title = "订单明细参数")
public class OrderDetailParam implements Serializable {
private static final long serialVersionUID = 2984639517325652160L;
@Schema(description= "类目id")
private Long categoryId;
@Schema(description= "活动ID")
private Long activeId;
@Schema(description= "店铺id")
private Long shopId;
@Schema(description= "商品id")
private Long goodsId;
@Schema(description= "sku id")
private Long skuId;
@Schema(description= "商品名")
private String goodsTitle;
@Schema(description= "商品价格")
private BigDecimal goodsPrice;
@Schema(description= "数量")
private int num;
@Schema(description= "附加参数 json")
private String addition;
@Schema(description= "使用的活动策略id集合")
private List<Long> activityIds;
}
|
3e00d6ae4e0255ba36f9a27de7e22890a1d88d51 | 5,404 | java | Java | google/storage/v1/google-cloud-storage-v1-java/proto-google-cloud-storage-v1-java/src/main/java/com/google/storage/v1/ChannelOrBuilder.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 7 | 2021-02-21T10:39:41.000Z | 2021-12-07T07:31:28.000Z | google/storage/v1/google-cloud-storage-v1-java/proto-google-cloud-storage-v1-java/src/main/java/com/google/storage/v1/ChannelOrBuilder.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 6 | 2021-02-02T23:46:11.000Z | 2021-11-15T01:46:02.000Z | google/storage/v1/google-cloud-storage-v1-java/proto-google-cloud-storage-v1-java/src/main/java/com/google/storage/v1/ChannelOrBuilder.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 4 | 2021-01-28T23:25:45.000Z | 2021-08-30T01:55:16.000Z | 24.017778 | 79 | 0.625093 | 347 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/storage/v1/storage_resources.proto
package com.google.storage.v1;
public interface ChannelOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.storage.v1.Channel)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* A UUID or similar unique string that identifies this channel.
* </pre>
*
* <code>string id = 1;</code>
* @return The id.
*/
java.lang.String getId();
/**
* <pre>
* A UUID or similar unique string that identifies this channel.
* </pre>
*
* <code>string id = 1;</code>
* @return The bytes for id.
*/
com.google.protobuf.ByteString
getIdBytes();
/**
* <pre>
* An opaque ID that identifies the resource being watched on this channel.
* Stable across different API versions.
* </pre>
*
* <code>string resource_id = 2;</code>
* @return The resourceId.
*/
java.lang.String getResourceId();
/**
* <pre>
* An opaque ID that identifies the resource being watched on this channel.
* Stable across different API versions.
* </pre>
*
* <code>string resource_id = 2;</code>
* @return The bytes for resourceId.
*/
com.google.protobuf.ByteString
getResourceIdBytes();
/**
* <pre>
* A version-specific identifier for the watched resource.
* </pre>
*
* <code>string resource_uri = 3;</code>
* @return The resourceUri.
*/
java.lang.String getResourceUri();
/**
* <pre>
* A version-specific identifier for the watched resource.
* </pre>
*
* <code>string resource_uri = 3;</code>
* @return The bytes for resourceUri.
*/
com.google.protobuf.ByteString
getResourceUriBytes();
/**
* <pre>
* An arbitrary string delivered to the target address with each notification
* delivered over this channel. Optional.
* </pre>
*
* <code>string token = 4;</code>
* @return The token.
*/
java.lang.String getToken();
/**
* <pre>
* An arbitrary string delivered to the target address with each notification
* delivered over this channel. Optional.
* </pre>
*
* <code>string token = 4;</code>
* @return The bytes for token.
*/
com.google.protobuf.ByteString
getTokenBytes();
/**
* <pre>
* Date and time of notification channel expiration. Optional.
* </pre>
*
* <code>.google.protobuf.Timestamp expiration = 5;</code>
* @return Whether the expiration field is set.
*/
boolean hasExpiration();
/**
* <pre>
* Date and time of notification channel expiration. Optional.
* </pre>
*
* <code>.google.protobuf.Timestamp expiration = 5;</code>
* @return The expiration.
*/
com.google.protobuf.Timestamp getExpiration();
/**
* <pre>
* Date and time of notification channel expiration. Optional.
* </pre>
*
* <code>.google.protobuf.Timestamp expiration = 5;</code>
*/
com.google.protobuf.TimestampOrBuilder getExpirationOrBuilder();
/**
* <pre>
* The type of delivery mechanism used for this channel.
* </pre>
*
* <code>string type = 6;</code>
* @return The type.
*/
java.lang.String getType();
/**
* <pre>
* The type of delivery mechanism used for this channel.
* </pre>
*
* <code>string type = 6;</code>
* @return The bytes for type.
*/
com.google.protobuf.ByteString
getTypeBytes();
/**
* <pre>
* The address where notifications are delivered for this channel.
* </pre>
*
* <code>string address = 7;</code>
* @return The address.
*/
java.lang.String getAddress();
/**
* <pre>
* The address where notifications are delivered for this channel.
* </pre>
*
* <code>string address = 7;</code>
* @return The bytes for address.
*/
com.google.protobuf.ByteString
getAddressBytes();
/**
* <pre>
* Additional parameters controlling delivery channel behavior. Optional.
* </pre>
*
* <code>map<string, string> params = 8;</code>
*/
int getParamsCount();
/**
* <pre>
* Additional parameters controlling delivery channel behavior. Optional.
* </pre>
*
* <code>map<string, string> params = 8;</code>
*/
boolean containsParams(
java.lang.String key);
/**
* Use {@link #getParamsMap()} instead.
*/
@java.lang.Deprecated
java.util.Map<java.lang.String, java.lang.String>
getParams();
/**
* <pre>
* Additional parameters controlling delivery channel behavior. Optional.
* </pre>
*
* <code>map<string, string> params = 8;</code>
*/
java.util.Map<java.lang.String, java.lang.String>
getParamsMap();
/**
* <pre>
* Additional parameters controlling delivery channel behavior. Optional.
* </pre>
*
* <code>map<string, string> params = 8;</code>
*/
java.lang.String getParamsOrDefault(
java.lang.String key,
java.lang.String defaultValue);
/**
* <pre>
* Additional parameters controlling delivery channel behavior. Optional.
* </pre>
*
* <code>map<string, string> params = 8;</code>
*/
java.lang.String getParamsOrThrow(
java.lang.String key);
/**
* <pre>
* A Boolean value to indicate whether payload is wanted. Optional.
* </pre>
*
* <code>bool payload = 9;</code>
* @return The payload.
*/
boolean getPayload();
}
|
3e00d6d0dcf8cb467c2f1833db8996ebaff34664 | 10,504 | java | Java | src/main/java/org/wso2/scim2/util/SCIMClient.java | senthalan/identity-client-scim2 | 38e5eb823ddf9d0cd0ae82a93ce7fe52d82009a1 | [
"Apache-2.0"
] | 6 | 2018-07-18T17:53:11.000Z | 2022-02-08T13:33:45.000Z | src/main/java/org/wso2/scim2/util/SCIMClient.java | senthalan/identity-client-scim2 | 38e5eb823ddf9d0cd0ae82a93ce7fe52d82009a1 | [
"Apache-2.0"
] | 2 | 2018-05-04T07:50:01.000Z | 2021-09-01T19:48:11.000Z | src/main/java/org/wso2/scim2/util/SCIMClient.java | senthalan/identity-client-scim2 | 38e5eb823ddf9d0cd0ae82a93ce7fe52d82009a1 | [
"Apache-2.0"
] | 13 | 2017-11-24T11:28:03.000Z | 2022-01-28T13:08:26.000Z | 37.784173 | 116 | 0.644516 | 348 | /*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.scim2.util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.wso2.charon3.core.encoder.JSONDecoder;
import org.wso2.charon3.core.encoder.JSONEncoder;
import org.wso2.charon3.core.exceptions.AbstractCharonException;
import org.wso2.charon3.core.exceptions.BadRequestException;
import org.wso2.charon3.core.exceptions.CharonException;
import org.wso2.charon3.core.exceptions.InternalErrorException;
import org.wso2.charon3.core.objects.AbstractSCIMObject;
import org.wso2.charon3.core.objects.Group;
import org.wso2.charon3.core.objects.SCIMObject;
import org.wso2.charon3.core.objects.User;
import org.wso2.charon3.core.objects.bulk.BulkData;
import org.wso2.charon3.core.objects.bulk.BulkResponseData;
import org.wso2.charon3.core.protocol.ResponseCodeConstants;
import org.wso2.charon3.core.schema.ResourceTypeSchema;
import org.wso2.charon3.core.schema.SCIMConstants;
import org.wso2.charon3.core.schema.SCIMSchemaDefinitions;
import java.util.List;
public class SCIMClient {
/**
* JSON encoder, decoder
*/
private JSONEncoder jsonEncoder;
private JSONDecoder jsonDecoder;
public SCIMClient() {
jsonEncoder = new JSONEncoder();
jsonDecoder = new JSONDecoder();
}
/**
* Return a SCIMUser object as defined in SCIM schema
*
* @return
*/
public User createUser() {
return new User();
}
public Group createGroup() {
return new Group();
}
public BulkData createBulkRequestData() {
return new BulkData();
}
/**
* This is to decode SCIM Response received for a SCIM List/Filter requests.
*
* @param scimResponse
* @param format
* @param containedResourceType
* @return
*/
public List<SCIMObject> decodeSCIMResponseWithListedResource(String scimResponse, String format,
int containedResourceType)
throws CharonException, BadRequestException {
if ((format.equals(SCIMConstants.JSON)) && (jsonDecoder != null)) {
SCIMDecoder scimDecoder = new SCIMDecoder();
switch (containedResourceType) {
case 1:
return scimDecoder.decodeListedResource(scimResponse,
SCIMSchemaDefinitions.SCIM_USER_SCHEMA, new User());
case 2:
return scimDecoder.decodeListedResource(scimResponse,
SCIMSchemaDefinitions.SCIM_GROUP_SCHEMA, new Group());
default:
throw new CharonException("Resource type didn't match any existing types.");
}
} else {
throw new CharonException("Encoder in the given format is not properly initialized.");
}
}
/**
* Decode the SCIMResponse, given the format and the resource type.
* Here we assume the resource type is of an existing SCIMObject type.
* Int type is given as parameter rather than AbstractSCIMObject - so that API user can
* select out of existing type without worrying about which extended type to pass.
*
* @param scimResponse
* @param format
* @return
*/
public SCIMObject decodeSCIMResponse(String scimResponse, String format, int resourceType)
throws AbstractCharonException {
if ((format.equals(SCIMConstants.JSON)) && (jsonDecoder != null)) {
return decodeSCIMResponse(scimResponse, jsonDecoder, resourceType);
} else {
throw new CharonException("Encoder in the given format is not properly initialized.");
}
}
private SCIMObject decodeSCIMResponse(String scimResponse, JSONDecoder decoder, int resourceType)
throws AbstractCharonException {
switch (resourceType) {
case 1:
User userObject = (User) decoder.decodeResource(scimResponse,
SCIMSchemaDefinitions.SCIM_USER_SCHEMA, new User());
ClientSideValidator.validateRetrievedSCIMObject(userObject, SCIMSchemaDefinitions.SCIM_USER_SCHEMA);
return userObject;
case 2:
Group groupObject = (Group) decoder.decodeResource(scimResponse,
SCIMSchemaDefinitions.SCIM_GROUP_SCHEMA, new Group());
ClientSideValidator.validateRetrievedSCIMObject(groupObject,
SCIMSchemaDefinitions.SCIM_GROUP_SCHEMA);
return groupObject;
default:
throw new CharonException("Resource type didn't match any existing types.");
}
}
/**
* Decode the SCIMResponse which contains a custom SCIMObject which is based on an extended
* Schema.
*
* @param scimResponse
* @param format
* @param resourceSchema
* @return
*/
public SCIMObject decodeSCIMResponse(String scimResponse, String format, ResourceTypeSchema resourceSchema,
AbstractSCIMObject scimObject)
throws CharonException, BadRequestException, InternalErrorException {
if ((format.equals(SCIMConstants.JSON)) && (jsonDecoder != null)) {
return jsonDecoder.decodeResource(scimResponse, resourceSchema, scimObject);
} else {
throw new CharonException("Encoder in the given format is not properly initialized..");
}
}
/**
* Once the response is identified as containing exception, decode the relevant e
*
* @param scimResponse
* @param format
* @return
* @throws CharonException
*/
public AbstractCharonException decodeSCIMException(String scimResponse, String format)
throws CharonException {
if ((format.equals(SCIMConstants.JSON)) && (jsonDecoder != null)) {
return this.decodeException(scimResponse);
} else {
throw new CharonException("Encoder in the given format is not properly initialized.");
}
}
/**
* Decode the string sent in the SCIM response payload, which is an exception.
* JSON encoded exception is usually like:
* {
* "Errors":[
* {
* "description":"Resource 2819c223-7f76-453a-919d-413861904646 not found",
* "code":"404"
* }
* ]
* }
*
* @param scimExceptionString
* @return
*/
public AbstractCharonException decodeException(String scimExceptionString)
throws CharonException {
try {
JSONObject decodedJsonObj = new JSONObject(new JSONTokener(scimExceptionString));
Object jsonError = decodedJsonObj.opt(ResponseCodeConstants.ERRORS);
//according to the SCIM spec, Error details returned as multivalued attribute.
//so we assume the same
if (jsonError instanceof JSONArray) {
//according to the spec, ERRORS are composed as complex attributes with
//"description" & "code" as the sub attributes. Since we return only one exception,
//only the first error is read.
JSONObject errorObject = (JSONObject) ((JSONArray) jsonError).get(0);
//decode the details of the error
String errorCode = (String) errorObject.opt("code");
String errorDescription = (String) errorObject.opt("description");
return new AbstractCharonException(errorDescription);
}
} catch (JSONException e) {
throw new CharonException("Error in building exception from the JSON representation");
}
return null;
}
/**
* Encode the SCIM object, in the given format.
*
* @param scimObject
* @param format
* @return
* @throws CharonException
*/
public String encodeSCIMObject(AbstractSCIMObject scimObject, String format) throws CharonException {
if ((format.equals(SCIMConstants.JSON)) && (jsonEncoder != null)) {
return jsonEncoder.encodeSCIMObject(scimObject);
} else {
throw new CharonException("Encoder in the given format is not properly initialized.");
}
}
/**
* Encode given BulkData object and return bulk data string
*
* @param bulkData
* @param format
* @return
*/
public String encodeSCIMObject(BulkResponseData bulkData, String format) throws AbstractCharonException {
if ((format.equals(SCIMConstants.JSON)) && (jsonEncoder != null)) {
return jsonEncoder.encodeBulkResponseData(bulkData);
} else {
throw new CharonException("Encoder in the given format is not properly initialized.");
}
}
/**
* Identify whether the response includes a success response or failure response according to the
* response status code.
*
* @param statusCode
* @return
*/
public boolean evaluateResponseStatus(int statusCode) {
switch (statusCode) {
case ResponseCodeConstants.CODE_OK:
return true;
case ResponseCodeConstants.CODE_CREATED:
return true;
case ResponseCodeConstants.CODE_NO_CONTENT:
return true;
case ResponseCodeConstants.CODE_UNAUTHORIZED:
return false;
case ResponseCodeConstants.CODE_FORMAT_NOT_SUPPORTED:
return false;
case ResponseCodeConstants.CODE_INTERNAL_ERROR:
return false;
case ResponseCodeConstants.CODE_RESOURCE_NOT_FOUND:
return false;
case ResponseCodeConstants.CODE_BAD_REQUEST:
return false;
default:
return false;
}
}
}
|
3e00d73be54258a1486f09509d79d4a8b2488240 | 1,396 | java | Java | src/main/java/powerapi/plugin/PasswordHelper.java | melonlee/powerapi | 57bb4c5d890230615a491046d7d32de20f842071 | [
"Apache-2.0"
] | null | null | null | src/main/java/powerapi/plugin/PasswordHelper.java | melonlee/powerapi | 57bb4c5d890230615a491046d7d32de20f842071 | [
"Apache-2.0"
] | null | null | null | src/main/java/powerapi/plugin/PasswordHelper.java | melonlee/powerapi | 57bb4c5d890230615a491046d7d32de20f842071 | [
"Apache-2.0"
] | null | null | null | 26.846154 | 92 | 0.696275 | 349 | package powerapi.plugin;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;
import powerapi.entity.User;
/**
* 用户密码加密辅助类
* <p/>
* Created by Melon on 17/2/28.
*/
@Service
public class PasswordHelper {
private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
private String algorithmName = "md5";
private int hashIterations = 2;
public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
this.randomNumberGenerator = randomNumberGenerator;
}
public void setAlgorithmName(String algorithmName) {
this.algorithmName = algorithmName;
}
public void setHashIterations(int hashIterations) {
this.hashIterations = hashIterations;
}
/**
* 密码加密 md5(name+salt)
*
* @param user
*/
public void encryptPassword(User user) {
user.setSalt(randomNumberGenerator.nextBytes().toHex());
String newPassword = new SimpleHash(
algorithmName,
user.getPasswd(),
ByteSource.Util.bytes(user.getCredentialsSalt()),
hashIterations).toHex();
user.setPasswd(newPassword);
}
}
|
3e00d7f7eafdd49702a0067b4668cda721c8771b | 1,158 | java | Java | src/main/java/legends/model/ScheduleFeature.java | danlangford/LegendsBrowser | 152b3c860d752f8121c3560a789ba6ad45e991be | [
"MIT"
] | 71 | 2016-01-07T14:29:47.000Z | 2022-02-22T18:48:35.000Z | src/main/java/legends/model/ScheduleFeature.java | danlangford/LegendsBrowser | 152b3c860d752f8121c3560a789ba6ad45e991be | [
"MIT"
] | 47 | 2016-01-14T17:50:16.000Z | 2022-02-04T05:03:41.000Z | src/main/java/legends/model/ScheduleFeature.java | danlangford/LegendsBrowser | 152b3c860d752f8121c3560a789ba6ad45e991be | [
"MIT"
] | 23 | 2016-03-02T09:38:16.000Z | 2022-01-29T17:01:11.000Z | 22.705882 | 100 | 0.67962 | 350 | package legends.model;
import legends.xml.annotation.Xml;
public class ScheduleFeature {
@Xml("type")
private String type = "";
@Xml("reference")
private int reference = -1;
public String getType() {
return type.replace("_", " ");
}
public void setType(String type) {
this.type = type;
}
public int getReference() {
return reference;
}
public void setReference(int reference) {
this.reference = reference;
}
public String getText() {
switch (getType()) {
case "poetry recital":
return "a recital of " + World.getPoeticForm(reference).getLink();
case "musical performance":
return "a performance of " + World.getMusicalForm(reference).getLink();
case "dance performance":
return "a performance of " + World.getDanceForm(reference).getLink();
case "storytelling":
if (reference != -1)
return "a telling of the story of " + World.getHistoricalEvent(reference).getShortDescription();
else
return "a story recital";
case "images":
if (reference == -1)
return "images";
else
return "images of " + World.getHistoricalFigure(reference).getLink();
default:
return getType();
}
}
}
|
3e00d924a63e2f21ccfdc5835d3fc2413bb473d2 | 2,701 | java | Java | src/main/java/by/bsuir/domain/ProfitabilityAnalysis.java | fobo66/BSUIRCryptoProfitabilityCoursework | c2bcd66917b2ee95dcbaeb83f23b6d66651c92c0 | [
"MIT"
] | null | null | null | src/main/java/by/bsuir/domain/ProfitabilityAnalysis.java | fobo66/BSUIRCryptoProfitabilityCoursework | c2bcd66917b2ee95dcbaeb83f23b6d66651c92c0 | [
"MIT"
] | 3 | 2020-05-04T09:36:33.000Z | 2020-05-04T10:09:24.000Z | src/main/java/by/bsuir/domain/ProfitabilityAnalysis.java | fobo66/BSUIRCryptoProfitabilityCoursework | c2bcd66917b2ee95dcbaeb83f23b6d66651c92c0 | [
"MIT"
] | null | null | null | 23.486957 | 109 | 0.626064 | 351 | package by.bsuir.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import javax.validation.constraints.*;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.io.Serializable;
import java.util.Objects;
import java.time.LocalDate;
/**
* A ProfitabilityAnalysis.
*/
@Entity
@Table(name = "profitability_analysis")
@org.springframework.data.elasticsearch.annotations.Document(indexName = "profitabilityanalysis")
public class ProfitabilityAnalysis implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@Column(name = "date", nullable = false)
private LocalDate date;
@NotNull
@Column(name = "result", nullable = false)
private Boolean result;
@ManyToOne(optional = false)
@NotNull
@JsonIgnoreProperties("profitabilityAnalyses")
private User user;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public ProfitabilityAnalysis date(LocalDate date) {
this.date = date;
return this;
}
public Boolean isResult() {
return result;
}
public ProfitabilityAnalysis result(Boolean result) {
this.result = result;
return this;
}
public void setResult(Boolean result) {
this.result = result;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public ProfitabilityAnalysis user(User user) {
this.user = user;
return this;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ProfitabilityAnalysis)) {
return false;
}
return id != null && id.equals(((ProfitabilityAnalysis) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "ProfitabilityAnalysis{" +
"id=" + getId() +
", date='" + getDate() + "'" +
", result='" + isResult() + "'" +
"}";
}
}
|
3e00d9290732a0e72e429cdcabb4024eef2aa231 | 73 | java | Java | src/com/masanta/ratan/leetcode/study/plan/programming/skills/day/one/package-info.java | RatanMasanta/DataStructure-StudyPlan-Leetcode | e309a4591e2792b8eea2ade08b2e9673a5053b72 | [
"MIT"
] | null | null | null | src/com/masanta/ratan/leetcode/study/plan/programming/skills/day/one/package-info.java | RatanMasanta/DataStructure-StudyPlan-Leetcode | e309a4591e2792b8eea2ade08b2e9673a5053b72 | [
"MIT"
] | null | null | null | src/com/masanta/ratan/leetcode/study/plan/programming/skills/day/one/package-info.java | RatanMasanta/DataStructure-StudyPlan-Leetcode | e309a4591e2792b8eea2ade08b2e9673a5053b72 | [
"MIT"
] | null | null | null | 73 | 73 | 0.849315 | 352 | package com.masanta.ratan.leetcode.study.plan.programming.skills.day.one; |
3e00d9b996cf760ed493f6f72f82dedde8d3de46 | 1,528 | java | Java | AndroidTaco/src/dk/itu/smdp/model/answer/Answer.java | tonybeltramelli/Taco-DSL | 64ff0e56ec9781f37f3dd981e8a281c16ba2dfd2 | [
"MIT"
] | 1 | 2021-07-11T04:42:44.000Z | 2021-07-11T04:42:44.000Z | AndroidTaco/src/dk/itu/smdp/model/answer/Answer.java | tonybeltramelli/Taco-DSL | 64ff0e56ec9781f37f3dd981e8a281c16ba2dfd2 | [
"MIT"
] | null | null | null | AndroidTaco/src/dk/itu/smdp/model/answer/Answer.java | tonybeltramelli/Taco-DSL | 64ff0e56ec9781f37f3dd981e8a281c16ba2dfd2 | [
"MIT"
] | 1 | 2015-05-28T09:28:38.000Z | 2015-05-28T09:28:38.000Z | 21.828571 | 65 | 0.700262 | 353 | package dk.itu.smdp.model.answer;
import dk.itu.smdp.Answerable;
import dk.itu.smdp.Viewable;
import dk.itu.smdp.model.question.Question;
import java.util.ArrayList;
/**
* Created by centos on 4/13/14.
*/
public abstract class Answer implements Viewable
{
public static final String BINARY = "binary";
public static final String USER_INPUT = "user_input";
public static final String OPEN_FIELD = "open_field";
public static final String RANKING = "ranking";
public static final String RATING = "rating";
protected String _description;
public Answer(String description)
{
this._description = description;
}
public String getDescription()
{
return _description;
}
protected ArrayList<Question> _subQuestions;
protected boolean isExpanded;
public abstract String getUserAnswer();
//defaule for every answer is not to have subs.
//only the binary answer will override
public boolean hasSubQuestions(){
return false;
}
public void addSubQuestion(Question q){
if( hasSubQuestions() )
_subQuestions.add(q);
}
public ArrayList<Question> getSubQuestions(){
if(hasSubQuestions())
return _subQuestions;
return new ArrayList<Question>();
}
public abstract void clear();
public abstract void setUpListener(final Answerable answerable);
public boolean isExpanded() {
return isExpanded;
}
public void setExpanded(boolean isExpanded) {
this.isExpanded = isExpanded;
}
}
|
3e00da65361d8f545135d00d1e6428dae916ed82 | 321 | java | Java | java_basics/aula25/Carro.java | SuhMoraes/loianegroner-javabasico | 7910dc9c1c938604816aa717851f3ae4596e1315 | [
"MIT"
] | null | null | null | java_basics/aula25/Carro.java | SuhMoraes/loianegroner-javabasico | 7910dc9c1c938604816aa717851f3ae4596e1315 | [
"MIT"
] | null | null | null | java_basics/aula25/Carro.java | SuhMoraes/loianegroner-javabasico | 7910dc9c1c938604816aa717851f3ae4596e1315 | [
"MIT"
] | null | null | null | 22.928571 | 114 | 0.676012 | 354 | package java_basics.aula25;
public class Carro {
String marca;
String modelo;
int numPassageiros;
double capCombustivel;
double consumoCombustível;
void exibirAutonomia(){
System.out.println("A autonomia do carro "+ modelo +" é: " + capCombustivel * consumoCombustível + " km");
}
}
|
3e00da6cd2e8b0e20e545801dc8bf3d107a52ec6 | 31,476 | java | Java | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/jar/JarVerifier.java | gaybro8777/j2objc | 9234ca9bed5d16a2f9914d55001ce1ec2e84dc9d | [
"Apache-2.0"
] | 4,901 | 2015-01-02T09:29:18.000Z | 2022-03-29T06:51:04.000Z | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/jar/JarVerifier.java | 1Crazymoney/j2objc | 444f387445b3f22fd807b7c72eca484ea8823c8e | [
"Apache-2.0"
] | 853 | 2015-01-03T08:13:19.000Z | 2022-03-22T18:51:24.000Z | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/jar/JarVerifier.java | 1Crazymoney/j2objc | 444f387445b3f22fd807b7c72eca484ea8823c8e | [
"Apache-2.0"
] | 964 | 2015-01-08T08:52:00.000Z | 2022-03-23T16:36:47.000Z | 34.513158 | 105 | 0.533454 | 355 | /*
* Copyright (C) 2014 The Android Open Source Project
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.jar;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.zip.ZipEntry;
/* J2ObjC removed.
import sun.misc.JarIndex;
*/
import sun.security.util.ManifestDigester;
import sun.security.util.ManifestEntryVerifier;
import sun.security.util.SignatureFileVerifier;
import sun.security.util.Debug;
/**
*
* @author Roland Schemers
*/
class JarVerifier {
/* J2ObjC added: copied from sun.misc.JarIndex */
public static final String INDEX_NAME = "META-INF/INDEX.LIST";
/* Are we debugging ? */
static final Debug debug = Debug.getInstance("jar");
/* a table mapping names to code signers, for jar entries that have
had their actual hashes verified */
private Hashtable<String, CodeSigner[]> verifiedSigners;
/* a table mapping names to code signers, for jar entries that have
passed the .SF/.DSA/.EC -> MANIFEST check */
private Hashtable<String, CodeSigner[]> sigFileSigners;
/* a hash table to hold .SF bytes */
private Hashtable<String, byte[]> sigFileData;
/** "queue" of pending PKCS7 blocks that we couldn't parse
* until we parsed the .SF file */
private ArrayList<SignatureFileVerifier> pendingBlocks;
/* cache of CodeSigner objects */
private ArrayList<CodeSigner[]> signerCache;
/* Are we parsing a block? */
private boolean parsingBlockOrSF = false;
/* Are we done parsing META-INF entries? */
private boolean parsingMeta = true;
/* Are there are files to verify? */
private boolean anyToVerify = true;
/* The output stream to use when keeping track of files we are interested
in */
private ByteArrayOutputStream baos;
/** The ManifestDigester object */
private volatile ManifestDigester manDig;
/** the bytes for the manDig object */
byte manifestRawBytes[] = null;
/** controls eager signature validation */
boolean eagerValidation;
/** makes code source singleton instances unique to us */
private Object csdomain = new Object();
/** collect -DIGEST-MANIFEST values for blacklist */
private List<Object> manifestDigests;
public JarVerifier(byte rawBytes[]) {
manifestRawBytes = rawBytes;
sigFileSigners = new Hashtable<>();
verifiedSigners = new Hashtable<>();
sigFileData = new Hashtable<>(11);
pendingBlocks = new ArrayList<>();
baos = new ByteArrayOutputStream();
manifestDigests = new ArrayList<>();
}
/**
* This method scans to see which entry we're parsing and
* keeps various state information depending on what type of
* file is being parsed.
*/
public void beginEntry(JarEntry je, ManifestEntryVerifier mev)
throws IOException
{
if (je == null)
return;
if (debug != null) {
debug.println("beginEntry "+je.getName());
}
String name = je.getName();
/*
* Assumptions:
* 1. The manifest should be the first entry in the META-INF directory.
* 2. The .SF/.DSA/.EC files follow the manifest, before any normal entries
* 3. Any of the following will throw a SecurityException:
* a. digest mismatch between a manifest section and
* the SF section.
* b. digest mismatch between the actual jar entry and the manifest
*/
if (parsingMeta) {
String uname = name.toUpperCase(Locale.ENGLISH);
if ((uname.startsWith("META-INF/") ||
uname.startsWith("/META-INF/"))) {
if (je.isDirectory()) {
mev.setEntry(null, je);
return;
}
/* J2ObjC modified: platform-specific implementation to avoid importing JarIndex */
if (uname.equals(JarFile.MANIFEST_NAME) ||
uname.equals(INDEX_NAME)) {
return;
}
if (SignatureFileVerifier.isBlockOrSF(uname)) {
/* We parse only DSA, RSA or EC PKCS7 blocks. */
parsingBlockOrSF = true;
baos.reset();
mev.setEntry(null, je);
return;
}
// If a META-INF entry is not MF or block or SF, they should
// be normal entries. According to 2 above, no more block or
// SF will appear. Let's doneWithMeta.
}
}
if (parsingMeta) {
doneWithMeta();
}
if (je.isDirectory()) {
mev.setEntry(null, je);
return;
}
// be liberal in what you accept. If the name starts with ./, remove
// it as we internally canonicalize it with out the ./.
if (name.startsWith("./"))
name = name.substring(2);
// be liberal in what you accept. If the name starts with /, remove
// it as we internally canonicalize it with out the /.
if (name.startsWith("/"))
name = name.substring(1);
// only set the jev object for entries that have a signature
// (either verified or not)
if (sigFileSigners.get(name) != null ||
verifiedSigners.get(name) != null) {
mev.setEntry(name, je);
return;
}
// don't compute the digest for this entry
mev.setEntry(null, je);
return;
}
/**
* update a single byte.
*/
public void update(int b, ManifestEntryVerifier mev)
throws IOException
{
if (b != -1) {
if (parsingBlockOrSF) {
baos.write(b);
} else {
mev.update((byte)b);
}
} else {
processEntry(mev);
}
}
/**
* update an array of bytes.
*/
public void update(int n, byte[] b, int off, int len,
ManifestEntryVerifier mev)
throws IOException
{
if (n != -1) {
if (parsingBlockOrSF) {
baos.write(b, off, n);
} else {
mev.update(b, off, n);
}
} else {
processEntry(mev);
}
}
/**
* called when we reach the end of entry in one of the read() methods.
*/
private void processEntry(ManifestEntryVerifier mev)
throws IOException
{
if (!parsingBlockOrSF) {
JarEntry je = mev.getEntry();
if ((je != null) && (je.signers == null)) {
je.signers = mev.verify(verifiedSigners, sigFileSigners);
je.certs = mapSignersToCertArray(je.signers);
}
} else {
try {
parsingBlockOrSF = false;
if (debug != null) {
debug.println("processEntry: processing block");
}
String uname = mev.getEntry().getName()
.toUpperCase(Locale.ENGLISH);
if (uname.endsWith(".SF")) {
String key = uname.substring(0, uname.length()-3);
byte bytes[] = baos.toByteArray();
// add to sigFileData in case future blocks need it
sigFileData.put(key, bytes);
// check pending blocks, we can now process
// anyone waiting for this .SF file
Iterator<SignatureFileVerifier> it = pendingBlocks.iterator();
while (it.hasNext()) {
SignatureFileVerifier sfv = it.next();
if (sfv.needSignatureFile(key)) {
if (debug != null) {
debug.println(
"processEntry: processing pending block");
}
sfv.setSignatureFile(bytes);
sfv.process(sigFileSigners, manifestDigests);
}
}
return;
}
// now we are parsing a signature block file
String key = uname.substring(0, uname.lastIndexOf("."));
if (signerCache == null)
signerCache = new ArrayList<>();
if (manDig == null) {
synchronized(manifestRawBytes) {
if (manDig == null) {
manDig = new ManifestDigester(manifestRawBytes);
manifestRawBytes = null;
}
}
}
SignatureFileVerifier sfv =
new SignatureFileVerifier(signerCache,
manDig, uname, baos.toByteArray());
if (sfv.needSignatureFileBytes()) {
// see if we have already parsed an external .SF file
byte[] bytes = sigFileData.get(key);
if (bytes == null) {
// put this block on queue for later processing
// since we don't have the .SF bytes yet
// (uname, block);
if (debug != null) {
debug.println("adding pending block");
}
pendingBlocks.add(sfv);
return;
} else {
sfv.setSignatureFile(bytes);
}
}
sfv.process(sigFileSigners, manifestDigests);
} catch (IOException ioe) {
// e.g. sun.security.pkcs.ParsingException
if (debug != null) debug.println("processEntry caught: "+ioe);
// ignore and treat as unsigned
} catch (SignatureException se) {
if (debug != null) debug.println("processEntry caught: "+se);
// ignore and treat as unsigned
} catch (NoSuchAlgorithmException nsae) {
if (debug != null) debug.println("processEntry caught: "+nsae);
// ignore and treat as unsigned
} catch (CertificateException ce) {
if (debug != null) debug.println("processEntry caught: "+ce);
// ignore and treat as unsigned
}
}
}
// Android-changed: @deprecated tag needs a description. http://b/110781661
/**
* Return an array of java.security.cert.Certificate objects for
* the given file in the jar.
* @deprecated Deprecated.
*/
@Deprecated
public java.security.cert.Certificate[] getCerts(String name)
{
return mapSignersToCertArray(getCodeSigners(name));
}
public java.security.cert.Certificate[] getCerts(JarFile jar, JarEntry entry)
{
return mapSignersToCertArray(getCodeSigners(jar, entry));
}
/**
* return an array of CodeSigner objects for
* the given file in the jar. this array is not cloned.
*
*/
public CodeSigner[] getCodeSigners(String name)
{
return verifiedSigners.get(name);
}
public CodeSigner[] getCodeSigners(JarFile jar, JarEntry entry)
{
String name = entry.getName();
if (eagerValidation && sigFileSigners.get(name) != null) {
/*
* Force a read of the entry data to generate the
* verification hash.
*/
try {
InputStream s = jar.getInputStream(entry);
byte[] buffer = new byte[1024];
int n = buffer.length;
while (n != -1) {
n = s.read(buffer, 0, buffer.length);
}
s.close();
} catch (IOException e) {
}
}
return getCodeSigners(name);
}
/*
* Convert an array of signers into an array of concatenated certificate
* arrays.
*/
private static java.security.cert.Certificate[] mapSignersToCertArray(
CodeSigner[] signers) {
if (signers != null) {
ArrayList<java.security.cert.Certificate> certChains = new ArrayList<>();
for (int i = 0; i < signers.length; i++) {
certChains.addAll(
signers[i].getSignerCertPath().getCertificates());
}
// Convert into a Certificate[]
return certChains.toArray(
new java.security.cert.Certificate[certChains.size()]);
}
return null;
}
/**
* returns true if there no files to verify.
* should only be called after all the META-INF entries
* have been processed.
*/
boolean nothingToVerify()
{
return (anyToVerify == false);
}
/**
* called to let us know we have processed all the
* META-INF entries, and if we re-read one of them, don't
* re-process it. Also gets rid of any data structures
* we needed when parsing META-INF entries.
*/
void doneWithMeta()
{
parsingMeta = false;
anyToVerify = !sigFileSigners.isEmpty();
baos = null;
sigFileData = null;
pendingBlocks = null;
signerCache = null;
manDig = null;
// MANIFEST.MF is always treated as signed and verified,
// move its signers from sigFileSigners to verifiedSigners.
if (sigFileSigners.containsKey(JarFile.MANIFEST_NAME)) {
CodeSigner[] codeSigners = sigFileSigners.remove(JarFile.MANIFEST_NAME);
verifiedSigners.put(JarFile.MANIFEST_NAME, codeSigners);
}
}
static class VerifierStream extends java.io.InputStream {
private InputStream is;
private JarVerifier jv;
private ManifestEntryVerifier mev;
private long numLeft;
VerifierStream(Manifest man,
JarEntry je,
InputStream is,
JarVerifier jv) throws IOException
{
// BEGIN Android-added: Throw IOE, not NPE, if stream is closed. http://b/110695212
// To know that null signals that the stream has been closed, we disallow
// it in the constructor. There's no need for anyone to pass null into this
// constructor, anyway.
if (is == null) {
throw new NullPointerException("is == null");
}
// END Android-added: Throw IOE, not NPE, if stream is closed. http://b/110695212
this.is = is;
this.jv = jv;
this.mev = new ManifestEntryVerifier(man);
this.jv.beginEntry(je, mev);
this.numLeft = je.getSize();
if (this.numLeft == 0)
this.jv.update(-1, this.mev);
}
public int read() throws IOException
{
// BEGIN Android-added: Throw IOE, not NPE, if stream is closed. http://b/110695212
if (is == null) {
throw new IOException("stream closed");
}
// END Android-added: Throw IOE, not NPE, if stream is closed. http://b/110695212
if (numLeft > 0) {
int b = is.read();
jv.update(b, mev);
numLeft--;
if (numLeft == 0)
jv.update(-1, mev);
return b;
} else {
return -1;
}
}
public int read(byte b[], int off, int len) throws IOException {
// BEGIN Android-added: Throw IOE, not NPE, if stream is closed. http://b/110695212
if (is == null) {
throw new IOException("stream closed");
}
// END Android-added: Throw IOE, not NPE, if stream is closed. http://b/110695212
if ((numLeft > 0) && (numLeft < len)) {
len = (int)numLeft;
}
if (numLeft > 0) {
int n = is.read(b, off, len);
jv.update(n, b, off, len, mev);
numLeft -= n;
if (numLeft == 0)
jv.update(-1, b, off, len, mev);
return n;
} else {
return -1;
}
}
public void close()
throws IOException
{
if (is != null)
is.close();
is = null;
mev = null;
jv = null;
}
public int available() throws IOException {
// BEGIN Android-added: Throw IOE, not NPE, if stream is closed. http://b/110695212
if (is == null) {
throw new IOException("stream closed");
}
// END Android-added: Throw IOE, not NPE, if stream is closed. http://b/110695212
return is.available();
}
}
// Extended JavaUtilJarAccess CodeSource API Support
private Map<URL, Map<CodeSigner[], CodeSource>> urlToCodeSourceMap = new HashMap<>();
private Map<CodeSigner[], CodeSource> signerToCodeSource = new HashMap<>();
private URL lastURL;
private Map<CodeSigner[], CodeSource> lastURLMap;
/*
* Create a unique mapping from codeSigner cache entries to CodeSource.
* In theory, multiple URLs origins could map to a single locally cached
* and shared JAR file although in practice there will be a single URL in use.
*/
private synchronized CodeSource mapSignersToCodeSource(URL url, CodeSigner[] signers) {
Map<CodeSigner[], CodeSource> map;
if (url == lastURL) {
map = lastURLMap;
} else {
map = urlToCodeSourceMap.get(url);
if (map == null) {
map = new HashMap<>();
urlToCodeSourceMap.put(url, map);
}
lastURLMap = map;
lastURL = url;
}
CodeSource cs = map.get(signers);
if (cs == null) {
cs = new VerifierCodeSource(csdomain, url, signers);
signerToCodeSource.put(signers, cs);
}
return cs;
}
private CodeSource[] mapSignersToCodeSources(URL url, List<CodeSigner[]> signers, boolean unsigned) {
List<CodeSource> sources = new ArrayList<>();
for (int i = 0; i < signers.size(); i++) {
sources.add(mapSignersToCodeSource(url, signers.get(i)));
}
if (unsigned) {
sources.add(mapSignersToCodeSource(url, null));
}
return sources.toArray(new CodeSource[sources.size()]);
}
private CodeSigner[] emptySigner = new CodeSigner[0];
/*
* Match CodeSource to a CodeSigner[] in the signer cache.
*/
private CodeSigner[] findMatchingSigners(CodeSource cs) {
if (cs instanceof VerifierCodeSource) {
VerifierCodeSource vcs = (VerifierCodeSource) cs;
if (vcs.isSameDomain(csdomain)) {
return ((VerifierCodeSource) cs).getPrivateSigners();
}
}
/*
* In practice signers should always be optimized above
* but this handles a CodeSource of any type, just in case.
*/
CodeSource[] sources = mapSignersToCodeSources(cs.getLocation(), getJarCodeSigners(), true);
List<CodeSource> sourceList = new ArrayList<>();
for (int i = 0; i < sources.length; i++) {
sourceList.add(sources[i]);
}
int j = sourceList.indexOf(cs);
if (j != -1) {
CodeSigner[] match;
match = ((VerifierCodeSource) sourceList.get(j)).getPrivateSigners();
if (match == null) {
match = emptySigner;
}
return match;
}
return null;
}
/*
* Instances of this class hold uncopied references to internal
* signing data that can be compared by object reference identity.
*/
private static class VerifierCodeSource extends CodeSource {
private static final long serialVersionUID = -9047366145967768825L;
URL vlocation;
CodeSigner[] vsigners;
java.security.cert.Certificate[] vcerts;
Object csdomain;
VerifierCodeSource(Object csdomain, URL location, CodeSigner[] signers) {
super(location, signers);
this.csdomain = csdomain;
vlocation = location;
vsigners = signers; // from signerCache
}
VerifierCodeSource(Object csdomain, URL location, java.security.cert.Certificate[] certs) {
super(location, certs);
this.csdomain = csdomain;
vlocation = location;
vcerts = certs; // from signerCache
}
/*
* All VerifierCodeSource instances are constructed based on
* singleton signerCache or signerCacheCert entries for each unique signer.
* No CodeSigner<->Certificate[] conversion is required.
* We use these assumptions to optimize equality comparisons.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof VerifierCodeSource) {
VerifierCodeSource that = (VerifierCodeSource) obj;
/*
* Only compare against other per-signer singletons constructed
* on behalf of the same JarFile instance. Otherwise, compare
* things the slower way.
*/
if (isSameDomain(that.csdomain)) {
if (that.vsigners != this.vsigners
|| that.vcerts != this.vcerts) {
return false;
}
if (that.vlocation != null) {
return that.vlocation.equals(this.vlocation);
} else if (this.vlocation != null) {
return this.vlocation.equals(that.vlocation);
} else { // both null
return true;
}
}
}
return super.equals(obj);
}
boolean isSameDomain(Object csdomain) {
return this.csdomain == csdomain;
}
private CodeSigner[] getPrivateSigners() {
return vsigners;
}
private java.security.cert.Certificate[] getPrivateCertificates() {
return vcerts;
}
}
private Map<String, CodeSigner[]> signerMap;
private synchronized Map<String, CodeSigner[]> signerMap() {
if (signerMap == null) {
/*
* Snapshot signer state so it doesn't change on us. We care
* only about the asserted signatures. Verification of
* signature validity happens via the JarEntry apis.
*/
signerMap = new HashMap<>(verifiedSigners.size() + sigFileSigners.size());
signerMap.putAll(verifiedSigners);
signerMap.putAll(sigFileSigners);
}
return signerMap;
}
public synchronized Enumeration<String> entryNames(JarFile jar, final CodeSource[] cs) {
final Map<String, CodeSigner[]> map = signerMap();
final Iterator<Map.Entry<String, CodeSigner[]>> itor = map.entrySet().iterator();
boolean matchUnsigned = false;
/*
* Grab a single copy of the CodeSigner arrays. Check
* to see if we can optimize CodeSigner equality test.
*/
List<CodeSigner[]> req = new ArrayList<>(cs.length);
for (int i = 0; i < cs.length; i++) {
CodeSigner[] match = findMatchingSigners(cs[i]);
if (match != null) {
if (match.length > 0) {
req.add(match);
} else {
matchUnsigned = true;
}
} else {
matchUnsigned = true;
}
}
final List<CodeSigner[]> signersReq = req;
final Enumeration<String> enum2 = (matchUnsigned) ? unsignedEntryNames(jar) : emptyEnumeration;
return new Enumeration<String>() {
String name;
public boolean hasMoreElements() {
if (name != null) {
return true;
}
while (itor.hasNext()) {
Map.Entry<String, CodeSigner[]> e = itor.next();
if (signersReq.contains(e.getValue())) {
name = e.getKey();
return true;
}
}
while (enum2.hasMoreElements()) {
name = enum2.nextElement();
return true;
}
return false;
}
public String nextElement() {
if (hasMoreElements()) {
String value = name;
name = null;
return value;
}
throw new NoSuchElementException();
}
};
}
/*
* Like entries() but screens out internal JAR mechanism entries
* and includes signed entries with no ZIP data.
*/
public Enumeration<JarEntry> entries2(final JarFile jar, Enumeration<? extends ZipEntry> e) {
final Map<String, CodeSigner[]> map = new HashMap<>();
map.putAll(signerMap());
final Enumeration<? extends ZipEntry> enum_ = e;
return new Enumeration<JarEntry>() {
Enumeration<String> signers = null;
JarEntry entry;
public boolean hasMoreElements() {
if (entry != null) {
return true;
}
while (enum_.hasMoreElements()) {
ZipEntry ze = enum_.nextElement();
if (JarVerifier.isSigningRelated(ze.getName())) {
continue;
}
entry = jar.newEntry(ze);
return true;
}
if (signers == null) {
signers = Collections.enumeration(map.keySet());
}
while (signers.hasMoreElements()) {
String name = signers.nextElement();
entry = jar.newEntry(new ZipEntry(name));
return true;
}
// Any map entries left?
return false;
}
public JarEntry nextElement() {
if (hasMoreElements()) {
JarEntry je = entry;
map.remove(je.getName());
entry = null;
return je;
}
throw new NoSuchElementException();
}
};
}
private Enumeration<String> emptyEnumeration = new Enumeration<String>() {
public boolean hasMoreElements() {
return false;
}
public String nextElement() {
throw new NoSuchElementException();
}
};
// true if file is part of the signature mechanism itself
static boolean isSigningRelated(String name) {
return SignatureFileVerifier.isSigningRelated(name);
}
private Enumeration<String> unsignedEntryNames(JarFile jar) {
final Map<String, CodeSigner[]> map = signerMap();
final Enumeration<JarEntry> entries = jar.entries();
return new Enumeration<String>() {
String name;
/*
* Grab entries from ZIP directory but screen out
* metadata.
*/
public boolean hasMoreElements() {
if (name != null) {
return true;
}
while (entries.hasMoreElements()) {
String value;
ZipEntry e = entries.nextElement();
value = e.getName();
if (e.isDirectory() || isSigningRelated(value)) {
continue;
}
if (map.get(value) == null) {
name = value;
return true;
}
}
return false;
}
public String nextElement() {
if (hasMoreElements()) {
String value = name;
name = null;
return value;
}
throw new NoSuchElementException();
}
};
}
private List<CodeSigner[]> jarCodeSigners;
private synchronized List<CodeSigner[]> getJarCodeSigners() {
CodeSigner[] signers;
if (jarCodeSigners == null) {
HashSet<CodeSigner[]> set = new HashSet<>();
set.addAll(signerMap().values());
jarCodeSigners = new ArrayList<>();
jarCodeSigners.addAll(set);
}
return jarCodeSigners;
}
public synchronized CodeSource[] getCodeSources(JarFile jar, URL url) {
boolean hasUnsigned = unsignedEntryNames(jar).hasMoreElements();
return mapSignersToCodeSources(url, getJarCodeSigners(), hasUnsigned);
}
public CodeSource getCodeSource(URL url, String name) {
CodeSigner[] signers;
signers = signerMap().get(name);
return mapSignersToCodeSource(url, signers);
}
public CodeSource getCodeSource(URL url, JarFile jar, JarEntry je) {
CodeSigner[] signers;
return mapSignersToCodeSource(url, getCodeSigners(jar, je));
}
public void setEagerValidation(boolean eager) {
eagerValidation = eager;
}
public synchronized List<Object> getManifestDigests() {
return Collections.unmodifiableList(manifestDigests);
}
static CodeSource getUnsignedCS(URL url) {
return new VerifierCodeSource(null, url, (java.security.cert.Certificate[]) null);
}
}
|
3e00da93e2990eaae2a167cf56849da14017a8b9 | 654 | java | Java | src/test/java/tdd_java/model/LanceTest.java | mupezzuol/tdd-java | c4a34c244dd66611403fe8d24fddfc6be53cdfec | [
"MIT"
] | null | null | null | src/test/java/tdd_java/model/LanceTest.java | mupezzuol/tdd-java | c4a34c244dd66611403fe8d24fddfc6be53cdfec | [
"MIT"
] | null | null | null | src/test/java/tdd_java/model/LanceTest.java | mupezzuol/tdd-java | c4a34c244dd66611403fe8d24fddfc6be53cdfec | [
"MIT"
] | null | null | null | 21.096774 | 65 | 0.744648 | 356 | package tdd_java.model;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class LanceTest {
private User murilloPezzuol;
@BeforeEach
public void mustCreateDefaultData() {
this.murilloPezzuol = new User("Murillo Pezzuol");
}
@Test
public void shouldNotCreateLanceWithValueZero() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
new Lance(murilloPezzuol, 0);
});
}
@Test
public void shouldNotCreateLanceWithValueLessZero() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
new Lance(murilloPezzuol, -1);
});
}
}
|
3e00dac352ffe0a5684032858491ad3f84c47e73 | 6,287 | java | Java | dhis-2/dhis-api/src/main/java/org/hisp/dhis/patientreport/PatientTabularReport.java | hispindia/MAHARASHTRA-2.13 | f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9 | [
"BSD-3-Clause"
] | null | null | null | dhis-2/dhis-api/src/main/java/org/hisp/dhis/patientreport/PatientTabularReport.java | hispindia/MAHARASHTRA-2.13 | f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9 | [
"BSD-3-Clause"
] | null | null | null | dhis-2/dhis-api/src/main/java/org/hisp/dhis/patientreport/PatientTabularReport.java | hispindia/MAHARASHTRA-2.13 | f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9 | [
"BSD-3-Clause"
] | null | null | null | 32.241026 | 95 | 0.686814 | 357 | package org.hisp.dhis.patientreport;
/*
* Copyright (c) 2004-2013, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.view.DetailedView;
import org.hisp.dhis.common.view.ExportView;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramStage;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
/**
* @author Chau Thu Tran
* @version $PatientTabularReport.java May 7, 2012 12:41:41 PM$
*/
@JacksonXmlRootElement( localName = "patientTabularReport", namespace = DxfNamespaces.DXF_2_0 )
public class PatientTabularReport
extends BaseIdentifiableObject
{
private static final long serialVersionUID = -2880334669266185058L;
public static String CASE_BASED_REPORT = "caseBasedReport";
public static String AGGREGATE_REPORT = "aggregateReport";
public static String PREFIX_DATA_ELEMENT = "de";
public static String VALUE_TYPE_OPTION_SET = "optionSet";
public static String PREFIX_NUMBER_DATA_ELEMENT = "numberDe";
private Program program;
private ProgramStage programStage;
private Date startDate;
private Date endDate;
private List<String> dimension = new ArrayList<String>();
private List<String> filter = new ArrayList<String>();
private String ouMode;
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
public PatientTabularReport()
{
}
public PatientTabularReport( String name )
{
this.name = name;
}
// -------------------------------------------------------------------------
// Getters && Setters
// -------------------------------------------------------------------------
@JsonProperty
@JsonView( { DetailedView.class, ExportView.class } )
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Date getStartDate()
{
return startDate;
}
public void setStartDate( Date startDate )
{
this.startDate = startDate;
}
@JsonProperty
@JsonView( { DetailedView.class, ExportView.class } )
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Date getEndDate()
{
return endDate;
}
public void setEndDate( Date endDate )
{
this.endDate = endDate;
}
@JsonView( { DetailedView.class, ExportView.class } )
@JacksonXmlElementWrapper( localName = "dimension", namespace = DxfNamespaces.DXF_2_0 )
@JacksonXmlProperty( localName = "dimension", namespace = DxfNamespaces.DXF_2_0 )
public List<String> getDimension()
{
return dimension;
}
public void setDimension( List<String> dimension )
{
this.dimension = dimension;
}
@JsonView( { DetailedView.class, ExportView.class } )
@JacksonXmlElementWrapper( localName = "filter", namespace = DxfNamespaces.DXF_2_0 )
@JacksonXmlProperty( localName = "filter", namespace = DxfNamespaces.DXF_2_0 )
public List<String> getFilter()
{
return filter;
}
public void setFilter( List<String> filter )
{
this.filter = filter;
}
@JsonProperty
@JsonView( { DetailedView.class, ExportView.class } )
@JsonSerialize( as = BaseIdentifiableObject.class )
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Program getProgram()
{
return program;
}
public void setProgram( Program program )
{
this.program = program;
}
@JsonProperty
@JsonView( { DetailedView.class, ExportView.class } )
@JacksonXmlElementWrapper( localName = "programStages", namespace = DxfNamespaces.DXF_2_0 )
@JacksonXmlProperty( localName = "programStage", namespace = DxfNamespaces.DXF_2_0 )
public ProgramStage getProgramStage()
{
return programStage;
}
public void setProgramStage( ProgramStage programStage )
{
this.programStage = programStage;
}
@JsonProperty
@JsonView( { DetailedView.class, ExportView.class } )
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String getOuMode()
{
return ouMode;
}
public void setOuMode( String ouMode )
{
this.ouMode = ouMode;
}
}
|
3e00db1237e907fc5da2866fc2b27bb0bea6523f | 119 | java | Java | app/src/main/java/com/kay/hoverstarter/listeners/MessageListener.java | kayrahman/UssdCallDemoWithHover | 13e1679f786fcff2cbc4822efe453086e0972da0 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/kay/hoverstarter/listeners/MessageListener.java | kayrahman/UssdCallDemoWithHover | 13e1679f786fcff2cbc4822efe453086e0972da0 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/kay/hoverstarter/listeners/MessageListener.java | kayrahman/UssdCallDemoWithHover | 13e1679f786fcff2cbc4822efe453086e0972da0 | [
"Apache-2.0"
] | null | null | null | 23.8 | 41 | 0.806723 | 358 | package com.kay.hoverstarter.listeners;
public interface MessageListener {
void messageReceived(String message);
} |
3e00db4efd3a359745d0ada34423ed1b608aa5fe | 216 | java | Java | src/main/java/com/rekoe/socialauth/Constants.java | gen2number/Rk_Cms | d4109b42a83846f07910004bd10e885412772a2d | [
"Apache-1.1"
] | 72 | 2015-01-16T15:21:04.000Z | 2021-11-26T08:13:57.000Z | src/main/java/com/rekoe/socialauth/Constants.java | gen2number/Rk_Cms | d4109b42a83846f07910004bd10e885412772a2d | [
"Apache-1.1"
] | 15 | 2015-01-19T10:52:49.000Z | 2017-07-03T01:50:40.000Z | src/main/java/com/rekoe/socialauth/Constants.java | gen2number/Rk_Cms | d4109b42a83846f07910004bd10e885412772a2d | [
"Apache-1.1"
] | 64 | 2015-01-03T04:29:32.000Z | 2020-10-28T06:16:02.000Z | 16.615385 | 61 | 0.671296 | 359 | package com.rekoe.socialauth;
public interface Constants {
/**
* UTF-8
*/
public static final String ENCODING = "UTF-8";
/**
* HMAC-SHA1
*/
public static final String HMACSHA1_SIGNATURE = "HMAC-SHA1";
}
|
3e00dba4fc89d968859253663e8ea85f16963e76 | 1,316 | java | Java | src/main/java/com/pinkman/dtboot/dao/SysLogMapper.java | PINKMAN0u0/dtboot | 9e1de421d07e1d15df00f296339ead57018bb76e | [
"Apache-2.0"
] | null | null | null | src/main/java/com/pinkman/dtboot/dao/SysLogMapper.java | PINKMAN0u0/dtboot | 9e1de421d07e1d15df00f296339ead57018bb76e | [
"Apache-2.0"
] | null | null | null | src/main/java/com/pinkman/dtboot/dao/SysLogMapper.java | PINKMAN0u0/dtboot | 9e1de421d07e1d15df00f296339ead57018bb76e | [
"Apache-2.0"
] | null | null | null | 24.830189 | 60 | 0.651976 | 360 | package com.pinkman.dtboot.dao;
import com.pinkman.dtboot.entity.SysLog;
public interface SysLogMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_log
*
* @mbggenerated
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_log
*
* @mbggenerated
*/
int insert(SysLog record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_log
*
* @mbggenerated
*/
int insertSelective(SysLog record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_log
*
* @mbggenerated
*/
SysLog selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_log
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(SysLog record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table sys_log
*
* @mbggenerated
*/
int updateByPrimaryKey(SysLog record);
} |
3e00dc56cd1c53fe43d8c975e6cc24bfc87b2055 | 680 | java | Java | src/org/minima/system/commands/base/hash.java | dmmeteo/Minima | d83bd20d077e3d3f718fe169f8bb3614c98df2aa | [
"Apache-2.0"
] | null | null | null | src/org/minima/system/commands/base/hash.java | dmmeteo/Minima | d83bd20d077e3d3f718fe169f8bb3614c98df2aa | [
"Apache-2.0"
] | null | null | null | src/org/minima/system/commands/base/hash.java | dmmeteo/Minima | d83bd20d077e3d3f718fe169f8bb3614c98df2aa | [
"Apache-2.0"
] | null | null | null | 20 | 63 | 0.707353 | 361 | package org.minima.system.commands.base;
import org.minima.objects.base.MiniData;
import org.minima.system.commands.Command;
import org.minima.utils.Crypto;
import org.minima.utils.json.JSONObject;
public class hash extends Command {
public hash() {
super("hash","[data:] - Hash the data using KECCAK 256");
}
@Override
public JSONObject runCommand() throws Exception {
JSONObject ret = getJSONReply();
MiniData data = getDataParam("data");
byte[] hash = Crypto.getInstance().hashData(data.getBytes());
ret.put("response", new MiniData(hash).to0xString());
return ret;
}
@Override
public Command getFunction() {
return new hash();
}
}
|
3e00dc669ed3621a27855bd708487d018f84080d | 1,771 | java | Java | src/main/java/org/olat/core/commons/services/vfs/ui/management/VFSOverviewFooterNameCellRenderer.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 191 | 2018-03-29T09:55:44.000Z | 2022-03-23T06:42:12.000Z | src/main/java/org/olat/core/commons/services/vfs/ui/management/VFSOverviewFooterNameCellRenderer.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 68 | 2018-05-11T06:19:00.000Z | 2022-01-25T18:03:26.000Z | src/main/java/org/olat/core/commons/services/vfs/ui/management/VFSOverviewFooterNameCellRenderer.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 139 | 2018-04-27T09:46:11.000Z | 2022-03-27T08:52:50.000Z | 40.522727 | 114 | 0.758273 | 362 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.core.commons.services.vfs.ui.management;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiCellRenderer;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiTableComponent;
import org.olat.core.gui.render.Renderer;
import org.olat.core.gui.render.StringOutput;
import org.olat.core.gui.render.URLBuilder;
import org.olat.core.gui.translator.Translator;
import org.olat.core.gui.util.CSSHelper;
/**
*
* Initial date: 23 Dec 2019<br>
* @author aboeckle, envkt@example.com, http://www.frentix.com
*
*/
public class VFSOverviewFooterNameCellRenderer implements FlexiCellRenderer{
@Override
public void render(Renderer renderer, StringOutput target, Object cellValue, int row, FlexiTableComponent source,
URLBuilder ubu, Translator translator) {
target.append(CSSHelper.getIcon(CSSHelper.CSS_CLASS_GLOBE));
target.append(translator.translate(cellValue.toString()));
}
}
|
3e00dc701556e905ef146a325f15c7e90a7dd2b3 | 381 | java | Java | spring-boot-rest-jpa/src/main/java/com/gauravbytes/gkart/jpa/UserRepository.java | Titov1982/J-vaExample | b6d14fdc10f1c3a5dcc10f9ff169aa2af68a5057 | [
"MIT"
] | 62 | 2017-01-16T07:28:43.000Z | 2020-06-17T03:57:43.000Z | spring-boot-rest-jpa/src/main/java/com/gauravbytes/gkart/jpa/UserRepository.java | Titov1982/J-vaExample | b6d14fdc10f1c3a5dcc10f9ff169aa2af68a5057 | [
"MIT"
] | 15 | 2018-04-04T07:07:49.000Z | 2020-06-05T22:58:19.000Z | spring-boot-rest-jpa/src/main/java/com/gauravbytes/gkart/jpa/UserRepository.java | UlrichGiorgioJaeger/gauravbytes | 3150466069a26e2b8ffc3deca25973597624ff5e | [
"MIT"
] | 159 | 2017-02-19T08:01:16.000Z | 2020-06-24T14:33:30.000Z | 21.166667 | 70 | 0.732283 | 363 | package com.gauravbytes.gkart.jpa;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.gauravbytes.gkart.entity.User;
/**
*
* @author Gaurav Rai Mazra
* <a href="http://www.gauravbytes.com">Catch me</a>
*/
@Transactional
public interface UserRepository extends JpaRepository<User, String> {
}
|
3e00dc884dfd2a4d8c0bafe64fee71af2460d042 | 290 | java | Java | clbs/src/main/java/com/zw/platform/domain/sendTxt/SetStreamObd.java | youyouqiu/hybrid-development | 784c5227a73d1e6609b701a42ef4cdfd6400d2b7 | [
"MIT"
] | 1 | 2021-09-29T02:13:49.000Z | 2021-09-29T02:13:49.000Z | clbs/src/main/java/com/zw/platform/domain/sendTxt/SetStreamObd.java | youyouqiu/hybrid-development | 784c5227a73d1e6609b701a42ef4cdfd6400d2b7 | [
"MIT"
] | null | null | null | clbs/src/main/java/com/zw/platform/domain/sendTxt/SetStreamObd.java | youyouqiu/hybrid-development | 784c5227a73d1e6609b701a42ef4cdfd6400d2b7 | [
"MIT"
] | null | null | null | 18.125 | 70 | 0.786207 | 364 | package com.zw.platform.domain.sendTxt;
import lombok.Data;
import java.io.Serializable;
@Data
public class SetStreamObd implements Serializable {
private static final long serialVersionUID = 4256998346040327393L;
private Long vehicleTypeId;
private Integer uploadTime;
}
|
3e00dcf38008dabbe62570e4d442c4a94960e2cc | 3,160 | java | Java | components/org.wso2.carbon.datasource.core/src/test/java/org/wso2/carbon/datasource/api/DataSourceManagementServiceTest.java | dewniMW/carbon-datasources | a1d1ee839f00c0242d34a5d69f525d508e3b474b | [
"Apache-2.0"
] | 2 | 2019-04-26T06:27:13.000Z | 2020-06-16T07:39:31.000Z | components/org.wso2.carbon.datasource.core/src/test/java/org/wso2/carbon/datasource/api/DataSourceManagementServiceTest.java | dewniMW/carbon-datasources | a1d1ee839f00c0242d34a5d69f525d508e3b474b | [
"Apache-2.0"
] | 24 | 2016-03-07T04:39:00.000Z | 2019-05-16T03:33:37.000Z | components/org.wso2.carbon.datasource.core/src/test/java/org/wso2/carbon/datasource/api/DataSourceManagementServiceTest.java | dewniMW/carbon-datasources | a1d1ee839f00c0242d34a5d69f525d508e3b474b | [
"Apache-2.0"
] | 45 | 2016-03-03T13:10:53.000Z | 2021-09-16T15:39:34.000Z | 45.797101 | 119 | 0.760443 | 365 | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.datasource.api;
import org.testng.Assert;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.wso2.carbon.config.ConfigurationException;
import org.wso2.carbon.datasource.core.BaseTest;
import org.wso2.carbon.datasource.core.api.DataSourceManagementService;
import org.wso2.carbon.datasource.core.beans.DataSourceMetadata;
import org.wso2.carbon.datasource.core.exception.DataSourceException;
import org.wso2.carbon.datasource.core.impl.DataSourceManagementServiceImpl;
import java.util.List;
/**
* Test class for {@code DataSourceManagementService}.
*/
public class DataSourceManagementServiceTest extends BaseTest {
private DataSourceManagementService dataSourceMgtService;
private static final String DATASOURCE_NAME = "WSO2_CARBON_DB_2";
@BeforeSuite
public void initialize() throws DataSourceException, ConfigurationException {
super.init();
dataSourceMgtService = new DataSourceManagementServiceImpl();
}
@Test
public void getDataSourceTest() throws DataSourceException {
DataSourceMetadata dataSourceMetadata = dataSourceMgtService.getDataSource(DATASOURCE_NAME);
Assert.assertNotNull(dataSourceMetadata, "metadata for \"" + DATASOURCE_NAME + "\" should not be null");
}
@Test(dependsOnMethods = "getDataSourceTest")
public void getDataSourceListTest() throws DataSourceException {
List<DataSourceMetadata> dataSourceMetadata = dataSourceMgtService.getDataSource();
Assert.assertEquals(1, dataSourceMetadata.size(), "Only one " + DATASOURCE_NAME + " exist in the repository.");
}
@Test(dependsOnMethods = "getDataSourceListTest")
public void addAndDeleteDataSourceTest() throws DataSourceException {
DataSourceMetadata dataSourceMetadata = dataSourceMgtService.getDataSource(DATASOURCE_NAME);
Assert.assertNotNull(dataSourceMetadata, "dataSourceMetadata should not be null");
dataSourceMgtService.deleteDataSource(DATASOURCE_NAME);
DataSourceMetadata dataSourceMetadata2 = dataSourceMgtService.getDataSource(DATASOURCE_NAME);
Assert.assertNull(dataSourceMetadata2, "After deleting, " + DATASOURCE_NAME + " should not exist in the "
+ "repository");
dataSourceMgtService.addDataSource(dataSourceMetadata);
Assert.assertNotNull(dataSourceMgtService.getDataSource(DATASOURCE_NAME), DATASOURCE_NAME + " should exist in"
+ " the repository");
}
}
|
3e00dde3a777cd70c6710a334e9d4cc96496914c | 676 | java | Java | src/main/java/com/lindar/dotmailer/vo/api/DataField.java | lindar-open/dotmailer-java-client | c09cceaffd42ae4f80480d4cbf0af2fc15d77c38 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/lindar/dotmailer/vo/api/DataField.java | lindar-open/dotmailer-java-client | c09cceaffd42ae4f80480d4cbf0af2fc15d77c38 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/lindar/dotmailer/vo/api/DataField.java | lindar-open/dotmailer-java-client | c09cceaffd42ae4f80480d4cbf0af2fc15d77c38 | [
"Apache-2.0"
] | 1 | 2021-05-12T16:38:12.000Z | 2021-05-12T16:38:12.000Z | 26 | 102 | 0.698225 | 366 | package com.lindar.dotmailer.vo.api;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(of = "name")
@Data
public class DataField <T> {
private String name;
private DataFieldType type;
private DataFieldVisibility visibility = DataFieldVisibility.PRIVATE;
private T defaultValue;
public DataField(String name, DataFieldType type){
this.name = name;
this.type = type;
}
public DataField(String name, DataFieldType type, DataFieldVisibility visibility, T defaultValue){
this.name = name;
this.type = type;
this.visibility = visibility;
this.defaultValue = defaultValue;
}
}
|
3e00df3c55632b719f5fa4d2bdf64f3522a163ac | 526 | java | Java | runtime/shell-osgi/src/main/java/org/springframework/roo/shell/osgi/converters/AvailableCommandsConverterComponent.java | springdev-projects/spring-roo | 4a2e9f1eb17d4e49ad947503a63afef7d5a37842 | [
"Apache-2.0"
] | 416 | 2015-01-07T10:54:15.000Z | 2021-11-16T21:59:38.000Z | runtime/shell-osgi/src/main/java/org/springframework/roo/shell/osgi/converters/AvailableCommandsConverterComponent.java | Huynhhung0/spring-roo | 1e7d745e389a9f6114b1618884e99bddd26251ee | [
"Apache-2.0"
] | 7 | 2015-01-09T12:29:16.000Z | 2016-10-24T06:57:49.000Z | runtime/shell-osgi/src/main/java/org/springframework/roo/shell/osgi/converters/AvailableCommandsConverterComponent.java | Huynhhung0/spring-roo | 1e7d745e389a9f6114b1618884e99bddd26251ee | [
"Apache-2.0"
] | 230 | 2015-01-05T05:11:24.000Z | 2021-11-16T21:59:45.000Z | 29.222222 | 85 | 0.821293 | 367 | package org.springframework.roo.shell.osgi.converters;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.springframework.roo.shell.converters.AvailableCommandsConverter;
import org.springframework.roo.shell.converters.StaticFieldConverterImpl;
/**
* OSGi component launcher for {@link StaticFieldConverterImpl}.
*
* @author Ben Alex
* @since 1.1
*/
@Component
@Service
public class AvailableCommandsConverterComponent extends AvailableCommandsConverter {
}
|
3e00df497692f8980d1ece858cb8040d55fac5fe | 718 | java | Java | code/framework/api/src/main/java/io/cattle/platform/api/auth/Policy.java | pranavs18/cattle | db64d9ffc782d82bbbc44709fb23e63b43c3c549 | [
"Apache-2.0"
] | null | null | null | code/framework/api/src/main/java/io/cattle/platform/api/auth/Policy.java | pranavs18/cattle | db64d9ffc782d82bbbc44709fb23e63b43c3c549 | [
"Apache-2.0"
] | null | null | null | code/framework/api/src/main/java/io/cattle/platform/api/auth/Policy.java | pranavs18/cattle | db64d9ffc782d82bbbc44709fb23e63b43c3c549 | [
"Apache-2.0"
] | null | null | null | 24.758621 | 76 | 0.71727 | 368 | package io.cattle.platform.api.auth;
import java.util.List;
public interface Policy {
public static final String AGENT_ID = "agentId";
public static final String AUTHORIZED_FOR_ALL_ACCOUNTS = "all.accounts";
public static final String REMOVED_VISIBLE = "removed.visible";
public static final String PLAIN_ID = "plain.id";
public static final String PLAIN_ID_OPTION = "plain.id.option";
public static final long NO_ACCOUNT = -1L;
boolean isOption(String optionName);
String getOption(String optionName);
List<Long> getAuthorizedAccounts();
long getAccountId();
String getUserName();
<T> List<T> authorizeList(List<T> list);
<T> T authorizeObject(T obj);
}
|
3e00dfbcf40d6bee08fe59f6024db239e0748399 | 735 | java | Java | src/me/songbx/action/parallel/model/TranscriptHashMapLostNumber.java | baoxingsong/Irisas | 9b3bafd76c7dca8be19d2d58dd09187db4684b80 | [
"MIT"
] | 6 | 2017-09-25T11:25:45.000Z | 2019-07-17T10:35:15.000Z | src/me/songbx/action/parallel/model/TranscriptHashMapLostNumber.java | baoxingsong/Irisas | 9b3bafd76c7dca8be19d2d58dd09187db4684b80 | [
"MIT"
] | 2 | 2018-10-23T09:16:48.000Z | 2019-02-20T04:57:47.000Z | src/me/songbx/action/parallel/model/TranscriptHashMapLostNumber.java | baoxingsong/Irisas | 9b3bafd76c7dca8be19d2d58dd09187db4684b80 | [
"MIT"
] | 3 | 2018-10-30T15:37:59.000Z | 2020-10-22T18:36:09.000Z | 30.625 | 88 | 0.8 | 369 | package me.songbx.action.parallel.model;
import java.util.HashMap;
public class TranscriptHashMapLostNumber {
private HashMap<String, Integer> transcriptLostNumber = new HashMap<String, Integer>();
public synchronized HashMap<String, Integer> getTranscriptLostNumber() {
return transcriptLostNumber;
}
public synchronized void setTranscriptLostNumber(
HashMap<String, Integer> transcriptLostNumber) {
this.transcriptLostNumber = transcriptLostNumber;
}
public synchronized void add(String transcriptName){
if(transcriptLostNumber.containsKey(transcriptName)){
transcriptLostNumber.put(transcriptName, transcriptLostNumber.get(transcriptName)+1);
}else{
transcriptLostNumber.put(transcriptName, 1);
}
}
}
|
3e00dff669a635e26b02da487fa33e7d4521fa2a | 1,133 | java | Java | cloudfoundry-client/src/main/java/org/cloudfoundry/client/v3/deployments/_DeploymentRelationships.java | zlatozar/cf-java-client | a411295d1768353b1f3405db0175725a6a6fe43d | [
"Apache-2.0"
] | null | null | null | cloudfoundry-client/src/main/java/org/cloudfoundry/client/v3/deployments/_DeploymentRelationships.java | zlatozar/cf-java-client | a411295d1768353b1f3405db0175725a6a6fe43d | [
"Apache-2.0"
] | null | null | null | cloudfoundry-client/src/main/java/org/cloudfoundry/client/v3/deployments/_DeploymentRelationships.java | zlatozar/cf-java-client | a411295d1768353b1f3405db0175725a6a6fe43d | [
"Apache-2.0"
] | 1 | 2021-07-22T10:47:20.000Z | 2021-07-22T10:47:20.000Z | 29.815789 | 75 | 0.754634 | 370 | /*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cloudfoundry.client.v3.deployments;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.client.v3.ToOneRelationship;
import org.immutables.value.Value;
/**
* The relationships for the Create Deployment request
*/
@Value.Immutable
@JsonDeserialize
abstract class _DeploymentRelationships {
/**
* The app relationship
*/
@JsonProperty("app")
abstract ToOneRelationship getApp();
}
|
3e00e0bccc07323c7ae4c37eaefa2bcceea25c2b | 1,422 | java | Java | src/main/java/com/yan/code/transcode/model/TransCode.java | yankj12/interview | a0b13e81099edce8c008c4a6f1434ce0e8bc6c65 | [
"MIT"
] | null | null | null | src/main/java/com/yan/code/transcode/model/TransCode.java | yankj12/interview | a0b13e81099edce8c008c4a6f1434ce0e8bc6c65 | [
"MIT"
] | 72 | 2017-12-12T11:11:23.000Z | 2018-10-09T01:34:06.000Z | src/main/java/com/yan/code/transcode/model/TransCode.java | yankj12/interview | a0b13e81099edce8c008c4a6f1434ce0e8bc6c65 | [
"MIT"
] | null | null | null | 15.626374 | 51 | 0.7173 | 371 | package com.yan.code.transcode.model;
import java.util.Date;
import java.util.List;
public class TransCode {
private String id;
//private String appCode;
private String codeType;
private String codeTypeName;
private List<CodeEntry> trans;
private String remark;
private String validStatus;
private Date insertTime;
private Date updateTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCodeType() {
return codeType;
}
public void setCodeType(String codeType) {
this.codeType = codeType;
}
public List<CodeEntry> getTrans() {
return trans;
}
public void setTrans(List<CodeEntry> trans) {
this.trans = trans;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getValidStatus() {
return validStatus;
}
public void setValidStatus(String validStatus) {
this.validStatus = validStatus;
}
public Date getInsertTime() {
return insertTime;
}
public void setInsertTime(Date insertTime) {
this.insertTime = insertTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getCodeTypeName() {
return codeTypeName;
}
public void setCodeTypeName(String codeTypeName) {
this.codeTypeName = codeTypeName;
}
}
|
3e00e13f059f5a8135231bc8876994b6706200a7 | 3,015 | java | Java | hackerden/commandproc/src/serial/SubmitCommand.java | demo-jasonk/SecureCodingDojo | f7eb6dd9eeec22c35a59a4b6ca127312b038d84c | [
"ECL-2.0",
"Apache-2.0"
] | 219 | 2017-08-22T22:17:31.000Z | 2021-02-03T10:03:57.000Z | hackerden/commandproc/src/serial/SubmitCommand.java | demo-jasonk/SecureCodingDojo | f7eb6dd9eeec22c35a59a4b6ca127312b038d84c | [
"ECL-2.0",
"Apache-2.0"
] | 39 | 2019-03-28T15:58:32.000Z | 2021-02-09T00:53:32.000Z | hackerden/commandproc/src/serial/SubmitCommand.java | demo-jasonk/SecureCodingDojo | f7eb6dd9eeec22c35a59a4b6ca127312b038d84c | [
"ECL-2.0",
"Apache-2.0"
] | 69 | 2017-10-06T22:29:11.000Z | 2021-02-07T03:13:46.000Z | 32.771739 | 305 | 0.748922 | 372 | /*
Copyright 2017-2018 Trend Micro Incorporated
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package serial;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.xml.sax.InputSource;
/**
* Servlet implementation class SubmitObject
*/
@WebServlet("/SubmitCommand")
@MultipartConfig
public class SubmitCommand extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SubmitCommand() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean loggedin = false;
HttpSession session = request.getSession();
if(session!=null){
if(session.getAttribute("loggedin") != null){
loggedin = (boolean)session.getAttribute("loggedin");
}
}
if(loggedin){
Part object = request.getPart("object");
InputStream objIs = object.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(objIs, writer);
String b64String = writer.toString();
if(b64String != null && !b64String.trim().isEmpty()){
byte [] objBytes = Base64.decodeBase64(b64String);
ByteArrayInputStream in = new ByteArrayInputStream(objBytes);
ObjectInputStream is = new ObjectInputStream(in);
try {
Object cat = is.readObject();
session.setAttribute("CAT", cat);
response.sendRedirect("index.jsp");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else{
response.sendRedirect("login.jsp");
}
}
}
|
3e00e35f4853e581f5a23751e7afeaba0f005310 | 843 | java | Java | app/src/main/java/ua/gov/dp/econtact/api/task/address/GetCitiesTask.java | Yalantis/e-contact-android | 2a9c18804927b405b12955ed23fc2146c0f4d487 | [
"Unlicense",
"MIT"
] | 253 | 2016-08-05T14:20:22.000Z | 2022-02-05T10:35:47.000Z | app/src/main/java/ua/gov/dp/econtact/api/task/address/GetCitiesTask.java | Yalantis/e-contact-android | 2a9c18804927b405b12955ed23fc2146c0f4d487 | [
"Unlicense",
"MIT"
] | 8 | 2017-01-25T19:21:59.000Z | 2018-03-27T12:39:49.000Z | app/src/main/java/ua/gov/dp/econtact/api/task/address/GetCitiesTask.java | Yalantis/e-contact-android | 2a9c18804927b405b12955ed23fc2146c0f4d487 | [
"Unlicense",
"MIT"
] | 78 | 2016-08-10T11:28:23.000Z | 2020-05-15T16:21:42.000Z | 23.416667 | 77 | 0.67497 | 373 | package ua.gov.dp.econtact.api.task.address;
import ua.gov.dp.econtact.App;
import ua.gov.dp.econtact.api.request.AddressApi;
import ua.gov.dp.econtact.api.task.ApiTask;
import ua.gov.dp.econtact.model.address.City;
import java.util.List;
import retrofit.client.Response;
/**
* Get tickets
*/
public class GetCitiesTask extends ApiTask<AddressApi, List<City>> {
private final long mId;
public GetCitiesTask(final AddressApi api, final long id) {
super(api, null);
mId = id;
}
@Override
public void run() {
api.getCitiesByDistrictId(mId, this);
}
@Override
public void onSuccess(final List<City> cities, final Response response) {
for (City city : cities) {
city.setDistrictId(mId);
}
App.dataManager.saveCitiesFromServerData(cities);
}
}
|
3e00e411340bd6f9bd0fb6b30e041e0aac3fa733 | 728 | java | Java | design-patterns/src/main/java/io/github/gozhuyinglong/designpatterns/singleton/SingletonDCL.java | Austinhang0922/Austinhang0922.github.io | 7b6cc690f4dbb255bbe1d2f96513589a813fd459 | [
"Apache-2.0"
] | 32 | 2020-12-07T03:20:26.000Z | 2022-03-26T17:16:11.000Z | design-patterns/src/main/java/io/github/gozhuyinglong/designpatterns/singleton/SingletonDCL.java | Austinhang0922/Austinhang0922.github.io | 7b6cc690f4dbb255bbe1d2f96513589a813fd459 | [
"Apache-2.0"
] | null | null | null | design-patterns/src/main/java/io/github/gozhuyinglong/designpatterns/singleton/SingletonDCL.java | Austinhang0922/Austinhang0922.github.io | 7b6cc690f4dbb255bbe1d2f96513589a813fd459 | [
"Apache-2.0"
] | 18 | 2020-11-30T12:55:01.000Z | 2022-03-16T10:17:03.000Z | 19.157895 | 57 | 0.537088 | 374 | package io.github.gozhuyinglong.designpatterns.singleton;
/**
* 单例模式 - 双重校验锁(double-checked-locking)
*
* @author 码农StayUp
* @date 2020/12/7 0007
*/
public class SingletonDCL {
/**
* 私有实例,volatile修饰的变量是具有可见性的(即被一个线程修改后,其他线程立即可见)
*/
private volatile static SingletonDCL instance;
/**
* 私有构造方法
*/
private SingletonDCL() {
}
/**
* 唯一公开获取实例的方法(静态工厂方法)
*
* @return
*/
public static SingletonDCL getInstance() {
if (instance == null) {
synchronized (SingletonDCL.class) {
if (instance == null) {
instance = new SingletonDCL();
}
}
}
return instance;
}
}
|
3e00e5bd04bb7f6145c997049e3696ecefa8cd65 | 931 | java | Java | src/main/java/io/github/easyobject/core/value/impl/NullValue.java | EasyObject/easy-object | a682cb997c564552fd3776e5448585de7b1b3c66 | [
"MIT"
] | null | null | null | src/main/java/io/github/easyobject/core/value/impl/NullValue.java | EasyObject/easy-object | a682cb997c564552fd3776e5448585de7b1b3c66 | [
"MIT"
] | 15 | 2020-10-14T05:33:29.000Z | 2021-04-23T12:57:55.000Z | src/main/java/io/github/easyobject/core/value/impl/NullValue.java | EasyObject/easy-object | a682cb997c564552fd3776e5448585de7b1b3c66 | [
"MIT"
] | null | null | null | 25.861111 | 115 | 0.696026 | 375 | /*
* Copyright (c) 2020-2021 Danila Varatyntsev
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.easyobject.core.value.impl;
import io.github.easyobject.core.value.Value;
/**
* Class that represents an empty value, analogue to {@code null}.
* Should be used throw static final value - {@link NullValue#NULL}.
*/
public class NullValue extends Value<Object> {
public static final NullValue NULL = new NullValue();
private NullValue() {
// Constructor is private to prevent you from creating additional NullValue instances. Use static instance.
}
@Override
public Object getValue() {
return null;
}
@Override
public String toString() {
return "NullValue{}";
}
}
|
3e00e603ebf3788f6778a265f995795f5aad8d82 | 3,374 | java | Java | cs-clrs/src/main/java/com/mmnaseri/cs/clrs/ch10/s4/impl/BinaryTreeNode.java | rfarhanian/cs-review | 5e958c12f7119aaf5386c7cb7d19c646e68b5ce6 | [
"MIT"
] | 247 | 2017-05-31T21:26:44.000Z | 2022-03-14T05:27:37.000Z | cs-clrs/src/main/java/com/mmnaseri/cs/clrs/ch10/s4/impl/BinaryTreeNode.java | codeAligned/cs-review | 2186bddc3bca6c045becd52f363268ca663dcbd7 | [
"MIT"
] | 11 | 2018-08-18T04:51:48.000Z | 2019-06-27T11:30:59.000Z | cs-clrs/src/main/java/com/mmnaseri/cs/clrs/ch10/s4/impl/BinaryTreeNode.java | codeAligned/cs-review | 2186bddc3bca6c045becd52f363268ca663dcbd7 | [
"MIT"
] | 77 | 2017-06-06T21:41:19.000Z | 2022-03-02T06:34:32.000Z | 27.479675 | 94 | 0.600592 | 376 | package com.mmnaseri.cs.clrs.ch10.s4.impl;
import com.mmnaseri.cs.clrs.ch10.s4.TreeNode;
import com.mmnaseri.cs.qa.annotation.Quality;
import com.mmnaseri.cs.qa.annotation.Stage;
import java.util.ArrayList;
import java.util.List;
/**
* @author Mohammad Milad Naseri (kenaa@example.com)
* @since 1.0 (7/13/15, 12:38 AM)
*/
@Quality(Stage.TESTED)
public class BinaryTreeNode<E> extends SimpleTreeNode<E> {
public static final int RIGHT_CHILD = 1;
public static final int LEFT_CHILD = 0;
public BinaryTreeNode() {
super.addChild(null);
super.addChild(null);
}
@Override
public int addChild(TreeNode<E> child) {
if (getLeftChild() == null) {
setLeftChild((BinaryTreeNode<E>) child);
return LEFT_CHILD;
} else if (getRightChild() == null) {
setRightChild((BinaryTreeNode<E>) child);
return getLeftChild() == null ? LEFT_CHILD : RIGHT_CHILD;
}
return -1;
}
@Override
public List<? extends BinaryTreeNode<E>> getChildren() {
final List<? extends TreeNode<E>> children = super.getChildren();
final ArrayList<BinaryTreeNode<E>> result = new ArrayList<>();
for (TreeNode<E> child : children) {
if (child != null) {
result.add((BinaryTreeNode<E>) child);
}
}
return result;
}
@Override
protected void setChild(int index, TreeNode<E> child) {
if (index == LEFT_CHILD || index == RIGHT_CHILD) {
super.setChild(index, child);
}
}
public void setLeftChild(BinaryTreeNode<E> leftChild) {
super.setChild(LEFT_CHILD, leftChild);
}
public void setRightChild(BinaryTreeNode<E> rightChild) {
super.setChild(RIGHT_CHILD, rightChild);
}
public BinaryTreeNode<E> getLeftChild() {
return (BinaryTreeNode<E>) super.getChildren().get(LEFT_CHILD);
}
public BinaryTreeNode<E> getRightChild() {
return (BinaryTreeNode<E>) super.getChildren().get(RIGHT_CHILD);
}
public void deleteLeftChild() {
deleteChild(LEFT_CHILD);
}
public void deleteRightChild() {
deleteChild(RIGHT_CHILD);
}
@Override
public BinaryTreeNode<E> getParent() {
return (BinaryTreeNode<E>) super.getParent();
}
@Override
public void deleteChild(int index) {
if (index == LEFT_CHILD || index == RIGHT_CHILD) {
final BinaryTreeNode<E> node = (BinaryTreeNode<E>) super.getChildren().get(index);
if (node != null) {
node.setParent(null);
}
setChild(index, null);
}
}
@Override
public boolean isLeaf() {
return getLeftChild() == null && getRightChild() == null;
}
@Override
public TreeNode<E> getPreviousSibling() {
if (getParent() == null || this == getParent().getLeftChild()) {
return null;
}
return getParent().getLeftChild();
}
@Override
public TreeNode<E> getNextSibling() {
if (getParent() == null || this == getParent().getRightChild()) {
return null;
}
return getParent().getRightChild();
}
@Override
public TreeNode<E> getFirstChild() {
return getLeftChild() != null ? getLeftChild() : getRightChild();
}
}
|
3e00e719420924f637baee4ffdbd53c14de45af9 | 1,113 | java | Java | src/Task4/Task4.java | ollieshadbolt/MCOMD3NPC-Assignment-2 | 2f9ece7be25cf08bc71fabb838e05fb68879dc98 | [
"MIT"
] | null | null | null | src/Task4/Task4.java | ollieshadbolt/MCOMD3NPC-Assignment-2 | 2f9ece7be25cf08bc71fabb838e05fb68879dc98 | [
"MIT"
] | null | null | null | src/Task4/Task4.java | ollieshadbolt/MCOMD3NPC-Assignment-2 | 2f9ece7be25cf08bc71fabb838e05fb68879dc98 | [
"MIT"
] | null | null | null | 21.403846 | 82 | 0.625337 | 377 |
// Task4.java
package Task4;
import Task2.Task2;
import Task3.Task3;
import Task3.Task3Thread;
public class Task4 extends Task3 {
private double failureRate;
public Task4(double failureRate) {
this.failureRate = failureRate;
}
@Override
public Task3Thread getThread(Task2 task2, int column, int row, double[][] data) {
Task4Thread task4Thread;
task4Thread = new Task4Thread(this, column, row, data, failureRate);
return task4Thread;
}
@Override
public void joinThreads() {
for (int i = 0; i < threads.size(); i++) {
Task4Thread task4Thread;
task4Thread = (Task4Thread) threads.get(i);
try {
task4Thread.join();
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
Double result;
int column;
int row;
result = task4Thread.getResult();
column = task4Thread.column;
row = task4Thread.row;
if (result == null) {
newThread(column, row);
} else {
setResult(column, row, result);
}
}
}
}
|
3e00e85fad6a0e4e14c46eac6b28a21ab21a5f09 | 4,549 | java | Java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/InventoryDeletionStatusItemJsonUnmarshaller.java | jplippi/aws-sdk-java | 147eefec220e2944dc571283af6552611bc94301 | [
"Apache-2.0"
] | 1 | 2020-08-27T17:36:34.000Z | 2020-08-27T17:36:34.000Z | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/InventoryDeletionStatusItemJsonUnmarshaller.java | jplippi/aws-sdk-java | 147eefec220e2944dc571283af6552611bc94301 | [
"Apache-2.0"
] | 3 | 2020-04-15T20:08:15.000Z | 2021-06-30T19:58:16.000Z | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/InventoryDeletionStatusItemJsonUnmarshaller.java | jplippi/aws-sdk-java | 147eefec220e2944dc571283af6552611bc94301 | [
"Apache-2.0"
] | 1 | 2020-10-10T15:59:17.000Z | 2020-10-10T15:59:17.000Z | 45.949495 | 150 | 0.662563 | 378 | /*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.simplesystemsmanagement.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* InventoryDeletionStatusItem JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InventoryDeletionStatusItemJsonUnmarshaller implements Unmarshaller<InventoryDeletionStatusItem, JsonUnmarshallerContext> {
public InventoryDeletionStatusItem unmarshall(JsonUnmarshallerContext context) throws Exception {
InventoryDeletionStatusItem inventoryDeletionStatusItem = new InventoryDeletionStatusItem();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("DeletionId", targetDepth)) {
context.nextToken();
inventoryDeletionStatusItem.setDeletionId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("TypeName", targetDepth)) {
context.nextToken();
inventoryDeletionStatusItem.setTypeName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("DeletionStartTime", targetDepth)) {
context.nextToken();
inventoryDeletionStatusItem.setDeletionStartTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
if (context.testExpression("LastStatus", targetDepth)) {
context.nextToken();
inventoryDeletionStatusItem.setLastStatus(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("LastStatusMessage", targetDepth)) {
context.nextToken();
inventoryDeletionStatusItem.setLastStatusMessage(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("DeletionSummary", targetDepth)) {
context.nextToken();
inventoryDeletionStatusItem.setDeletionSummary(InventoryDeletionSummaryJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("LastStatusUpdateTime", targetDepth)) {
context.nextToken();
inventoryDeletionStatusItem.setLastStatusUpdateTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return inventoryDeletionStatusItem;
}
private static InventoryDeletionStatusItemJsonUnmarshaller instance;
public static InventoryDeletionStatusItemJsonUnmarshaller getInstance() {
if (instance == null)
instance = new InventoryDeletionStatusItemJsonUnmarshaller();
return instance;
}
}
|
3e00e8efd34c8c0153c1c674ca6332e804862c79 | 1,092 | java | Java | src/com/xpple/im/config/BmobConstants.java | nEdAy/Xpple_Im | 091d971da97ffa78290fe2edaf997f3b8aa8f2fb | [
"Apache-2.0"
] | 5 | 2016-11-01T08:00:40.000Z | 2020-02-28T05:07:10.000Z | src/com/xpple/im/config/BmobConstants.java | nEdAy/Xpple_Im | 091d971da97ffa78290fe2edaf997f3b8aa8f2fb | [
"Apache-2.0"
] | null | null | null | src/com/xpple/im/config/BmobConstants.java | nEdAy/Xpple_Im | 091d971da97ffa78290fe2edaf997f3b8aa8f2fb | [
"Apache-2.0"
] | null | null | null | 28 | 102 | 0.757326 | 379 | package com.xpple.im.config;
import android.annotation.SuppressLint;
import android.os.Environment;
/**
* @ClassName: BmobConstants
* @Description: TODO
* @author nEdAy
* @date 2015-4-17 下午5:05:00
*/
@SuppressLint("SdCardPath")
public class BmobConstants {
/**
* 存放发送图片的目录
*/
public static String BMOB_PICTURE_PATH = Environment
.getExternalStorageDirectory() + "/bmobimdemo/image/";
/**
* 我的头像保存目录
*/
public static String MyAvatarDir = "/sdcard/bmobimdemo/avatar/";
/**
* 拍照回调
*/
public static final int REQUESTCODE_UPLOADAVATAR_CAMERA = 1;// 拍照修改头像
public static final int REQUESTCODE_UPLOADAVATAR_LOCATION = 2;// 本地相册修改头像
public static final int REQUESTCODE_UPLOADAVATAR_CROP = 3;// 系统裁剪头像
public static final int REQUESTCODE_TAKE_CAMERA = 0x000001;// 拍照
public static final int REQUESTCODE_TAKE_LOCAL = 0x000002;// 本地图片
public static final int REQUESTCODE_TAKE_LOCATION = 0x000003;// 位置
public static final String EXTRA_STRING = "extra_string";
public static final String ACTION_REGISTER_SUCCESS_FINISH = "register.success.finish";// 注册成功之后登陆页面退出
}
|
3e00e92fba4c55add597f025e8b5feee1cd840ab | 7,423 | java | Java | src/main/java/org/stevewinfield/suja/idk/game/rooms/tasks/RoomTask.java | SteveWinfield/IDK-Server-Java | 5cbab8e921a2623f8d5af3d758306cf979a40ae0 | [
"Apache-2.0"
] | 6 | 2015-01-10T23:46:33.000Z | 2017-05-16T17:53:15.000Z | src/main/java/org/stevewinfield/suja/idk/game/rooms/tasks/RoomTask.java | StefanNemeth/IDK-Server-Java | 5cbab8e921a2623f8d5af3d758306cf979a40ae0 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/stevewinfield/suja/idk/game/rooms/tasks/RoomTask.java | StefanNemeth/IDK-Server-Java | 5cbab8e921a2623f8d5af3d758306cf979a40ae0 | [
"Apache-2.0"
] | 2 | 2015-08-11T07:02:55.000Z | 2017-12-21T10:09:39.000Z | 38.46114 | 131 | 0.64125 | 380 | /*
* IDK Game Server by Steve Winfield
* https://github.com/WinfieldSteve
*/
package org.stevewinfield.suja.idk.game.rooms.tasks;
import org.magicwerk.brownies.collections.GapList;
import org.stevewinfield.suja.idk.Bootloader;
import org.stevewinfield.suja.idk.communication.MessageWriter;
import org.stevewinfield.suja.idk.communication.room.writers.RoomPlayerStatusListWriter;
import org.stevewinfield.suja.idk.game.miscellaneous.ChatMessage;
import org.stevewinfield.suja.idk.game.rooms.RoomInstance;
import org.stevewinfield.suja.idk.game.rooms.RoomItem;
import org.stevewinfield.suja.idk.game.rooms.RoomPlayer;
import org.stevewinfield.suja.idk.game.rooms.coordination.Vector2;
import org.stevewinfield.suja.idk.game.rooms.tasks.games.BattleBanzaiTask;
import org.stevewinfield.suja.idk.game.rooms.wired.WiredDelayEvent;
import org.stevewinfield.suja.idk.threadpools.ServerTask;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
public class RoomTask extends ServerTask {
private final RoomInstance room;
private int updates;
private int emptyRoomCounter;
private final Queue<RoomPlayer> playersToAdd;
private final Queue<RoomPlayer> playersToRemove;
private final Queue<MessageWriter> roomMessageWriters;
private final Queue<ChatMessage> chatMessages;
private final Queue<RoomItem> itemCycleRequests;
private final Queue<WiredDelayEvent> wiredItemDelay;
private ScheduledFuture<?> scheduledFuture;
private final GameTask banzaiTask;
private boolean canceled;
public RoomTask(final RoomInstance room) {
this.room = room;
this.playersToAdd = new ArrayBlockingQueue<>(1024);
this.playersToRemove = new ArrayBlockingQueue<>(1024);
this.roomMessageWriters = new ArrayBlockingQueue<>(1024);
this.chatMessages = new ArrayBlockingQueue<>(1024);
this.itemCycleRequests = new ArrayBlockingQueue<>(1024);
this.wiredItemDelay = new ArrayBlockingQueue<>(1024);
this.updates = 0;
this.emptyRoomCounter = 0;
this.canceled = false;
this.banzaiTask = new BattleBanzaiTask(room);
}
public void offerRoomPlayerAdd(final RoomPlayer player) {
this.playersToAdd.offer(player);
}
public void offerWiredItemDelay(final WiredDelayEvent item) {
this.wiredItemDelay.offer(item);
}
public GameTask getBanzaiTask() {
return banzaiTask;
}
public boolean isCanceled() {
return canceled;
}
public void setCanceled(final boolean c) {
this.canceled = c;
}
public void offerChatMessageAdd(final ChatMessage message) {
this.chatMessages.offer(message);
}
public void offerRoomPlayerRemove(final RoomPlayer player) {
this.playersToRemove.offer(player);
}
public void offerRoomMessageWriter(final MessageWriter writer) {
this.roomMessageWriters.offer(writer);
}
public void offerItemCycle(final RoomItem item) {
this.itemCycleRequests.offer(item);
}
public void setScheduledFuture(final ScheduledFuture<?> scheduledFuture) {
this.scheduledFuture = scheduledFuture;
}
@Override
public void run() {
if (this.canceled) {
if (this.scheduledFuture == null) {
return;
}
for (final RoomPlayer player : this.room.getRoomPlayers().values()) {
if (player.getSession() != null) {
room.removePlayerFromRoom(player.getSession(), true, false);
}
}
this.scheduledFuture.cancel(true);
room.getInformation().totalPlayers = 0;
Bootloader.getGame().getNavigatorListManager().setRoom(room.getInformation(), 0, true);
Bootloader.getGame().getRoomManager().removeLoadedRoomInstance(room.getInformation().getId());
return;
}
if (this.emptyRoomCounter >= 60) {
this.room.save();
this.canceled = true;
this.emptyRoomCounter = 0;
return;
}
if (this.room.getInformation().getTotalPlayers() == 0) {
this.emptyRoomCounter++;
}
final GapList<MessageWriter> messages = new GapList<>();
final List<RoomPlayer> updatedPlayers = new GapList<>();
final ConcurrentHashMap<Vector2, Integer> setTileStates = new ConcurrentHashMap<>();
for (final RoomPlayer player : room.getRoomPlayers().values()) {
player.onCycle(setTileStates);
if (player.needsUpdate()) {
updatedPlayers.add(player);
player.setUpdateNeeded(false);
}
}
for (final Map.Entry<Vector2, Integer> tileState : setTileStates.entrySet()) {
this.room.getGamemap().updateTile(tileState.getKey(), tileState.getValue());
}
while (!this.chatMessages.isEmpty()) {
this.room.onPlayerChat(this.chatMessages.poll());
}
final List<RoomItem> toCycle = new GapList<>();
while (!itemCycleRequests.isEmpty()) {
toCycle.add(itemCycleRequests.poll());
}
for (final RoomItem item : toCycle) {
item.onCycle();
}
while (!this.roomMessageWriters.isEmpty()) {
messages.add(this.roomMessageWriters.poll());
}
if (updatedPlayers.size() > 0) {
messages.add(new RoomPlayerStatusListWriter(updatedPlayers));
}
while (!this.playersToRemove.isEmpty()) {
final RoomPlayer player = this.playersToRemove.poll();
this.room.getRoomPlayers().remove(player.getVirtualId());
this.room.onPlayerLeaves(player);
}
if (messages.size() > 0) {
for (final RoomPlayer player : this.room.getRoomPlayers().values()) {
if (player.isBot()) {
continue;
}
for (final MessageWriter message : messages) {
if (message.getSenderId() < 1 || player.getSession().getId() != message.getSenderId()) {
player.getSession().writeMessage(message);
}
}
}
}
while (!this.playersToAdd.isEmpty()) {
final RoomPlayer player = this.playersToAdd.poll();
this.room.getRoomPlayers().put(player.getVirtualId(), player);
this.room.onPlayerEnters(player);
}
room.getWiredHandler().onTriggerPeriodically();
final GapList<WiredDelayEvent> reAdd = new GapList<>();
while (!this.wiredItemDelay.isEmpty()) {
final WiredDelayEvent delayEvent = this.wiredItemDelay.poll();
delayEvent.getAction().onHandle(delayEvent.getPlayer(), delayEvent);
if (!delayEvent.isFinished()) {
reAdd.add(delayEvent);
}
}
for (final WiredDelayEvent delay : reAdd) {
this.wiredItemDelay.offer(delay);
}
if (this.updates == 0 || this.updates == 3) {
Bootloader.getGame().getNavigatorListManager().setRoom(room.getInformation(), room.getInformation().getTotalPlayers());
this.updates = 0;
}
this.updates++;
}
} |
3e00e95d7e0675ae4002f93058cf968eccd50d32 | 2,679 | java | Java | ready-work-core/src/main/java/work/ready/core/component/cache/CacheConfig.java | LyuWeihua/ReadyWork | d85d294c739d04052b6b4b365f0d3670564fc05e | [
"Apache-2.0"
] | 2 | 2021-09-29T17:26:31.000Z | 2021-11-02T10:26:14.000Z | ready-work-core/src/main/java/work/ready/core/component/cache/CacheConfig.java | LyuWeihua/ReadyWork | d85d294c739d04052b6b4b365f0d3670564fc05e | [
"Apache-2.0"
] | null | null | null | ready-work-core/src/main/java/work/ready/core/component/cache/CacheConfig.java | LyuWeihua/ReadyWork | d85d294c739d04052b6b4b365f0d3670564fc05e | [
"Apache-2.0"
] | null | null | null | 27.916667 | 80 | 0.70597 | 381 | /**
*
* Original work Copyright (c) 2015-2020, Michael Yang 杨福海 (envkt@example.com).
* Modified work Copyright (c) 2020 WeiHua Lyu [ready.work]
*
* 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 work.ready.core.component.cache;
import work.ready.core.component.cache.caffeine.CaffeineCache;
import work.ready.core.component.cache.redis.RedisCache;
import work.ready.core.component.redis.RedisConfig;
import work.ready.core.config.BaseConfig;
import java.util.HashMap;
import java.util.Map;
public class CacheConfig extends BaseConfig {
public static final String TYPE_IGNITE = "ignite";
public static final String TYPE_REDIS = "redis";
public static final String TYPE_CAFFEINE = "caffeine";
public static final String TYPE_NONE = "none";
final Map<String, Class<? extends Cache>> cacheProvider = new HashMap<>();
private String cacheType = TYPE_CAFFEINE;
private RedisConfig redis;
private int aopCacheLiveSeconds = 0;
private String aopCacheType;
private String dbCacheType;
public CacheConfig() {
cacheProvider.put(TYPE_NONE, DummyCache.class);
cacheProvider.put(TYPE_CAFFEINE, CaffeineCache.class);
cacheProvider.put(TYPE_REDIS, RedisCache.class);
}
public String getCacheType() {
return cacheType;
}
public void setCacheType(String cacheType) {
this.cacheType = cacheType;
}
public RedisConfig getRedis(){
return redis;
}
public void setRedis(RedisConfig redis){
this.redis = redis;
}
public int getAopCacheLiveSeconds() {
return aopCacheLiveSeconds;
}
public void setAopCacheLiveSeconds(int aopCacheLiveSeconds) {
this.aopCacheLiveSeconds = aopCacheLiveSeconds;
}
public String getAopCacheType() {
return aopCacheType;
}
public void setAopCacheType(String aopCacheType) {
this.aopCacheType = aopCacheType;
}
public String getDbCacheType() {
return dbCacheType;
}
public void setDbCacheType(String dbCacheType) {
this.dbCacheType = dbCacheType;
}
@Override
public void validate() {
}
}
|
3e00e9a10b29058b339f55d6f9c27fe8b9723eec | 2,966 | java | Java | agent/java/engine/src/main/java/com/baidu/openrasp/dependency/DependencyReport.java | G3G4X5X6/openrasp | a11eec7227b021215dc57c2c7fe8e3a63e466cda | [
"Apache-2.0"
] | 2,219 | 2017-08-10T11:47:31.000Z | 2022-03-29T08:58:56.000Z | agent/java/engine/src/main/java/com/baidu/openrasp/dependency/DependencyReport.java | ccoqueiro/openrasp | 11e64e509cba789bf169a7a4556f4d46469b6462 | [
"Apache-2.0"
] | 206 | 2017-08-14T02:37:15.000Z | 2022-03-31T23:01:00.000Z | agent/java/engine/src/main/java/com/baidu/openrasp/dependency/DependencyReport.java | ccoqueiro/openrasp | 11e64e509cba789bf169a7a4556f4d46469b6462 | [
"Apache-2.0"
] | 551 | 2017-08-10T11:47:41.000Z | 2022-03-30T12:29:47.000Z | 35.73494 | 101 | 0.711396 | 382 | /*
* Copyright 2017-2021 Baidu Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baidu.openrasp.dependency;
import com.baidu.openrasp.cloud.CloudHttp;
import com.baidu.openrasp.cloud.CloudTimerTask;
import com.baidu.openrasp.cloud.model.CloudCacheModel;
import com.baidu.openrasp.cloud.model.CloudRequestUrl;
import com.baidu.openrasp.cloud.model.GenericResponse;
import com.baidu.openrasp.cloud.utils.CloudUtils;
import com.baidu.openrasp.config.Config;
import com.baidu.openrasp.messaging.ErrorType;
import com.baidu.openrasp.messaging.LogTool;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.logging.Logger;
/**
* @description: 依赖检查上报
* @author: anyang
* @create: 2019/04/19 16:07
*/
public class DependencyReport extends CloudTimerTask {
public static final Logger LOGGER = Logger.getLogger(DependencyReport.class.getName());
private static int reportTimes = 0;
private static final int FIRST_INTERNAL = 15;
private static final int INIT_INTERNAL = 120;
public DependencyReport() {
super("OpenRASP Dependency Report Thread");
}
@Override
public long getSleepTime() {
if (reportTimes < 3) {
reportTimes++;
return FIRST_INTERNAL;
} else if (reportTimes < 6) {
reportTimes++;
return INIT_INTERNAL;
}
return Config.getConfig().getDependencyCheckInterval();
}
@Override
public void execute() {
HashSet<Dependency> dependencyHashSet = DependencyFinder.getDependencySet();
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("rasp_id", CloudCacheModel.getInstance().getRaspId());
parameters.put("dependency", dependencyHashSet);
LOGGER.info("start reporting " + dependencyHashSet.size() + " dependencies");
String url = CloudRequestUrl.CLOUD_DEPENDENCY_REPORT_URL;
GenericResponse response = new CloudHttp().commonRequest(url, new Gson().toJson(parameters));
if (!CloudUtils.checkResponse(response)) {
LogTool.warn(ErrorType.DEPENDENCY_REPORT_ERROR,
CloudUtils.handleError(ErrorType.DEPENDENCY_REPORT_ERROR, response));
}
}
@Override
public void handleError(Throwable t) {
LogTool.warn(ErrorType.REGISTER_ERROR, "dependency report failed: " + t.getMessage(), t);
}
}
|
3e00e9ee0d3a80aef51ae5f9f39a2df583bb3965 | 291 | java | Java | dutil-basic/src/main/java/com/dwarfeng/dutil/basic/prog/Loader.java | DwArFeng/DwarfFunction | d679e13afabc4a2ea0e100a3f7d0f0f6190d5a6a | [
"Apache-2.0"
] | 1 | 2017-01-15T14:13:22.000Z | 2017-01-15T14:13:22.000Z | dutil-basic/src/main/java/com/dwarfeng/dutil/basic/prog/Loader.java | DwArFeng/DwarfFunction | d679e13afabc4a2ea0e100a3f7d0f0f6190d5a6a | [
"Apache-2.0"
] | 2 | 2021-12-10T00:51:53.000Z | 2021-12-14T21:11:06.000Z | dutil-basic/src/main/java/com/dwarfeng/dutil/basic/prog/Loader.java | DwArFeng/DwarfFunction | d679e13afabc4a2ea0e100a3f7d0f0f6190d5a6a | [
"Apache-2.0"
] | null | null | null | 19.4 | 74 | 0.701031 | 383 | package com.dwarfeng.dutil.basic.prog;
/**
* 读取器。
* <p>
* 实现该接口意味着该对象能够将某些数据加载到指定的对象中。
*
* @deprecated 该类的位置不合理,已经由 {@link com.dwarfeng.dutil.basic.io.Loader}代替
* @author DwArFeng
* @since 0.0.3-beta
*/
public interface Loader<T> extends com.dwarfeng.dutil.basic.io.Loader<T> {
}
|
3e00ea0426db327602278cbe293bd8805ac95af9 | 534 | java | Java | LACCPlus/Hadoop/324_2.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | LACCPlus/Hadoop/324_2.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | LACCPlus/Hadoop/324_2.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | 25.428571 | 71 | 0.651685 | 384 | //,temp,TestDistCpViewFs.java,213,229,temp,TestIntegration.java,165,180
//,3
public class xxx {
private void caseSingleDirTargetMissing(boolean sync) {
try {
addEntries(listFile, "singledir");
mkdirs(root + "/singledir/dir1");
runTest(listFile, target, false, sync);
checkResult(target, 1, "dir1");
} catch (IOException e) {
LOG.error("Exception encountered while testing distcp", e);
Assert.fail("distcp failure");
} finally {
TestDistCpUtils.delete(fs, root);
}
}
}; |
3e00eb832fc347ad46498f8153a92f0a2b15db19 | 440 | java | Java | Course.java | xxCallum/apcsa | 5d95a391f6819dd56848167ade6c9e372b8a65e5 | [
"CC0-1.0"
] | null | null | null | Course.java | xxCallum/apcsa | 5d95a391f6819dd56848167ade6c9e372b8a65e5 | [
"CC0-1.0"
] | null | null | null | Course.java | xxCallum/apcsa | 5d95a391f6819dd56848167ade6c9e372b8a65e5 | [
"CC0-1.0"
] | null | null | null | 14.193548 | 45 | 0.584091 | 385 | //NOT AN ASSIGNMENT
public class Course
{
private String name;
public Course()
{
name = "";
}
public Course (String name)
{
this.name = name;
}
public String toString()
{
return "this course is " + name;
}
public void setName (String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void printName()
{
System.out.println("Welcome to " + name);
}
} |
3e00ec306187e9780dae6d8678bbc063d9af4243 | 11,019 | java | Java | OneSignalSDK/unittest/src/test/java/com/onesignal/ShadowOneSignalRestClient.java | mingalevme/OneSignal-Android-SDK | 59dce1c88c4a37faa4bd3bb4821ade759dde413c | [
"Apache-2.0"
] | 2 | 2019-08-05T08:25:25.000Z | 2020-01-19T04:37:27.000Z | OneSignalSDK/unittest/src/test/java/com/onesignal/ShadowOneSignalRestClient.java | mingalevme/OneSignal-Android-SDK | 59dce1c88c4a37faa4bd3bb4821ade759dde413c | [
"Apache-2.0"
] | null | null | null | OneSignalSDK/unittest/src/test/java/com/onesignal/ShadowOneSignalRestClient.java | mingalevme/OneSignal-Android-SDK | 59dce1c88c4a37faa4bd3bb4821ade759dde413c | [
"Apache-2.0"
] | 1 | 2019-12-01T03:34:26.000Z | 2019-12-01T03:34:26.000Z | 34.327103 | 132 | 0.682548 | 386 | /**
* Modified MIT License
*
* Copyright 2018 OneSignal
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* 1. The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 2. All copies of substantial portions of the Software may only be used in connection
* with services provided by OneSignal.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.onesignal;
import org.json.JSONException;
import org.json.JSONObject;
import org.robolectric.annotation.Implements;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
@Implements(OneSignalRestClient.class)
public class ShadowOneSignalRestClient {
public enum REST_METHOD {
GET, POST, PUT
}
public static class Request {
public REST_METHOD method;
public JSONObject payload;
public String url;
Request(REST_METHOD method, JSONObject payload, String url) {
this.method = method;
this.payload = payload;
this.url = url;
}
}
private static class PendingResponse {
boolean success;
String response;
OneSignalRestClient.ResponseHandler responseHandler;
Object waitingThread;
PendingResponse(boolean success, String response, OneSignalRestClient.ResponseHandler responseHandler) {
this.success = success;
this.response = response;
this.responseHandler = responseHandler;
}
PendingResponse(Object waitingThread) {
this.waitingThread = waitingThread;
}
}
public static JSONObject lastPost;
public static ArrayList<Request> requests;
public static String lastUrl;
public static boolean failNext, failNextPut, failAll, failPosts, failGetParams;
public static int failHttpCode;
public static String failResponse, nextSuccessResponse, nextSuccessfulGETResponse, nextSuccessfulRegistrationResponse;
public static Pattern nextSuccessfulGETResponsePattern;
public static int networkCallCount;
public static String pushUserId, emailUserId;
public static JSONObject paramExtras;
// Pauses any network callbacks from firing.
// Also blocks any sync network calls.
public static boolean freezeResponses;
private static ConcurrentHashMap<Object, PendingResponse> pendingResponses;
public static void resetStatics() {
pushUserId = "a2f7f967-e8cc-11e4-bed1-118f05be4511";
emailUserId = "b007f967-98cc-11e4-bed1-118f05be4522";
requests = new ArrayList<>();
lastPost = null;
networkCallCount = 0;
nextSuccessfulGETResponse = null;
nextSuccessfulGETResponsePattern = null;
failResponse = "{}";
nextSuccessfulRegistrationResponse = null;
nextSuccessResponse = null;
failNext = false;
failNextPut = false;
failAll = false;
failPosts = false;
failGetParams = false;
failHttpCode = 400;
paramExtras = null;
freezeResponses = false;
pendingResponses = new ConcurrentHashMap<>();
}
public static void unFreezeResponses() {
if (!freezeResponses)
return;
freezeResponses = false;
for (Object thread : pendingResponses.keySet()) {
if (thread instanceof Thread) {
System.out.println("Start thread notify: " + thread);
synchronized (thread) {
thread.notifyAll();
}
System.out.println("End thread notify: " + thread);
}
}
}
public static void setNextSuccessfulJSONResponse(JSONObject response) throws JSONException {
nextSuccessResponse = response.toString(1);
}
public static void setNextFailureJSONResponse(JSONObject response) throws JSONException {
failResponse = response.toString(1);
}
public static void setNextSuccessfulGETJSONResponse(JSONObject response) throws JSONException {
nextSuccessfulGETResponse = response.toString(1);
}
public static void setNextSuccessfulRegistrationResponse(JSONObject response) throws JSONException {
nextSuccessfulRegistrationResponse = response.toString(1);
}
private static void freezeSyncCall() {
if (!freezeResponses)
return;
Object toLock = Thread.currentThread();
pendingResponses.put(toLock, new PendingResponse(toLock));
synchronized (toLock) {
try {
toLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static boolean isAFrozenThread(Thread thread) {
synchronized (thread) {
boolean isIt = pendingResponses.containsKey(thread);
return isIt;
}
}
private static void trackRequest(REST_METHOD method, JSONObject payload, String url) {
if (method == REST_METHOD.POST || method == REST_METHOD.PUT)
lastPost = payload;
lastUrl = url;
networkCallCount++;
requests.add(new Request(method, payload, url));
System.out.println(networkCallCount + ":" + method + "@URL:" + url + "\nBODY: " + payload);
}
private static boolean suspendResponse(
boolean success,
String response,
OneSignalRestClient.ResponseHandler responseHandler) {
if (!freezeResponses || responseHandler == null)
return false;
pendingResponses.put(responseHandler, new PendingResponse(success, response, responseHandler));
return true;
}
private static boolean doFail(OneSignalRestClient.ResponseHandler responseHandler, boolean doFail) {
if (failNext || failAll || doFail) {
if (!suspendResponse(false, failResponse, responseHandler))
responseHandler.onFailure(failHttpCode, failResponse, new Exception());
failNext = failNextPut = false;
return true;
}
return false;
}
private static boolean doFail(OneSignalRestClient.ResponseHandler responseHandler) {
return doFail(responseHandler, false);
}
private static void mockPost(String url, JSONObject jsonBody, OneSignalRestClient.ResponseHandler responseHandler) {
if (doFail(responseHandler, failPosts)) return;
String retJson;
if (nextSuccessfulRegistrationResponse != null) {
retJson = nextSuccessfulRegistrationResponse;
nextSuccessfulRegistrationResponse = null;
}
else if (url.contains("on_session"))
retJson = "{}";
else {
int device_type = jsonBody.optInt("device_type", 0);
String id = device_type == 11 ? emailUserId : pushUserId;
retJson = "{\"id\": \"" + id + "\"}";
}
if (nextSuccessResponse != null) {
if (responseHandler != null) {
if (!suspendResponse(true, nextSuccessResponse, responseHandler))
responseHandler.onSuccess(nextSuccessResponse);
}
nextSuccessResponse = null;
}
else if (responseHandler != null) {
if (!suspendResponse(true, retJson, responseHandler))
responseHandler.onSuccess(retJson);
}
}
public static void post(String url, JSONObject jsonBody, OneSignalRestClient.ResponseHandler responseHandler) {
trackRequest(REST_METHOD.POST, jsonBody, url);
mockPost(url, jsonBody, responseHandler);
}
public static void postSync(String url, JSONObject jsonBody, OneSignalRestClient.ResponseHandler responseHandler) {
trackRequest(REST_METHOD.POST, jsonBody, url);
freezeSyncCall();
mockPost(url, jsonBody, responseHandler);
}
public static void putSync(String url, JSONObject jsonBody, OneSignalRestClient.ResponseHandler responseHandler) {
trackRequest(REST_METHOD.PUT, jsonBody, url);
freezeSyncCall();
if (doFail(responseHandler, failNextPut)) return;
String response = "{\"id\": \"" + pushUserId + "\"}";
if (!suspendResponse(true, response, responseHandler))
responseHandler.onSuccess(response);
}
public static void put(String url, JSONObject jsonBody, OneSignalRestClient.ResponseHandler responseHandler) {
trackRequest(REST_METHOD.PUT, jsonBody, url);
if (doFail(responseHandler, failNextPut)) return;
responseHandler.onSuccess("{}");
}
public static void get(final String url, final OneSignalRestClient.ResponseHandler responseHandler, String cacheKey) {
trackRequest(REST_METHOD.GET, null, url);
if (failGetParams && doFail(responseHandler, true)) return;
if (doNextSuccessfulGETResponse(url, responseHandler))
return;
if (nextSuccessResponse != null) {
responseHandler.onSuccess(nextSuccessResponse);
nextSuccessResponse = null;
}
else {
try {
JSONObject getResponseJson = new JSONObject(
"{\"awl_list\": {}, \"android_sender_id\": \"87654321\"}"
);
if (paramExtras != null) {
Iterator<String> keys = paramExtras.keys();
while(keys.hasNext()) {
String key = keys.next();
getResponseJson.put(key, paramExtras.get(key));
}
}
responseHandler.onSuccess(getResponseJson.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public static void getSync(final String url, final OneSignalRestClient.ResponseHandler responseHandler, String cacheKey) {
trackRequest(REST_METHOD.GET, null, url);
if (doFail(responseHandler)) return;
if (doNextSuccessfulGETResponse(url, responseHandler))
return;
responseHandler.onSuccess("{}");
}
private static boolean doNextSuccessfulGETResponse(final String url, final OneSignalRestClient.ResponseHandler responseHandler) {
if (nextSuccessfulGETResponse != null &&
(nextSuccessfulGETResponsePattern == null || nextSuccessfulGETResponsePattern.matcher(url).matches())) {
responseHandler.onSuccess(nextSuccessfulGETResponse);
nextSuccessfulGETResponse = null;
return true;
}
return false;
}
}
|
3e00ed04990943a8a7d01f7d267adb68bdcd4905 | 10,719 | java | Java | eclipse/plugins/it.mdc.tool/src/it/mdc/tool/core/NetworkClockDomainCombiner.java | mdc-suite/mdc | ba79bdc3ea11fe538100b43b07baab850a324fc1 | [
"BSD-3-Clause"
] | 8 | 2019-09-05T14:24:44.000Z | 2021-07-12T08:34:44.000Z | eclipse/plugins/it.mdc.tool/src/it/mdc/tool/core/NetworkClockDomainCombiner.java | mdc-suite/mdc | ba79bdc3ea11fe538100b43b07baab850a324fc1 | [
"BSD-3-Clause"
] | 2 | 2020-10-26T12:53:48.000Z | 2020-12-09T04:24:18.000Z | eclipse/plugins/it.mdc.tool/src/it/mdc/tool/core/NetworkClockDomainCombiner.java | mdc-suite/mdc | ba79bdc3ea11fe538100b43b07baab850a324fc1 | [
"BSD-3-Clause"
] | 1 | 2022-01-12T11:57:13.000Z | 2022-01-12T11:57:13.000Z | 38.010638 | 93 | 0.647355 | 387 | /*
* Copyright (c) 2013, Ecole Polytechnique Fédérale de Lausanne
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the Ecole Polytechnique Fédérale de Lausanne nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package it.mdc.tool.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
* TODO Add description and comments
* @author
*
*/
public class NetworkClockDomainCombiner {
private class ClockDomainParser {
private static final String ELM_CLOCK_RATIO = "clockRatio";
private static final String ELM_DOMAIN = "domain";
private static final String ELM_ACTOR = "actor";
public ClockDomainParser(String clockDomainFile,
Map<String,Set<String>> clockDomains) {
File inputFile = new File(clockDomainFile);
Set<String> actorSet = new HashSet<String>();
String domain = "";
try {
InputStream inStream = new FileInputStream(inputFile);
XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
try {
XMLStreamReader reader = xmlFactory
.createXMLStreamReader(inStream);
while (reader.hasNext()) {
reader.next();
if (reader.getEventType() == XMLStreamReader.START_ELEMENT
&& reader.getLocalName().equals(ELM_DOMAIN)) {
domain = reader.getAttributeValue("", ELM_CLOCK_RATIO);
actorSet = new HashSet<String>();
} else if (reader.getEventType() == XMLStreamReader.START_ELEMENT
&& reader.getLocalName().equals(ELM_ACTOR)) {
String actor = reader.getElementText();
actorSet.add(actor);
} else if (reader.getEventType() == XMLStreamReader.END_ELEMENT
&& reader.getLocalName().equals(ELM_DOMAIN)) {
clockDomains.put(domain, actorSet);
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private Map<String,Set<String>> clockDomains;
private Map<String,Map<String,Set<String>>> clockDomainMap;
private Map<String,Map<String,String>> networkVertexMap;
public NetworkClockDomainCombiner(List<String> clockDomainFileList,
Map<String,Map<String,String>> networkVertexMap) {
this.networkVertexMap = networkVertexMap;
clockDomainMap = new HashMap<String,Map<String,Set<String>>>();
// Parse the Xml File
for(String clockDomainFile : clockDomainFileList) {
Map<String,Set<String>> map = new HashMap<String,Set<String>>();
new ClockDomainParser(clockDomainFile, map);
clockDomainMap.put(clockDomainFile.split("report_partitioning_")[1].replace(".xml", "")
.replace(".xml",""),map);
}
}
public void combineClockDomain() {
clockDomains = new HashMap<String,Set<String>>();
CleanActorNames();
// for each merged network
for(String network : clockDomainMap.keySet()) {
// if clock domain is empty set the network clock domain as initial configuration
if(clockDomains.isEmpty()) {
for(String domain : clockDomainMap.get(network).keySet()) {
Set<String> actors = new HashSet<String>();
for(String actor : clockDomainMap.get(network).get(domain)) {
if(networkVertexMap.get(network).containsKey(actor)) {
actors.add(networkVertexMap.get(network).get(actor));
}
}
clockDomains.put(domain,actors);
}
} else {
boolean associated = false;
Map<String,Set<String>> newDomains = new HashMap<String,Set<String>>();
Map<String,Set<String>> updDomains = new HashMap<String,Set<String>>();
Map<String,Set<String>> rmvDomains = new HashMap<String,Set<String>>();
int n=1;
// for each domain in the current network clock domains
for(String domain : clockDomainMap.get(network).keySet()) {
// for each actor in this domain
for(String actor : clockDomainMap.get(network).get(domain)) {
// for each already set domain
for(String alreadySetDomain : clockDomains.keySet()) {
// for each already set actor
for(String alreadySetActor : clockDomains.get(alreadySetDomain)) {
// if the current actor is equal to the already set actor
if(networkVertexMap.get(network).containsKey(actor)) {
if(networkVertexMap.get(network).get(actor).equals(alreadySetActor)) {
// if the domain period is smaller than the domain of the already set actor
if(Float.parseFloat(domain)<Float.parseFloat(alreadySetDomain)) {
System.out.println("upd " + actor + " from " + alreadySetDomain + " to " + domain
+ "(tot " + n + ")");
n++;
// remove the already set actor from the already set domain
//clockDomains.get(alreadySetDomain).remove(alreadySetActor);
if(rmvDomains.containsKey(alreadySetDomain)) {
rmvDomains.get(alreadySetDomain).add(alreadySetActor);
} else {
Set<String> set = new HashSet<String>();
set.add(alreadySetActor);
rmvDomains.put(alreadySetDomain,set);
}
// if the current clock domain is already set
if(clockDomains.containsKey(domain)) {
// put the actor in the new domain
//clockDomains.get(domain).add(networkVertexMap.get(network).get(actor));
if(updDomains.containsKey(domain)) {
updDomains.get(domain).add(alreadySetActor);
} else {
Set<String> set = new HashSet<String>();
set.add(alreadySetActor);
updDomains.put(domain,set);
}
} else {
// add a new domain with the current actor
/*Set<String> set = new HashSet<String>();
set.add(networkVertexMap.get(network).get(actor));
clockDomains.put(domain,set);
*/if(newDomains.containsKey(domain)) {
newDomains.get(domain).add(alreadySetActor);
} else {
Set<String> set = new HashSet<String>();
set.add(alreadySetActor);
newDomains.put(domain,set);
}
}
}
// the actor has been already set
associated = true;
}
}
}
}
// Update clock domains
for(String rmvDomain : rmvDomains.keySet()) {
clockDomains.get(rmvDomain).removeAll(rmvDomains.get(rmvDomain));
}
for(String updDomain : updDomains.keySet()) {
clockDomains.get(updDomain).addAll(updDomains.get(updDomain));
}
for(String newDomain : newDomains.keySet()) {
Set<String> set = new HashSet<String>();
set.addAll(newDomains.get(newDomain));
clockDomains.put(newDomain,set);
}
// if the actor has not been already set (it is not a shared actor)
if(!associated) {
// if the current clock domain is already set
if(clockDomains.containsKey(domain)) {
// put the actor in the new domain
clockDomains.get(domain).add(networkVertexMap.get(network).get(actor));
} else {
// add a new domain with the current actor
Set<String> set = new HashSet<String>();
set.add(networkVertexMap.get(network).get(actor));
clockDomains.put(domain,set);
}
associated = false;
newDomains = new HashMap<String,Set<String>>();
updDomains = new HashMap<String,Set<String>>();
rmvDomains = new HashMap<String,Set<String>>();
}
}
}
}
}
//System.out.println("combined domains: " + clockDomains);
}
public Map<String,Set<String>> getClockDomains() {
return clockDomains;
}
private void CleanActorNames() {
for(String network : networkVertexMap.keySet()) {
Map<String,List<Map<String,String>>> domainMap =
new HashMap<String,List<Map<String,String>>>();
for(String domain : clockDomainMap.get(network).keySet()) {
List<Map<String,String>> actorSubs =
new ArrayList<Map<String,String>>();
for(String actor : clockDomainMap.get(network).get(domain)) {
for(String mappedActor : networkVertexMap.get(network).keySet()) {
if(actor.contains(mappedActor.toLowerCase())) {
Map<String,String> actorMap = new HashMap<String,String>();
actorMap.put(actor, mappedActor);
actorSubs.add(actorMap);
}
}
}
domainMap.put(domain, actorSubs);
}
for(String domain : domainMap.keySet()) {
for(Map<String,String> actorMap : domainMap.get(domain)) {
clockDomainMap.get(network).get(domain).removeAll(actorMap.keySet());
clockDomainMap.get(network).get(domain).addAll(actorMap.values());
}
}
// TODO \todo possibile problema per le porte che potrebbero generare falsi matching
}
};
}
|
3e00ed643bc8381a3fa33fc84d33e0b4c75da235 | 2,849 | java | Java | src/main/java/com/aceql/client/jdbc/AceQLException.java | chenyiwan/aceql-http-client-sdk | 943ade9de67b331a9d47873a8948ec6d67ef3bbd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/aceql/client/jdbc/AceQLException.java | chenyiwan/aceql-http-client-sdk | 943ade9de67b331a9d47873a8948ec6d67ef3bbd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/aceql/client/jdbc/AceQLException.java | chenyiwan/aceql-http-client-sdk | 943ade9de67b331a9d47873a8948ec6d67ef3bbd | [
"Apache-2.0"
] | null | null | null | 34.325301 | 100 | 0.598105 | 388 | /*
* This file is part of AceQL Client SDK.
* AceQL Client SDK: Remote JDBC access over HTTP with AceQL HTTP.
* Copyright (C) 2020, KawanSoft SAS
* (http://www.kawansoft.com). 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.aceql.client.jdbc;
import java.sql.SQLException;
/**
* Wrapper class for Exceptions thrown on client side or server side.
*
* @author Nicolas de Pomereu
*
*/
public class AceQLException extends SQLException {
private static final long serialVersionUID = 1L;
private int httpStatusCode;
private String remoteStackTrace;
/**
* Builds an AceQLException that wraps/traps an Exception.
*
* @param reason
* the error message
* @param vendorCode
* The error type:
* <ul>
* <li>0 for local Exception.</li>
* <li>1 for JDBC Driver Exception on the server.</li>
* <li>2 for AceQL Exception on the server.</li>
* <li>3 for AceQL Security Exception on the server.</li>
* <li>4 for AceQL failure.</li>
* </ul>
* @param cause
* the wrapped/trapped Exception
* @param remoteStackTrace
* the stack trace in case for remote Exception
* @param httpStatusCode
* the http status code
*/
public AceQLException(String reason, int vendorCode, Throwable cause,
String remoteStackTrace, int httpStatusCode) {
super(reason, null, vendorCode, cause);
this.remoteStackTrace = remoteStackTrace;
this.httpStatusCode = httpStatusCode;
}
/**
* Returns the http status code associated to the Exception
*
* @return the http status code associated to the Exception
*/
public int getHttpStatusCode() {
return httpStatusCode;
}
/**
* Returns the stack trace of the Exception thrown on server side
*
* @return the stack trace of the Exception thrown on server side
*/
public String getRemoteStackTrace() {
return remoteStackTrace;
}
}
|
3e00ed667d695da284260c7aa3a8b115e1f2b097 | 397 | java | Java | gulimall-member/src/main/java/com/vivi/gulimall/member/dao/MemberCollectSpuDao.java | leige1027/gulimall | 3fdc3b1f98bcd44383992db269304c84528e1a88 | [
"Apache-2.0"
] | 33 | 2021-02-20T03:20:37.000Z | 2022-03-29T15:21:57.000Z | gulimall-member/src/main/java/com/vivi/gulimall/member/dao/MemberCollectSpuDao.java | ZhangGR123/gulimall | dda2975ea5e9200090b2c1a93b08d1c1693685b8 | [
"Apache-2.0"
] | null | null | null | gulimall-member/src/main/java/com/vivi/gulimall/member/dao/MemberCollectSpuDao.java | ZhangGR123/gulimall | dda2975ea5e9200090b2c1a93b08d1c1693685b8 | [
"Apache-2.0"
] | 14 | 2021-03-15T08:27:21.000Z | 2022-03-19T08:02:41.000Z | 21.833333 | 81 | 0.776081 | 389 | package com.vivi.gulimall.member.dao;
import com.vivi.gulimall.member.entity.MemberCollectSpuEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 会员收藏的商品
*
* @author wanwgei
* @email hzdkv@example.com
* @date 2020-09-13 10:51:13
*/
@Mapper
public interface MemberCollectSpuDao extends BaseMapper<MemberCollectSpuEntity> {
}
|
3e00f05359d226e9d21373aecf63023951566015 | 1,885 | java | Java | efluid-datagate-common/src/main/java/fr/uem/efluid/model/shared/ExportAwareProject.java | efluid/datagate | 0181409ea67bc93d682f360c2039f29f36aa248b | [
"Apache-2.0"
] | 7 | 2019-07-18T06:39:51.000Z | 2021-12-16T14:30:44.000Z | efluid-datagate-common/src/main/java/fr/uem/efluid/model/shared/ExportAwareProject.java | efluid/datagate | 0181409ea67bc93d682f360c2039f29f36aa248b | [
"Apache-2.0"
] | 9 | 2020-03-13T16:11:38.000Z | 2022-01-20T09:30:13.000Z | efluid-datagate-common/src/main/java/fr/uem/efluid/model/shared/ExportAwareProject.java | efluid/datagate | 0181409ea67bc93d682f360c2039f29f36aa248b | [
"Apache-2.0"
] | 4 | 2020-02-28T15:17:13.000Z | 2022-02-11T10:15:55.000Z | 22.987805 | 83 | 0.550133 | 390 | package fr.uem.efluid.model.shared;
import fr.uem.efluid.model.Shared;
import fr.uem.efluid.model.SharedDictionary;
import fr.uem.efluid.utils.SharedOutputInputUtils;
import java.time.LocalDateTime;
/**
* <p>
* Shared information on top level organization : data is managed in projects
* </p>
*
* @author elecomte
* @version 1
* @since v0.2.0
*/
public abstract class ExportAwareProject implements Shared {
/**
* @return
*/
public abstract String getName();
/**
* @return
*/
public abstract int getColor();
public abstract LocalDateTime getCreatedTime();
/**
* @return
* @see fr.uem.efluid.model.Shared#serialize()
*/
@Override
public final String serialize() {
return SharedOutputInputUtils.newJson()
.with("uid", getUuid())
.with("cre", getCreatedTime())
.with("nam", getName())
.with("col", getColor())
.toString();
}
/**
* @return
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getUuid() == null) ? 0 : getUuid().hashCode());
return result;
}
/**
* @param obj
* @return
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ExportAwareProject other = (ExportAwareProject) obj;
if (this.getUuid() == null) {
if (other.getUuid() != null)
return false;
} else if (!getUuid().equals(other.getUuid()))
return false;
return true;
}
}
|
3e00f0862b3feefe1f7fa23f035cd50ce97e81fc | 2,295 | java | Java | runelite-api/src/main/java/net/runelite/api/widgets/Widget.java | crackint/runelite-runelite-parent-1.2.11 | 96a8d4a0bf61c45d60af394dd019318b30deec6e | [
"BSD-2-Clause"
] | null | null | null | runelite-api/src/main/java/net/runelite/api/widgets/Widget.java | crackint/runelite-runelite-parent-1.2.11 | 96a8d4a0bf61c45d60af394dd019318b30deec6e | [
"BSD-2-Clause"
] | null | null | null | runelite-api/src/main/java/net/runelite/api/widgets/Widget.java | crackint/runelite-runelite-parent-1.2.11 | 96a8d4a0bf61c45d60af394dd019318b30deec6e | [
"BSD-2-Clause"
] | null | null | null | 24.677419 | 82 | 0.749455 | 391 | /*
* Copyright (c) 2017, Adam <ychag@example.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.api.widgets;
import java.awt.Rectangle;
import java.util.Collection;
import net.runelite.api.Point;
public interface Widget
{
int getId();
int getType();
int getContentType();
Widget getParent();
int getParentId();
Widget getChild(int index);
Widget[] getDynamicChildren();
Widget[] getStaticChildren();
Widget[] getNestedChildren();
int getRelativeX();
void setRelativeX(int x);
int getRelativeY();
void setRelativeY(int y);
String getText();
void setText(String text);
int getTextColor();
String getName();
int getModelId();
int getSpriteId();
boolean isHidden();
void setHidden(boolean hidden);
Point getCanvasLocation();
int getWidth();
int getHeight();
Rectangle getBounds();
Collection<WidgetItem> getWidgetItems();
WidgetItem getWidgetItem(int index);
int getItemId();
int getItemQuantity();
boolean contains(Point point);
}
|
3e00f19db9bf4463c5d132f907b6235207a376fd | 1,089 | java | Java | java/api/src/main/java/jp/ad/sinet/stream/spi/PluginMessageWriter.java | nii-gakunin-cloud/sinetstream | abcf8ce800c9970bb51b2eaff54f3845c40c114f | [
"Apache-2.0"
] | 5 | 2020-03-24T15:28:53.000Z | 2022-03-18T06:59:42.000Z | java/api/src/main/java/jp/ad/sinet/stream/spi/PluginMessageWriter.java | nii-gakunin-cloud/sinetstream | abcf8ce800c9970bb51b2eaff54f3845c40c114f | [
"Apache-2.0"
] | null | null | null | java/api/src/main/java/jp/ad/sinet/stream/spi/PluginMessageWriter.java | nii-gakunin-cloud/sinetstream | abcf8ce800c9970bb51b2eaff54f3845c40c114f | [
"Apache-2.0"
] | 3 | 2020-03-24T15:28:52.000Z | 2021-04-01T14:51:42.000Z | 32.029412 | 63 | 0.737374 | 392 | /*
* Copyright (C) 2020 National Institute of Informatics
*
* 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 jp.ad.sinet.stream.spi;
public interface PluginMessageWriter extends PluginMessageIO {
void write(byte[] message);
String getTopic();
default boolean isThreadSafe() {
return false;
}
}
|
3e00f2bf6f1cf51eddea68074345668481fe8635 | 3,442 | java | Java | src/main/java/cc/moecraft/icq/sender/HttpApiNode.java | CrazyKidCN/PicqBotX | c9f8cd02a8ae0fb5845b2549c979c9297948acf6 | [
"MIT"
] | 260 | 2018-05-27T01:00:19.000Z | 2022-03-23T07:33:13.000Z | src/main/java/cc/moecraft/icq/sender/HttpApiNode.java | CrazyKidCN/PicqBotX | c9f8cd02a8ae0fb5845b2549c979c9297948acf6 | [
"MIT"
] | 46 | 2018-06-14T00:32:51.000Z | 2020-12-31T00:21:58.000Z | src/main/java/cc/moecraft/icq/sender/HttpApiNode.java | CrazyKidCN/PicqBotX | c9f8cd02a8ae0fb5845b2549c979c9297948acf6 | [
"MIT"
] | 94 | 2018-06-04T19:43:25.000Z | 2021-11-19T08:32:20.000Z | 39.563218 | 70 | 0.570017 | 393 | package cc.moecraft.icq.sender;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* The enum {@code HttpApiNode} contains the api nodes and their info.
* <p>
* Class created by the HyDEV Team on 2019-03-25!
*
* @author HyDEV Team (https://github.com/HyDevelop)
* @author Hykilpikonna (https://github.com/hykilpikonna)
* @author Vanilla (https://github.com/VergeDX)
* @since 2019-03-25 07:25
*/
@Getter
@AllArgsConstructor
public enum HttpApiNode
{
// 发送区
SEND_PRIVATE_MSG ("send_private_msg", true),
SEND_GROUP_MSG ("send_group_msg", true),
SEND_DISCUSS_MSG ("send_discuss_msg", true),
SEND_LIKE ("send_like", true),
DELETE_MSG ("delete_msg", true),
SEND_GROUP_NOTICE ("_send_group_notice", true),
// 获取区
GET_MSG ("get_msg", true),
// 应用设置区
SET_GROUP_KICK ("set_group_kick", true),
SET_GROUP_BAN ("set_group_ban", true),
SET_GROUP_ANONYMOUS_BAN ("set_group_anonymous_ban", true),
SET_GROUP_WHOLE_BAN ("set_group_whole_ban", true),
SET_GROUP_ADMIN ("set_group_admin", true),
SET_GROUP_ANONYMOUS ("set_group_anonymous", true),
SET_GROUP_CARD ("set_group_card", true),
SET_GROUP_LEAVE ("set_group_leave", true),
SET_GROUP_SPECIAL_TITLE ("set_group_special_title", true),
SET_DISCUSS_LEAVE ("set_discuss_leave", true),
SET_FRIEND_ADD_REQUEST ("set_friend_add_request", true),
SET_GROUP_ADD_REQUEST ("set_group_add_request", true),
// ICQ(酷Q, 以及HTTP插件)设置区
SET_RESTART ("_set_restart", true),
SET_RESTART_PLUGIN ("set_restart_plugin", true),
CLEAN_DATA_DIR ("clean_data_dir", true),
CLEAN_PLUGIN_LOG ("clean_plugin_log", true),
// 应用内获取区
GET_LOGIN_INFO ("get_login_info", false),
GET_STRANGER_INFO ("get_stranger_info", false),
GET_GROUP_LIST ("get_group_list", false),
GET_GROUP_MEMBER_INFO ("get_group_member_info", false),
GET_GROUP_MEMBER_LIST ("get_group_member_list", false),
GET_FRIEND_LIST_NEW ("get_friend_list", false),
GET_FRIEND_LIST_OLD ("_get_friend_list", false),
GET_GROUP_INFO_NEW ("get_group_info", false),
GET_GROUP_INFO_OLD ("_get_group_info", false),
GET_VIP_INFO ("_get_vip_info", false),
GET_RECORD ("get_record", false),
GET_IMAGE ("get_image", false),
GET_GROUP_NOTICE ("_get_group_notice", false),
// 条件判断区
CAN_SEND_IMAGE ("can_send_image", false),
CAN_SEND_RECORD ("can_send_record", false),
// ICQ(酷Q, 以及HTTP插件)获取区
GET_VERSION_INFO ("get_version_info", false),
GET_STATUS ("get_status", false),
GET_COOKIES ("get_cookies", false),
GET_CSRF_TOKEN ("get_csrf_token", false),
GET_CREDENTIALS ("get_credentials", false);
/**
* 子URL
*/
private String subUrl;
/**
* 能不能异步调用
*/
private boolean canAsync;
}
|
3e00f417533c77b7856559fac92e4011a829ba13 | 1,617 | java | Java | src/main/java/org/jetbrains/research/refactorinsight/data/types/attributes/SplitAttributeHandler.java | ElenaErratic/RefactorInsight | aefb30ccc60535d4a83a0b9e2c1e1a83cf13cea1 | [
"MIT"
] | 40 | 2020-07-10T18:58:35.000Z | 2020-08-17T15:46:30.000Z | src/main/java/org/jetbrains/research/refactorinsight/data/types/attributes/SplitAttributeHandler.java | ElenaErratic/RefactorInsight | aefb30ccc60535d4a83a0b9e2c1e1a83cf13cea1 | [
"MIT"
] | 33 | 2020-07-06T08:39:17.000Z | 2020-09-01T07:19:21.000Z | src/main/java/org/jetbrains/research/refactorinsight/data/types/attributes/SplitAttributeHandler.java | ElenaErratic/RefactorInsight | aefb30ccc60535d4a83a0b9e2c1e1a83cf13cea1 | [
"MIT"
] | 4 | 2020-07-19T16:52:42.000Z | 2020-08-05T15:55:23.000Z | 41.461538 | 114 | 0.771181 | 394 | package org.jetbrains.research.refactorinsight.data.types.attributes;
import gr.uom.java.xmi.decomposition.VariableDeclaration;
import gr.uom.java.xmi.diff.SplitAttributeRefactoring;
import java.util.stream.Collectors;
import org.jetbrains.research.refactorinsight.adapters.CodeRange;
import org.jetbrains.research.refactorinsight.data.Group;
import org.jetbrains.research.refactorinsight.data.RefactoringInfo;
import org.jetbrains.research.refactorinsight.data.types.Handler;
import org.refactoringminer.api.Refactoring;
public class SplitAttributeHandler extends Handler {
@Override
public RefactoringInfo specify(Refactoring refactoring, RefactoringInfo info) {
SplitAttributeRefactoring ref = (SplitAttributeRefactoring) refactoring;
ref.getSplitAttributes().forEach(attr ->
info.addMarking(new CodeRange(ref.getOldAttribute().codeRange()), new CodeRange(attr.codeRange()), true));
String classNameBefore = ref.getClassNameBefore();
String classNameAfter = ref.getClassNameAfter();
return info.setGroup(Group.ATTRIBUTE)
.setDetailsBefore(classNameBefore)
.setDetailsAfter(classNameAfter)
.setNameBefore(ref.getOldAttribute().getVariableName())
.setNameAfter(ref.getSplitAttributes().stream().map(VariableDeclaration::getVariableName)
.collect(Collectors.joining()));
}
@Override
public RefactoringInfo specify(org.jetbrains.research.kotlinrminer.api.Refactoring refactoring,
RefactoringInfo info) {
//This kind of refactoring is not supported by kotlinRMiner yet.
return null;
}
} |
3e00f4cc74bcff349aa0277d6d2f9e1dcff2ea0c | 4,803 | java | Java | src/main/java/org/akomantoso/schema/v3/csd11/Step.java | lewismc/akomantoso-lib | 438f7b8956cbcab29788128c3b7b807dacb92f01 | [
"Apache-2.0"
] | 2 | 2015-12-29T14:57:01.000Z | 2018-02-15T20:56:06.000Z | src/main/java/org/akomantoso/schema/v3/csd11/Step.java | lewismc/akomantoso-lib | 438f7b8956cbcab29788128c3b7b807dacb92f01 | [
"Apache-2.0"
] | 11 | 2015-01-07T15:58:37.000Z | 2017-07-04T16:27:22.000Z | src/main/java/org/akomantoso/schema/v3/csd11/Step.java | lewismc/akomantoso-lib | 438f7b8956cbcab29788128c3b7b807dacb92f01 | [
"Apache-2.0"
] | 1 | 2016-09-04T11:57:20.000Z | 2016-09-04T11:57:20.000Z | 25.278947 | 122 | 0.580679 | 395 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.01.16 at 12:56:36 PM IST
//
package org.akomantoso.schema.v3.csd11;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD11}anyOtherType">
* <attGroup ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD11}date"/>
* <attGroup ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD11}outcome"/>
* <attGroup ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD11}role"/>
* <attGroup ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD11}refers"/>
* <attGroup ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD11}actor"/>
* <anyAttribute processContents='lax' namespace='##other'/>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "step")
public class Step
extends AnyOtherType
{
@XmlAttribute(name = "date", required = true)
protected String date;
@XmlAttribute(name = "outcome")
@XmlSchemaType(name = "anyURI")
protected String outcome;
@XmlAttribute(name = "as")
@XmlSchemaType(name = "anyURI")
protected String as;
@XmlAttribute(name = "refersTo")
protected List<String> refersTo;
@XmlAttribute(name = "actor")
@XmlSchemaType(name = "anyURI")
protected String actor;
/**
* Gets the value of the date property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDate() {
return date;
}
/**
* Sets the value of the date property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDate(String value) {
this.date = value;
}
/**
* Gets the value of the outcome property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOutcome() {
return outcome;
}
/**
* Sets the value of the outcome property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOutcome(String value) {
this.outcome = value;
}
/**
* Gets the value of the as property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAs() {
return as;
}
/**
* Sets the value of the as property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAs(String value) {
this.as = value;
}
/**
* Gets the value of the refersTo property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the refersTo property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRefersTo().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getRefersTo() {
if (refersTo == null) {
refersTo = new ArrayList<String>();
}
return this.refersTo;
}
/**
* Gets the value of the actor property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getActor() {
return actor;
}
/**
* Sets the value of the actor property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setActor(String value) {
this.actor = value;
}
}
|
3e00f4f0106e742924357032473f1ab8efdbd2fd | 4,595 | java | Java | app/src/main/java/net/selsela/carRental/ui/explore/ExploreFragment.java | salmaziada/pp | 1eeea96ff008c81c37dce95e1a93b3139b800f96 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/net/selsela/carRental/ui/explore/ExploreFragment.java | salmaziada/pp | 1eeea96ff008c81c37dce95e1a93b3139b800f96 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/net/selsela/carRental/ui/explore/ExploreFragment.java | salmaziada/pp | 1eeea96ff008c81c37dce95e1a93b3139b800f96 | [
"Apache-2.0"
] | null | null | null | 33.297101 | 175 | 0.702067 | 396 | package net.selsela.carRental.ui.explore;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import net.selsela.carRental.R;
import net.selsela.carRental.ui.base.BaseFragment;
import net.selsela.carRental.ui.explore.adapter.AllCarAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class ExploreFragment extends BaseFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
@BindView(R.id.label)
TextView label;
@BindView(R.id.car_list)
RecyclerView carList;
Unbinder unbinder;
@BindView(R.id.filter)
ImageView filter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private BottomSheetDialog mBottomSheetDialog;
public ExploreFragment() {
}
public static ExploreFragment newInstance(String param1, String param2) {
ExploreFragment fragment = new ExploreFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_explore, container, false);
unbinder = ButterKnife.bind(this, view);
getActivityComponent().inject(this);
carList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
carList.setAdapter(new AllCarAdapter(getContext(), new AllCarAdapter.UpdateDataClickListener() {
}));
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@OnClick(R.id.filter)
public void onViewClicked() {
filter_dialoge();
}
public void filter_dialoge() {
mBottomSheetDialog = new BottomSheetDialog(getContext());
View sheetView = getLayoutInflater().inflate(R.layout.filter_bottom_sheet, null);
mBottomSheetDialog.setContentView(sheetView);
mBottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackground(getContext().getResources().getDrawable(R.drawable.shape_button_sheet_background));
BottomSheetBehavior mBottomSheetBehavior = BottomSheetBehavior.from(((View) sheetView.getParent()));
mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
mBottomSheetBehavior.setSkipCollapsed(true);
final TextView automatic_action=mBottomSheetDialog.findViewById(R.id.automatic_action);
final TextView normal_action=mBottomSheetDialog.findViewById(R.id.normal_action);
final ImageView dismiss_action = mBottomSheetDialog.findViewById(R.id.dismiss_action);
dismiss_action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBottomSheetDialog.dismiss();
}
});
automatic_action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
automatic_action.setBackground(getActivity().getDrawable(R.drawable.rec5_black));
normal_action.setBackground(getActivity().getDrawable(R.drawable.rec5_orange));
}
});
normal_action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
normal_action.setBackground(getActivity().getDrawable(R.drawable.rec5_black));
automatic_action.setBackground(getActivity().getDrawable(R.drawable.rec5_orange));
}
});
mBottomSheetDialog.show();
}
}
|
3e00f540cea89bb9d478861870a799021be3e12a | 10,548 | java | Java | SQLiteCrudExpandable/app/src/main/java/com/example/alexey/sqlitecrudexpandable/DatabaseAdapter.java | AlexeyBuryanov/SimpleAndroidProjects | 3a008021baedf155303cd02dea3db6e95dcbe9ac | [
"MIT"
] | null | null | null | SQLiteCrudExpandable/app/src/main/java/com/example/alexey/sqlitecrudexpandable/DatabaseAdapter.java | AlexeyBuryanov/SimpleAndroidProjects | 3a008021baedf155303cd02dea3db6e95dcbe9ac | [
"MIT"
] | null | null | null | SQLiteCrudExpandable/app/src/main/java/com/example/alexey/sqlitecrudexpandable/DatabaseAdapter.java | AlexeyBuryanov/SimpleAndroidProjects | 3a008021baedf155303cd02dea3db6e95dcbe9ac | [
"MIT"
] | null | null | null | 51.453659 | 136 | 0.675199 | 397 | package com.example.alexey.sqlitecrudexpandable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
/**
* Created by Alexey on 31.01.2018.
* Фактически репозиторий данных для упрощённой работы с базой.
*/
public class DatabaseAdapter {
private DatabaseHelper _dbHelper;
private SQLiteDatabase _database;
public DatabaseAdapter (Context context) {
_dbHelper = new DatabaseHelper(context.getApplicationContext());
}
public DatabaseAdapter open() {
_database = _dbHelper.getWritableDatabase();
return this;
}
public void close(){
_dbHelper.close();
}
//private Cursor getAllAuthors() {
// return _database.query(DatabaseHelper.AUTHORS_TABLE, DatabaseHelper.COLUMNS_AUTHORS,
// null, null, null, null, null);
//}
public Cursor getAllPublishers() {
return _database.query(DatabaseHelper.PUBLISHERS_TABLE, DatabaseHelper.COLUMNS_PUBLISHERS,
null, null, null, null, null);
}
public Cursor getAllTitles() {
return _database.query(DatabaseHelper.TITLES_TABLE, DatabaseHelper.COLUMNS_TITLES,
null, null, null, null, null);
}
public Cursor getAllTitles(int pubId) {
Cursor cursor = _database.query(DatabaseHelper.TITLES_TABLE, DatabaseHelper.COLUMNS_TITLES,
DatabaseHelper.COL_PUBLISHER_ID + " = " + String.valueOf(pubId),
null, null, null, null);
if (cursor != null) cursor.moveToFirst();
return cursor;
}
//public ArrayList<Author> getAuthors() {
// ArrayList<Author> authors = new ArrayList<>();
// Cursor cursor = getAllAuthors();
// if (cursor.moveToFirst()) {
// do {
// int id = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COL_AUTHOR_ID));
// String firstName = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_AUTHOR_FIRSTNAME));
// String middleName = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_AUTHOR_MIDDLENAME));
// String country = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_AUTHOR_COUNTRY));
// String city = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_AUTHOR_CITY));
// authors.add(new Author(id, firstName, middleName, country, city));
// } while (cursor.moveToNext());
// }
// cursor.close();
// return authors;
//}
public ArrayList<Publisher> getPublishers() {
ArrayList<Publisher> publishers = new ArrayList<>();
Cursor cursor = getAllPublishers();
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COL_PUBLISHER_ID));
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_PUBLISHER_NAME));
String country = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_PUBLISHER_COUNTRY));
String city = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_PUBLISHER_CITY));
publishers.add(new Publisher(id, name, country, city));
} while (cursor.moveToNext());
}
cursor.close();
return publishers;
}
public ArrayList<Title> getTitles() {
ArrayList<Title> titles = new ArrayList<>();
Cursor cursor = getAllTitles();
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COL_TITLES_ID));
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_TITLES_NAME));
int price = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COL_TITLES_PRICE));
String type = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_TITLES_TYPE));
int pubId = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COL_TITLES_PUBID));
titles.add(new Title(id, name, price, type, pubId));
} while (cursor.moveToNext());
}
cursor.close();
return titles;
}
//public Author getAuthor(int id) {
// Author author = null;
// String query = String.format("SELECT * FROM %s WHERE %s = ?", DatabaseHelper.AUTHORS_TABLE, DatabaseHelper.COL_AUTHOR_ID);
// Cursor cursor = _database.rawQuery(query, new String[] { String.valueOf(id) });
// if (cursor.moveToFirst()) {
// String firstName = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_AUTHOR_FIRSTNAME));
// String middleName = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_AUTHOR_MIDDLENAME));
// String country = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_AUTHOR_COUNTRY));
// String city = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_AUTHOR_CITY));
// author = new Author(id, firstName, middleName, country, city);
// } // if
// cursor.close();
// return author;
//}
public Publisher getPublisher(int id) {
Publisher publisher = null;
String query = String.format("SELECT * FROM %s WHERE %s = ?", DatabaseHelper.PUBLISHERS_TABLE, DatabaseHelper.COL_PUBLISHER_ID);
Cursor cursor = _database.rawQuery(query, new String[] { String.valueOf(id) });
if (cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_PUBLISHER_NAME));
String country = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_PUBLISHER_COUNTRY));
String city = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_PUBLISHER_CITY));
publisher = new Publisher(id, name, country, city);
} // if
cursor.close();
return publisher;
}
public Title getTitle(int id) {
Title title = null;
String query = String.format("SELECT * FROM %s WHERE %s = ?", DatabaseHelper.TITLES_TABLE, DatabaseHelper.COL_TITLES_ID);
Cursor cursor = _database.rawQuery(query, new String[] { String.valueOf(id) });
if (cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_PUBLISHER_NAME));
int price = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COL_PUBLISHER_COUNTRY));
String type = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_PUBLISHER_CITY));
int pubId = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COL_TITLES_PUBID));
title = new Title(id, name, price, type, pubId);
} // if
cursor.close();
return title;
}
//public long insertAuthor(Author author) {
// ContentValues cv = new ContentValues();
// cv.put(DatabaseHelper.COL_AUTHOR_FIRSTNAME, author.get_firstName());
// cv.put(DatabaseHelper.COL_AUTHOR_MIDDLENAME, author.get_middleName());
// cv.put(DatabaseHelper.COL_AUTHOR_COUNTRY, author.get_country());
// cv.put(DatabaseHelper.COL_AUTHOR_CITY, author.get_city());
// return _database.insert(DatabaseHelper.AUTHORS_TABLE, null, cv);
//}
public long insertPublisher(Publisher publisher) {
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.COL_PUBLISHER_NAME, publisher.get_name());
cv.put(DatabaseHelper.COL_PUBLISHER_COUNTRY, publisher.get_country());
cv.put(DatabaseHelper.COL_PUBLISHER_CITY, publisher.get_city());
return _database.insert(DatabaseHelper.PUBLISHERS_TABLE, null, cv);
}
public long insertTitle(Title title) {
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.COL_TITLES_NAME, title.get_name());
cv.put(DatabaseHelper.COL_TITLES_PRICE, title.get_price());
cv.put(DatabaseHelper.COL_TITLES_TYPE, title.get_type());
cv.put(DatabaseHelper.COL_TITLES_PUBID, title.get_pubId());
return _database.insert(DatabaseHelper.TITLES_TABLE, null, cv);
}
//public long deleteAuthor(int userId) {
// String whereClause = DatabaseHelper.COL_AUTHOR_ID + " = " + String.valueOf(userId);
// return _database.delete(DatabaseHelper.AUTHORS_TABLE, whereClause, null);
//}
public long deletePublisher(int pubId) {
String whereClause = DatabaseHelper.COL_PUBLISHER_ID + " = " + String.valueOf(pubId);
return _database.delete(DatabaseHelper.PUBLISHERS_TABLE, whereClause, null);
}
public long deleteTitle(int pubId) {
String whereClause = DatabaseHelper.COL_PUBLISHER_ID + " = " + String.valueOf(pubId);
return _database.delete(DatabaseHelper.TITLES_TABLE, whereClause, null);
}
//public long updateAuthor(Author author) {
// String whereClause = DatabaseHelper.COL_AUTHOR_ID + " = " + String.valueOf(author.get_id());
// ContentValues cv = new ContentValues();
// cv.put(DatabaseHelper.COL_AUTHOR_FIRSTNAME, author.get_firstName());
// cv.put(DatabaseHelper.COL_AUTHOR_MIDDLENAME, author.get_middleName());
// cv.put(DatabaseHelper.COL_AUTHOR_COUNTRY, author.get_country());
// cv.put(DatabaseHelper.COL_AUTHOR_CITY, author.get_city());
// return _database.update(DatabaseHelper.AUTHORS_TABLE, cv, whereClause, null);
//}
public long updatePublisher(Publisher publisher) {
String whereClause = DatabaseHelper.COL_PUBLISHER_ID + " = " + String.valueOf(publisher.get_id());
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.COL_PUBLISHER_NAME, publisher.get_name());
cv.put(DatabaseHelper.COL_PUBLISHER_COUNTRY, publisher.get_country());
cv.put(DatabaseHelper.COL_PUBLISHER_CITY, publisher.get_city());
return _database.update(DatabaseHelper.PUBLISHERS_TABLE, cv, whereClause, null);
}
public long updateTitle(Title title) {
String whereClause = DatabaseHelper.COL_TITLES_ID + " = " + String.valueOf(title.get_id());
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.COL_TITLES_NAME, title.get_name());
cv.put(DatabaseHelper.COL_TITLES_PRICE, title.get_price());
cv.put(DatabaseHelper.COL_TITLES_TYPE, title.get_type());
cv.put(DatabaseHelper.COL_TITLES_PUBID, title.get_pubId());
return _database.update(DatabaseHelper.TITLES_TABLE, cv, whereClause, null);
}
} // DatabaseAdapter |
3e00f54ff515a729afa7c3c1d841829eea85bf6f | 2,316 | java | Java | src/main/java/com/restfb/examples/webhook/bots/EchoBotServlet.java | restfb/restfb-example-chatbot | 82d3c43f7c5f746b081c63dfe157dd277ef0e6e3 | [
"MIT"
] | 10 | 2017-02-18T14:42:25.000Z | 2020-01-06T11:29:37.000Z | src/main/java/com/restfb/examples/webhook/bots/EchoBotServlet.java | restfb/restfb-example-chatbot | 82d3c43f7c5f746b081c63dfe157dd277ef0e6e3 | [
"MIT"
] | 1 | 2020-07-03T20:31:21.000Z | 2020-07-03T20:31:21.000Z | src/main/java/com/restfb/examples/webhook/bots/EchoBotServlet.java | restfb/restfb-example-chatbot | 82d3c43f7c5f746b081c63dfe157dd277ef0e6e3 | [
"MIT"
] | 6 | 2016-09-29T13:45:49.000Z | 2019-10-24T14:49:38.000Z | 39.254237 | 112 | 0.724525 | 398 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.restfb.examples.webhook.bots;
import com.restfb.*;
import com.restfb.examples.webhook.Config;
import com.restfb.examples.webhook.bots.base.AbstractFacebookBotServlet;
import com.restfb.types.GraphResponse;
import com.restfb.types.send.IdMessageRecipient;
import com.restfb.types.send.Message;
import com.restfb.types.webhook.WebhookEntry;
import com.restfb.types.webhook.WebhookObject;
import com.restfb.types.webhook.messaging.MessagingItem;
import java.io.IOException;
import java.util.List;
import java.util.stream.Stream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EchoBotServlet extends AbstractFacebookBotServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final String body = req.getReader().lines().reduce("", (accumulator, actual) -> accumulator + actual);
JsonMapper mapper = new DefaultJsonMapper();
WebhookObject whObject = mapper.toJavaObject(body, WebhookObject.class);
for (final WebhookEntry entry : whObject.getEntryList()) {
for (final MessagingItem item : entry.getMessaging()) {
final String senderId = item.getSender().getId();
Message simpleTextMessage = null;
// create the echo message
if (item.getMessage() != null && item.getMessage().getText() != null) {
simpleTextMessage = new Message("Echo: " + item.getMessage().getText());
}
// build the recipient
final IdMessageRecipient recipient = new IdMessageRecipient(senderId);
// send response if it is a message and not send a "echo"
if (simpleTextMessage != null && !item.getMessage().isEcho()) {
final FacebookClient sendClient =
new DefaultFacebookClient(Config.getInstance().getBotTokenAccess(), Version.LATEST);
sendClient.publish("me/messages", GraphResponse.class, Parameter.with("recipient", recipient),
Parameter.with("message", simpleTextMessage));
}
}
}
}
} |
3e00f6978039148af175d1ae5d0491b93409d297 | 1,003 | java | Java | src/main/java/com/instagram/giveaway/service/UserDetailsServiceImpl.java | Xlarchs/instagram-giveaway | 114cae26f441315ee1beb5cfe92101cf745d6b21 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/instagram/giveaway/service/UserDetailsServiceImpl.java | Xlarchs/instagram-giveaway | 114cae26f441315ee1beb5cfe92101cf745d6b21 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/instagram/giveaway/service/UserDetailsServiceImpl.java | Xlarchs/instagram-giveaway | 114cae26f441315ee1beb5cfe92101cf745d6b21 | [
"Apache-2.0"
] | null | null | null | 34.586207 | 105 | 0.801595 | 399 | package com.instagram.giveaway.service;
import com.instagram.giveaway.model.User;
import com.instagram.giveaway.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException("User Not Found with email: " + email));
return UserDetailsImpl.build(user);
}
}
|
3e00f6a0422acffc71bcf81d71d0f3481854391f | 222 | java | Java | ExitGame/src/base/Move.java | stealthness/games | 6787f42d3860828f324ae2b0425148c77d0342a9 | [
"MIT"
] | null | null | null | ExitGame/src/base/Move.java | stealthness/games | 6787f42d3860828f324ae2b0425148c77d0342a9 | [
"MIT"
] | null | null | null | ExitGame/src/base/Move.java | stealthness/games | 6787f42d3860828f324ae2b0425148c77d0342a9 | [
"MIT"
] | null | null | null | 12.333333 | 42 | 0.648649 | 400 | package base;
import res.ORDER;
/**
* Adds behaviour of movement
* @author steve
*
*/
public interface Move {
/**
* Moves a character based on order given
* @param order
*/
public void move(ORDER order);
}
|
Subsets and Splits