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
list | 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
list | 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
list | 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e081a8a35e736783062acf6aaacc97560792436
| 2,860 |
java
|
Java
|
jrugged-spring/src/test/java/org/fishwife/jrugged/spring/TestAnnotatedMethodScanner.java
|
comcast-jonm/jrugged
|
4727960945365e00560f207f0224fab5d5ac4622
|
[
"Apache-2.0"
] | 200 |
2015-01-01T11:09:22.000Z
|
2022-03-29T02:16:32.000Z
|
jrugged-spring/src/test/java/org/fishwife/jrugged/spring/TestAnnotatedMethodScanner.java
|
comcast-jonm/jrugged
|
4727960945365e00560f207f0224fab5d5ac4622
|
[
"Apache-2.0"
] | 30 |
2015-01-27T17:25:37.000Z
|
2019-07-22T15:34:58.000Z
|
jrugged-spring/src/test/java/org/fishwife/jrugged/spring/TestAnnotatedMethodScanner.java
|
comcast-jonm/jrugged
|
4727960945365e00560f207f0224fab5d5ac4622
|
[
"Apache-2.0"
] | 80 |
2015-01-19T16:39:44.000Z
|
2022-02-03T13:10:19.000Z
| 32.5 | 90 | 0.743706 | 3,418 |
/* TestAnnotatedMethodScanner.java
*
* Copyright 2009-2019 Comcast Interactive Media, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fishwife.jrugged.spring;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.easymock.EasyMock.eq;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.HashSet;
import java.util.Set;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
public class TestAnnotatedMethodScanner {
private ClassLoader mockClassLoader;
private ClassPathScanningCandidateComponentProvider mockProvider;
private AnnotatedMethodScanner impl;
@Before
public void setUp() {
mockClassLoader = createMock(ClassLoader.class);
mockProvider = createMock(ClassPathScanningCandidateComponentProvider.class);
impl = new AnnotatedMethodScanner(mockClassLoader, mockProvider);
}
@Test
public void testFindCandidateBeansAppliesAnnotatedMethodFilter() {
String basePackage = "faux.package";
Set<BeanDefinition> filteredComponents = new HashSet<BeanDefinition>();
mockProvider.resetFilters(false);
expectLastCall();
mockProvider.addIncludeFilter(EasyMock.isA(AnnotatedMethodFilter.class));
expectLastCall();
expect(mockProvider.findCandidateComponents(eq(basePackage.replace('.', '/')))).
andReturn(filteredComponents);
replayMocks();
impl.findCandidateBeans(basePackage, SomeAnno.class);
verifyMocks();
}
void replayMocks() {
replay(mockClassLoader);
replay(mockProvider);
}
void verifyMocks() {
verify(mockClassLoader);
verify(mockProvider);
}
// Dummy anno for test
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
private @interface SomeAnno {
}
}
|
3e081b3a86e51ecf0afccce0bc39468b0bd2e569
| 1,976 |
java
|
Java
|
src/main/java/MyMain.java
|
apcs-assignments-fall2020/9-pepys-problem-amandacutrer
|
aff316230108ba95ada065f7aa8fe51156a8fca4
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/MyMain.java
|
apcs-assignments-fall2020/9-pepys-problem-amandacutrer
|
aff316230108ba95ada065f7aa8fe51156a8fca4
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/MyMain.java
|
apcs-assignments-fall2020/9-pepys-problem-amandacutrer
|
aff316230108ba95ada065f7aa8fe51156a8fca4
|
[
"Apache-2.0"
] | null | null | null | 31.365079 | 76 | 0.45496 | 3,419 |
public class MyMain {
// Calculate the probability of rolling at least one 6 when rolling
// six dice. Uses 10000 trials.
// Returns in the answer as a double corresponding to the percentage
// For example, 75.5% would be 75.5
public static double probabilityOneSix() {
int trial = 0;
for (int i = 0; i < 10000; i++){
for(int j = 0; j < 6; j++){
if ((int)((Math.random() * 6)+1) == 6){
trial++;
break;
}
}
}
return (double)trial / (double)(10000) * 100;
}
// Calculate the probability of rolling at least two 6's when rolling
// twelve dice. Uses 10000 trials.
public static double probabilityTwoSixes() {
int trial = 0;
for (int i = 0; i < 10000; i++){
int sixes = 0;
for(int j = 0; j < 12; j++){
if ((int)((Math.random() * 6)+1) == 6){
sixes++;
}
}
if (sixes >= 2){
trial++;
}
}
return (double)trial / (double)(10000) * 100;
}
// Calculate the probability of rolling at least three 6's when rolling
// eighteen dice. Uses 10000 trials.
public static double probabilityThreeSixes() {
int trial = 0;
for (int i = 0; i < 10000; i++){
int sixes = 0;
for(int j = 0; j < 18; j++){
if ((int)((Math.random() * 6)+1) == 6){
sixes++;
}
}
if (sixes >= 3){
trial++;
}
}
return (double)trial / (double)(10000) * 100;
}
public static void main(String[] args) {
System.out.println(probabilityOneSix());
System.out.println(probabilityTwoSixes());
System.out.println(probabilityThreeSixes());
}
}
|
3e081be90b617d43068b804a2d094f79a41fc83f
| 2,941 |
java
|
Java
|
src/main/java/com/devproserv/courses/form/SignupParams.java
|
codacy-badger/courses
|
5b156dfc12d1fe7bad9fc50591eba2eb30fbf249
|
[
"MIT"
] | null | null | null |
src/main/java/com/devproserv/courses/form/SignupParams.java
|
codacy-badger/courses
|
5b156dfc12d1fe7bad9fc50591eba2eb30fbf249
|
[
"MIT"
] | null | null | null |
src/main/java/com/devproserv/courses/form/SignupParams.java
|
codacy-badger/courses
|
5b156dfc12d1fe7bad9fc50591eba2eb30fbf249
|
[
"MIT"
] | null | null | null | 23.34127 | 80 | 0.622917 | 3,420 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Vladimir
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.devproserv.courses.form;
import javax.servlet.http.HttpServletRequest;
/**
* Extracts sign up form parameters from HTTP request.
*
* @since 0.5.0
*/
public class SignupParams {
/**
* HTTP request.
*/
private final HttpServletRequest request;
/**
* Login.
*/
private String login;
/**
* Password.
*/
private String password;
/**
* First name.
*/
private String fname;
/**
* Last name.
*/
private String lname;
/**
* Faculty.
*/
private String faculty;
/**
* Constructor.
* @param request HTTP request
*/
public SignupParams(final HttpServletRequest request) {
this.request = request;
}
/**
* Extracts parameters from the HTTP request.
* @return This instance
*/
public SignupParams extract() {
this.login = this.request.getParameter("login");
this.password = this.request.getParameter("password");
this.fname = this.request.getParameter("firstname");
this.lname = this.request.getParameter("lastname");
this.faculty = this.request.getParameter("faculty");
return this;
}
/**
* Getter.
* @return Login
*/
String getLogin() {
return this.login;
}
/**
* Getter.
* @return Password
*/
String getPassword() {
return this.password;
}
/**
* Getter.
* @return First name
*/
String getFName() {
return this.fname;
}
/**
* Getter.
* @return Last name
*/
String getLName() {
return this.lname;
}
/**
* Getter.
* @return Faculty
*/
String getFaculty() {
return this.faculty;
}
}
|
3e081bedbff2a81848f33f17be8f60f9148ed81b
| 85 |
java
|
Java
|
src/main/java/com/example/mvcp/util/RestEnum.java
|
hamidbayrak/SpringREST-eCommerce-website-example
|
9336d2afdfe809bd7cc0544cc488ead44097cf97
|
[
"MIT"
] | 2 |
2021-02-19T16:09:31.000Z
|
2021-05-20T12:01:13.000Z
|
src/main/java/com/example/mvcp/util/RestEnum.java
|
hamidbayrak/SpringREST-eCommerce-website-example
|
9336d2afdfe809bd7cc0544cc488ead44097cf97
|
[
"MIT"
] | null | null | null |
src/main/java/com/example/mvcp/util/RestEnum.java
|
hamidbayrak/SpringREST-eCommerce-website-example
|
9336d2afdfe809bd7cc0544cc488ead44097cf97
|
[
"MIT"
] | 1 |
2021-02-19T16:09:40.000Z
|
2021-02-19T16:09:40.000Z
| 14.166667 | 30 | 0.729412 | 3,421 |
package com.example.mvcp.util;
public enum RestEnum {
status, message, result
}
|
3e081c0e9f262931e0572e9500f7f14a7b728437
| 2,105 |
java
|
Java
|
src/main/java/com/google/api/codegen/util/Inflector.java
|
jpoehnelt/gapic-generator
|
06463219f95bedb0f9c788dffa888c5ebfc199cc
|
[
"ECL-2.0",
"Apache-2.0"
] | 239 |
2018-04-20T05:25:37.000Z
|
2022-03-15T17:24:10.000Z
|
src/main/java/com/google/api/codegen/util/Inflector.java
|
jpoehnelt/gapic-generator
|
06463219f95bedb0f9c788dffa888c5ebfc199cc
|
[
"ECL-2.0",
"Apache-2.0"
] | 1,888 |
2016-04-21T18:50:01.000Z
|
2018-04-12T23:37:32.000Z
|
src/main/java/com/google/api/codegen/util/Inflector.java
|
jpoehnelt/gapic-generator
|
06463219f95bedb0f9c788dffa888c5ebfc199cc
|
[
"ECL-2.0",
"Apache-2.0"
] | 88 |
2018-04-20T19:46:35.000Z
|
2022-03-14T22:12:07.000Z
| 32.384615 | 93 | 0.620903 | 3,422 |
/* Copyright 2016 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 com.google.api.codegen.util;
/** Utility class for manipulating words */
public class Inflector {
/** Gives the singular form of an English word (only works for regular English plurals). */
public static String singularize(String in) {
if (in.endsWith("lves") || in.endsWith("rves")) {
return in.substring(0, in.length() - 3) + "f";
} else if (in.endsWith("ies")) {
return in.substring(0, in.length() - 3) + "y";
} else if (in.endsWith("sses")) {
return in.substring(0, in.length() - 2);
} else if (in.endsWith("shes")) {
return in.substring(0, in.length() - 2);
} else if (in.endsWith("zzes")) {
return in.substring(0, in.length() - 2);
} else if (in.endsWith("ses")) {
return in.substring(0, in.length() - 1);
} else if (in.endsWith("ces")) {
return in.substring(0, in.length() - 1);
} else if (in.endsWith("res")) {
return in.substring(0, in.length() - 1);
} else if (in.endsWith("zes")) {
return in.substring(0, in.length() - 1);
} else if (in.charAt(in.length() - 1) == 's' && in.charAt(in.length() - 2) != 's') {
return in.substring(0, in.length() - 1);
}
return in;
}
/** Gives the singular form of an English word (only works for regular English plurals). */
public static String pluralize(String in) {
if (in.endsWith("x") || in.endsWith("s") || in.endsWith("sh") || in.endsWith("ch")) {
return in + "es";
} else {
return in + "s";
}
}
}
|
3e081c3196c201bd7bd8985a925c39ef5fac9bb3
| 6,017 |
java
|
Java
|
src/java/org/apache/cassandra/service/paxos/cleanup/PaxosCleanupRequest.java
|
ErickRamirezAU/cassandra
|
c7e7984008062aa2cf2de5a1fc080674bb2139ff
|
[
"Apache-2.0"
] | null | null | null |
src/java/org/apache/cassandra/service/paxos/cleanup/PaxosCleanupRequest.java
|
ErickRamirezAU/cassandra
|
c7e7984008062aa2cf2de5a1fc080674bb2139ff
|
[
"Apache-2.0"
] | null | null | null |
src/java/org/apache/cassandra/service/paxos/cleanup/PaxosCleanupRequest.java
|
ErickRamirezAU/cassandra
|
c7e7984008062aa2cf2de5a1fc080674bb2139ff
|
[
"Apache-2.0"
] | null | null | null | 42.076923 | 160 | 0.699019 | 3,423 |
/*
* 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.cassandra.service.paxos.cleanup;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import javax.annotation.Nullable;
import com.google.common.util.concurrent.FutureCallback;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.TypeSizes;
import org.apache.cassandra.dht.AbstractBounds;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.DataOutputPlus;
import org.apache.cassandra.net.IVerbHandler;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.schema.TableId;
import org.apache.cassandra.utils.UUIDSerializer;
import static org.apache.cassandra.net.MessagingService.instance;
import static org.apache.cassandra.net.NoPayload.noPayload;
import static org.apache.cassandra.net.Verb.PAXOS2_CLEANUP_RSP;
import static org.apache.cassandra.net.Verb.PAXOS2_CLEANUP_RSP2;
// TODO: send the high bound as a minimum commit point, so later repairs can terminate early if a later commit has been witnessed
public class PaxosCleanupRequest
{
public final UUID session;
public final TableId tableId;
public final Collection<Range<Token>> ranges;
static Collection<Range<Token>> rangesOrMin(Collection<Range<Token>> ranges)
{
if (ranges != null && !ranges.isEmpty())
return ranges;
Token min = DatabaseDescriptor.getPartitioner().getMinimumToken();
return Collections.singleton(new Range<>(min, min));
}
public PaxosCleanupRequest(UUID session, TableId tableId, Collection<Range<Token>> ranges)
{
this.session = session;
this.tableId = tableId;
this.ranges = rangesOrMin(ranges);
}
public static final IVerbHandler<PaxosCleanupRequest> verbHandler = in -> {
PaxosCleanupRequest request = in.payload;
if (!PaxosCleanup.isInRangeAndShouldProcess(request.ranges, request.tableId))
{
String msg = String.format("Rejecting cleanup request %s from %s. Some ranges are not replicated (%s)",
request.session, in.from(), request.ranges);
Message<PaxosCleanupResponse> response = Message.out(PAXOS2_CLEANUP_RSP2, PaxosCleanupResponse.failed(request.session, msg));
instance().send(response, in.respondTo());
return;
}
PaxosCleanupLocalCoordinator coordinator = PaxosCleanupLocalCoordinator.create(request);
coordinator.addCallback(new FutureCallback<PaxosCleanupResponse>()
{
public void onSuccess(@Nullable PaxosCleanupResponse finished)
{
Message<PaxosCleanupResponse> response = Message.out(PAXOS2_CLEANUP_RSP2, coordinator.getNow());
instance().send(response, in.respondTo());
}
public void onFailure(Throwable throwable)
{
Message<PaxosCleanupResponse> response = Message.out(PAXOS2_CLEANUP_RSP2, PaxosCleanupResponse.failed(request.session, throwable.getMessage()));
instance().send(response, in.respondTo());
}
});
// ack the request so the coordinator knows we've started
instance().respond(noPayload, in);
coordinator.start();
};
public static final IVersionedSerializer<PaxosCleanupRequest> serializer = new IVersionedSerializer<PaxosCleanupRequest>()
{
public void serialize(PaxosCleanupRequest completer, DataOutputPlus out, int version) throws IOException
{
UUIDSerializer.serializer.serialize(completer.session, out, version);
completer.tableId.serialize(out);
out.writeInt(completer.ranges.size());
for (Range<Token> range: completer.ranges)
AbstractBounds.tokenSerializer.serialize(range, out, version);
}
public PaxosCleanupRequest deserialize(DataInputPlus in, int version) throws IOException
{
UUID session = UUIDSerializer.serializer.deserialize(in, version);
TableId tableId = TableId.deserialize(in);
int numRanges = in.readInt();
List<Range<Token>> ranges = new ArrayList<>(numRanges);
for (int i=0; i<numRanges; i++)
{
ranges.add((Range<Token>) AbstractBounds.tokenSerializer.deserialize(in, DatabaseDescriptor.getPartitioner(), version));
}
return new PaxosCleanupRequest(session, tableId, ranges);
}
public long serializedSize(PaxosCleanupRequest completer, int version)
{
long size = UUIDSerializer.serializer.serializedSize(completer.session, version);
size += completer.tableId.serializedSize();
size += TypeSizes.sizeof(completer.ranges.size());
for (Range<Token> range: completer.ranges)
size += AbstractBounds.tokenSerializer.serializedSize(range, version);
return size;
}
};
}
|
3e081db0ed726c521ca79368a4b03079de09b05a
| 13,865 |
java
|
Java
|
ccven_java/src/main/java/view_cvven/AllUser.java
|
illanchristoffel/projet_cvven_final
|
5064b8e25702134a898c918b9972efd5c55802df
|
[
"MIT"
] | null | null | null |
ccven_java/src/main/java/view_cvven/AllUser.java
|
illanchristoffel/projet_cvven_final
|
5064b8e25702134a898c918b9972efd5c55802df
|
[
"MIT"
] | 1 |
2022-02-16T01:09:35.000Z
|
2022-02-16T01:09:35.000Z
|
ccven_java/src/main/java/view_cvven/AllUser.java
|
illanchristoffel/projet_cvven_final
|
5064b8e25702134a898c918b9972efd5c55802df
|
[
"MIT"
] | null | null | null | 41.264881 | 163 | 0.62005 | 3,424 |
/*
* 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 view_cvven;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import net.proteanit.sql.DbUtils;
/**
*
* @author Illan
*/
public class AllUser extends javax.swing.JFrame {
public AllUser() {
initComponents();
DisplayTable();
}
public Connection getConnection()
{
Connection con;
try{
con = DriverManager.getConnection("jdbc:postgresql://chamilo.rene-descartes.fr/GroupeA", "groupea", "grpa");
return con;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
public ArrayList<Archiver> getarchiverList()
{
ArrayList<Archiver> archiverList = new ArrayList<Archiver>();
Connection connection = getConnection();
String query = "SELECT * FROM utilisateur_participant";
Statement st;
ResultSet rs;
try{
st = connection.createStatement();
rs = st.executeQuery(query);
Archiver archiver;
while(rs.next()){
archiver = new Archiver(rs.getInt("id"), rs.getString("nom"), rs.getString("salle"));
archiverList.add(archiver);
}
}catch(Exception e){
e.printStackTrace();
}
return archiverList;
}
public void executeQuery(String query, String message)
{
Connection con = getConnection();
Statement st;
try{
st = con.createStatement();
if((st.executeUpdate(query)==1))
{
DefaultTableModel model =(DefaultTableModel)table.getModel();
model.setRowCount(0);
//Show_archive();
JOptionPane.showMessageDialog(null, "Utilisateur supprimé");
}else{
JOptionPane.showMessageDialog(null, "Il y'a une erreur !");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
private void DisplayTable(){
try {
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://chamilo.rene-descartes.fr/GroupeA", "groupea", "grpa");
System.out.println("Connexion au serveur réussie !");
String sql = "Select * from utilisateur_participant ORDER BY id DESC";
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
jScrollPane2 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
archive = new javax.swing.JButton();
jlib = new javax.swing.JTextField();
jtheme = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
table.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Libellé", "Thème", "Date de début", "Date de fin"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, true, true, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setMaximumSize(new java.awt.Dimension(2147483647, 200));
table.setRowHeight(25);
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableMouseClicked(evt);
}
});
table.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
tablePropertyChange(evt);
}
});
jScrollPane2.setViewportView(table);
jButton1.setText("Retour");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
archive.setText("Supprimer un participant");
archive.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
archiveActionPerformed(evt);
}
});
jlib.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jlibActionPerformed(evt);
}
});
jtheme.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jthemeActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setText("Tous les participants");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jlib, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(366, 366, 366)
.addComponent(jtheme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 602, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(archive, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38)
.addComponent(jButton1))
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 972, Short.MAX_VALUE))))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(426, 426, 426)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(45, 45, 45)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jlib, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jtheme, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(107, 107, 107)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(archive)
.addComponent(jButton1))
.addGap(0, 422, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
menu retour=new menu ();
retour.setVisible(true);
this.hide();
}//GEN-LAST:event_jButton1ActionPerformed
private void archiveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_archiveActionPerformed
String query = "DELETE FROM utilisateur_participant where id="+jtheme.getText();
executeQuery(query, "Supprimer");
}//GEN-LAST:event_archiveActionPerformed
private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
int i = table.getSelectedRow();
TableModel model = table.getModel();
jtheme.setText(model.getValueAt(i, 0).toString());
jlib.setText(model.getValueAt(i, 1).toString());
}//GEN-LAST:event_tableMouseClicked
private void tablePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_tablePropertyChange
// TODO add your handling code here:
}//GEN-LAST:event_tablePropertyChange
private void jlibActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jlibActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jlibActionPerformed
private void jthemeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jthemeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jthemeActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AllUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AllUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AllUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AllUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AllUser().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton archive;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JTextField jlib;
private javax.swing.JTextField jtheme;
private javax.swing.JTable table;
// End of variables declaration//GEN-END:variables
private void executeSQlQuery(String query, String updated) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
3e081e28b99b1718d5c565bddb108cd9c566d92d
| 634 |
java
|
Java
|
references/bcb_chosen_clones/selected#1095966#20#32.java
|
cragkhit/elasticsearch
|
05567b30c5bde08badcac1bf421454e5d995eb91
|
[
"Apache-2.0"
] | 23 |
2018-10-03T15:02:53.000Z
|
2021-09-16T11:07:36.000Z
|
references/bcb_chosen_clones/selected#1095966#20#32.java
|
cragkhit/elasticsearch
|
05567b30c5bde08badcac1bf421454e5d995eb91
|
[
"Apache-2.0"
] | 18 |
2019-02-10T04:52:54.000Z
|
2022-01-25T02:14:40.000Z
|
references/bcb_chosen_clones/selected#1095966#20#32.java
|
cragkhit/Siamese
|
05567b30c5bde08badcac1bf421454e5d995eb91
|
[
"Apache-2.0"
] | 19 |
2018-11-16T13:39:05.000Z
|
2021-09-05T23:59:30.000Z
| 45.285714 | 115 | 0.665615 | 3,425 |
private void handleFile(File file, HttpServletRequest request, HttpServletResponse response) throws Exception {
String filename = file.getName();
long filesize = file.length();
String mimeType = getMimeType(filename);
response.setContentType(mimeType);
if (filesize > getDownloadThreshhold()) {
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
}
response.setContentLength((int) filesize);
ServletOutputStream out = response.getOutputStream();
IOUtils.copy(new FileInputStream(file), out);
out.flush();
}
|
3e081ff3215e5a3ae8b3bf598b8e0d1b0e35c8bb
| 7,341 |
java
|
Java
|
src/test/java/io/gravitee/policy/requestvalidation/RequestValidationPolicyTest.java
|
brightlizard/gravitee-policy-request-validation
|
22a9b38e95a8150398cf6d2e5156a5f035bb8ca6
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/io/gravitee/policy/requestvalidation/RequestValidationPolicyTest.java
|
brightlizard/gravitee-policy-request-validation
|
22a9b38e95a8150398cf6d2e5156a5f035bb8ca6
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/io/gravitee/policy/requestvalidation/RequestValidationPolicyTest.java
|
brightlizard/gravitee-policy-request-validation
|
22a9b38e95a8150398cf6d2e5156a5f035bb8ca6
|
[
"Apache-2.0"
] | null | null | null | 37.075758 | 111 | 0.707533 | 3,426 |
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.policy.requestvalidation;
import io.gravitee.common.http.HttpHeaders;
import io.gravitee.common.http.HttpStatusCode;
import io.gravitee.common.util.MultiValueMap;
import io.gravitee.el.TemplateEngine;
import io.gravitee.gateway.api.ExecutionContext;
import io.gravitee.gateway.api.Request;
import io.gravitee.gateway.api.Response;
import io.gravitee.policy.api.PolicyChain;
import io.gravitee.policy.requestvalidation.configuration.RequestValidationPolicyConfiguration;
import io.gravitee.policy.requestvalidation.el.EvaluableRequest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.Collections;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.*;
/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
@RunWith(MockitoJUnitRunner.class)
public class RequestValidationPolicyTest {
private RequestValidationPolicy policy;
@Mock
private RequestValidationPolicyConfiguration configuration;
@Mock
protected Request request;
@Mock
protected Response response;
@Mock
protected PolicyChain policyChain;
@Mock
protected ExecutionContext executionContext;
@Before
public void init() {
policy = new RequestValidationPolicy(configuration);
when(configuration.getStatus()).thenReturn(HttpStatusCode.BAD_REQUEST_400);
}
@Test
public void shouldValidateQueryParameter() {
// Prepare inbound request
MultiValueMap<String, String> parameters = mock(MultiValueMap.class);
when(parameters.get("my-param")).thenReturn(Collections.singletonList("my-value"));
when(request.parameters()).thenReturn(parameters);
// Prepare template engine
TemplateEngine engine = TemplateEngine.templateEngine();
engine.getTemplateContext().setVariable("request", new EvaluableRequest(request));
when(executionContext.getTemplateEngine()).thenReturn(engine);
// Prepare constraint rule
Rule rule = new Rule();
rule.setInput("{#request.params['my-param']}");
Constraint constraint = new Constraint();
constraint.setType(ConstraintType.NOT_NULL);
rule.setConstraint(constraint);
when(configuration.getRules()).thenReturn(Collections.singletonList(rule));
// Execute policy
policy.onRequest(request, response, executionContext, policyChain);
// Check results
verify(policyChain).doNext(request, response);
}
@Test
public void shouldNotValidateQueryParameter_notNull() {
// Prepare inbound request
MultiValueMap<String, String> parameters = mock(MultiValueMap.class);
when(request.parameters()).thenReturn(parameters);
// Prepare template engine
TemplateEngine engine = TemplateEngine.templateEngine();
engine.getTemplateContext().setVariable("request", new EvaluableRequest(request));
when(executionContext.getTemplateEngine()).thenReturn(engine);
// Prepare constraint rule
Rule rule = new Rule();
rule.setInput("{#request.params['my-param']}");
Constraint constraint = new Constraint();
constraint.setType(ConstraintType.NOT_NULL);
rule.setConstraint(constraint);
when(configuration.getRules()).thenReturn(Collections.singletonList(rule));
// Execute policy
policy.onRequest(request, response, executionContext, policyChain);
// Check results
verify(policyChain).failWith(argThat(result -> result.statusCode() == HttpStatusCode.BAD_REQUEST_400));
}
@Test
public void shouldNotValidateQueryParameter_invalidMinConstraint() {
// Prepare inbound request
MultiValueMap<String, String> parameters = mock(MultiValueMap.class);
when(request.parameters()).thenReturn(parameters);
// Prepare template engine
TemplateEngine engine = TemplateEngine.templateEngine();
engine.getTemplateContext().setVariable("request", new EvaluableRequest(request));
when(executionContext.getTemplateEngine()).thenReturn(engine);
// Prepare constraint rule
Rule rule = new Rule();
rule.setInput("{#request.params['my-param']}");
Constraint constraint = new Constraint();
constraint.setType(ConstraintType.MIN);
constraint.setParameters(new String []{"toto"}); // Toto is not a valid number
rule.setConstraint(constraint);
when(configuration.getRules()).thenReturn(Collections.singletonList(rule));
// Execute policy
policy.onRequest(request, response, executionContext, policyChain);
// Check results
verify(policyChain).failWith(argThat(result -> result.statusCode() == HttpStatusCode.BAD_REQUEST_400));
}
@Test
public void shouldValidateQueryParameter_multipleRules() {
// Prepare inbound request
MultiValueMap<String, String> parameters = mock(MultiValueMap.class);
when(parameters.get("my-param")).thenReturn(Collections.singletonList("80"));
when(request.parameters()).thenReturn(parameters);
HttpHeaders headers = mock(HttpHeaders.class);
when(headers.get("my-header")).thenReturn(Collections.singletonList("header-value"));
when(request.headers()).thenReturn(headers);
// Prepare template engine
TemplateEngine engine = TemplateEngine.templateEngine();
engine.getTemplateContext().setVariable("request", new EvaluableRequest(request));
when(executionContext.getTemplateEngine()).thenReturn(engine);
// Prepare constraint rule
Rule rule = new Rule();
rule.setInput("{#request.params['my-param']}");
Constraint constraint = new Constraint();
constraint.setType(ConstraintType.NOT_NULL);
Constraint constraintMin = new Constraint();
constraintMin.setType(ConstraintType.MIN);
constraintMin.setParameters(new String []{"50"});
rule.setConstraint(constraint);
Rule rule2 = new Rule();
rule2.setInput("{#request.headers['my-header']}");
Constraint constraint2 = new Constraint();
constraint2.setType(ConstraintType.NOT_NULL);
rule2.setConstraint(constraint2);
when(configuration.getRules()).thenReturn(Arrays.asList(rule, rule2));
// Execute policy
policy.onRequest(request, response, executionContext, policyChain);
// Check results
verify(policyChain).doNext(request, response);
}
}
|
3e0822be656bc4af26137729609f056b314689c3
| 1,659 |
java
|
Java
|
3-03-2020/Backend/Example/src/main/java/com/example/demo/controller/StockPriceRestServiceController.java
|
saikrishna2409/My-First-Repo
|
b58c09dc083ed55777ef77a1c536f76df09e60d9
|
[
"Apache-2.0"
] | null | null | null |
3-03-2020/Backend/Example/src/main/java/com/example/demo/controller/StockPriceRestServiceController.java
|
saikrishna2409/My-First-Repo
|
b58c09dc083ed55777ef77a1c536f76df09e60d9
|
[
"Apache-2.0"
] | 27 |
2020-06-15T21:05:41.000Z
|
2022-03-02T09:29:43.000Z
|
3-03-2020/Backend/Example/src/main/java/com/example/demo/controller/StockPriceRestServiceController.java
|
saikrishna2409/My-First-Repo
|
b58c09dc083ed55777ef77a1c536f76df09e60d9
|
[
"Apache-2.0"
] | null | null | null | 32.529412 | 112 | 0.792646 | 3,427 |
package com.example.demo.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.demo.models.StockExchange;
import com.example.demo.models.StockPrice;
import com.example.demo.repo.StockExchangeRepo;
import com.example.demo.repo.StockPriceRepo;
public class StockPriceRestServiceController {
@Autowired
StockPriceRepo sr;
@RequestMapping(value="/stockprice",method= RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
public List<StockPrice> findAll() {
return sr.findAll();
}
@RequestMapping(value="/stockprice/{id}",method= RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
public StockPrice findOne(@PathVariable int id) {
Optional<StockPrice> sp = sr.findById(id);
StockPrice stockpricereturn = sp.get();
return stockpricereturn;
}
@RequestMapping(value="/stockprice",method= RequestMethod.POST)
public StockPrice save(@RequestBody StockPrice stp) {
StockPrice spr = sr.save(stp);
return spr;
}
@RequestMapping(value="/stockprice/{id}",method= RequestMethod.DELETE)
public void delete(@PathVariable int id) {
sr.deleteById(id);
}
@RequestMapping(value="/stockprice",method= RequestMethod.PUT)
public StockPrice update(@RequestBody StockPrice spr) {
StockPrice spreturn = sr.save(spr);
return spreturn;
}
}
|
3e0822ce154352bee3ea92f004b4b6628b6a7215
| 7,152 |
java
|
Java
|
src/main/java/io/swagger/client/model/EventMetadata.java
|
dehora/nakadi-swagger-gen
|
e261d4398f04bcb2f89325efad9d134ec030d281
|
[
"MIT"
] | null | null | null |
src/main/java/io/swagger/client/model/EventMetadata.java
|
dehora/nakadi-swagger-gen
|
e261d4398f04bcb2f89325efad9d134ec030d281
|
[
"MIT"
] | null | null | null |
src/main/java/io/swagger/client/model/EventMetadata.java
|
dehora/nakadi-swagger-gen
|
e261d4398f04bcb2f89325efad9d134ec030d281
|
[
"MIT"
] | null | null | null | 34.887805 | 321 | 0.701902 | 3,428 |
package io.swagger.client.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-06-15T21:24:42.545+01:00")
public class EventMetadata {
private UUID eid = null;
private String eventType = null;
private Date occurredAt = null;
private Date receivedAt = null;
private List<UUID> parentEids = new ArrayList<UUID>();
private String flowId = null;
private String partition = null;
/**
* Identifier of this Event.\n\nClients MUST generate this value and it SHOULD be guaranteed to be unique from the\nperspective of the producer. Consumers MIGHT use this value to assert uniqueness of\nreception of the Event.\n
**/
public EventMetadata eid(UUID eid) {
this.eid = eid;
return this;
}
@ApiModelProperty(example = "105a76d8-db49-4144-ace7-e683e8f4ba46", required = true, value = "Identifier of this Event.\n\nClients MUST generate this value and it SHOULD be guaranteed to be unique from the\nperspective of the producer. Consumers MIGHT use this value to assert uniqueness of\nreception of the Event.\n")
@JsonProperty("eid")
public UUID getEid() {
return eid;
}
public void setEid(UUID eid) {
this.eid = eid;
}
/**
* The EventType of this Event. This is enriched by Nakadi on reception of the Event\nbased on the endpoint where the Producer sent the Event to.\n\nIf provided MUST match the endpoint. Failure to do so will cause rejection of the\nEvent.\n
**/
public EventMetadata eventType(String eventType) {
this.eventType = eventType;
return this;
}
@ApiModelProperty(example = "pennybags.payment-business-event", value = "The EventType of this Event. This is enriched by Nakadi on reception of the Event\nbased on the endpoint where the Producer sent the Event to.\n\nIf provided MUST match the endpoint. Failure to do so will cause rejection of the\nEvent.\n")
@JsonProperty("event_type")
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
/**
* Timestamp of creation of the Event generated by the producer.\n
**/
public EventMetadata occurredAt(Date occurredAt) {
this.occurredAt = occurredAt;
return this;
}
@ApiModelProperty(example = "1996-12-19T16:39:57-08:00", required = true, value = "Timestamp of creation of the Event generated by the producer.\n")
@JsonProperty("occurred_at")
public Date getOccurredAt() {
return occurredAt;
}
public void setOccurredAt(Date occurredAt) {
this.occurredAt = occurredAt;
}
/**
* Timestamp of the reception of the Event by Nakadi. This is enriched upon reception of\nthe Event.\nIf set by the producer Event will be rejected.\n
**/
public EventMetadata receivedAt(Date receivedAt) {
this.receivedAt = receivedAt;
return this;
}
@ApiModelProperty(example = "1996-12-19T16:39:57-08:00", value = "Timestamp of the reception of the Event by Nakadi. This is enriched upon reception of\nthe Event.\nIf set by the producer Event will be rejected.\n")
@JsonProperty("received_at")
public Date getReceivedAt() {
return receivedAt;
}
public void setReceivedAt(Date receivedAt) {
this.receivedAt = receivedAt;
}
/**
**/
public EventMetadata parentEids(List<UUID> parentEids) {
this.parentEids = parentEids;
return this;
}
@ApiModelProperty(example = "null", value = "")
@JsonProperty("parent_eids")
public List<UUID> getParentEids() {
return parentEids;
}
public void setParentEids(List<UUID> parentEids) {
this.parentEids = parentEids;
}
/**
* The flow-id of the producer of this Event. As this is usually a HTTP header, this is\nenriched from the header into the metadata by Nakadi to avoid clients having to\nexplicitly copy this.\n
**/
public EventMetadata flowId(String flowId) {
this.flowId = flowId;
return this;
}
@ApiModelProperty(example = "JAh6xH4OQhCJ9PutIV_RYw", value = "The flow-id of the producer of this Event. As this is usually a HTTP header, this is\nenriched from the header into the metadata by Nakadi to avoid clients having to\nexplicitly copy this.\n")
@JsonProperty("flow_id")
public String getFlowId() {
return flowId;
}
public void setFlowId(String flowId) {
this.flowId = flowId;
}
/**
* Indicates the partition assigned to this Event.\n\nRequired to be set by the client if partition strategy of the EventType is\n'user_defined'.\n
**/
public EventMetadata partition(String partition) {
this.partition = partition;
return this;
}
@ApiModelProperty(example = "0", value = "Indicates the partition assigned to this Event.\n\nRequired to be set by the client if partition strategy of the EventType is\n'user_defined'.\n")
@JsonProperty("partition")
public String getPartition() {
return partition;
}
public void setPartition(String partition) {
this.partition = partition;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EventMetadata eventMetadata = (EventMetadata) o;
return Objects.equals(this.eid, eventMetadata.eid) &&
Objects.equals(this.eventType, eventMetadata.eventType) &&
Objects.equals(this.occurredAt, eventMetadata.occurredAt) &&
Objects.equals(this.receivedAt, eventMetadata.receivedAt) &&
Objects.equals(this.parentEids, eventMetadata.parentEids) &&
Objects.equals(this.flowId, eventMetadata.flowId) &&
Objects.equals(this.partition, eventMetadata.partition);
}
@Override
public int hashCode() {
return Objects.hash(eid, eventType, occurredAt, receivedAt, parentEids, flowId, partition);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EventMetadata {\n");
sb.append(" eid: ").append(toIndentedString(eid)).append("\n");
sb.append(" eventType: ").append(toIndentedString(eventType)).append("\n");
sb.append(" occurredAt: ").append(toIndentedString(occurredAt)).append("\n");
sb.append(" receivedAt: ").append(toIndentedString(receivedAt)).append("\n");
sb.append(" parentEids: ").append(toIndentedString(parentEids)).append("\n");
sb.append(" flowId: ").append(toIndentedString(flowId)).append("\n");
sb.append(" partition: ").append(toIndentedString(partition)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e08235852d73ffd3a1b651aa2b0a497f331b2f0
| 1,601 |
java
|
Java
|
study-notes/geekbang.org/训练营/Java进阶训练营/第14周 | 分布式消息分布式系统架构/01-其他MQ介绍与动手写MQ/pulsar/src/main/java/io/kimmking/mq/pulsar/ProducerDemo.java
|
coderZsq/coderZsq.practice.server
|
f789ee4b43b4a8dee5d8872e86c04ca2fe139b68
|
[
"MIT"
] | 1 |
2020-06-14T12:43:47.000Z
|
2020-06-14T12:43:47.000Z
|
study-notes/geekbang.org/训练营/Java进阶训练营/第14周 | 分布式消息分布式系统架构/01-其他MQ介绍与动手写MQ/pulsar/src/main/java/io/kimmking/mq/pulsar/ProducerDemo.java
|
coderZsq/coderZsq.practice.server
|
f789ee4b43b4a8dee5d8872e86c04ca2fe139b68
|
[
"MIT"
] | 88 |
2020-03-03T15:16:28.000Z
|
2022-01-04T16:44:37.000Z
|
study-notes/geekbang.org/训练营/Java进阶训练营/第14周 | 分布式消息分布式系统架构/01-其他MQ介绍与动手写MQ/pulsar/src/main/java/io/kimmking/mq/pulsar/ProducerDemo.java
|
coderZsq/coderZsq.practice.server
|
f789ee4b43b4a8dee5d8872e86c04ca2fe139b68
|
[
"MIT"
] | 1 |
2021-09-08T06:34:11.000Z
|
2021-09-08T06:34:11.000Z
| 26.245902 | 77 | 0.570269 | 3,429 |
package io.kimmking.mq.pulsar;
import lombok.SneakyThrows;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.Schema;
import org.springframework.stereotype.Component;
@Component
public class ProducerDemo {
Producer<String> stringProducer;
@SneakyThrows
public ProducerDemo(){
stringProducer = Config.createClient().newProducer(Schema.STRING)
.topic("my-kk")
.create();
}
@SneakyThrows
public void sendMsg() {
for (int i = 0; i < 1000; i++) {
stringProducer.send(i + " message from pulsar.");
}
}
// //关闭操作也可以是异步的:
//
// producer.closeAsync()
// .thenRun(() -> System.out.println("Producer closed"));
// .exceptionally((ex) -> {
// System.err.println("Failed to close producer: " + ex);
// return ex;
// });
// 控制发送行为
// Producer<byte[]> producer = client.newProducer()
// .topic("my-topic")
// .batchingMaxPublishDelay(10, TimeUnit.MILLISECONDS)
// .sendTimeout(10, TimeUnit.SECONDS)
// .blockIfQueueFull(true)
// .create();
//异步发送
// producer.sendAsync("my-async-message".getBytes()).thenAccept(msgId -> {
// System.out.printf("Message with ID %s successfully sent", msgId);
// });
// 添加参数
// producer.newMessage()
// .key("my-message-key")
// .value("my-async-message".getBytes())
// .property("my-key", "my-value")
// .property("my-other-key", "my-other-value")
// .send();
}
|
3e0824199287b3a93dc3b0bd2846fa0d6a386f2a
| 14,517 |
java
|
Java
|
src/main/java/com/datafibers/util/ConstantApp.java
|
yjdxwz/df_data_service
|
19257c0989952d8b5ab2ed527e1d302b2687ef46
|
[
"Apache-2.0"
] | 37 |
2016-10-15T01:45:21.000Z
|
2021-09-06T10:00:50.000Z
|
src/main/java/com/datafibers/util/ConstantApp.java
|
yjdxwz/df_data_service
|
19257c0989952d8b5ab2ed527e1d302b2687ef46
|
[
"Apache-2.0"
] | 158 |
2016-10-13T14:21:44.000Z
|
2018-09-24T15:15:44.000Z
|
src/main/java/com/datafibers/util/ConstantApp.java
|
yjdxwz/df_data_service
|
19257c0989952d8b5ab2ed527e1d302b2687ef46
|
[
"Apache-2.0"
] | 42 |
2016-10-15T01:45:41.000Z
|
2019-11-06T09:20:31.000Z
| 56.267442 | 116 | 0.743129 | 3,430 |
package com.datafibers.util;
public final class ConstantApp {
// DF Service generic settings
public static final int REGULAR_REFRESH_STATUS_TO_REPO = 10000;
// Vertx REST Client settings
public static final int REST_CLIENT_CONNECT_TIMEOUT = 1000;
public static final int REST_CLIENT_GLOBAL_REQUEST_TIMEOUT = 5000;
public static final Boolean REST_CLIENT_KEEP_LIVE = true;
public static final int REST_CLIENT_MAX_POOL_SIZE = 500;
// DF REST endpoint URLs for all processors, connects and transforms
public static final String DF_PROCESSOR_REST_URL = "/api/df/processor";
public static final String DF_PROCESSOR_REST_URL_WILD = "/api/df/processor*";
public static final String DF_PROCESSOR_REST_URL_WITH_ID = DF_PROCESSOR_REST_URL + "/:id";
// DF REST endpoint URLs for all processors installed information and default config
public static final String DF_PROCESSOR_CONFIG_REST_URL = "/api/df/config";
public static final String DF_PROCESSOR_CONFIG_REST_URL_WILD = "/api/df/config*";
public static final String DF_PROCESSOR_CONFIG_REST_URL_WITH_ID = DF_PROCESSOR_CONFIG_REST_URL + "/:id";
// DF Connects REST endpoint URLs
public static final String DF_CONNECTS_REST_URL = "/api/df/ps";
public static final String DF_CONNECTS_REST_URL_WILD = "/api/df/ps*";
public static final String DF_CONNECTS_REST_URL_WITH_ID = DF_CONNECTS_REST_URL + "/:id";
// DF Transforms REST endpoint URLs
public static final String DF_TRANSFORMS_REST_URL = "/api/df/tr";
public static final String DF_TRANSFORMS_REST_URL_WILD = "/api/df/tr*";
public static final String DF_TRANSFORMS_REST_URL_WITH_ID = DF_TRANSFORMS_REST_URL + "/:id";
public static final String DF_TRANSFORMS_UPLOAD_FILE_REST_URL_WILD = "/api/df/uploaded_files*";
public static final String DF_TRANSFORMS_UPLOAD_FILE_REST_URL = "/api/df/uploaded_files";
// DF Model REST endpoint URLs
public static final String DF_MODEL_REST_URL = "/api/df/ml";
public static final String DF_MODEL_REST_URL_WILD = "/api/df/ml*";
public static final String DF_MODEL_REST_URL_WITH_ID = DF_MODEL_REST_URL + "/:id";
// DF Schema registry endpoint URLs
public static final String DF_SCHEMA_REST_URL = "/api/df/schema";
public static final String DF_SCHEMA_REST_URL_WILD = "/api/df/schema*";
public static final String DF_SCHEMA_REST_URL_WITH_ID = DF_SCHEMA_REST_URL + "/:id";
public static final String AVRO_REGISTRY_CONTENT_TYPE = "application/vnd.schemaregistry.v1+json";
// DF process history endpoint URLs
public static final String DF_PROCESS_HIST_REST_URL = "/api/df/hist";
public static final String DF_PROCESS_HIST_URL_WILD = "/api/df/hist*";
// DF log endpoint URLs
public static final String DF_LOGGING_REST_URL = "/api/df/logs";
public static final String DF_LOGGING_REST_URL_WILD = "/api/df/logs*";
public static final String DF_LOGGING_REST_URL_WITH_ID = DF_LOGGING_REST_URL + "/:id";
// DF task status endpoint URLs
public static final String DF_TASK_STATUS_REST_URL = "/api/df/status";
public static final String DF_TASK_STATUS_REST_URL_WILD = "/api/df/status*";
public static final String DF_TASK_STATUS_REST_URL_WITH_ID = DF_TASK_STATUS_REST_URL + "/:id";
// DF subject/topic to tasks mapping endpoint URLs
public static final String DF_SUBJECT_TO_TASK_REST_URL = "/api/df/s2t";
public static final String DF_SUBJECT_TO_TASK_REST_URL_WILD = "/api/df/s2t*";
public static final String DF_SUBJECT_TO_TASK_REST_URL_WITH_ID = DF_SUBJECT_TO_TASK_REST_URL + "/:id";
// DF subject/topic simple consumer endpoint URLs
public static final String DF_AVRO_CONSUMER_REST_URL = "/api/df/avroconsumer";
public static final String DF_AVRO_CONSUMER_REST_URL_WILD = "/api/df/avroconsumer*";
public static final String DF_AVRO_CONSUMER_REST_URL_WITH_ID = DF_AVRO_CONSUMER_REST_URL + "/:id";
// DF subject/topic partition information endpoint URLs
public static final String DF_SUBJECT_TO_PAR_REST_URL = "/api/df/s2p";
public static final String DF_SUBJECT_TO_PAR_REST_URL_WILD = "/api/df/s2p*";
public static final String DF_SUBJECT_TO_PAR_REST_URL_WITH_ID = DF_SUBJECT_TO_PAR_REST_URL + "/:id";
// Kafka Connect endpoint URLs
public static final String KAFKA_CONNECT_REST_URL = "/connectors";
public static final String KAFKA_CONNECT_PLUGIN_REST_URL = "/connector-plugins";
public static String KAFKA_CONNECT_PLUGIN_CONFIG = "/connectors/CONNECTOR_NAME_PLACEHOLDER/config";
public static final String KAFKA_CONNECT_ACTION_PAUSE = "pause";
public static final String KAFKA_CONNECT_ACTION_RESUME = "resume";
// Kafka Other default settings
public static String DF_TRANSFORMS_KAFKA_CONSUMER_GROUP_ID_FOR_FLINK = "df_trans_flink_group_id";
public static String DF_CONNECT_KAFKA_CONSUMER_GROUP_ID = "df_connect_avro_consumer_group_id";
public static int DF_CONNECT_KAFKA_CONSUMER_POLL_TIMEOUT = 100;
public static int AVRO_CONSUMER_BATCH_SIE = 10;
// Flink rest api setting
public static final String FLINK_REST_URL = "/jobs";
public static final String FLINK_REST_URL_JARS = "/jars";
public static final String FLINK_REST_URL_JARS_UPLOAD = FLINK_REST_URL_JARS + "/upload";
public static final String FLINK_JAR_ID_IN_MONGO = "df_jar_uploaded_to_flink";
public static final String FLINK_JAR_VALUE_IN_MONGO = "filename";
public static final String FLINK_JOB_SUBMIT_RESPONSE_KEY = "jobid";
public static final String FLINK_JOB_ERROR_RESPONSE_KEY = "error";
public static final String FLINK_SQL_CLIENT_CLASS_NAME = "com.datafibers.util.FlinkAvroSQLClient";
public static final String FLINK_TABLEAPI_CLIENT_CLASS_NAME = "com.datafibers.util.FlinkAvroTableAPIClient";
public static final String FLINK_DUMMY_JOB_ID = "00000000000000000000000000000000";
// Schema registry rest api setting
public static final String SR_REST_URL_SUBJECTS = "/subjects";
public static final String SR_REST_URL_CONFIG = "/config";
public static final String SR_REST_URL_VERSIONS = "/versions";
// Spark Livy rest api setting
public static final String LIVY_REST_URL_SESSIONS = "/sessions";
public static final String LIVY_REST_URL_STATEMENTS = "/statements";
public static final String TRANSFORM_STREAM_BACK_PATH = "/tmp/streamback";
// WebHDFS rest setting
public static final String WEBHDFS_REST_URL = "/webhdfs/v1";
public static final String WEBHDFS_REST_DELETE_PARA = "?op=DELETE&recursive=true";
// HTTP req/res constants
public static final String HTTP_HEADER_CONTENT_TYPE = "content-type";
public static final String HTTP_HEADER_APPLICATION_JSON_CHARSET = "application/json; charset=utf-8";
public static final String HTTP_HEADER_TOTAL_COUNT = "X-Total-Count";
// HTTP status codes
public static final int STATUS_CODE_OK = 200;
public static final int STATUS_CODE_OK_CREATED = 201;
public static final int STATUS_CODE_OK_ACCEPTED = 202;
public static final int STATUS_CODE_OK_NO_CONTENT = 204;
public static final int STATUS_CODE_BAD_REQUEST = 400;
public static final int STATUS_CODE_NOT_FOUND = 404;
public static final int STATUS_CODE_CONFLICT = 409;
// Kafka Confluent Protocol
public static final byte MAGIC_BYTE = 0x0;
public static final int idSize = 4;
public enum DF_STATUS {
UNASSIGNED, // The connector/task has not yet been assigned to a worker. This is the initial state.
RUNNING, // The connector/task is running.
STREAMING, // Streaming the data back to Queue.
PAUSED, // The connector/task has been administratively paused.
FAILED, // The connector/task has failed.
LOST, // The connect restart and lost the connector job in DF repository.
CANCELED, // Job (Flink) is canceled
RWE, // Connector/Transform is running with one of task is failed - RUNNING_WITH_ERROR
FINISHED,
NONE
}
/*
Type to differ from connect or transform. We delivered the ConnectorCategory field from the word before 1st _
The pattern here is [ConnectorCategory]_[Engine]_[Details]
*/
public enum DF_CONNECT_TYPE {
CONNECT_SOURCE_KAFKA_AvroFile,
CONNECT_SINK_KAFKA_AvroFile,
CONNECT_SINK_KAFKA_FlatFile,
CONNECT_SOURCE_KAFKA_FlatFile,
CONNECT_SOURCE_KAFKA_JDBC,
CONNECT_SINK_KAFKA_JDBC,
CONNECT_SOURCE_MONGODB_AvroDB,
CONNECT_SINK_MONGODB_AvroDB,
CONNECT_SOURCE_HDFS_AvroFile,
CONNECT_SINK_HDFS_AvroFile,
CONNECT_SOURCE_STOCK_AvroFile,
TRANSFORM_EXCHANGE_FLINK_SQLA2A,
TRANSFORM_EXCHANGE_FLINK_Script,
TRANSFORM_EXCHANGE_FLINK_UDF,
TRANSFORM_EXCHANGE_SPARK_SQL, // Spark batch SQL
TRANSFORM_EXCHANGE_SPARK_STREAM, // Spark streaming SQL
TRANSFORM_EXCHANGE_SPARK_JOINS, // Spark streaming of Data Join
TRANSFORM_EXCHANGE_SPARK_UDF, // Spark user defined jar/program
TRANSFORM_EXCHANGE_HIVE_TRANS, // Hive batch SQL
TRANSFORM_EXCHANGE_HIVE_JOINS, // Hive batch join
TRANSFORM_MODEL_SPARK_STREAM, // ML model over spark stream
TRANSFORM_MODEL_SPARK_TRAIN, // ML model training
INTERNAL_METADATA_COLLECT, // Reserved metadata sink
NONE
}
// Schema Registry Properties Keys
public static final String SCHEMA_REGISTRY_KEY_SCHEMA = "schema";
public static final String SCHEMA_REGISTRY_KEY_SUBJECT = "subject";
public static final String SCHEMA_REGISTRY_KEY_COMPATIBILITY = "compatibility";
public static final String SCHEMA_REGISTRY_KEY_COMPATIBILITY_LEVEL = "compatibilityLevel";
public static final int WORKER_POOL_SIZE = 20; // VERT.X Worker pool size
public static final int MAX_RUNTIME = 120000; // VERT.X Worker timeout in 6 sec
public static final String SCHEMA_URI_KEY = "schema.registry.url";
// Topic property keys in web ui
public static final String TOPIC_KEY_PARTITIONS = "partitions";
public static final String TOPIC_KEY_REPLICATION_FACTOR = "replicationFactor";
// Properties keys for admin
public static final String PK_DF_TOPICS_ALIAS = "topics,topic_in";
public static final String PK_DF_TOPIC_ALIAS = "topic,topic_out";
public static final String PK_DF_ALL_TOPIC_ALIAS = PK_DF_TOPICS_ALIAS + "," + PK_DF_TOPIC_ALIAS;
// Properties keys for UI
/*
JobConfig properties
*/
public static final String PK_TRANSFORM_CUID = "cuid";
public static final String PK_FLINK_SUBMIT_JOB_ID = "flink_job_id";
public static final String PK_LIVY_SESSION_ID = "livy_session_id";
public static final String PK_LIVY_SESSION_STATE = "livy_session_state";
public static final String PK_LIVY_STATEMENT_ID = "livy_statement_id";
public static final String PK_LIVY_STATEMENT_STATE = "livy_statement_state";
public static final String PK_LIVY_STATEMENT_STATUS = "livy_statement_status";
public static final String PK_LIVY_STATEMENT_OUTPUT = "livy_statement_output";
public static final String PK_LIVY_STATEMENT_PROGRESS = "livy_statement_progress";
public static final String PK_LIVY_STATEMENT_TRACEBACK = "livy_statement_traceback";
public static final String PK_LIVY_STATEMENT_EXCEPTION = "livy_statement_exception";
public static final String PK_LIVY_STATEMENT_CODE = "livy_statement_code";
/*
ConnectConfig properties
*/
// Used for stream back csv only
public static final String PK_STREAM_BACK_CONNECT_TASK = "tasks_max";
public static final String PK_STREAM_BACK_CONNECT_SRURI = "schema_registry_uri";
public static final String PK_STREAM_BACK_CONNECT_OW = "file_overwrite";
public static final String PK_STREAM_BACK_CONNECT_LOC = "file_location";
public static final String PK_STREAM_BACK_CONNECT_GLOB = "file_glob";
public static final String PK_STREAM_BACK_CONNECT_TOPIC = "topic";
// Used for flink client
public static final String PK_SCHEMA_ID_INPUT = "schema_ids_in";
public static final String PK_SCHEMA_ID_OUTPUT = "schema_ids_out";
public static final String PK_SCHEMA_STR_INPUT = "schema_string_in";
public static final String PK_SCHEMA_STR_OUTPUT = "schema_string_out";
public static final String PK_SCHEMA_SUB_INPUT = "schema_subject_in";
public static final String PK_SCHEMA_SUB_OUTPUT = "schema_subject_out";
public static final String PK_KAFKA_HOST_PORT = "bootstrap_servers";
public static final String PK_KAFKA_CONSUMER_GROURP = "group_id";
public static final String PK_KAFKA_SCHEMA_REGISTRY_HOST_PORT = "schema_registry";
public static final String PK_KAFKA_CONNECTOR_CLASS = "connector_class";
public static final String PK_FLINK_TABLE_SINK_KEYS = "sink_key_fields";
public static final String PK_KAFKA_TOPIC_INPUT = "topic_in";
public static final String PK_KAFKA_TOPIC_OUTPUT = "topic_out";
public static final String PK_TRANSFORM_SQL = "trans_sql";
public static final String PK_TRANSFORM_SCRIPT = "trans_script";
public static final String PK_TRANSFORM_JAR_CLASS_NAME = "trans_jar_class";
public static final String PK_TRANSFORM_JAR_PARA = "trans_jar_para";
// Used for stream back transform
public static final String PK_TRANSFORM_STREAM_BACK_FLAG = "stream_back_flag";
public static final String PK_TRANSFORM_STREAM_BACK_PATH = "stream_back_path";
public static final String PK_TRANSFORM_STREAM_BACK_TOPIC = "stream_back_topic";
public static final String PK_TRANSFORM_STREAM_BACK_TOPIC_CREATION = "choose_or_create";
public static final String PK_TRANSFORM_STREAM_BACK_TASK_ID = "stream_back_task_id";
public static final String PK_TRANSFORM_STREAM_BACK_TASK_STATE = "stream_back_task_state";
// Used for spark ml training
public static final String PK_TRANSFORM_MT_GUIDE_ENABLE = "ml_guide_enabled";
public static final String PK_TRANSFORM_MT_CODE_KIND = "ml_pipe_kind";
public static final String PK_TRANSFORM_MT_CODE = "ml_pipe";
}
|
3e08241ffb953ec6465da5b8a86365d01d3920d4
| 1,110 |
java
|
Java
|
CM5/Core/gui-client-impl/src/main/java/ru/intertrust/cm/core/gui/impl/client/form/widget/tableviewer/FiltersRemoteManagement.java
|
InterTurstCo/ActiveFrame5
|
a042afd5297be9636656701e502918bdbd63ce80
|
[
"Apache-2.0"
] | 4 |
2019-11-24T14:14:05.000Z
|
2021-03-30T14:35:30.000Z
|
CM5/Core/gui-client-impl/src/main/java/ru/intertrust/cm/core/gui/impl/client/form/widget/tableviewer/FiltersRemoteManagement.java
|
InterTurstCo/ActiveFrame5
|
a042afd5297be9636656701e502918bdbd63ce80
|
[
"Apache-2.0"
] | 4 |
2019-11-20T14:05:11.000Z
|
2021-12-06T16:59:54.000Z
|
CM5/Core/gui-client-impl/src/main/java/ru/intertrust/cm/core/gui/impl/client/form/widget/tableviewer/FiltersRemoteManagement.java
|
InterTurstCo/ActiveFrame5
|
a042afd5297be9636656701e502918bdbd63ce80
|
[
"Apache-2.0"
] | 2 |
2019-12-26T15:19:53.000Z
|
2022-03-27T11:01:41.000Z
| 24.666667 | 94 | 0.693694 | 3,431 |
package ru.intertrust.cm.core.gui.impl.client.form.widget.tableviewer;
import ru.intertrust.cm.core.config.gui.form.widget.filter.extra.CollectionExtraFiltersConfig;
import java.util.List;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* Developer: Ravil Abdulkhairov
* Date: 12.07.2016
* Time: 11:54
* To change this template use File | Settings | File and Code Templates.
*/
public interface FiltersRemoteManagement {
/**
* Возвращает текущие дополнительные фильтры
* @return
*/
CollectionExtraFiltersConfig getCollectionExtraFilters();
/**
* Применяет указанные дополнительные фильтры
* @param config
*/
void applyCollectionExtraFilters(CollectionExtraFiltersConfig config);
/**
* Сброс фильтров в колонках
*/
void resetColumnFilters();
/**
* Возвращает текущее состояние фильтров в колонках
* @return
*/
Map<String, List<String>> getColumnFiltersMap();
/**
* Применить фильтры к колонкам
* @param filtersMap
*/
void applyColumnFilters(Map<String, List<String>> filtersMap);
}
|
3e0824860bd01e78bc2d0b7d1f25f961020b0c05
| 2,044 |
java
|
Java
|
src/main/java/com/maxmilianoandriani/acmeapp/domain/Cliente.java
|
maxandriani/igti-soa-acme-app
|
80b3ac36b579adbd68d8e710dbbd3d4bc10c6b50
|
[
"MIT"
] | null | null | null |
src/main/java/com/maxmilianoandriani/acmeapp/domain/Cliente.java
|
maxandriani/igti-soa-acme-app
|
80b3ac36b579adbd68d8e710dbbd3d4bc10c6b50
|
[
"MIT"
] | null | null | null |
src/main/java/com/maxmilianoandriani/acmeapp/domain/Cliente.java
|
maxandriani/igti-soa-acme-app
|
80b3ac36b579adbd68d8e710dbbd3d4bc10c6b50
|
[
"MIT"
] | null | null | null | 20.237624 | 106 | 0.757828 | 3,432 |
package com.maxmilianoandriani.acmeapp.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
public class Cliente {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "id_endereco")
private Endereco enderecoCobranca;
//@JsonIgnore
@JsonBackReference
@OneToMany(mappedBy = "cliente", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Instalacao> listaInstalacao = new ArrayList<Instalacao>();
private String nome;
private String cpf;
private Date dataNascimento;
protected Cliente() {
}
public Cliente(String nome, String cpf, Date dataNascimento) {
super();
this.nome = nome;
this.cpf = cpf;
this.dataNascimento = dataNascimento;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Endereco getEnderecoCobranca() {
return enderecoCobranca;
}
public void setEnderecoCobranca(Endereco enderecoCobranca) {
this.enderecoCobranca = enderecoCobranca;
}
public List<Instalacao> getListaInstalacao() {
return listaInstalacao;
}
public void setListaInstalacao(List<Instalacao> listaInstalacao) {
this.listaInstalacao = listaInstalacao;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
}
|
3e08248766aef5d01bbe2a30706b5b06de04c245
| 3,221 |
java
|
Java
|
test/fx/dom/core/Printer.java
|
benravago/fx.html
|
a7ca6eb0554342b96eec94ca4ba8cb5594b44442
|
[
"MIT"
] | null | null | null |
test/fx/dom/core/Printer.java
|
benravago/fx.html
|
a7ca6eb0554342b96eec94ca4ba8cb5594b44442
|
[
"MIT"
] | null | null | null |
test/fx/dom/core/Printer.java
|
benravago/fx.html
|
a7ca6eb0554342b96eec94ca4ba8cb5594b44442
|
[
"MIT"
] | null | null | null | 39.280488 | 119 | 0.559143 | 3,433 |
package fx.dom.core;
import javax.xml.stream.events.*;
import fx.dom.parser.ScannerDT;
class Printer extends ScannerDT {
@Override protected void startElement(StartElement e) {
System.out.println(types[e.getEventType()]+' '+e.getName());
var a = e.getAttributes();
while (a.hasNext()) {
var t = a.next();
System.out.println("a "+t.getName()+' '+t.getValue()+' '+t.getDTDType()+' '+t.isSpecified());
}
}
@Override protected void endElement(EndElement e) {
System.out.println(types[e.getEventType()]+' '+e.getName());
}
@Override protected void processingInstruction(ProcessingInstruction e) { print(e.getEventType()); }
@Override protected void characters(Characters e) {
System.out.println(types[e.getEventType()]+' '+e.getData());
}
@Override protected void cdata(Characters e) {
System.out.println(types[12]+' '+e.getData());
}
@Override protected void whitespace(Characters e) {
System.out.println(types[6]+" ["+e.getData()+']');
}
@Override protected void comment(Comment e) { print(e.getEventType()); }
@Override protected void startDocument(StartDocument e) { print(e.getEventType()); }
@Override protected void endDocument(EndDocument e) { print(e.getEventType()); }
@Override protected void entityReference(EntityReference e) { print(e.getEventType()); }
@Override protected void attribute(Attribute e) { print(e.getEventType()); }
@Override protected void dtd(DTD e) {
System.out.println(types[e.getEventType()]);
super.dtd(e);
}
@Override protected void namespace(Namespace e) { print(e.getEventType()); }
@Override protected void notationDeclaration(NotationDeclaration e) {
System.out.println(types[e.getEventType()]+' '+e.getName());
}
@Override protected void entityDeclaration(EntityDeclaration e) {
System.out.println(types[e.getEventType()]+' '+e.getName());
}
@Override protected void elementDeclaration(String name, String model) {
System.out.println("elementDecl "+name+' '+model);
}
@Override protected void attributeDeclaration(String eName, String aName, String type, String mode, String value) {
System.out.println("attrDecl "+eName+' '+aName+' '+type+' '+mode+' '+value);
}
void print(int type) {
System.out.println(types[type]);
}
static String[] types = {
"", // 0
"START_ELEMENT", "END_ELEMENT", // 1, 2
"PROCESSING_INSTRUCTION", // 3
"CHARACTERS", "COMMENT", // 4, 5
"SPACE", // 6
"START_DOCUMENT", "END_DOCUMENT", // 7, 8
"ENTITY_REFERENCE", // 9
"ATTRIBUTE", // 10
"DTD", // 11
"CDATA", // 12
"NAMESPACE", // 13
"NOTATION_DECLARATION", // 14
"ENTITY_DECLARATION" // 15
};
}
|
3e0824af0d0f3af0b4d73ce73f86ffc1e9c11858
| 3,601 |
java
|
Java
|
fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientDetailData.java
|
cloudbankin/vivardhana-incubator-fineract
|
4bc27d093f4695b46459a11729e6e5291fa25ec5
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientDetailData.java
|
cloudbankin/vivardhana-incubator-fineract
|
4bc27d093f4695b46459a11729e6e5291fa25ec5
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
fineract-provider/src/main/java/org/apache/fineract/portfolio/client/data/ClientDetailData.java
|
cloudbankin/vivardhana-incubator-fineract
|
4bc27d093f4695b46459a11729e6e5291fa25ec5
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 19.677596 | 145 | 0.766454 | 3,434 |
package org.apache.fineract.portfolio.client.data;
import java.util.Date;
public class ClientDetailData {
private final Long client_id;
private final String clientExternal;
private final int nomineeAge;
private final String officeExtrenal;
private final String client_name;
private final String mobileNo;
private final String gender;
private final String maritalStatus;
private final String groupExternal;
public String getMaritalStatus() {
return maritalStatus;
}
private final String nomineeName;
private final Date nomineeDOB;
private final int nomineeRelation;
private final String bankName;
private final String bankAccount;
private final String accHolderName;
private final String voterId;
private final String aadhaarId;
private final String pancardId;
private final Date activateDate;
private final Date dob;
private int age;
private final String groupExternalid;
private final String external;
private final Date loanDisburedonDate;
public ClientDetailData(String clientExternal2, long client_id2, String officeExtrenal2, String client_name2,
String mobileNo2, String gender2,String maritalStatus, String groupExternal2, String nomineeName2, int nomineeAge2,
Date nomineeDOB, int nomineeRelation2, String bankName2, String bankAccount2, String accHolderName2, String voterId2,
String aadhaarId2, String pancardId2, Date activateDate2, Date dob2,int age,String groupExternalid,String external, Date loanDisburedonDate) {
this.aadhaarId=aadhaarId2;
this.accHolderName=accHolderName2;
this.activateDate=activateDate2;
this.bankAccount=bankAccount2;
this.bankName=bankName2;
this.client_id=client_id2;
this.client_name=client_name2;
this.clientExternal=clientExternal2;
this.dob=dob2;
this.gender=gender2;
this.maritalStatus = maritalStatus;
this.groupExternal=groupExternal2;
this.mobileNo=mobileNo2;
this.nomineeAge=nomineeAge2;
this.nomineeDOB=nomineeDOB;
this.nomineeName=nomineeName2;
this.nomineeRelation=nomineeRelation2;
this.officeExtrenal=officeExtrenal2;
this.pancardId=pancardId2;
this.voterId=voterId2;
this.age=age;
this.groupExternalid = groupExternalid;
this.external = external;
this.loanDisburedonDate=loanDisburedonDate;
}
public Date getLoanDisburedonDate() {
return loanDisburedonDate;
}
public Date getNomineeDOB() {
return nomineeDOB;
}
public int getAge() {
return age;
}
public Long getClient_id() {
return client_id;
}
public String getClientExternal() {
return clientExternal;
}
public int getNomineeAge() {
return nomineeAge;
}
public String getOfficeExtrenal() {
return officeExtrenal;
}
public String getClient_name() {
return client_name;
}
public String getMobileNo() {
return mobileNo;
}
public String getGender() {
return gender;
}
public String getGroupExternal() {
return groupExternal;
}
public String getNomineeName() {
return nomineeName;
}
public int getNomineeRelation() {
return nomineeRelation;
}
public String getBankName() {
return bankName;
}
public String getBankAccount() {
return bankAccount;
}
public String getAccHolderName() {
return accHolderName;
}
public String getVoterId() {
return voterId;
}
public String getAadhaarId() {
return aadhaarId;
}
public String getPancardId() {
return pancardId;
}
public Date getActivateDate() {
return activateDate;
}
public Date getDob() {
return dob;
}
public String getGroupExternalid() {
return groupExternalid;
}
public String getExternal() {
return external;
}
}
|
3e0824cc7aada2deb4f2ce5da6e4d4266f6048f6
| 1,180 |
java
|
Java
|
00_framework/core/src/main/java/com/bizzan/bitrade/entity/MemberInviteStasticRank.java
|
sumsudo/CoinExchange_CryptoExchange_Java
|
8adf508b996020d3efbeeb2473d7235bd01436fa
|
[
"Apache-2.0"
] | 498 |
2020-06-29T04:13:12.000Z
|
2022-03-30T10:59:20.000Z
|
00_framework/core/src/main/java/com/bizzan/bitrade/entity/MemberInviteStasticRank.java
|
tomxi444/uu2knowCoinEx
|
00d3a1fd6121520b96cdea545d127c32220ed456
|
[
"Apache-2.0"
] | 39 |
2021-05-06T17:48:33.000Z
|
2022-03-31T19:53:30.000Z
|
00_framework/core/src/main/java/com/bizzan/bitrade/entity/MemberInviteStasticRank.java
|
SularCuipealiuz/05_Web_Front
|
ba5afa3bf470b58fe0b9d4e355f81e333aaa4639
|
[
"Apache-2.0"
] | 488 |
2020-06-29T07:32:29.000Z
|
2022-03-29T02:54:33.000Z
| 18.4375 | 68 | 0.677966 | 3,435 |
package com.bizzan.bitrade.entity;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
/**
* 邀请日榜、周榜、月榜排名数据
* @author shaox
*
*/
@Entity
@Data
public class MemberInviteStasticRank {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
private Long id;
private Long memberId;
/**
* 用户账户标识,手机或邮箱
*/
private String userIdentify;
/**
* 邀请一级好友数量
*/
private int levelOne;
/**
* 邀请二级好友数量
*/
private int levelTwo;
/**
* 类型:0 = 日榜,1 = 周榜, 2 = 月榜
*/
@NotNull
private int type;
/**
* 是否机器人(0:否,1:是)
*/
@JsonIgnore
private int isRobot = 0;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date stasticDate;
}
|
3e082518471700d149974fec4cad963c7ca52cee
| 1,241 |
java
|
Java
|
src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Exception.java
|
rfmejia/WorldWindJava-pcm
|
bf0e675bda96313684ba3cf025078f0c4ce6a03e
|
[
"NASA-1.3"
] | 4 |
2017-03-31T14:29:22.000Z
|
2019-07-04T14:57:32.000Z
|
src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Exception.java
|
rfmejia/WorldWindJava-pcm
|
bf0e675bda96313684ba3cf025078f0c4ce6a03e
|
[
"NASA-1.3"
] | 3 |
2018-08-22T06:41:24.000Z
|
2019-04-19T11:22:50.000Z
|
src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Exception.java
|
rfmejia/WorldWindJava-pcm
|
bf0e675bda96313684ba3cf025078f0c4ce6a03e
|
[
"NASA-1.3"
] | 7 |
2017-07-07T20:17:30.000Z
|
2019-08-24T11:25:18.000Z
| 25.326531 | 97 | 0.663175 | 3,436 |
/*
* Copyright (C) 2014 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration.
* All Rights Reserved.
*/
package gov.nasa.worldwind.ogc.wcs.wcs100;
import gov.nasa.worldwind.util.WWUtil;
import gov.nasa.worldwind.util.xml.*;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import java.util.*;
/**
* @author tag
* @version $Id: WCS100Exception.java 2061 2014-06-19 19:59:40Z tgaskins $
*/
public class WCS100Exception extends AbstractXMLEventParser
{
protected List<String> formats = new ArrayList<String>(1);
public WCS100Exception(String namespaceURI)
{
super(namespaceURI);
}
public List<String> getFormats()
{
return this.formats;
}
protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args)
throws XMLStreamException
{
if (ctx.isStartElement(event, "Format"))
{
String s = ctx.getStringParser().parseString(ctx, event);
if (!WWUtil.isEmpty(s))
this.formats.add(s);
}
else
{
super.doParseEventContent(ctx, event, args);
}
}
}
|
3e08253a8d10bf0c36e19aec26962d1cfa443cad
| 2,990 |
java
|
Java
|
smt-cloudformation-objects/src/main/java/shiver/me/timbers/aws/apigateway/DomainNameEndpointConfiguration.java
|
shiver-me-timbers/smt-cloudformation-parent
|
e2600814428a92ff8ea5977408ccc6a8f511a561
|
[
"Apache-2.0"
] | 4 |
2018-10-12T02:52:38.000Z
|
2019-10-02T21:16:00.000Z
|
smt-cloudformation-objects/src/main/java/shiver/me/timbers/aws/apigateway/DomainNameEndpointConfiguration.java
|
shiver-me-timbers/smt-cloudformation-parent
|
e2600814428a92ff8ea5977408ccc6a8f511a561
|
[
"Apache-2.0"
] | 1 |
2021-04-26T17:00:09.000Z
|
2021-04-26T17:00:09.000Z
|
smt-cloudformation-objects/src/main/java/shiver/me/timbers/aws/apigateway/DomainNameEndpointConfiguration.java
|
shiver-me-timbers/smt-cloudformation-parent
|
e2600814428a92ff8ea5977408ccc6a8f511a561
|
[
"Apache-2.0"
] | null | null | null | 34.767442 | 211 | 0.742475 | 3,437 |
package shiver.me.timbers.aws.apigateway;
import java.util.LinkedHashSet;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import shiver.me.timbers.aws.Property;
/**
* DomainNameEndpointConfiguration
* <p>
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-domainname-endpointconfiguration.html
*
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonPropertyOrder({
"Types"
})
public class DomainNameEndpointConfiguration implements Property<DomainNameEndpointConfiguration>
{
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-domainname-endpointconfiguration.html#cfn-apigateway-domainname-endpointconfiguration-types
*
*/
@JsonProperty("Types")
@JsonDeserialize(as = java.util.LinkedHashSet.class)
@JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-domainname-endpointconfiguration.html#cfn-apigateway-domainname-endpointconfiguration-types")
private Set<CharSequence> types = new LinkedHashSet<CharSequence>();
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-domainname-endpointconfiguration.html#cfn-apigateway-domainname-endpointconfiguration-types
*
*/
@JsonIgnore
public Set<CharSequence> getTypes() {
return types;
}
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-domainname-endpointconfiguration.html#cfn-apigateway-domainname-endpointconfiguration-types
*
*/
@JsonIgnore
public void setTypes(Set<CharSequence> types) {
this.types = types;
}
public DomainNameEndpointConfiguration withTypes(Set<CharSequence> types) {
this.types = types;
return this;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("types", types).toString();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(types).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof DomainNameEndpointConfiguration) == false) {
return false;
}
DomainNameEndpointConfiguration rhs = ((DomainNameEndpointConfiguration) other);
return new EqualsBuilder().append(types, rhs.types).isEquals();
}
}
|
3e082549fcc4d61115931305f191fef548ee12e6
| 2,245 |
java
|
Java
|
src/test/java/com/jeeneee/realworld/tag/service/TagServiceTest.java
|
jeeneee/realworld
|
1d607c284c4e0c084723ed578c009e6aa786a762
|
[
"MIT"
] | null | null | null |
src/test/java/com/jeeneee/realworld/tag/service/TagServiceTest.java
|
jeeneee/realworld
|
1d607c284c4e0c084723ed578c009e6aa786a762
|
[
"MIT"
] | null | null | null |
src/test/java/com/jeeneee/realworld/tag/service/TagServiceTest.java
|
jeeneee/realworld
|
1d607c284c4e0c084723ed578c009e6aa786a762
|
[
"MIT"
] | 1 |
2021-07-15T06:58:06.000Z
|
2021-07-15T06:58:06.000Z
| 29.539474 | 78 | 0.696659 | 3,438 |
package com.jeeneee.realworld.tag.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.when;
import com.jeeneee.realworld.tag.domain.Tag;
import com.jeeneee.realworld.tag.domain.TagRepository;
import com.jeeneee.realworld.tag.dto.MultipleTagResponse;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class TagServiceTest {
@Mock
private TagRepository tagRepository;
private TagService tagService;
private List<String> tagList;
private List<Tag> tags;
@BeforeEach
void setUp() {
tagService = new TagService(tagRepository);
tagList = List.of("reactjs", "angularjs");
tags = tagList.stream().map(Tag::create).collect(Collectors.toList());
}
@DisplayName("태그 조회/생성 - 태그가 있으면 조회한다.")
@Test
void findOrSave_TagsExist_Find() {
when(tagRepository.findByName(any()))
.thenReturn(Optional.of(tags.get(0)))
.thenReturn(Optional.of(tags.get(1)));
List<Tag> result = tagService.findOrSave(tagList);
assertThat(result).containsAll(tags);
}
@DisplayName("태그 조회/생성 - 태그가 없으면 생성한다.")
@Test
void findOrSave_TagsNotExist_Save() {
when(tagRepository.findByName(any()))
.thenReturn(Optional.empty())
.thenReturn(Optional.empty());
when(tagRepository.save(any(Tag.class)))
.thenReturn(tags.get(0))
.thenReturn(tags.get(1));
List<Tag> result = tagService.findOrSave(tagList);
assertThat(result).containsAll(tags);
}
@DisplayName("태그 전체 조회")
@Test
void findAll_Normal_Success() {
given(tagRepository.findAll()).willReturn(tags);
MultipleTagResponse response = tagService.findAll();
assertThat(response.getTags()).containsAll(tagList);
}
}
|
3e08255b7249af1361df537fae5ae8d90499e3d1
| 10,461 |
java
|
Java
|
SCAIIF/src/vista/controlador/RegistrodeAsistenciaController.java
|
Eduardox18/SCAIIF
|
2a00d1b3d156b7a6f5fadd7606b6b867ed277bf7
|
[
"MIT"
] | null | null | null |
SCAIIF/src/vista/controlador/RegistrodeAsistenciaController.java
|
Eduardox18/SCAIIF
|
2a00d1b3d156b7a6f5fadd7606b6b867ed277bf7
|
[
"MIT"
] | null | null | null |
SCAIIF/src/vista/controlador/RegistrodeAsistenciaController.java
|
Eduardox18/SCAIIF
|
2a00d1b3d156b7a6f5fadd7606b6b867ed277bf7
|
[
"MIT"
] | null | null | null | 36.072414 | 119 | 0.62365 | 3,439 |
package vista.controlador;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXDrawer;
import com.jfoenix.controls.JFXHamburger;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import modelo.dao.ActividadDAO;
import modelo.dao.AlumnoDAO;
import modelo.dao.ReservacionDAO;
import modelo.pojos.Actividad;
import modelo.pojos.Alumno;
import modelo.pojos.Reservacion;
import vista.Dialogo;
/**
*
* @author Hernández González Esmeralda Yamileth
*/
public class RegistrodeAsistenciaController implements Initializable {
@FXML
private JFXButton botonCancelar;
@FXML
private JFXButton botonAsistencia;
@FXML
private TableView tablaAlumnos;
@FXML
private TableColumn colNombre;
@FXML
private TableColumn colMatricula;
@FXML
private TableColumn colApPaterno;
@FXML
private TableColumn colApMaterno;
@FXML
private JFXComboBox<String> comboFecha;
@FXML
private JFXComboBox<String> comboActividad;
@FXML
JFXHamburger menuIcon = new JFXHamburger();
@FXML
JFXDrawer menuDrawer = new JFXDrawer();
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
try {
VBox box = FXMLLoader.load(getClass().getResource("/vista/DrawerPrincipal.fxml"));
menuDrawer.setSidePane(box);
menuDrawer.setDisable(true);
} catch (IOException ex) {
Dialogo dialogo = new Dialogo(Alert.AlertType.ERROR,
"Servidor no disponible, intente más tarde", "Error", ButtonType.OK);
dialogo.show();
}
menuIcon.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {
menuDrawer.open();
menuDrawer.setDisable(false);
menuIcon.setVisible(false);
});
botonCancelar.setDisable(true);
botonAsistencia.setDisable(true);
llenarComboBox();
}
/**
* Método que hace visible e invisible el menú drawer.
*/
@FXML
public void mostrarIcono() {
if (!menuDrawer.isShown()) {
menuIcon.setVisible(true);
menuDrawer.setDisable(true);
}
}
/**
* Recupera de la base de datos las fechas y noActividad de las reservaciones registradas.
*/
private void llenarComboBox() {
List<Reservacion> fechas = null;
Dialogo dialogo = null;
try {
fechas = ReservacionDAO.recuperarFechas();
List<String> fechaReservacion = new ArrayList<>();
for (Reservacion reservacion : fechas) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
String fechaTexto = formatter.format(reservacion.getFecha());
fechaReservacion.add(fechaTexto);
}
ObservableList<String> fechasObservable = FXCollections.observableArrayList(fechaReservacion);
comboFecha.setItems(fechasObservable);
} catch (IOException ex) {
dialogo = new Dialogo(Alert.AlertType.ERROR,
"Error al recuperar fechas.", "Error", ButtonType.OK);
dialogo.show();
}
}
/**
* Recupera el nombre de las actividades de acuerdo a la fecha seleccionada.
*/
@FXML
public void recuperarActividades() {
List<Actividad> nombreActividad = null;
Dialogo dialogo = null;
try {
nombreActividad = ActividadDAO.recuperarNombreActividad(comboFecha.getSelectionModel().getSelectedItem());
List<String> nombreActividades = new ArrayList<>();
for (Actividad actividad : nombreActividad) {
nombreActividades.add(actividad.getNombre());
}
ObservableList<String> noActividadObservable = FXCollections.observableArrayList(nombreActividades);
comboActividad.setItems(noActividadObservable);
} catch (IOException ex) {
dialogo = new Dialogo(Alert.AlertType.ERROR,
"Error al recuperar nombre de actividades.", "Error", ButtonType.OK);
dialogo.show();
}
}
/**
* Recupera los alumnos que reservación la actividad seleccionada a la hora seleccionada.
*/
@FXML
public void recuperarLista() {
Dialogo dialogo = null;
Date fechaDate = null;
List<Integer> noActividades = null;
String fecha = comboFecha.getValue();
SimpleDateFormat fechaFormat = new SimpleDateFormat("yyyy/MM/dd");
List<Actividad> noActividad = null;
int numActividad = 0;
try {
fechaDate = fechaFormat.parse(fecha);
} catch (ParseException ex) {
}
try {
noActividad = ActividadDAO.recuperarNombreActividad(comboFecha.getSelectionModel().getSelectedItem());
noActividades = new ArrayList<>();
for (Actividad actividad : noActividad) {
noActividades.add(actividad.getNoActividad());
}
numActividad = noActividades.get(comboActividad.getSelectionModel().getSelectedIndex());
} catch (IOException | ArrayIndexOutOfBoundsException ex) {
}
List<Alumno> reservaciones = new ArrayList<>();
Reservacion reservacion = new Reservacion();
reservacion.setFecha(fechaDate);
reservacion.setNoActividad(numActividad);
reservacion.setAsistencia(false);
try {
reservaciones = AlumnoDAO.recuperarLista(reservacion);
ObservableList<Alumno> alumnosReservados = FXCollections.observableArrayList(reservaciones);
colMatricula.setCellValueFactory(new PropertyValueFactory<>("matricula"));
colNombre.setCellValueFactory(new PropertyValueFactory<>("nombre"));
colApPaterno.setCellValueFactory(new PropertyValueFactory<>("apPaterno"));
colApMaterno.setCellValueFactory(new PropertyValueFactory<>("apMaterno"));
tablaAlumnos.setItems(alumnosReservados);
} catch (IOException ex) {
dialogo = new Dialogo(Alert.AlertType.ERROR,
"Error al recuperar actividades", "Error", ButtonType.OK);
dialogo.show();
}
}
/**
* Comprueba que se encuentre seleccionado un alumno antes de registrar su asistencia.
*/
@FXML
private void seleccionarRegistro() {
if (tablaAlumnos.getSelectionModel().getSelectedItem() != null) {
botonCancelar.setDisable(false);
botonAsistencia.setDisable(false);
} else {
botonCancelar.setDisable(false);
botonAsistencia.setDisable(false);
}
}
/**
* Comprueba que el registro haya sido exitoso.
*/
@FXML
private void comprobarRegistroAsistencia() {
Dialogo dialogo = null;
String matricula = tablaAlumnos.getSelectionModel().getSelectedItem().toString();
Date fechaDate = null;
List<Actividad> noActividad = null;
List<Integer> noActividades = null;
int numActividad = 0;
String fecha = comboFecha.getValue();
SimpleDateFormat fechaFormat = new SimpleDateFormat("yyyy/MM/dd");
try {
noActividad = ActividadDAO.recuperarNombreActividad(comboFecha.getSelectionModel().getSelectedItem());
noActividades = new ArrayList<>();
for (Actividad actividad : noActividad) {
noActividades.add(actividad.getNoActividad());
}
numActividad = noActividades.get(comboActividad.getSelectionModel().getSelectedIndex());
} catch (IOException | ArrayIndexOutOfBoundsException ex) {
}
try {
fechaDate = fechaFormat.parse(fecha);
} catch (ParseException ex) {
}
Reservacion reservacion = new Reservacion();
reservacion.setMatricula(matricula);
reservacion.setFecha(fechaDate);
reservacion.setNoActividad(numActividad);
reservacion.setAsistencia(true);
try {
ReservacionDAO.registrarAsistencia(reservacion);
dialogo = new Dialogo(Alert.AlertType.INFORMATION,
"Asistencia registrada correctamente.", "Éxito", ButtonType.OK);
dialogo.show();
botonCancelar.setDisable(true);
botonAsistencia.setDisable(true);
recuperarLista();
limpiarCampos();
} catch (IOException ex) {
dialogo = new Dialogo(Alert.AlertType.ERROR,
"Error al registrar asistencias.", "Error", ButtonType.OK);
dialogo.show();
}
}
/**
* Limpia los campos.
*/
public void limpiarCampos() {
comboFecha.setValue("");
comboActividad.setValue("");
}
/**
*
* Cierra la ventana actual cuando se cancela la operación o una vez que se haya concluido y
* limpia los campos de búsqueda.
*/
@FXML
public void botonCerrarVentana() {
Dialogo dialogo = new Dialogo(Alert.AlertType.CONFIRMATION,
"¿Seguro que desea cancelar el registro de asistencia?", "Confirmación",
ButtonType.OK, ButtonType.CANCEL);
dialogo.showAndWait().ifPresent(response -> {
if (response == ButtonType.OK) {
limpiarCampos();
botonCancelar.setDisable(true);
botonAsistencia.setDisable(true);
}
});
}
}
|
3e0825b9754397556a6abd382a184e0859f96a13
| 497 |
java
|
Java
|
src/main/java/com/moqi/archive/corejava/v1ch13/systemInfo/SystemInfo.java
|
moqimoqidea/moqi-tool-java
|
f8f2a1fd37db98caa2468c5c7f76762637585ebd
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/moqi/archive/corejava/v1ch13/systemInfo/SystemInfo.java
|
moqimoqidea/moqi-tool-java
|
f8f2a1fd37db98caa2468c5c7f76762637585ebd
|
[
"Apache-2.0"
] | 2 |
2021-05-30T05:02:48.000Z
|
2022-01-08T15:32:46.000Z
|
src/main/java/com/moqi/archive/corejava/v1ch13/systemInfo/SystemInfo.java
|
moqimoqidea/moqi-tool-java
|
f8f2a1fd37db98caa2468c5c7f76762637585ebd
|
[
"Apache-2.0"
] | null | null | null | 19.115385 | 57 | 0.619718 | 3,440 |
package com.moqi.archive.corejava.v1ch13.systemInfo;
import java.io.*;
import java.util.*;
/**
* This program prints out all system properties.
* @version 1.10 2002-07-06
* @author Cay Horstmann
*/
public class SystemInfo
{
public static void main(String args[])
{
try
{
Properties sysprops = System.getProperties();
sysprops.store(System.out, "System Properties");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
|
3e082615c1ba586becff4e698515b8bdd7ad3494
| 684 |
java
|
Java
|
src/main/java/com/cehome/apimanager/ApiManagerApplication.java
|
NightRunner/api-manager
|
ffdf0d259b514a47e97b18814962328d8db98ff7
|
[
"Apache-2.0"
] | 16 |
2018-03-09T07:28:21.000Z
|
2019-10-30T11:39:15.000Z
|
src/main/java/com/cehome/apimanager/ApiManagerApplication.java
|
easy-ware/api-manager
|
c0d92278f644542a7a99fe2138fcc44bc9598d6f
|
[
"Apache-2.0"
] | 10 |
2018-07-12T02:33:47.000Z
|
2019-10-31T01:54:04.000Z
|
src/main/java/com/cehome/apimanager/ApiManagerApplication.java
|
easy-ware/api-manager
|
c0d92278f644542a7a99fe2138fcc44bc9598d6f
|
[
"Apache-2.0"
] | 7 |
2018-07-10T09:32:34.000Z
|
2019-07-23T16:47:03.000Z
| 36 | 84 | 0.818713 | 3,441 |
package com.cehome.apimanager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class ApiManagerApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(ApiManagerApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(ApiManagerApplication.class, args);
}
}
|
3e08261a81708b26b15a92261e4078adb17f04a5
| 1,234 |
java
|
Java
|
src/main/java/io/github/apace100/origins/power/common/MultiplyPotionDurationPower.java
|
apace100/origins-forge
|
ef51e7e7980ca870add1918d20ecc8c53e35979e
|
[
"MIT"
] | 2 |
2021-02-18T03:51:38.000Z
|
2021-05-18T19:53:11.000Z
|
src/main/java/io/github/apace100/origins/power/common/MultiplyPotionDurationPower.java
|
apace100/origins-forge
|
ef51e7e7980ca870add1918d20ecc8c53e35979e
|
[
"MIT"
] | null | null | null |
src/main/java/io/github/apace100/origins/power/common/MultiplyPotionDurationPower.java
|
apace100/origins-forge
|
ef51e7e7980ca870add1918d20ecc8c53e35979e
|
[
"MIT"
] | 3 |
2021-05-01T18:37:30.000Z
|
2022-02-08T23:17:11.000Z
| 36.294118 | 130 | 0.790924 | 3,442 |
package io.github.apace100.origins.power.common;
import io.github.apace100.origins.power.Power;
import io.github.apace100.origins.utils.Reflection;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.potion.EffectInstance;
import net.minecraftforge.event.entity.living.PotionEvent.PotionAddedEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
public class MultiplyPotionDurationPower extends Power {
private double multiplier;
public MultiplyPotionDurationPower(String name, double multiplier) {
super(name);
this.multiplier = multiplier;
this.setEventHandler();
}
@SubscribeEvent
public void onApplyPotion(PotionAddedEvent event) {
if(!event.getEntity().world.isRemote) {
if(event.getEntityLiving() instanceof PlayerEntity) {
PlayerEntity player = (PlayerEntity)event.getEntityLiving();
if(this.isActive(player) && event.getPotionEffect().getPotion().isBeneficial()) {
int newDuration = (int)(event.getPotionEffect().getDuration() * this.multiplier);
ObfuscationReflectionHelper.setPrivateValue(EffectInstance.class, event.getPotionEffect(), newDuration, Reflection.DURATION);
}
}
}
}
}
|
3e082633613b5e7abaaae148ab435df06db7a604
| 844 |
java
|
Java
|
raspberry-pi-feature-test/src/test/java/org/robbins/raspberry/pi/feature/test/StatusIT.java
|
justinhrobbins/raspberry-pi-api
|
0543402a794796500e7410f6ed4680e55f7a6288
|
[
"Apache-2.0"
] | 2 |
2016-01-01T22:59:09.000Z
|
2016-12-14T23:50:32.000Z
|
raspberry-pi-feature-test/src/test/java/org/robbins/raspberry/pi/feature/test/StatusIT.java
|
justinhrobbins/raspberry-pi-api
|
0543402a794796500e7410f6ed4680e55f7a6288
|
[
"Apache-2.0"
] | null | null | null |
raspberry-pi-feature-test/src/test/java/org/robbins/raspberry/pi/feature/test/StatusIT.java
|
justinhrobbins/raspberry-pi-api
|
0543402a794796500e7410f6ed4680e55f7a6288
|
[
"Apache-2.0"
] | 1 |
2018-09-27T09:09:35.000Z
|
2018-09-27T09:09:35.000Z
| 29.103448 | 78 | 0.780806 | 3,443 |
package org.robbins.raspberry.pi.feature.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robbins.raspberry.pi.client.StatusClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicatonContext-client.xml"})
public class StatusIT {
@Autowired
private StatusClient statusClient;
private static final String STATUS_OK = "Status: Ok";
@Test
public void testStatus() {
String status = statusClient.getStatus();
assertThat(status, is(STATUS_OK));
}
}
|
3e08263d33ce1c3c5fe6e56693c1aa3bc1fc1384
| 9,207 |
java
|
Java
|
src/main/java/org/corehat/common/scaffold/Scaffold.java
|
corehat/common-scaffold
|
8a4813e49d9d4072645c298bff9973c2502d0c1c
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/corehat/common/scaffold/Scaffold.java
|
corehat/common-scaffold
|
8a4813e49d9d4072645c298bff9973c2502d0c1c
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/corehat/common/scaffold/Scaffold.java
|
corehat/common-scaffold
|
8a4813e49d9d4072645c298bff9973c2502d0c1c
|
[
"Apache-2.0"
] | null | null | null | 32.648936 | 118 | 0.546867 | 3,444 |
package org.corehat.common.scaffold;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.corehat.common.util.PropertiesUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* 代码生成脚手架.
*
* @author: lijx
* @since 1.0.0
* @date: 2016-8-25 上午1:41:23
*/
public class Scaffold {
/**
* 数据库连接池
*/
private DriverManagerDataSource source;
/**
* 通用数据库操作类
*/
private JdbcTemplate jdbcTemplate;
/**
* main方法.
*
* @param args 调用参数
* @author lijx
* @since 1.0.0
* @date 2018-05-07 02:51
*/
public static void main(String[] args) {
Scaffold factory = new Scaffold();
try {
factory.build();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成后台文件
*/
public void build() {
// 获取配置信息
Map<String, Object> root = PropertiesUtils.getProopertyMap();
// 初始化数据库连接池
source = new DriverManagerDataSource();
// 设置jdbc信息
source.setDriverClassName(PropertiesUtils.getValue("jdbc.driver"));
source.setUrl(PropertiesUtils.getValue("jdbc.url"));
source.setUsername(PropertiesUtils.getValue("jdbc.username"));
source.setPassword(PropertiesUtils.getValue("jdbc.password"));
// 创建通用数据库操作类
jdbcTemplate = new JdbcTemplate(source);
// 获取表相关信息
String tableName = PropertiesUtils.getValue("tableName");
String showColumnSql = " SHOW FULL COLUMNS FROM " + tableName;
try {
List<Map<String, Object>> columnList = jdbcTemplate.queryForList(showColumnSql);
List<Map<String, Object>> list = ColumnUtils.columnAddType(columnList);
root.put("columnList", list);
} catch (Exception e) {
System.out.println("数据库连接异常!");
e.printStackTrace();
return;
}
// 设置模板生成时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ahh:mm:ss");
root.put("createDate", sdf.format(new Date()));
// 自定义字段名称格式化函数
root.put("nameFmt", new ColumnFormat());
// 创建配置文件
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setDefaultEncoding("UTF-8");
// 模板路径
String templatePath = PropertiesUtils.getValue("templatePath");
if (templatePath == null || "".equals(templatePath.trim())) {
templatePath = "/template/scaffold";
}
// 获取模板文件列表
List<String> templatePathL = new ArrayList<String>();
// 1、判断是否为绝对路径
try {
File file = new File(templatePath);
getTemplateFilesByDir(file, templatePathL);
cfg.setDirectoryForTemplateLoading(file);
} catch (Exception e1) {
e1.printStackTrace();
// 2、判断是否为相对路径
try {
File file = new File(this.getClass().getResource("/").getPath() + templatePath);
getTemplateFilesByDir(file, templatePathL);
cfg.setDirectoryForTemplateLoading(file);
} catch (Exception e2) {
e2.printStackTrace();
// 3、或取jar模板文件列表
try {
cfg.setClassForTemplateLoading(this.getClass(), templatePath);
// 处理jar包文件前面没有斜杠问题
if (templatePath.startsWith("/")) {
if (templatePath.length() > 1) {
templatePath = templatePath.substring(1);
} else {
templatePath = "";
}
}
getTemplateFilesByJar(templatePath, templatePathL);
} catch (Exception e3) {
e3.printStackTrace();
System.out.println("读取模板文件失败!");
return;
}
}
}
if (templatePathL == null || templatePathL.isEmpty()) {
System.out.println("没有找到模板文件!");
return;
}
// 输出路径
File output = new File(PropertiesUtils.getValue("outPath"));
// 生成模板
generateFile(templatePathL, templatePath, output, cfg, root);
}
/**
* 根据目录获取模板文件列表
*
* @param dir
* 模板目录
* @param templatePathL
* 模板列表
*/
private void getTemplateFilesByDir(File dir, List<String> templatePathL) {
if (dir.isDirectory()) {
File[] filelist = dir.listFiles();
for (int i = 0; i < filelist.length; i++) {
getTemplateFilesByDir(filelist[i], templatePathL);
}
} else if (dir.getName().indexOf(".ftl") > -1) {
templatePathL.add(dir.getPath());
}
}
/**
* 获取jar模板文件列表
*
* @param templatePath
* 模板目录
* @param templatePathL
* 模板列表
* @throws Exception
*/
private void getTemplateFilesByJar(String templatePath, List<String> templatePathL) throws Exception {
// 如果是jar获取的是jar包路径,如果不是jar文件获取的是目录
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
// 转换处理中文及空格
path = java.net.URLDecoder.decode(path, "UTF-8");
if (path.endsWith(".jar")) {
// 读取jar包文件
JarFile jarFile = new JarFile(path);
Enumeration<JarEntry> em = jarFile.entries();
while (em.hasMoreElements()) {
JarEntry je = em.nextElement();
System.out.println(je.getName());
if (je.getName().startsWith(templatePath) && je.getName().endsWith(".ftl")) {
templatePathL.add(je.getName());
}
}
} else {
File file = new File(path);
getTemplateFilesByDir(file, templatePathL);
}
}
/**
* 根据模板和数据生成代码
*
* @param templatePathList 模板路径
* @param templateDir 模板根目录
* @param targetroot 输出路径
* @param cfg 配置对象
* @param root 数据来源
* @date: 2016-8-25 上午1:51:17
*/
private void generateFile(List<String> templatePathList, String templateDir, File targetroot, Configuration cfg,
Map<String, Object> root) {
for (String templatePath : templatePathList) {
try {
templatePath = templatePath.replaceAll("\\\\", "/");
String relatePath = templatePath.substring(templatePath.indexOf(templateDir) + templateDir.length());
int lastIndex = relatePath.lastIndexOf("/");
String parentPath = lastIndex > 0 ? relatePath.substring(0, lastIndex) : "";
File targetParent = new File((targetroot.getPath() + valueParam(parentPath, root)).toLowerCase());
if (!targetParent.exists()) {
targetParent.mkdirs();
}
String tempfilename = relatePath;
if (lastIndex > 0) {
tempfilename = tempfilename.substring(lastIndex + 1);
}
tempfilename = valueParam(tempfilename, root);
File target = new File(
targetroot.getPath() + valueParam(parentPath, root) + "/" + tempfilename.replace(".ftl", ""));
if (target.exists()) {
target.delete();
}
Template temp = cfg.getTemplate(relatePath);
Writer out = new FileWriter(target);
try {
temp.process(root, out);
} catch (TemplateException e) {
e.printStackTrace();
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 将目录中的freemaker变量进行识别和替换
* @param str 需要识别的目录
* @param root 数据来源
* @return 目录名称
* @author lijx
* @since 1.0.0
* @date 2018-05-07 02:56
*/
private String valueParam(String str, Map<String, Object> root) {
List<String> list = new ArrayList<String>();
Pattern pattern = Pattern.compile("\\$\\{[^\\$|\\{|\\}]*\\}");
Matcher mather = pattern.matcher(str);
while (mather.find()) {
list.add(mather.group(0));
}
for (int i = 0; i < list.size(); i++) {
String param = list.get(i);
String key = param.replace("${", "").replace("}", "");
str = str.replace(param, StringUtils.capitalize(String.valueOf(root.get(key))));
}
return str;
}
}
|
3e08274a855affd40997f77c24c08bcaa15c6cb5
| 4,368 |
java
|
Java
|
modules/fixflow-core/src/main/java/com/founder/fix/fixflow/core/exception/ExceptionResourceCore.java
|
DamonTung/fixflow
|
e2d4045899baa7782dd9ce986a9c4594f0aeac26
|
[
"Apache-2.0"
] | 502 |
2015-01-05T09:33:19.000Z
|
2022-03-09T00:32:35.000Z
|
modules/fixflow-core/src/main/java/com/founder/fix/fixflow/core/exception/ExceptionResourceCore.java
|
tftmtgh/fixflow
|
68d401090efc5d620dc10aeecca36dc0743316b2
|
[
"Apache-2.0"
] | 12 |
2015-01-09T08:43:33.000Z
|
2017-11-13T09:20:54.000Z
|
modules/fixflow-core/src/main/java/com/founder/fix/fixflow/core/exception/ExceptionResourceCore.java
|
tftmtgh/fixflow
|
68d401090efc5d620dc10aeecca36dc0743316b2
|
[
"Apache-2.0"
] | 234 |
2015-01-05T13:40:52.000Z
|
2022-03-22T00:33:37.000Z
| 29.12 | 105 | 0.679945 | 3,445 |
/**
* Copyright 1996-2013 Founder International Co.,Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author ych
*/
package com.founder.fix.fixflow.core.exception;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.founder.fix.fixflow.core.impl.Context;
import com.founder.fix.fixflow.core.impl.util.ReflectUtil;
import com.founder.fix.fixflow.core.impl.util.StringUtil;
/**
* 异常国际化信息处理类
* 默认加载resourcePath下的 zh_CN、en_US等目录下的FixFlowExceptionResource.properties文件
* 默认从线程副本读取当前session语言,取对应的国际化值
* @author ych
*
*/
public class ExceptionResourceCore {
private static Logger log = LoggerFactory.getLogger(ExceptionResourceCore.class);
public static final String EXCEPTION_PROPERTIES = "FixFlowExceptionResource.properties";
private static String RESOURCE_PATH="";
public static Map<String,Properties> exceptionResource = new HashMap<String,Properties>();
/**
* 系统初始化,加载resourcePath下的 zh_CN、en_US等目录下的FixFlowExceptionResource.properties文件
* @param resourcePath 资源文件目录
*/
public static void system_init(String resourcePath){
RESOURCE_PATH = resourcePath;
List<String> languages = getLanguages();
for(String language :languages){
loadExceptionResource(language);
}
}
/**
* 获取资源值,如果不存在则返回key本身
* @param key
* @return
*/
public static String getResourceValue(String key){
return getResourceValue(key,new Object[]{});
}
/**
* 获取资源值,如果不存在则返回key本身(带占位符)
* @param key
* @param args
* @return
*/
public static String getResourceValue(String key,Object... args){
String result = "";
String localLanguage = Context.getLanguageType();
if(exceptionResource!=null && StringUtil.isNotEmpty(key)){
Properties props = exceptionResource.get(localLanguage);
if(props!=null){
result = props.getProperty(key);
if(StringUtil.isNotEmpty(result)){
try {
result = new String(result.getBytes("ISO8859-1"), "UTF-8");
result = MessageFormat.format(result, args);
} catch (UnsupportedEncodingException e) {
log.error("国际化:"+key+"取值时转码失败!", e);
}
}
}
}
if(StringUtil.isEmpty(result))
result = key;
return result;
}
/**
* 获取国际化语言列表 加载resourcePath目录下的以及目录为语言名
* @return
*/
private static List<String> getLanguages(){
List<String> resultList = new ArrayList<String>();
URL url = ReflectUtil.getResource(RESOURCE_PATH);
if(url == null){
return resultList;
}
File file =new File(url.getPath());
if(file.isDirectory()){
for(File tmp :file.listFiles()){
if(tmp.isDirectory()){
resultList.add(tmp.getName());
}
}
}
return resultList;
}
/**
* 加载对应语言的国际化资源文件
* @param languageType
*/
private static void loadExceptionResource(String languageType){
String path = RESOURCE_PATH + File.separator + languageType + File.separator + EXCEPTION_PROPERTIES;
InputStream is = null;
try{
Properties props = new Properties();
is = ReflectUtil.getResourceAsStream(path);
props.load(is);
is.close();
exceptionResource.put(languageType, props);
log.debug("加载异常国际化资源文件成功:文件名{},国际化值个数:{}",languageType,props.size());
}catch(Exception e){
log.error("国际化资源文件"+languageType+"加载失败",e);
}finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
log.error("国际化资源文件"+languageType+"关闭失败",e);
}
}
}
}
}
|
3e082751cc3b60ca424cf230d3dd6982f6851573
| 386 |
java
|
Java
|
twitter-sentiment-processor/demos/javademo/provider/src/main/java/io/dapr/apps/twitter/provider/twitterprovider/model/Sentiment.java
|
DarqueWarrior/samples
|
5021d0021a698a8057cca0db85d5afbc981aba84
|
[
"MIT"
] | 1 |
2021-05-27T13:54:38.000Z
|
2021-05-27T13:54:38.000Z
|
twitter-sentiment-processor/demos/javademo/provider/src/main/java/io/dapr/apps/twitter/provider/twitterprovider/model/Sentiment.java
|
DarqueWarrior/samples
|
5021d0021a698a8057cca0db85d5afbc981aba84
|
[
"MIT"
] | null | null | null |
twitter-sentiment-processor/demos/javademo/provider/src/main/java/io/dapr/apps/twitter/provider/twitterprovider/model/Sentiment.java
|
DarqueWarrior/samples
|
5021d0021a698a8057cca0db85d5afbc981aba84
|
[
"MIT"
] | 4 |
2021-02-05T17:30:28.000Z
|
2021-08-16T21:26:55.000Z
| 20.315789 | 60 | 0.722798 | 3,446 |
package io.dapr.apps.twitter.provider.twitterprovider.model;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Sentiment {
@JsonProperty("sentiment")
String sentiment;
public String getSentiment() {
return this.sentiment;
}
@JsonProperty("confidence")
float confidence;
public float getConfidence() {
return this.confidence;
}
}
|
3e082847243fce111f267b12911a18bf36e4daa2
| 1,934 |
java
|
Java
|
src/main/java/org/tugraz/sysds/runtime/instructions/cp/BinaryTensorTensorCPInstruction.java
|
gilgenbergg/systemds
|
3f2203e3a158e62aabd36dc9ffec557c42992573
|
[
"Apache-2.0"
] | 42 |
2018-11-23T16:55:30.000Z
|
2021-03-15T15:01:44.000Z
|
src/main/java/org/tugraz/sysds/runtime/instructions/cp/BinaryTensorTensorCPInstruction.java
|
kev-inn/systemds
|
2d0f219e02af1174a97a04191590441821fbfab6
|
[
"Apache-2.0"
] | 120 |
2019-02-07T22:13:40.000Z
|
2020-04-15T10:42:17.000Z
|
src/main/java/org/tugraz/sysds/runtime/instructions/cp/BinaryTensorTensorCPInstruction.java
|
kev-inn/systemds
|
2d0f219e02af1174a97a04191590441821fbfab6
|
[
"Apache-2.0"
] | 28 |
2019-02-07T11:13:14.000Z
|
2021-12-20T10:14:25.000Z
| 38.68 | 100 | 0.775078 | 3,447 |
/*
* Copyright 2019 Graz University of Technology
*
* 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.tugraz.sysds.runtime.instructions.cp;
import org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;
import org.tugraz.sysds.runtime.data.TensorBlock;
import org.tugraz.sysds.runtime.matrix.operators.BinaryOperator;
import org.tugraz.sysds.runtime.matrix.operators.Operator;
public class BinaryTensorTensorCPInstruction extends BinaryCPInstruction {
protected BinaryTensorTensorCPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand out,
String opcode, String istr) {
super(CPType.Binary, op, in1, in2, out, opcode, istr);
}
@Override
public void processInstruction(ExecutionContext ec) {
// Read input tensors
TensorBlock inBlock1 = ec.getTensorInput(input1.getName());
TensorBlock inBlock2 = ec.getTensorInput(input2.getName());
// Perform computation using input tensors, and produce the result tensor
BinaryOperator bop = (BinaryOperator) _optr;
TensorBlock retBlock = inBlock1.binaryOperations(bop, inBlock2, null);
// Release the memory occupied by input matrices
ec.releaseTensorInput(input1.getName(), input2.getName());
// TODO Ensure right dense/sparse output representation (guarded by released input memory)
// Attach result matrix with MatrixObject associated with output_name
ec.setTensorOutput(output.getName(), retBlock);
}
}
|
3e0829d35103a14686f2268a3c554da99f4d8286
| 5,445 |
java
|
Java
|
src/main/java/net/floodlightcontroller/devicemanager/internal/IndexedEntity.java
|
netgroup/floodlight-0.90-local
|
5fa7b6eb3075d4368f7156f4791682e81ce69d1d
|
[
"Apache-2.0"
] | 30 |
2015-01-30T01:41:05.000Z
|
2021-08-24T13:08:50.000Z
|
src/main/java/net/floodlightcontroller/devicemanager/internal/IndexedEntity.java
|
netgroup/floodlight-0.90-local
|
5fa7b6eb3075d4368f7156f4791682e81ce69d1d
|
[
"Apache-2.0"
] | 2 |
2017-03-14T00:25:09.000Z
|
2019-09-08T15:31:51.000Z
|
src/main/java/net/floodlightcontroller/devicemanager/internal/IndexedEntity.java
|
netgroup/floodlight-0.90-local
|
5fa7b6eb3075d4368f7156f4791682e81ce69d1d
|
[
"Apache-2.0"
] | 30 |
2015-01-13T16:21:26.000Z
|
2021-03-13T15:22:18.000Z
| 34.903846 | 80 | 0.471809 | 3,448 |
package net.floodlightcontroller.devicemanager.internal;
import java.util.EnumSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.floodlightcontroller.devicemanager.IDeviceService;
import net.floodlightcontroller.devicemanager.IDeviceService.DeviceField;
/**
* This is a thin wrapper around {@link Entity} that allows overriding
* the behavior of {@link Object#hashCode()} and {@link Object#equals(Object)}
* so that the keying behavior in a hash map can be changed dynamically
* @author readams
*/
public class IndexedEntity {
protected EnumSet<DeviceField> keyFields;
protected Entity entity;
private int hashCode = 0;
protected static Logger logger =
LoggerFactory.getLogger(IndexedEntity.class);
/**
* Create a new {@link IndexedEntity} for the given {@link Entity} using
* the provided key fields.
* @param keyFields The key fields that will be used for computing
* {@link IndexedEntity#hashCode()} and {@link IndexedEntity#equals(Object)}
* @param entity the entity to wrap
*/
public IndexedEntity(EnumSet<DeviceField> keyFields, Entity entity) {
super();
this.keyFields = keyFields;
this.entity = entity;
}
/**
* Check whether this entity has non-null values in any of its key fields
* @return true if any key fields have a non-null value
*/
public boolean hasNonNullKeys() {
for (DeviceField f : keyFields) {
switch (f) {
case MAC:
return true;
case IPV4:
if (entity.ipv4Address != null) return true;
break;
case SWITCH:
if (entity.switchDPID != null) return true;
break;
case PORT:
if (entity.switchPort != null) return true;
break;
case VLAN:
if (entity.vlan != null) return true;
break;
}
}
return false;
}
@Override
public int hashCode() {
if (hashCode != 0) {
return hashCode;
}
final int prime = 31;
hashCode = 1;
for (DeviceField f : keyFields) {
switch (f) {
case MAC:
hashCode = prime * hashCode
+ (int) (entity.macAddress ^
(entity.macAddress >>> 32));
break;
case IPV4:
hashCode = prime * hashCode
+ ((entity.ipv4Address == null)
? 0
: entity.ipv4Address.hashCode());
break;
case SWITCH:
hashCode = prime * hashCode
+ ((entity.switchDPID == null)
? 0
: entity.switchDPID.hashCode());
break;
case PORT:
hashCode = prime * hashCode
+ ((entity.switchPort == null)
? 0
: entity.switchPort.hashCode());
break;
case VLAN:
hashCode = prime * hashCode
+ ((entity.vlan == null)
? 0
: entity.vlan.hashCode());
break;
}
}
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
IndexedEntity other = (IndexedEntity) obj;
if (!keyFields.equals(other.keyFields))
return false;
for (IDeviceService.DeviceField f : keyFields) {
switch (f) {
case MAC:
if (entity.macAddress != other.entity.macAddress)
return false;
break;
case IPV4:
if (entity.ipv4Address == null) {
if (other.entity.ipv4Address != null) return false;
} else if (!entity.ipv4Address.
equals(other.entity.ipv4Address)) return false;
break;
case SWITCH:
if (entity.switchDPID == null) {
if (other.entity.switchDPID != null) return false;
} else if (!entity.switchDPID.
equals(other.entity.switchDPID)) return false;
break;
case PORT:
if (entity.switchPort == null) {
if (other.entity.switchPort != null) return false;
} else if (!entity.switchPort.
equals(other.entity.switchPort)) return false;
break;
case VLAN:
if (entity.vlan == null) {
if (other.entity.vlan != null) return false;
} else if (!entity.vlan.
equals(other.entity.vlan)) return false;
break;
}
}
return true;
}
}
|
3e082a2ebddca217d0599f4a6882e4b7420aa600
| 14,395 |
java
|
Java
|
src/main/java/tratz/parse/train/StandardPerSentenceTrainer.java
|
igorbrigadir/bewte
|
f69a85556c889b805c89c5c71d7b77a983e75a05
|
[
"Info-ZIP"
] | 2 |
2018-10-12T11:58:12.000Z
|
2020-08-15T14:55:11.000Z
|
src/main/java/tratz/parse/train/StandardPerSentenceTrainer.java
|
igorbrigadir/bewte
|
f69a85556c889b805c89c5c71d7b77a983e75a05
|
[
"Info-ZIP"
] | null | null | null |
src/main/java/tratz/parse/train/StandardPerSentenceTrainer.java
|
igorbrigadir/bewte
|
f69a85556c889b805c89c5c71d7b77a983e75a05
|
[
"Info-ZIP"
] | null | null | null | 40.097493 | 182 | 0.683432 | 3,449 |
/*
* Copyright 2011 University of Southern California
*
* 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 tratz.parse.train;
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 tratz.parse.NLParser;
import tratz.parse.ParseAction;
import tratz.parse.featgen.ParseFeatureGenerator;
import tratz.parse.ml.ParseModel;
import tratz.parse.types.Arc;
import tratz.parse.types.Token;
import tratz.parse.types.TokenPointer;
import tratz.types.IntArrayList;
/**
* The standard <code>PerSentenceTrainer</code>.
* This code is not particularly easy to read. TODO: fix this
*
*/
public class StandardPerSentenceTrainer implements PerSentenceTrainer {
public final static double DEFAULT_MAX_UPDATE = 0.1;
public final static int DEFAULT_MAX_ITERATIONS = 10;
private double mMaxUpdate;
private int mMaxIterations;
public StandardPerSentenceTrainer() {
mMaxUpdate = DEFAULT_MAX_UPDATE;
mMaxIterations = DEFAULT_MAX_ITERATIONS;
}
public IntArrayList getValues(ParseModel model, Set<String> fts, boolean addFeats) {
IntArrayList values = new IntArrayList(fts.size());
for(String f : fts) {
int index = model.getIndex(f,addFeats);
if(index != Integer.MIN_VALUE) {
values.add(index);
}
}
return values;
}
public static boolean hasAllItsDependents(Token topOfStack, List<Arc> arcListFull, List<Arc> arcListWorking) {
int numFull = arcListFull == null ? 0 : arcListFull.size();
int numWorking = arcListWorking == null ? 0 : arcListWorking.size();
return numFull == numWorking;
}
private PenaltyFunction mPenaltyFunction = new DefaultPenaltyFunction();
public TrainingResult train(
List<Token> sentence,
List[] goldArcs,
Arc[] goldTokenToHead,
ParseModel w,
ParseFeatureGenerator featGen,
Token[] tokenToSubcomponentHead,
int[] projectiveIndices) throws Exception {
boolean maxIterationsReached = false, fatalError = false;
// holder for action indices
int[] indicesHolder = new int[w.getActions().size()];
// holder for action scores
double[] scores = new double[w.getActions().size()];
// used for parameter averaging
w.incrementCount();
final int numTokens = sentence.size();
int numInvalids = 0;
List[] currentArcs = new List[numTokens+1];
// Create the linked-list data structure as well as the action-is-stale holder
TokenPointer first = null;
TokenPointer[] tokenToPtr = new TokenPointer[numTokens+1];
boolean[] actionListStale = new boolean[numTokens+1];
TokenPointer prev = null;
for(int i = 0; i < numTokens; i++) {
Token t = sentence.get(i);
TokenPointer ptr = new TokenPointer(t, null, prev);
if(first == null) first = ptr;
tokenToPtr[t.getIndex()] = ptr;
if(prev != null) {
prev.next = ptr;
}
prev = ptr;
actionListStale[i] = true;
}
actionListStale[numTokens] = true; // indices start at 1 for non-Root tokens
// Hold the mapping from tokens to features (features as an IntArrayList of feature indices)
IntArrayList[] featureCache = new IntArrayList[numTokens+1];
// Hold the possible parse actions for a given token given its current context
Map<Token, List<ParseAction>> actionCache = new HashMap<Token, List<ParseAction>>();
// Set for collecting features. Created out here to allow for reused of object
Set<String> feats = new HashSet<String>();
// Enter the training loop for this sentence
int numIterations = 0;
while(first.next != null) {
numIterations++;
// Calculate weights for all the actions
ParseAction highestScoredValidAction = null;
ParseAction highestScoredInvalidAction = null;
ParseAction lowestScoredValidAction = null;
double lowestScoredValidActionScore = Double.POSITIVE_INFINITY;
double highestScoredInvalidActionScore = Double.NEGATIVE_INFINITY;
double highestScoredValidActionScore = Double.NEGATIVE_INFINITY;
// Not currently using this, but it might be useful sometime
List<ParseAction> invalidActions = new ArrayList<ParseAction>();
//List<ParseAction> validActions = new ArrayList<ParseAction>();
TokenPointer ptr = first;
while(ptr != null) {
Token token = ptr.tok;
List<ParseAction> actions = actionCache.get(token);
// First check if the actions need to be updated
if(actionListStale[token.getIndex()]) {
actions = null; // TODO: in the future it might make sense to reuse the same List
// Generate the features and get their indices
featGen.genFeats(feats, w, sentence, ptr, currentArcs);
IntArrayList values = getValues(w, feats, true);
feats.clear();
IntArrayList tokenFeatures = featureCache[token.getIndex()];
featureCache[token.getIndex()] = tokenFeatures = values;
// Get the list of possible actions
List<String> actionNames = w.getActions(token, ptr.next == null ? null : ptr.next.tok, goldTokenToHead);
// Score the actions
w.scoreIntermediate(actionNames, tokenFeatures, indicesHolder, scores);
if(actions == null) { // this will always be null (for now)
actionCache.put(token, actions = new ArrayList<ParseAction>());
final int numActions = actionNames.size();
for(int i = 0; i < numActions; i++) {
actions.add(new ParseAction(token, ptr, actionNames.get(i), scores[i]));
}
}
else {
final int numActions = actionNames.size();
for(int i = 0; i < numActions; i++) {
ParseAction action = actions.get(i);
action.score = scores[i];
}
}
// Ok, we've updated the actions for this token. No longer stale.
actionListStale[token.getIndex()] = false;
}
// Time to evaluate the actions... now this is the UGLY part
for(ParseAction action : actions) {
TokenPointer tmpPtr = null;
int tokenIndex = action.token.getIndex();
double penalty = mPenaltyFunction.calculatePenalty(tokenToPtr[tokenIndex], action, goldTokenToHead, goldArcs, currentArcs, tokenToSubcomponentHead, projectiveIndices);
if(penalty > 0 ||
// a valid swap is invalidated by an earlier valid non-SWAP if the SWAP is not simple (has all its dependents and token+/-2 is its head)
(
lowestScoredValidAction != null &&
(
(action.actionName.equals("SWAPRIGHT") &&
!lowestScoredValidAction.actionName.equals("SWAPRIGHT")
&&!((tmpPtr = tokenToPtr[tokenIndex].next) != null &&
(tmpPtr = tmpPtr.next) != null &&
hasAllItsDependentsAndIsAMatch(action.token, tmpPtr.tok, goldTokenToHead[tokenIndex], goldTokenToHead, goldArcs[tokenIndex], currentArcs[tokenIndex])
)
)
||
(action.actionName.equals("SWAPLEFT") &&
!lowestScoredValidAction.actionName.equals("SWAPLEFT")
&&!((tmpPtr = tokenToPtr[tokenIndex].prev) != null &&
(tmpPtr = tmpPtr.prev) != null &&
hasAllItsDependentsAndIsAMatch(action.token, tmpPtr.tok, goldTokenToHead[tokenIndex], goldTokenToHead, goldArcs[tokenIndex], currentArcs[tokenIndex])
)
)
)
)
) {
// If we got here, the action must be invalid
invalidActions.add(action);
if(action.score > highestScoredInvalidActionScore) {
highestScoredInvalidAction = action;
highestScoredInvalidActionScore = action.score;
}
}
else {
// If we get here, the action must be valid
// Ok. Now let's check if the previous best action was some sort of SWAP, because we may want to invalidate it (SWAPs have low priority--weird things happen otherwise)
if(lowestScoredValidAction != null) {
tokenIndex = lowestScoredValidAction.token.getIndex();
if(!action.actionName.startsWith("SWAP") &&
(
(lowestScoredValidAction.actionName.equals("SWAPRIGHT")
&& !((tmpPtr = tokenToPtr[tokenIndex].next) != null &&
(tmpPtr = tmpPtr.next) != null &&
hasAllItsDependentsAndIsAMatch(lowestScoredValidAction.token, tmpPtr.tok, goldTokenToHead[tokenIndex], goldTokenToHead, goldArcs[tokenIndex], currentArcs[tokenIndex])
)
)
||
(lowestScoredValidAction.actionName.equals("SWAPLEFT")
&& !((tmpPtr = tokenToPtr[tokenIndex].prev) != null &&
(tmpPtr = tmpPtr.prev) != null &&
hasAllItsDependentsAndIsAMatch(lowestScoredValidAction.token, tmpPtr.tok, goldTokenToHead[tokenIndex], goldTokenToHead, goldArcs[tokenIndex], currentArcs[tokenIndex])
)
)
)
) {
invalidActions.add(lowestScoredValidAction);
// no longer consider this swap to be valid because (it is non-simple AND) we found a new, non-SWAP valid action
lowestScoredValidActionScore = Double.POSITIVE_INFINITY;
highestScoredValidActionScore = Double.NEGATIVE_INFINITY;
// probably don't need to include the penalty here.. but I could be mistaken
if(lowestScoredValidAction.score > highestScoredInvalidActionScore) {
highestScoredInvalidAction = lowestScoredValidAction;
highestScoredInvalidActionScore = lowestScoredValidAction.score;
lowestScoredValidAction = null;
highestScoredValidAction = null;
}
}
}
// Alright, time to update the lowest/highest scored action holders
if(action.score < lowestScoredValidActionScore || lowestScoredValidActionScore == Double.MAX_VALUE) {
lowestScoredValidAction = action;
lowestScoredValidActionScore = action.score;
}
if(action.score > highestScoredValidActionScore || Double.isInfinite(highestScoredValidActionScore)) {
highestScoredValidAction = action;
highestScoredValidActionScore = action.score;
}
}
} // end for(ParseAction action : actions)
// Moving on to the next token
ptr = ptr.next;
}
if(lowestScoredValidAction == null) {
// We should not get in here... if we do, something bad happened
System.err.println("ERROR: No Valid Action Found! Do cycles or multi-headed tokens exist? Moving on to next sentence...");
TokenPointer ptrZ = first;
while(ptrZ != null && ptrZ.tok != null) {
IntArrayList tokenFeatures = featureCache[ptrZ.tok.getIndex()];
if(tokenFeatures == null) {
//featureCache[ptrZ.tok.getIndex()] = tokenFeatures = featGen.genFeats(w, sentence, tokenLevelFeats, ptrZ, currentArcs, true);
}
List<String> actionNames2 = w.getActions(ptrZ.tok, ptrZ.next == null ? null : ptrZ.next.tok, goldTokenToHead);
final int numActions = actionNames2.size();
System.err.print(ptrZ.tok.getText() + " " + ptrZ.tok.getPos() + " ");
w.scoreIntermediate(actionNames2, tokenFeatures, indicesHolder, scores);
for(int i = 0; i < numActions; i++) {
String actionName = actionNames2.get(i);
System.err.print(actionName + ":"+scores[i]+", ");
}
System.err.println();
ptrZ = ptrZ.next;
}
fatalError=true;
break;
}
// Determine if we should perform an action or if we should update the weights
if(highestScoredInvalidActionScore < lowestScoredValidAction.score || numIterations > mMaxIterations) {
// Chosen action is valid, so let's take it
if(numIterations > mMaxIterations) {
// check to see if we've exceeded the max updates-in-a-row threshold for this sentence
maxIterationsReached = true;
}
numIterations = 0;
// Perform the action, conceivably this could alter the pointer to the front of the linked list
first = NLParser.performAction(sentence, first, tokenToPtr, highestScoredValidAction, actionListStale, featureCache, currentArcs,-1,featGen.getContextWidth());
}
else {
// Chosen action is invalid
numInvalids++;
// So, let's update the model
performUpdate(lowestScoredValidAction, highestScoredInvalidAction, first, actionListStale, featureCache, w);
}
}
return new TrainingResult(maxIterationsReached, fatalError, numInvalids);
}
/**
* Update the model parameters
*/
private void performUpdate(ParseAction lowestScoredValidAction,
ParseAction maxInvalidAction,
TokenPointer first,
boolean[] actionListStale,
IntArrayList[] featureCache,
ParseModel w) {
ParseAction goodAction = lowestScoredValidAction;
ParseAction badAction = maxInvalidAction;
// Everything becomes stale because the model weights are changing
for(TokenPointer tptr = first; tptr != null; tptr = tptr.next) {
actionListStale[tptr.tok.getIndex()] = true;
}
// Hmm... Actually, would it make more sense to find the intersection of these and take the size of that?
double denominator = featureCache[badAction.token.getIndex()].size()+featureCache[goodAction.token.getIndex()].size();
// uniform penalty of 1
double change = 1;
// magnitude of error is typically around .0055-.0035
double update = Math.min(mMaxUpdate, (badAction.score-goodAction.score+change)/denominator);
// update feature vector weights
w.update(badAction.actionName, featureCache[badAction.token.getIndex()], -update);
w.update(goodAction.actionName, featureCache[goodAction.token.getIndex()], update);
}
private boolean hasAllItsDependentsAndIsAMatch(Token tokenToMove,
Token newNeighbor,
Arc goldHeadArc,
Arc[] goldTokenToHead,
List<Arc> goldArcs,
List<Arc> currentArcs) {
return goldHeadArc != null &&
goldHeadArc.getHead() == newNeighbor &&
hasAllItsDependents(tokenToMove, goldArcs, currentArcs);
}
}
|
3e082a6e7ab6662ab214f0ff90dec58b9c80f566
| 298 |
java
|
Java
|
bubble/robot/src/main/java/com/barley/robot/ClasspathXMLResover.java
|
trainkg/expect
|
16652eb47ca75113c468162a33ba3a1231cdf3ac
|
[
"Apache-2.0"
] | 1 |
2021-03-30T09:26:34.000Z
|
2021-03-30T09:26:34.000Z
|
bubble/robot/src/main/java/com/barley/robot/ClasspathXMLResover.java
|
trainkg/expect
|
16652eb47ca75113c468162a33ba3a1231cdf3ac
|
[
"Apache-2.0"
] | 10 |
2020-04-16T16:46:55.000Z
|
2022-02-27T10:45:58.000Z
|
bubble/robot/src/main/java/com/barley/robot/ClasspathXMLResover.java
|
trainkg/expect
|
16652eb47ca75113c468162a33ba3a1231cdf3ac
|
[
"Apache-2.0"
] | null | null | null | 15.736842 | 71 | 0.655518 | 3,450 |
package com.barley.robot;
/**
* classpath XML配置
*
* @author [email protected]
* @version $ID: ClasspathXMLResover.java, V1.0.0 2021年2月3日 下午3:55:43 $
*/
public interface ClasspathXMLResover<T> extends XmlResolver<T> {
/**
*
* 获取XML配置路径
* @return
*/
public String xmlPath();
}
|
3e082a7544ac753d766d131b60355a97f480ff9f
| 1,561 |
java
|
Java
|
app/src/main/java/com/example/dispatchtoucheventtest/view/MyRecycleView.java
|
huaidanlk/DispatchTouchEventTest
|
b780fee313f1f331d93c6c1f25ffecdcbb495d24
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/example/dispatchtoucheventtest/view/MyRecycleView.java
|
huaidanlk/DispatchTouchEventTest
|
b780fee313f1f331d93c6c1f25ffecdcbb495d24
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/example/dispatchtoucheventtest/view/MyRecycleView.java
|
huaidanlk/DispatchTouchEventTest
|
b780fee313f1f331d93c6c1f25ffecdcbb495d24
|
[
"Apache-2.0"
] | null | null | null | 29.45283 | 78 | 0.595772 | 3,451 |
package com.example.dispatchtoucheventtest.view;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
/**
* Created by 坏蛋 on 2017/4/11.
*/
public class MyRecycleView extends RecyclerView {
private int touchSlop;
private float xDown, yDown, xMove, yMove;
public MyRecycleView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
/*
内部拦截法
* */
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
getParent().requestDisallowInterceptTouchEvent(true);
xDown = ev.getRawX();
yDown = ev.getRawY();
Log.d("TAG", "onTouch---xDown:" + xDown + " yDown:" + yDown);
break;
case MotionEvent.ACTION_MOVE:
xMove = ev.getRawX();
yMove = ev.getRawY();
int deltaX = (int) (xMove - xDown);
int deltaY = (int) (yMove - yDown);
//滑动到起始点右边
if (Math.abs(deltaX) >= touchSlop) {
getParent().requestDisallowInterceptTouchEvent(false);
}
break;
}
return super.dispatchTouchEvent(ev);
}
}
|
3e082a7d2db8054ce866f175fb2979c23bcdcead
| 937 |
java
|
Java
|
rox-client-java/src/main/java/com/lotaris/rox/core/serializer/RoxSerializer.java
|
lotaris/rox-client-java
|
3c366ca0749db5aadf976b119a6720d7c00f8d81
|
[
"MIT"
] | null | null | null |
rox-client-java/src/main/java/com/lotaris/rox/core/serializer/RoxSerializer.java
|
lotaris/rox-client-java
|
3c366ca0749db5aadf976b119a6720d7c00f8d81
|
[
"MIT"
] | null | null | null |
rox-client-java/src/main/java/com/lotaris/rox/core/serializer/RoxSerializer.java
|
lotaris/rox-client-java
|
3c366ca0749db5aadf976b119a6720d7c00f8d81
|
[
"MIT"
] | null | null | null | 26.305556 | 103 | 0.747624 | 3,452 |
package com.lotaris.rox.core.serializer;
import com.lotaris.rox.common.model.RoxPayload;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
* Serializer interface
*
* @author Laurent Prevost, [email protected]
*/
public interface RoxSerializer {
/**
* Serialize a payload
*
* @param osw Output stream
* @param payload The payload to serialize
* @param pretty Whether to indent the output
* @exception IOException
*/
void serializePayload(OutputStreamWriter osw, RoxPayload payload, boolean pretty) throws IOException;
/**
* Deserialize a payload
*
* @param <T> The type of payload to deserialize
* @param isr Input stream
* @param clazz The type to deserialize
* @return Payload The payload deserialized
* @throws IOException I/O Errors
*/
<T extends RoxPayload> T deserializePayload(InputStreamReader isr, Class<T> clazz) throws IOException;
}
|
3e082aa127022534d8b6832d631ebeca0e72ca54
| 3,870 |
java
|
Java
|
src/main/java/com/zrlog/web/interceptor/VisitorInterceptor.java
|
luoyefengyun/zrlog
|
e825a378d9084231d7a844bc530c7c73f1cafa53
|
[
"Apache-2.0"
] | 2 |
2018-03-10T08:51:03.000Z
|
2018-04-04T02:48:47.000Z
|
src/main/java/com/zrlog/web/interceptor/VisitorInterceptor.java
|
luoyefengyun/zrlog
|
e825a378d9084231d7a844bc530c7c73f1cafa53
|
[
"Apache-2.0"
] | 3 |
2020-05-21T19:09:22.000Z
|
2021-06-04T02:27:08.000Z
|
src/main/java/com/zrlog/web/interceptor/VisitorInterceptor.java
|
luoyefengyun/zrlog
|
e825a378d9084231d7a844bc530c7c73f1cafa53
|
[
"Apache-2.0"
] | 5 |
2018-02-24T10:08:31.000Z
|
2018-12-07T06:20:50.000Z
| 33.362069 | 133 | 0.578036 | 3,453 |
package com.zrlog.web.interceptor;
import com.zrlog.web.config.ZrlogConfig;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.json.Json;
import com.jfinal.kit.PathKit;
import com.jfinal.render.ViewType;
import java.io.File;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 目前这里分为3种情况,
* 1. /post / 前台页面,扩展其他页面请使用 /** 这样的。
* 2. /install 用于安装向导的路由
* 3. /api 用于将文章相关的数据数据转化JSON数据
*/
class VisitorInterceptor implements Interceptor {
@Override
public void intercept(Invocation ai) {
String actionKey = ai.getActionKey();
if (actionKey.startsWith("/install")) {
installPermission(ai);
} else {
if (ZrlogConfig.isInstalled()) {
if (actionKey.startsWith("/api")) {
apiPermission(ai);
} else if (actionKey.startsWith("/")) {
visitorPermission(ai);
}
}
}
}
/**
* 查询出来的文章数据存放在request域里面,通过判断Key,选择对应需要渲染的模板文件
*
* @param ai
*/
private void visitorPermission(Invocation ai) {
ai.invoke();
String templateName = ai.getReturnValue();
if (templateName == null) {
return;
}
String ext = "";
if (JFinal.me().getConstants().getViewType() == ViewType.JSP) {
ext = ".jsp";
}
String basePath = TemplateHelper.fullTemplateInfo(ai.getController());
if (ai.getController().getAttr("log") != null) {
ai.getController().setAttr("pageLevel", 1);
} else if (ai.getController().getAttr("data") != null) {
if (ai.getActionKey().equals("/") && new File(PathKit.getWebRootPath() + basePath + "/" + templateName + ext).exists()) {
ai.getController().setAttr("pageLevel", 2);
} else {
templateName = "page";
ai.getController().setAttr("pageLevel", 1);
}
} else {
ai.getController().setAttr("pageLevel", 2);
}
fullDevData(ai.getController());
ai.getController().render(basePath + "/" + templateName + ext);
}
/**
* 方便开发环境使用,将Servlet的Request域的数据转化JSON字符串,配合dev.jsp使用,定制主题更加方便
*
* @param controller
*/
private void fullDevData(Controller controller) {
boolean dev = JFinal.me().getConstants().getDevMode();
controller.setAttr("dev", dev);
if (dev) {
Map<String, Object> attrMap = new LinkedHashMap<>();
Enumeration<String> enumerations = controller.getAttrNames();
while (enumerations.hasMoreElements()) {
String key = enumerations.nextElement();
attrMap.put(key, controller.getAttr(key));
}
controller.setAttr("requestScopeJsonString", Json.getJson().toJson(attrMap));
}
}
private void apiPermission(Invocation ai) {
ai.invoke();
if (ai.getController().getAttr("log") != null) {
ai.getController().renderJson(ai.getController().getAttr("log"));
} else if (ai.getController().getAttr("data") != null) {
ai.getController().renderJson(ai.getController().getAttr("data"));
} else {
Map<String, Object> error = new HashMap<>();
error.put("status", 500);
error.put("message", "unSupport");
ai.getController().renderJson(error);
}
}
private void installPermission(Invocation ai) {
if (!ZrlogConfig.isInstalled()) {
ai.invoke();
} else {
ai.getController().getRequest().getSession();
ai.getController().render("/install/forbidden.jsp");
}
}
}
|
3e082aa8e2a250537cdb9fd77d4f9cfc15a644e8
| 3,506 |
java
|
Java
|
org/w3c/css/properties/css/CssBorderRadius.java
|
BeckyDTP/css-validator
|
b86f61ae8c167cbaa174ec3adc7b2a266733a293
|
[
"W3C-19980720",
"W3C-20150513"
] | 194 |
2015-03-12T00:14:19.000Z
|
2022-03-29T20:09:37.000Z
|
org/w3c/css/properties/css/CssBorderRadius.java
|
BeckyDTP/css-validator
|
b86f61ae8c167cbaa174ec3adc7b2a266733a293
|
[
"W3C-19980720",
"W3C-20150513"
] | 247 |
2015-01-05T14:14:32.000Z
|
2022-03-03T08:57:04.000Z
|
org/w3c/css/properties/css/CssBorderRadius.java
|
BeckyDTP/css-validator
|
b86f61ae8c167cbaa174ec3adc7b2a266733a293
|
[
"W3C-19980720",
"W3C-20150513"
] | 106 |
2015-01-05T11:15:18.000Z
|
2022-03-22T15:14:21.000Z
| 27.286822 | 76 | 0.626989 | 3,454 |
// $Id$
// From Philippe Le Hegaret ([email protected])
// Rewritten 2010 Yves Lafon <[email protected]>
// (c) COPYRIGHT MIT, ERCIM and Keio, 1997-2010.
// Please first read the full copyright statement in file COPYRIGHT.html
package org.w3c.css.properties.css;
import org.w3c.css.parser.CssStyle;
import org.w3c.css.properties.css1.Css1Style;
import org.w3c.css.util.ApplContext;
import org.w3c.css.util.InvalidParamException;
import org.w3c.css.values.CssExpression;
/**
* @since CSS3
*/
public class CssBorderRadius extends CssProperty {
// those are @since CSS3
public CssBorderTopLeftRadius topLeft;
public CssBorderTopRightRadius topRight;
public CssBorderBottomLeftRadius bottomLeft;
public CssBorderBottomRightRadius bottomRight;
public boolean shorthand;
/**
* Create a new CssBorderRadius
*/
public CssBorderRadius() {
}
/**
* Set the value of the property<br/>
* Does not check the number of values
*
* @param expression The expression for this property
* @throws org.w3c.css.util.InvalidParamException
* The expression is incorrect
*/
public CssBorderRadius(ApplContext ac, CssExpression expression)
throws InvalidParamException {
this(ac, expression, false);
}
/**
* Set the value of the property
*
* @param expression The expression for this property
* @param check set it to true to check the number of values
* @throws org.w3c.css.util.InvalidParamException
* The expression is incorrect
*/
public CssBorderRadius(ApplContext ac, CssExpression expression,
boolean check) throws InvalidParamException {
throw new InvalidParamException("unrecognize", ac);
}
/**
* Returns the value of this property
*/
public Object get() {
return null;
}
/**
* Returns the name of this property
*/
public final String getPropertyName() {
return "border-radius";
}
/**
* Returns a string representation of the object.
*/
public String toString() {
return value.toString();
}
/**
* Add this property to the CssStyle
*
* @param style The CssStyle
*/
public void addToStyle(ApplContext ac, CssStyle style) {
((Css1Style) style).cssBorder.borderRadius.shorthand = shorthand;
((Css1Style) style).cssBorder.borderRadius.byUser = byUser;
if (topLeft != null) {
topLeft.addToStyle(ac, style);
}
if (topRight != null) {
topRight.addToStyle(ac, style);
}
if (bottomLeft != null) {
bottomLeft.addToStyle(ac, style);
}
if (bottomRight != null) {
bottomRight.addToStyle(ac, style);
}
}
/**
* Get this property in the style.
*
* @param style The style where the property is
* @param resolve if true, resolve the style to find this property
*/
public CssProperty getPropertyInStyle(CssStyle style, boolean resolve) {
if (resolve) {
return ((Css1Style) style).getBorder().borderRadius;
} else {
return ((Css1Style) style).cssBorder.borderRadius;
}
}
/**
* Compares two properties for equality.
*
* @param property The other property.
*/
public boolean equals(CssProperty property) {
return false; // FIXME
}
}
|
3e082b4c7a33ac331dbfc722fc47fa57e30d5d82
| 7,276 |
java
|
Java
|
src/main/java/com/nsn/ngdb/hive/udf/GetRange.java
|
WANdisco/hive-udf
|
22438782426627098f68584678e1c5936961b582
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/nsn/ngdb/hive/udf/GetRange.java
|
WANdisco/hive-udf
|
22438782426627098f68584678e1c5936961b582
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/nsn/ngdb/hive/udf/GetRange.java
|
WANdisco/hive-udf
|
22438782426627098f68584678e1c5936961b582
|
[
"Apache-2.0"
] | null | null | null | 32.19469 | 163 | 0.656817 | 3,455 |
package com.nsn.ngdb.hive.udf;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.Text;
public class GetRange extends GenericUDF {
public static final Log LOG = LogFactory.getLog(GetRange.class);
private Map<String, HashMap<String, ArrayList<Float>>> binTableMap = null;
private static final String DB_URL = "db_url";
private static final String DB_Driver = "db_driver";
private static String NO_RANGE_FOUND = "No Range Found";
private static String CEI_BIN_QUERY ="cei_bin" ;
private static String CQI_BIN_QUERY ="cqi_bin";
private static Properties prop = new Properties();
private Text text = new Text();
private void loadMap() throws SQLException{
loadProperties();
cacheBintable(prop.getProperty(CQI_BIN_QUERY));
cacheBintable(prop.getProperty(CEI_BIN_QUERY));
}
private GenericUDFUtils.ReturnObjectInspectorResolver returnOIResolver;
private ObjectInspector returnInspector;
// private String[] cei = {"AGE","SMS_CEI_INDEX_SAT_LEVEL","CEI_INDEX_SAT_LEVEL","CEI_INDEX","VOICE_CEI_INDEX_SAT_LEVEL","SUBS_COUNT","DATA_CEI_INDEX_SAT_LEVEL"};
//
// private String[] cqi = {"B1","B2"};
@Override
public ObjectInspector initialize(ObjectInspector[] arguments)
throws UDFArgumentException {
LOG.debug("Enter into initilize ......");
if (arguments.length != 2) {
throw new UDFArgumentLengthException(
"The operator 'Range' accepts 2 arguments.");
}
binTableMap = new HashMap<String, HashMap<String, ArrayList<Float>>>();
returnInspector = PrimitiveObjectInspectorFactory.writableStringObjectInspector;
returnOIResolver = new GenericUDFUtils.ReturnObjectInspectorResolver(
true);
returnOIResolver.update(arguments[0]);
returnOIResolver.update(arguments[1]);
try {
loadMap();
} catch (SQLException e) {
LOG.error("Error :"+e.getMessage());
}
LOG.debug("Bin Table Map Object:"+binTableMap);
return returnInspector;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
if (arguments != null && arguments.length > 0) {
if (arguments[0].get() != null && arguments[1].get() != null) {
double fieldValue = Double.parseDouble(arguments[1].get().toString());
String binType = arguments[0].get().toString();
if(binTableMap.get(binType) != null){
HashMap<String, ArrayList<Float>> binValues = binTableMap.get(binType);
Iterator iterator = binValues.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pairs = (Map.Entry)iterator.next();
ArrayList<Float> valuePair =(ArrayList<Float>) pairs.getValue();
if(fieldValue >= valuePair.get(0) && fieldValue <= valuePair.get(1)){
text.set(pairs.getKey().toString());
// text.set(valuePair.get(0) + "-" + valuePair.get(1));
LOG.debug("Range Returning:"+text);
return text;
}
}
}
}
}
text.set(NO_RANGE_FOUND);
return text;
}
@Override
public String getDisplayString(String[] children) {
StringBuilder sb = new StringBuilder();
sb.append("returns the number");
sb.append(children[0]);
sb.append(" in tens range ");
return sb.toString();
}
private void cacheBintable(String query) throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet result = null;
try{
String url = prop.getProperty(DB_URL);
String driver = prop.getProperty(DB_Driver);
Class.forName(driver);
conn = DriverManager.getConnection(url, "", "");
st = conn.createStatement();
result = st.executeQuery(query);
while (result.next()) {
HashMap<String, ArrayList<Float>> innerlist = new HashMap<String, ArrayList<Float>>();
ArrayList<Float> list = new ArrayList<Float>();
list.add(result.getFloat(3));
list.add(result.getFloat(4));
innerlist.put(result.getString(2),list);
if (binTableMap.get(result.getString(1)) == null){
binTableMap.put(result.getString(1),innerlist);
}else{
binTableMap.get(result.getString(1)).put(result.getString(2), list);
}
}
}catch(Exception e){
LOG.error("Error :"+e.getMessage());
}
finally{
LOG.debug("Closing Connection...");
if (result != null)
{
result.close();
}
if (st != null)
{
st.close() ;
}
if(conn != null)
{
conn.close() ;
}
}
}
private static void loadProperties() {
LOG.debug("Loading Properties file.....");
InputStream input = null;
try {
input = new FileInputStream("/usr/local/hiveconf-hdp1/hive-config.properties");
//input = new FileInputStream("hive-config.properties");
// load a properties file
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@SuppressWarnings("resource")
public static void main(String[] args) throws HiveException, SQLException{
// loadProperties();
GetRange getRange = new GetRange();
getRange.loadMap();
Object result = getRange.evaluate(new DeferredObject[]{new DeferredJavaObject("B2"), new DeferredJavaObject(6145)});
System.out.println("result:"+result);
// System.out.println("Age :" +getRange(32,"AGE"));
// System.out.println("SMS_CEI_INDEX_SAT_LEVEL :" +getRange(32,"SMS_CEI_INDEX_SAT_LEVEL"));
// System.out.println("CEI_INDEX_SAT_LEVEL :" +getRange(40,"CEI_INDEX_SAT_LEVEL"));
// System.out.println("CEI_INDEX :" +getRange(40,"CEI_INDEX"));
// System.out.println("VOICE_CEI_INDEX_SAT_LEVEL:" +getRange(40,"VOICE_CEI_INDEX_SAT_LEVEL"));
// System.out.println("SUBS_COUNT :" +getRange(40,"SUBS_COUNT"));
// System.out.println("DATA_CEI_INDEX_SAT_LEVEL :" +getRange(6146,"DATA_CEI_INDEX_SAT_LEVEL"));
// System.out.println("B1 :" +getRange(3074,"B1"));
// System.out.println("B2 :" +getRange(46,"B2"));
}
}
|
3e082b82b8ad35dd64221899fec1234b1d9e6b8a
| 1,328 |
java
|
Java
|
src/binary_search/Boj2805.java
|
minuk8932/Algorithm_BaekJoon
|
9ba6e6669d7cdde622c7d527fef77c2035bf2528
|
[
"Apache-2.0"
] | 3 |
2019-05-10T08:23:46.000Z
|
2020-08-20T10:35:30.000Z
|
src/binary_search/Boj2805.java
|
minuk8932/Algorithm_BaekJoon
|
9ba6e6669d7cdde622c7d527fef77c2035bf2528
|
[
"Apache-2.0"
] | null | null | null |
src/binary_search/Boj2805.java
|
minuk8932/Algorithm_BaekJoon
|
9ba6e6669d7cdde622c7d527fef77c2035bf2528
|
[
"Apache-2.0"
] | 3 |
2019-05-15T13:06:50.000Z
|
2021-04-19T08:40:40.000Z
| 21.419355 | 75 | 0.605422 | 3,456 |
package binary_search;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author minchoba
* 백준 2805번: 나무 자르기
*
* @see https://www.acmicpc.net/problem/2805/
*
*/
public class Boj2805 {
private static final long INF = 4_000_000_001L;
private static long end = INF;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
long[] tree = new long[N];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < N; i++) {
tree[i] = Long.parseLong(st.nextToken());
if(end < tree[i]) end = tree[i];
}
System.out.println(binarySearch(N, M, tree));
}
private static long binarySearch(int n, long m, long[] arr) {
long high = 0;
long start = 0;
while(start <= end) {
long mid = (start + end) / 2;
long sum = 0;
for(int i = 0; i < n; i++) {
long diff = arr[i] - mid; // cut
if(diff < 0) diff = 0;
sum += diff; // make get sum
}
if(m <= sum) {
high = Math.max(high, mid);
start = mid + 1;
}
else {
end = mid - 1;
}
}
return high;
}
}
|
3e082be73699bd17d327b4443634b15631ca6c94
| 6,570 |
java
|
Java
|
vocabulary-rest-ws/src/test/java/org/gbif/vocabulary/restws/resources/mock/BaseResourceTest.java
|
gbif/vocabulary
|
ef37956a2bc78dfd1424f0bc31976ec50953374b
|
[
"ECL-2.0",
"Apache-2.0"
] | 5 |
2019-03-13T11:53:26.000Z
|
2022-03-18T13:15:09.000Z
|
vocabulary-rest-ws/src/test/java/org/gbif/vocabulary/restws/resources/mock/BaseResourceTest.java
|
gbif/vocabulary
|
ef37956a2bc78dfd1424f0bc31976ec50953374b
|
[
"ECL-2.0",
"Apache-2.0"
] | 84 |
2019-03-21T12:31:05.000Z
|
2022-03-09T15:45:21.000Z
|
vocabulary-rest-ws/src/test/java/org/gbif/vocabulary/restws/resources/mock/BaseResourceTest.java
|
gbif/vocabulary
|
ef37956a2bc78dfd1424f0bc31976ec50953374b
|
[
"ECL-2.0",
"Apache-2.0"
] | 1 |
2019-02-20T14:30:16.000Z
|
2019-02-20T14:30:16.000Z
| 38.647059 | 100 | 0.746575 | 3,457 |
/*
* 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.gbif.vocabulary.restws.resources.mock;
import org.gbif.vocabulary.api.DeprecateAction;
import org.gbif.vocabulary.model.LanguageRegion;
import org.gbif.vocabulary.model.UserRoles;
import org.gbif.vocabulary.model.Vocabulary;
import org.gbif.vocabulary.model.VocabularyEntity;
import org.gbif.vocabulary.model.search.KeyNameResult;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/** Base class for resources tests. */
@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(properties = {"spring.liquibase.enabled=false"})
@ActiveProfiles({"mock", "test"})
abstract class BaseResourceTest<T extends VocabularyEntity> {
// util constants
static final Long TEST_KEY = 1L;
static final String NAMESPACE_TEST = "ns";
static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Autowired MockMvc mockMvc;
@Test
public void getNotFoundEntityTest() throws Exception {
mockMvc.perform(get(getBasePath() + "/foo")).andExpect(status().isNotFound());
}
@WithMockUser(authorities = {UserRoles.VOCABULARY_ADMIN})
@Test
public void createNullEntityTest() throws Exception {
mockMvc
.perform(post(getBasePath()).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@WithMockUser(authorities = {UserRoles.VOCABULARY_ADMIN})
@Test
public void updateNullEntityTest() throws Exception {
mockMvc
.perform(put(getBasePath() + "/fake").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
public void suggestWithoutQueryTest() throws Exception {
mockMvc.perform(get(getBasePath() + "/suggest")).andExpect(status().isBadRequest()).andReturn();
}
@WithMockUser(authorities = {UserRoles.VOCABULARY_ADMIN})
@Test
public void deprecateEntityNotFoundTest() throws Exception {
// mock not set, so the service returns null
mockMvc
.perform(
put(getBasePath() + "/fake/deprecate")
.contentType(MediaType.APPLICATION_JSON)
.content(OBJECT_MAPPER.writeValueAsString(createDeprecateAction())))
.andExpect(status().isUnprocessableEntity());
}
@WithMockUser(authorities = {UserRoles.VOCABULARY_ADMIN})
@Test
public void restoreDeprecatedEntityNotFoundNameTest() throws Exception {
// mock not set, so the service returns null
mockMvc
.perform(delete(getBasePath() + "/fake/deprecate"))
.andExpect(status().isUnprocessableEntity());
}
@Test
public void corsHeadersTest() throws Exception {
mockMvc
.perform(
options(getBasePath())
.header("origin", "localhost")
.header("access-control-request-headers", "authorization,content-type")
.header("access-control-request-method", "GET"))
.andExpect(header().string("Access-Control-Allow-Origin", "*"))
.andExpect(
header().string("Access-Control-Allow-Methods", "HEAD,GET,POST,DELETE,PUT,OPTIONS"))
.andExpect(header().string("Access-Control-Allow-Headers", "authorization, content-type"));
}
Vocabulary createVocabulary(String name) {
Vocabulary vocabulary = new Vocabulary();
vocabulary.setName(name);
vocabulary.setNamespace(NAMESPACE_TEST);
vocabulary.setLabel(Collections.singletonMap(LanguageRegion.ENGLISH, "Label"));
vocabulary.setEditorialNotes(Arrays.asList("note1", "note2"));
return vocabulary;
}
void suggestTest(List<KeyNameResult> suggestions) throws Exception {
MvcResult mvcResult =
mockMvc
.perform(get(getBasePath() + "/suggest?q=foo"))
.andExpect(status().isOk())
.andReturn();
List<KeyNameResult> resultList =
OBJECT_MAPPER.readValue(
mvcResult.getResponse().getContentAsString(),
new TypeReference<List<KeyNameResult>>() {});
assertEquals(suggestions.size(), resultList.size());
}
List<KeyNameResult> createSuggestions() {
KeyNameResult keyNameResult1 = new KeyNameResult();
keyNameResult1.setKey(1);
keyNameResult1.setName("n1");
KeyNameResult keyNameResult2 = new KeyNameResult();
keyNameResult2.setKey(2);
keyNameResult2.setName("n2");
return ImmutableList.of(keyNameResult1, keyNameResult2);
}
abstract String getBasePath();
abstract T createEntity();
abstract DeprecateAction createDeprecateAction();
}
|
3e082c8433443cd4a9e1d64445da238b2141f59b
| 1,793 |
java
|
Java
|
src/main/java/com/augustnagro/vaa/AsyncAwait.java
|
AugustNagro/vertx-async-await
|
3b8b8f3d5db171f6e4e0ab1e16031a3e0fdf515c
|
[
"Apache-2.0"
] | 7 |
2021-11-01T04:46:02.000Z
|
2022-02-17T11:16:37.000Z
|
src/main/java/com/augustnagro/vaa/AsyncAwait.java
|
AugustNagro/vertx-loom
|
3b8b8f3d5db171f6e4e0ab1e16031a3e0fdf515c
|
[
"Apache-2.0"
] | 2 |
2021-11-03T04:39:10.000Z
|
2021-12-14T03:08:06.000Z
|
src/main/java/com/augustnagro/vaa/AsyncAwait.java
|
AugustNagro/vertx-loom
|
3b8b8f3d5db171f6e4e0ab1e16031a3e0fdf515c
|
[
"Apache-2.0"
] | 1 |
2021-11-01T04:46:05.000Z
|
2021-11-01T04:46:05.000Z
| 26.367647 | 87 | 0.660904 | 3,458 |
package com.augustnagro.vaa;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.impl.ContextInternal;
import java.util.Objects;
import java.util.concurrent.Callable;
public class AsyncAwait {
private static final ContinuationScope ASYNC_SCOPE =
new ContinuationScope("vertx-async-await-scope");
/**
* Execute some code with a Coroutine. Within the Callable, you can
* {@link } on Futures to program in an imperative style.
* Stack traces are also significantly improved.
* <p>
* No new threads (virtual or otherwise) are created.
*/
public static <A> Future<A> async(Callable<A> prog) {
Context ctx = Objects.requireNonNull(
Vertx.currentContext(),
"Must be running on a Vertx Context to call async()"
);
Promise<A> promise = Promise.promise();
Coroutine coroutine = new Coroutine(
ctx,
ASYNC_SCOPE,
() -> {
try {
promise.complete(prog.call());
} catch (Throwable t) {
promise.fail(t);
}
}
);
coroutine.run();
return promise.future();
}
/**
* Awaits this Future by suspending the current Coroutine.
*/
public static <A> A await(Future<A> f) {
Coroutine coroutine = (Coroutine) Objects.requireNonNull(
Continuation.getCurrentContinuation(ASYNC_SCOPE),
"await must be called inside of an async scope"
);
Context ctx = Objects.requireNonNull(
Vertx.currentContext(),
"Must be on Vertx Context to call await()"
);
if (ctx != coroutine.ctx) throw new IllegalStateException(
"Must call await() on the same Vertx Context as its async{} scope was started on"
);
return coroutine.suspend(f);
}
}
|
3e082d9b382cc27f56137c29d8e8900d283bf972
| 410 |
java
|
Java
|
src/org/jruby/runtime/opto/GenerationInvalidator.java
|
janx/jruby
|
c780525394626ea0f74843187854aa8c6ff4b005
|
[
"Ruby",
"Apache-2.0"
] | 2 |
2018-02-18T01:05:13.000Z
|
2021-12-10T16:45:58.000Z
|
src/org/jruby/runtime/opto/GenerationInvalidator.java
|
janx/jruby
|
c780525394626ea0f74843187854aa8c6ff4b005
|
[
"Ruby",
"Apache-2.0"
] | null | null | null |
src/org/jruby/runtime/opto/GenerationInvalidator.java
|
janx/jruby
|
c780525394626ea0f74843187854aa8c6ff4b005
|
[
"Ruby",
"Apache-2.0"
] | 1 |
2016-09-15T12:25:22.000Z
|
2016-09-15T12:25:22.000Z
| 20.5 | 59 | 0.673171 | 3,459 |
package org.jruby.runtime.opto;
import org.jruby.RubyModule;
public class GenerationInvalidator implements Invalidator {
private final RubyModule module;
public GenerationInvalidator(RubyModule module) {
this.module = module;
}
public void invalidate() {
module.updateGeneration();
}
public Object getData() {
return module.getGeneration();
}
}
|
3e082dd2543209f16c4d88e9ac574d828ddb0d75
| 983 |
java
|
Java
|
common/src/main/java/com/distkv/common/id/GroupId.java
|
kairbon/distkv
|
25655a745b250ef5c282f295f9fc4f3ae51e116d
|
[
"BSD-3-Clause"
] | 53 |
2020-01-18T10:48:37.000Z
|
2022-03-08T09:23:13.000Z
|
common/src/main/java/com/distkv/common/id/GroupId.java
|
ou-taku14/distkv
|
4b30b1cda93fa5e7e83fcf2b012987b8587ad688
|
[
"BSD-3-Clause"
] | 306 |
2020-01-16T15:54:30.000Z
|
2021-05-10T07:34:58.000Z
|
common/src/main/java/com/distkv/common/id/GroupId.java
|
ou-taku14/distkv
|
4b30b1cda93fa5e7e83fcf2b012987b8587ad688
|
[
"BSD-3-Clause"
] | 21 |
2019-08-17T03:15:03.000Z
|
2020-01-15T16:01:09.000Z
| 17.872727 | 69 | 0.64293 | 3,460 |
package com.distkv.common.id;
import java.io.Serializable;
/**
* The class that represents the Id of a partition.
*/
public class GroupId implements Serializable {
private static final long serialVersionUID = -5170144234860018298L;
/**
* The index of the partition in the Dst cluster.
*/
private short index;
private GroupId(short index) {
this.index = index;
}
public short getIndex() {
return index;
}
public void setIndex(short i) {
index = i;
}
public static GroupId fromIndex(short index) {
return new GroupId(index);
}
@Override
public int hashCode() {
return Short.hashCode(index);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!this.getClass().equals(obj.getClass())) {
return false;
}
return (((GroupId) obj).index == index);
}
@Override
public String toString() {
return String.format("PartitionId{%d}", index);
}
}
|
3e082e4d53c1d71ecaef8dad7f2510aabccdfa72
| 847 |
java
|
Java
|
ruoyi-modules/ruoyi-system/src/main/java/com/tianhai/designMode/observer/SubjectOne.java
|
wuynje/myCloud
|
c28e0a67af34c729dc0c139dade895b64f34353c
|
[
"MIT"
] | null | null | null |
ruoyi-modules/ruoyi-system/src/main/java/com/tianhai/designMode/observer/SubjectOne.java
|
wuynje/myCloud
|
c28e0a67af34c729dc0c139dade895b64f34353c
|
[
"MIT"
] | null | null | null |
ruoyi-modules/ruoyi-system/src/main/java/com/tianhai/designMode/observer/SubjectOne.java
|
wuynje/myCloud
|
c28e0a67af34c729dc0c139dade895b64f34353c
|
[
"MIT"
] | null | null | null | 18.413043 | 70 | 0.600945 | 3,461 |
package com.tianhai.designMode.observer;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: wuynje
* @Date: 2021/7/22 15:13
* @Description:话题类型一
*/
public class SubjectOne implements Subject {
/**
* 订阅者列表
*/
protected List<Ovserver> ovserverList = new ArrayList<Ovserver>();
/**
* 订阅
* @param ovserver
*/
@Override
public void subscribe(Ovserver ovserver){
this.ovserverList.add(ovserver);
}
/**
* 取消订阅
* @param ovserver
*/
@Override
public void cancelSubscribe(Ovserver ovserver){
this.ovserverList.remove(ovserver);
}
/**
* 通知订阅者,订阅者被通知后做出相应的反应
*/
@Override
public void notifyOvserver(String msg){
for(Ovserver ovserver : ovserverList){
ovserver.doSomeThing(msg);
}
}
}
|
3e082e52b1342110ae0614eddf807a629fb954fc
| 1,036 |
java
|
Java
|
chapter_005/src/main/java/ru/job4j/store/Store.java
|
ikibis/job4j
|
6aec9bed9759613253b4766fc7a50ca6cddfbf8f
|
[
"Apache-2.0"
] | null | null | null |
chapter_005/src/main/java/ru/job4j/store/Store.java
|
ikibis/job4j
|
6aec9bed9759613253b4766fc7a50ca6cddfbf8f
|
[
"Apache-2.0"
] | 5 |
2021-05-12T00:28:05.000Z
|
2022-02-16T00:56:12.000Z
|
chapter_005/src/main/java/ru/job4j/store/Store.java
|
ikibis/job4j
|
6aec9bed9759613253b4766fc7a50ca6cddfbf8f
|
[
"Apache-2.0"
] | null | null | null | 25.9 | 61 | 0.560811 | 3,462 |
package ru.job4j.store;
import java.util.HashMap;
public class Store {
public HashMap<Integer, User> previous = new HashMap<>();
public HashMap<Integer, User> current = new HashMap<>();
public int setted;
public void removeUser(int id) {
User user = this.findById(id);
previous.put(user.getId(), user);
current.remove(user);
}
public void addUser(int id, String name) {
User user = new User(id, name);
current.put(user.getId(), user);
}
public void setUser(int id, String name) {
User user = this.findById(id);
previous.put(user.getId(), user);
User settedUser = new User(user.getId(), name);
current.put(user.getId(), settedUser);
setted++;
}
private User findById(int id) {
User result = null;
for (Integer userId : current.keySet()) {
if (userId == id) {
result = current.get(userId);
break;
}
}
return result;
}
}
|
3e082e613df922519cd8ff9aa1d576c5501ad2cf
| 755 |
java
|
Java
|
samples/data-jpa/src/main/java/app/main/hierarchy/ProxyClass.java
|
ellkrauze/spring-native
|
e5a0ef8b4befe689529cc26d64b7eeb94f292383
|
[
"Apache-2.0"
] | 1,702 |
2021-01-06T10:02:54.000Z
|
2022-03-29T17:51:08.000Z
|
samples/data-jpa/src/main/java/app/main/hierarchy/ProxyClass.java
|
ellkrauze/spring-native
|
e5a0ef8b4befe689529cc26d64b7eeb94f292383
|
[
"Apache-2.0"
] | 1,032 |
2021-01-06T08:10:57.000Z
|
2022-03-31T15:55:11.000Z
|
samples/data-jpa/src/main/java/app/main/hierarchy/ProxyClass.java
|
ellkrauze/spring-native
|
e5a0ef8b4befe689529cc26d64b7eeb94f292383
|
[
"Apache-2.0"
] | 216 |
2021-01-09T10:13:54.000Z
|
2022-03-31T03:14:56.000Z
| 29.038462 | 75 | 0.73245 | 3,463 |
/*
* Copyright 2021 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
*
* 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 app.main.hierarchy;
public class ProxyClass implements TransactionalInterface {
@Override
public void foo() {
}
}
|
3e082e62e95aa52905515a837248fd4a070f9128
| 1,230 |
java
|
Java
|
src/main/java/xin/sunce/chapter6/jvm/chapter1/params/JvmDemo.java
|
sexylowrie/teach
|
67674ccc8461dcb0eefccc683f97688f01e6497f
|
[
"Apache-2.0"
] | 1 |
2018-12-27T06:04:06.000Z
|
2018-12-27T06:04:06.000Z
|
src/main/java/xin/sunce/chapter6/jvm/chapter1/params/JvmDemo.java
|
sexylowrie/java-base-teach
|
67674ccc8461dcb0eefccc683f97688f01e6497f
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/xin/sunce/chapter6/jvm/chapter1/params/JvmDemo.java
|
sexylowrie/java-base-teach
|
67674ccc8461dcb0eefccc683f97688f01e6497f
|
[
"Apache-2.0"
] | null | null | null | 28.604651 | 70 | 0.636585 | 3,464 |
package xin.sunce.chapter6.jvm.chapter1.params;
/**
* Copyright (C), 2010-2020, sun ce. Personal.
*
* @author lowrie
* @version 1.0.0
* @date 2020-03-31
*/
public class JvmDemo {
/**
* -Xmx == -XX:MaxHeapSize 默认物理内存1/4
* -Xms == -XX:InitialHeapSize 默认物理内存1/64 一般简单优化会把-Xmx与-Xms调整成一样的
* <p>
* -Xmn == -XX:NewSizes
* -Xss == -XX:ThreadStackSize 默认物理1024k
* -XX:MetaspaceSize 设置元空间大小
* -XX:MaxMetaspaceSize 设置最大元空间大小
* -XX:SurvivorRatio 默认8,Eden:S0:S1=8:1:1
* -XX:NewRatio 默认2,Old:New =2:1
* -XX:MaxtenuringThreshold 默认15,一个对象经历15次GC之后还存活则进入老年代
* -XX:PrintGCDetails 输出GC细节
* -XX:+PrintFlagsInitial 输出默认参数
* -XX:+PrintFlagsFinal 输出修改后参数
* -XX:+PrintCommandLineFlags 输出GC Collector相关参数
* <p>
* 如何查看正在运行的java应用参数配置
* 首先:jps 获取java进程号
* 其次:jinfo -flag 参数名 进程号 例如:jinfo -flag MaxHeapSize 27981
* 或者:jinfo -flags xxx
* <p>
* 或者启动时输出
* -XX:+PrintFlagsInitial 输出默认参数
* -XX:+PrintFlagsFinal 输出修改后参数
* -XX:+PrintCommandLineFlags 输出GC Collector相关参数
*/
public static void main(String[] args) throws Exception {
System.out.println("Hello GC");
Thread.sleep(Integer.MAX_VALUE);
}
}
|
3e082fca0cdfb075d1b788339230ca48b3b4a49c
| 272 |
java
|
Java
|
Java Web/Basics/04. Introduction to Java EE/src/main/java/fdmc/domain/entities/Cat.java
|
GabrielGardev/skill-receiving
|
7227323d065f3472a6aedc1cbf3efd41562269f2
|
[
"MIT"
] | 3 |
2019-01-24T20:22:38.000Z
|
2019-08-19T13:45:31.000Z
|
Java Web/Basics/04. Introduction to Java EE/src/main/java/fdmc/domain/entities/Cat.java
|
GabrielGardev/soft-uni
|
7227323d065f3472a6aedc1cbf3efd41562269f2
|
[
"MIT"
] | null | null | null |
Java Web/Basics/04. Introduction to Java EE/src/main/java/fdmc/domain/entities/Cat.java
|
GabrielGardev/soft-uni
|
7227323d065f3472a6aedc1cbf3efd41562269f2
|
[
"MIT"
] | null | null | null | 17 | 32 | 0.764706 | 3,465 |
package fdmc.domain.entities;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class Cat {
private String name;
private String breed;
private String color;
private int numberOfLegs;
}
|
3e08307ead91dc342763ea3e7482a6070a52969c
| 168 |
java
|
Java
|
database-core/src/main/java/gaarason/database/contract/builder/package-info.java
|
gaarason/database-all
|
3d3581cd2eb5d2e71b28666985409d91fe504726
|
[
"MIT"
] | 158 |
2019-12-12T11:29:43.000Z
|
2022-03-10T01:27:25.000Z
|
database-core/src/main/java/gaarason/database/contract/builder/package-info.java
|
gaarason/database-all
|
3d3581cd2eb5d2e71b28666985409d91fe504726
|
[
"MIT"
] | 27 |
2019-12-12T08:26:16.000Z
|
2022-03-24T01:41:33.000Z
|
database-core/src/main/java/gaarason/database/contract/builder/package-info.java
|
gaarason/database-all
|
3d3581cd2eb5d2e71b28666985409d91fe504726
|
[
"MIT"
] | 13 |
2021-04-21T08:42:52.000Z
|
2021-12-03T02:19:21.000Z
| 28 | 49 | 0.857143 | 3,466 |
@NonNullFields
@NonNullApi
package gaarason.database.contract.builder;
import gaarason.database.core.lang.NonNullApi;
import gaarason.database.core.lang.NonNullFields;
|
3e0830977243e16c775d8752056b9ebab393a1bf
| 905 |
java
|
Java
|
wu-module/wu-admin/src/test/java/com/wuwii/repositry/AdminUserRepositryTest.java
|
kaimz/wu-security
|
aa2ff7365961c845ab6ec1fb28f07718fc676a32
|
[
"Apache-2.0"
] | null | null | null |
wu-module/wu-admin/src/test/java/com/wuwii/repositry/AdminUserRepositryTest.java
|
kaimz/wu-security
|
aa2ff7365961c845ab6ec1fb28f07718fc676a32
|
[
"Apache-2.0"
] | null | null | null |
wu-module/wu-admin/src/test/java/com/wuwii/repositry/AdminUserRepositryTest.java
|
kaimz/wu-security
|
aa2ff7365961c845ab6ec1fb28f07718fc676a32
|
[
"Apache-2.0"
] | 1 |
2019-06-21T02:50:55.000Z
|
2019-06-21T02:50:55.000Z
| 25.857143 | 62 | 0.730387 | 3,467 |
package com.wuwii.repositry;
import com.wuwii.model.domain.AdminUser;
import com.wuwii.repository.AdminUserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author KronChan
* @version 1.0
* @since <pre>2018/4/24 23:25</pre>
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class AdminUserRepositryTest {
@Autowired
private AdminUserRepository adminUserRepository;
@Test
public void testFindAll() {
System.out.println(adminUserRepository.findAll());
}
@Test
public void testAdd() {
AdminUser user = new AdminUser();
user.setUsername("kronchan");
user.setPassword("123456");
adminUserRepository.save(user);
}
}
|
3e083204544d355ff281eb2ab688569620e9d86c
| 537 |
java
|
Java
|
implementation/src/test/java/tck/MultiOnSubscriptionCallTckTest.java
|
oaklandcorp/smallrye-mutiny
|
d20b7e61d3e3d8279d7eeb71f4639488b38a4740
|
[
"Apache-2.0"
] | 454 |
2019-12-03T18:29:15.000Z
|
2022-03-30T11:56:16.000Z
|
implementation/src/test/java/tck/MultiOnSubscriptionCallTckTest.java
|
oaklandcorp/smallrye-mutiny
|
d20b7e61d3e3d8279d7eeb71f4639488b38a4740
|
[
"Apache-2.0"
] | 625 |
2019-12-10T12:27:05.000Z
|
2022-03-30T18:46:33.000Z
|
implementation/src/test/java/tck/MultiOnSubscriptionCallTckTest.java
|
oaklandcorp/smallrye-mutiny
|
d20b7e61d3e3d8279d7eeb71f4639488b38a4740
|
[
"Apache-2.0"
] | 87 |
2019-12-05T11:54:29.000Z
|
2022-03-20T08:58:00.000Z
| 25.571429 | 80 | 0.67784 | 3,468 |
package tck;
import org.reactivestreams.Publisher;
import io.smallrye.mutiny.Uni;
public class MultiOnSubscriptionCallTckTest extends AbstractPublisherTck<Long> {
@Override
public Publisher<Long> createPublisher(long elements) {
return upstream(elements)
.onSubscription().call(x -> Uni.createFrom().nullItem());
}
@Override
public Publisher<Long> createFailedPublisher() {
return failedUpstream()
.onSubscription().call(x -> Uni.createFrom().nullItem());
}
}
|
3e0832ae63b26c6871794ac5786c2b105e80c1ef
| 1,007 |
java
|
Java
|
src/main/java/de/guntram/mcmod/crowdintranslate/GradlePlugin/DownloadTask.java
|
OliverDeBrisbane/CrowdinTranslate
|
2d1e84a23c893d6ddcb40e671d3212afd00d3d6a
|
[
"MIT"
] | 21 |
2020-10-04T22:02:32.000Z
|
2022-03-15T12:05:16.000Z
|
src/main/java/de/guntram/mcmod/crowdintranslate/GradlePlugin/DownloadTask.java
|
OliverDeBrisbane/CrowdinTranslate
|
2d1e84a23c893d6ddcb40e671d3212afd00d3d6a
|
[
"MIT"
] | 11 |
2020-11-07T16:01:25.000Z
|
2022-03-24T07:44:58.000Z
|
src/main/java/de/guntram/mcmod/crowdintranslate/GradlePlugin/DownloadTask.java
|
OliverDeBrisbane/CrowdinTranslate
|
2d1e84a23c893d6ddcb40e671d3212afd00d3d6a
|
[
"MIT"
] | 8 |
2021-05-30T09:21:22.000Z
|
2022-03-11T20:14:15.000Z
| 33.566667 | 84 | 0.630586 | 3,469 |
package de.guntram.mcmod.crowdintranslate.GradlePlugin;
import de.guntram.mcmod.crowdintranslate.CrowdinTranslate;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
public class DownloadTask extends DefaultTask {
@TaskAction
public void action() {
CrowdinTranslateParameters parms = CrowdinTranslatePlugin.parameters;
if (parms.getCrowdinProjectName() == null) {
System.err.println("No crowdin project name given, nothing downloaded");
return;
}
String[] args = new String[ (parms.getVerbose() ? 4 : 3) ];
int argc = 0;
if (parms.getVerbose()) {
args[argc++] = "-v";
}
String cpn = parms.getCrowdinProjectName();
String mpn = parms.getMinecraftProjectName();
args[argc++] = cpn;
args[argc++] = (mpn == null ? cpn : mpn);
args[argc++] = parms.getJsonSourceName();
CrowdinTranslate.main(args);
this.setDidWork(true);
}
}
|
3e0832c369e6ca471f52c24d9fbb20973ee1f650
| 2,053 |
java
|
Java
|
server/src/main/java/com/inventage/airmock/waf/proxy/AirmockHttpProxy.java
|
inventage/airmock
|
8001e8e8d2306f5be13459924f61abf5de5746d9
|
[
"MIT"
] | 2 |
2020-01-27T12:08:44.000Z
|
2020-10-22T14:16:32.000Z
|
server/src/main/java/com/inventage/airmock/waf/proxy/AirmockHttpProxy.java
|
inventage/airmock
|
8001e8e8d2306f5be13459924f61abf5de5746d9
|
[
"MIT"
] | 3 |
2020-02-03T14:16:10.000Z
|
2021-08-04T14:24:20.000Z
|
server/src/main/java/com/inventage/airmock/waf/proxy/AirmockHttpProxy.java
|
inventage/airmock
|
8001e8e8d2306f5be13459924f61abf5de5746d9
|
[
"MIT"
] | 1 |
2021-02-25T10:16:25.000Z
|
2021-02-25T10:16:25.000Z
| 37.327273 | 151 | 0.619094 | 3,470 |
package com.inventage.airmock.waf.proxy;
import com.inventage.airmock.kernel.proxy.HttpProxy;
import com.inventage.airmock.kernel.proxy.internal.BackendRequestImpl;
import com.inventage.airmock.kernel.proxy.internal.HttpProxyImpl;
import io.vertx.core.http.HttpClient;
import io.vertx.reactivex.ext.web.RoutingContext;
public class AirmockHttpProxy extends HttpProxyImpl {
public AirmockHttpProxy(String hostName, String hostPort) {
super(hostName, hostPort);
}
@Override
public BackendRequestImpl getBackendRequestImpl(String proxyHostName,
String proxyHostPort,
String applicationJwtCookieName,
HttpClient client,
RoutingContext routingContext,
HttpProxy proxy) {
return new AirmockBackendRequest(proxyHost(routingContext), proxyPort(routingContext), applicationJwtCookieName, client, routingContext, this);
}
/**
*
* @param routingContext the current routing context
* @return the host used for X-Forwarded-Host
*/
protected String proxyHost(RoutingContext routingContext) {
return proxyHostName != null ? proxyHostName : filterPort(routingContext.request().host());
}
/**
*
* @param routingContext the current routing context
* @return the port used for X-Forwarded-Port
*/
protected String proxyPort(RoutingContext routingContext) {
return proxyHostPort != null ? proxyHostPort : String.valueOf(routingContext.request().localAddress().port());
}
/**
* Filter out if the port is given, e.g. localhost:8080.
*
* @param host the host from the request (header)
* @return the host name
*/
protected String filterPort(String host) {
if (host == null) {
return host;
}
return host.split(":")[0];
}
}
|
3e083351956bcea3040dcca75fa936996cb6f91b
| 15,641 |
java
|
Java
|
src/main/java/com/paulzhangcc/tools/swagger/cmd/CustomDefaultGenerator.java
|
zhijiansihang/mybatis-generator
|
572d174c3ddf3066100cdf90f3507b09dadd410d
|
[
"MIT"
] | null | null | null |
src/main/java/com/paulzhangcc/tools/swagger/cmd/CustomDefaultGenerator.java
|
zhijiansihang/mybatis-generator
|
572d174c3ddf3066100cdf90f3507b09dadd410d
|
[
"MIT"
] | null | null | null |
src/main/java/com/paulzhangcc/tools/swagger/cmd/CustomDefaultGenerator.java
|
zhijiansihang/mybatis-generator
|
572d174c3ddf3066100cdf90f3507b09dadd410d
|
[
"MIT"
] | null | null | null | 48.126154 | 233 | 0.622339 | 3,471 |
package com.paulzhangcc.tools.swagger.cmd;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.*;
import io.swagger.codegen.utils.ImplementationVersion;
import io.swagger.util.Json;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import java.io.*;
import java.net.URL;
import java.util.*;
/**
* @author paul
* @description
* @date 2019/4/23
*/
public class CustomDefaultGenerator extends DefaultGenerator {
/**
* 修改判断是否生成支持文件
*/
@Override
protected void configureGeneratorProperties() {
// allows generating only models by specifying a CSV of models to generate, or empty for all
// NOTE: Boolean.TRUE is required below rather than `true` because of JVM boxing constraints and type inference.
isGenerateApis = System.getProperty(CodegenConstants.APIS) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.APIS, null);
isGenerateModels = System.getProperty(CodegenConstants.MODELS) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.MODELS, null);
Map<String, Object> map = config.additionalProperties();
Object useSwaggerAnnotation = map.get("isGenerateSupportingFiles");
if (useSwaggerAnnotation != null) {
isGenerateSupportingFiles = true;
} else {
isGenerateSupportingFiles = false;
}
if (isGenerateApis == null && isGenerateModels == null) {
// no specifics are set, generate everything
isGenerateApis = isGenerateModels = true;
} else {
if(isGenerateApis == null) {
isGenerateApis = false;
}
if(isGenerateModels == null) {
isGenerateModels = false;
}
}
// model/api tests and documentation options rely on parent generate options (api or model) and no other options.
// They default to true in all scenarios and can only be marked false explicitly
isGenerateModelTests = System.getProperty(CodegenConstants.MODEL_TESTS) != null ? Boolean.valueOf(System.getProperty(CodegenConstants.MODEL_TESTS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.MODEL_TESTS, true);
isGenerateModelDocumentation = System.getProperty(CodegenConstants.MODEL_DOCS) != null ? Boolean.valueOf(System.getProperty(CodegenConstants.MODEL_DOCS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.MODEL_DOCS, true);
isGenerateApiTests = System.getProperty(CodegenConstants.API_TESTS) != null ? Boolean.valueOf(System.getProperty(CodegenConstants.API_TESTS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.API_TESTS, true);
isGenerateApiDocumentation = System.getProperty(CodegenConstants.API_DOCS) != null ? Boolean.valueOf(System.getProperty(CodegenConstants.API_DOCS)) : getGeneratorPropertyDefaultSwitch(CodegenConstants.API_DOCS, true);
// Additional properties added for tests to exclude references in project related files
config.additionalProperties().put(CodegenConstants.GENERATE_API_TESTS, isGenerateApiTests);
config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_TESTS, isGenerateModelTests);
config.additionalProperties().put(CodegenConstants.GENERATE_API_DOCS, isGenerateApiDocumentation);
config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_DOCS, isGenerateModelDocumentation);
config.additionalProperties().put(CodegenConstants.GENERATE_APIS, isGenerateApis);
config.additionalProperties().put(CodegenConstants.GENERATE_MODELS, isGenerateModels);
if(!isGenerateApiTests && !isGenerateModelTests) {
config.additionalProperties().put(CodegenConstants.EXCLUDE_TESTS, true);
}
if (System.getProperty("debugSwagger") != null) {
Json.prettyPrint(swagger);
}
config.processOpts();
config.preprocessSwagger(swagger);
config.additionalProperties().put("generatorVersion", ImplementationVersion.read());
config.additionalProperties().put("generatedDate", DateTime.now().toString());
config.additionalProperties().put("generatedYear", String.valueOf(DateTime.now().getYear()));
config.additionalProperties().put("generatorClass", config.getClass().getName());
config.additionalProperties().put("inputSpec", config.getInputSpec());
if (swagger.getVendorExtensions() != null) {
config.vendorExtensions().putAll(swagger.getVendorExtensions());
}
contextPath = config.escapeText(swagger.getBasePath() == null ? "" : swagger.getBasePath());
basePath = config.escapeText(getHost());
basePathWithoutHost = config.escapeText(swagger.getBasePath());
this.isGenerateSwaggerMetadata = getAdditionalPropertyDefaultSwitch("isGenerateSwaggerMetadata",Boolean.FALSE);
}
private Boolean getAdditionalPropertyDefaultSwitch(final String key, final Boolean defaultValue) {
Object result = null;
if (this.config.additionalProperties().containsKey(key)) {
result = this.config.additionalProperties().get(key);
}
if (result != null && result instanceof String) {
return Boolean.valueOf((String) result);
}
return defaultValue;
}
private String getHost() {
StringBuilder hostBuilder = new StringBuilder();
hostBuilder.append(getScheme());
hostBuilder.append("://");
if (!StringUtils.isEmpty(swagger.getHost())) {
hostBuilder.append(swagger.getHost());
} else {
hostBuilder.append("localhost");
LOGGER.warn("'host' not defined in the spec. Default to 'localhost'.");
}
if (!StringUtils.isEmpty(swagger.getBasePath()) && !swagger.getBasePath().equals("/")) {
hostBuilder.append(swagger.getBasePath());
}
return hostBuilder.toString();
}
/**
* 支持扩展目录 先从templateDir中查找(支持文件目录或者classpath文件),再从embeddedLibTemplateFile查找
* @param config
* @param templateFile
* @return
*/
@Override
public String getFullTemplateFile(CodegenConfig config, String templateFile) {
//1st the code will check if there's a <template folder>/libraries/<library> folder containing the file
//2nd it will check for the file in the specified <template folder> folder
//3rd it will check if there's an <embedded template>/libraries/<library> folder containing the file
//4th and last it will assume the file is in <embedded template> folder.
//check the supplied template library folder for the file
final String library = config.getLibrary();
if (StringUtils.isNotEmpty(library)) {
//look for the file in the library subfolder of the supplied template
final String libTemplateFile = buildLibraryFilePath(config.templateDir(), library, templateFile);
if (new File(libTemplateFile).exists() || existClassPath(libTemplateFile)) {
return libTemplateFile;
}
}
//check the supplied template main folder for the file
final String template = config.templateDir() + File.separator + templateFile;
if (new File(template).exists() || existClassPath(template)) {
return template;
}
//try the embedded template library folder next
if (StringUtils.isNotEmpty(library)) {
final String embeddedLibTemplateFile = buildLibraryFilePath(config.embeddedTemplateDir(), library, templateFile);
if (embeddedTemplateExists(embeddedLibTemplateFile)) {
// Fall back to the template file embedded/packaged in the JAR file library folder...
return embeddedLibTemplateFile;
}
}
// Fall back to the template file embedded/packaged in the JAR file...
return config.embeddedTemplateDir() + File.separator + templateFile;
}
private String buildLibraryFilePath(String dir, String library, String file) {
return dir + File.separator + "libraries" + File.separator + library + File.separator + file;
}
private boolean existClassPath(String name){
try {
URL resource = this.getClass().getClassLoader().getResource((getCPResourcePath(name)));
String file = resource.getFile();
if (new File(file).exists()){
return true;
}
}catch (Exception e){
}
return false;
}
/**
* 调整目录创建of.mkdirs();放到是否存在支持列表判断后面,以防止生成多余的目录
* @param files
* @param bundle
*/
@Override
protected void generateSupportingFiles(List<File> files, Map<String, Object> bundle) {
if (!isGenerateSupportingFiles) {
return;
}
Set<String> supportingFilesToGenerate = null;
String supportingFiles = System.getProperty(CodegenConstants.SUPPORTING_FILES);
if (supportingFiles != null && !supportingFiles.isEmpty()) {
supportingFilesToGenerate = new HashSet<String>(Arrays.asList(supportingFiles.split(",")));
}
for (SupportingFile support : config.supportingFiles()) {
try {
String outputFolder = config.outputFolder();
if (StringUtils.isNotEmpty(support.folder)) {
outputFolder += File.separator + support.folder;
}
boolean shouldGenerate = true;
if (supportingFilesToGenerate != null && !supportingFilesToGenerate.isEmpty()) {
shouldGenerate = supportingFilesToGenerate.contains(support.destinationFilename);
}
if (!shouldGenerate) {
continue;
}
File of = new File(outputFolder);
if (!of.isDirectory()) {
of.mkdirs();
}
String outputFilename = outputFolder + File.separator + support.destinationFilename.replace('/', File.separatorChar);
if (!config.shouldOverwrite(outputFilename)) {
LOGGER.info("Skipped overwriting " + outputFilename);
continue;
}
String templateFile;
if (support instanceof GlobalSupportingFile) {
templateFile = config.getCommonTemplateDir() + File.separator + support.templateFile;
} else {
templateFile = getFullTemplateFile(config, support.templateFile);
}
if (ignoreProcessor.allowsFile(new File(outputFilename))) {
if (templateFile.endsWith("mustache")) {
String template = readTemplate(templateFile);
Mustache.Compiler compiler = Mustache.compiler();
compiler = config.processCompiler(compiler);
Template tmpl = compiler
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(outputFilename, tmpl.execute(bundle));
files.add(new File(outputFilename));
} else {
InputStream in = null;
try {
in = new FileInputStream(templateFile);
} catch (Exception e) {
// continue
}
if (in == null) {
in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile));
}
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if (in != null) {
LOGGER.info("writing file " + outputFile);
IOUtils.copy(in, out);
out.close();
} else {
LOGGER.error("can't open " + templateFile + " for input");
}
files.add(outputFile);
}
} else {
LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore");
}
} catch (Exception e) {
throw new RuntimeException("Could not generate supporting file '" + support + "'", e);
}
}
// Consider .swagger-codegen-ignore a supporting file
// Output .swagger-codegen-ignore if it doesn't exist and wasn't explicitly created by a generator
final String swaggerCodegenIgnore = ".swagger-codegen-ignore";
String ignoreFileNameTarget = config.outputFolder() + File.separator + swaggerCodegenIgnore;
File ignoreFile = new File(ignoreFileNameTarget);
if (isGenerateSwaggerMetadata && !ignoreFile.exists()) {
String ignoreFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + swaggerCodegenIgnore;
String ignoreFileContents = readResourceContents(ignoreFileNameSource);
try {
writeToFile(ignoreFileNameTarget, ignoreFileContents);
} catch (IOException e) {
throw new RuntimeException("Could not generate supporting file '" + swaggerCodegenIgnore + "'", e);
}
files.add(ignoreFile);
}
if(isGenerateSwaggerMetadata) {
final String swaggerVersionMetadata = config.outputFolder() + File.separator + ".swagger-codegen" + File.separator + "VERSION";
File swaggerVersionMetadataFile = new File(swaggerVersionMetadata);
try {
writeToFile(swaggerVersionMetadata, ImplementationVersion.read());
files.add(swaggerVersionMetadataFile);
} catch (IOException e) {
throw new RuntimeException("Could not generate supporting file '" + swaggerVersionMetadata + "'", e);
}
}
/*
* The following code adds default LICENSE (Apache-2.0) for all generators
* To use license other than Apache2.0, update the following file:
* modules/swagger-codegen/src/main/resources/_common/LICENSE
*
final String apache2License = "LICENSE";
String licenseFileNameTarget = config.outputFolder() + File.separator + apache2License;
File licenseFile = new File(licenseFileNameTarget);
String licenseFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + apache2License;
String licenseFileContents = readResourceContents(licenseFileNameSource);
try {
writeToFile(licenseFileNameTarget, licenseFileContents);
} catch (IOException e) {
throw new RuntimeException("Could not generate LICENSE file '" + apache2License + "'", e);
}
files.add(licenseFile);
*/
}
}
|
3e0833e08eb6b4107d85d3c4fb3406dee065cf9d
| 3,759 |
java
|
Java
|
07_collections/session_final/linkedlist/SetTests.java
|
thewillyhuman/uniovi-eii-1.010
|
68687f1e32733fd79f03ae828f09568db5001710
|
[
"MIT"
] | 1 |
2022-02-25T11:56:15.000Z
|
2022-02-25T11:56:15.000Z
|
07_collections/session_final/linkedlist/SetTests.java
|
thewillyhuman/uniovi-eii-1.010
|
68687f1e32733fd79f03ae828f09568db5001710
|
[
"MIT"
] | null | null | null |
07_collections/session_final/linkedlist/SetTests.java
|
thewillyhuman/uniovi-eii-1.010
|
68687f1e32733fd79f03ae828f09568db5001710
|
[
"MIT"
] | null | null | null | 22.781818 | 65 | 0.631817 | 3,472 |
package uo.mp.collections.linkedlist;
import org.junit.Before;
import org.junit.Test;
import uo.mp.collections.LinkedList;
import uo.mp.collections.List;
import uo.mp.collections.setting.Settings;
import static org.junit.Assert.assertTrue;
/**
* TEST CASE 1
* GIVEN: An empty list.
* Set any position to a null value.
*
* TEST CASE 2
* GIVEN: An empty list.
* Set position 0 to a null value.
*
* TEST CASE 3
* GIVEN: An empty list.
* Set position 0 to a non null value.
*
* TEST CASE 4
* GIVEN: A non empty list.
* Set position 0 to a null value.
*
* TEST CASE 5
* GIVEN: A non empty list.
* Set position 0 to a non null value.
*
* TEST CASE 6
* GIVEN: A non empty list.
* Set position<0 and >size()-1 to a null value.
*
* TEST CASE 7
* GIVEN: A non empty list.
* Set position<0 and >size()-1 to a non null value.
*
* TEST CASE 8
* GIVEN: A non empty list.
* Set a valid position != 0 to a non null value.
*
* TEST CASE 9
* GIVEN: A non empty list.
* Set a valid position != 0 to a null value.
*
* TEST CASE 10
* GIVEN: A non empty list.
* Set the last position to a non null value.
*
* TEST CASE 11
* GIVEN: A non empty list.
* Set the last position to a null value.
*/
public class SetTests {
private List list;
@Before
public void setUp() throws Exception {
list = new LinkedList();
}
/**
* GIVEN: an empty list
* WHEN: trying to set an element
* THEN: it throws IndexOutOfBoundsException
*/
@Test(expected=IndexOutOfBoundsException.class)
public void testEmpty() {
list.set(0, "testing");
}
/**
* GIVEN: a non empty list
* WHEN: trying to set an element beyond the last element
* THEN: it throws IndexOutOfBoundsException
*/
@Test(expected=IndexOutOfBoundsException.class)
public void testUpper() {
list.add("testing");
list.add("with");
list.add("JUnit");
list.add("framework");
list.set(list.size(), "framework");
}
/**
* GIVEN: a non empty list
* WHEN: trying to set an element below the first element
* THEN: it throws IndexOutOfBoundsException
*/
@Test(expected=IndexOutOfBoundsException.class)
public void testLower() {
list.add("testing");
list.add("with");
list.add("JUnit");
list.add("framework");
list.set(-1, "framework");
}
/**
* GIVEN: a non empty list
* WHEN: trying to set an element at first element
* THEN: the size remains unchanged, the first element changes
*/
@Test
public void setFirst() {
list.add("testing");
list.add("with");
list.add("JUnit");
list.add("framework");
int size = list.size();
assertTrue(list.set(0, "TESTING").equals("testing"));
assertTrue(list.get(0).equals("TESTING"));
assertTrue(list.size() == size);
}
/**
* GIVEN: a non empty list
* WHEN: trying to set an element at the end
* THEN: the size remains unchanged, last element is replaced
*/
@Test
public void setFinal() {
list.add("testing");
list.add("with");
list.add("JUnit");
list.add("framework");
int size = list.size();
assertTrue(list.set(size-1, "FRAMEWORK").equals("framework"));
assertTrue(list.get(size-1).equals("FRAMEWORK"));
assertTrue(list.size() == size);
}
/**
* GIVEN: a non empty list
* WHEN: trying to set an element in the middle
* THEN: the size remains unchanged, this element is replaced
*/
@Test
public void setMiddle() {
list.add("testing");
list.add("with");
list.add("JUnit");
list.add("framework");
int size = list.size();
assertTrue(list.set(2, "junit").equals("JUnit"));
assertTrue(list.get(2).equals("junit"));
assertTrue(list.size() == size);
}
}
|
3e0834e03a7abf4af7139d70fc8118a5e4b4f6ad
| 638 |
java
|
Java
|
app/src/main/java/com/david/clicker/ui/profile/ProfileViewModel.java
|
The-Commuters/Click
|
1ab79fd1b85db2e011f44ef95583dc013abf3b91
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/david/clicker/ui/profile/ProfileViewModel.java
|
The-Commuters/Click
|
1ab79fd1b85db2e011f44ef95583dc013abf3b91
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/david/clicker/ui/profile/ProfileViewModel.java
|
The-Commuters/Click
|
1ab79fd1b85db2e011f44ef95583dc013abf3b91
|
[
"MIT"
] | null | null | null | 26.583333 | 63 | 0.780564 | 3,473 |
package com.david.clicker.ui.profile;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import com.david.clicker.data.entities.Profile;
import com.david.clicker.data.repository.ProfileRepository;
public class ProfileViewModel extends AndroidViewModel {
private ProfileRepository profileRepository;
public ProfileViewModel(@NonNull Application application) {
super(application);
profileRepository = new ProfileRepository(application);
}
public void insert(Profile profile) {
profileRepository.insertLocalProfile(profile);
}
}
|
3e08365bc60301a02b5162a92e86934e48612983
| 2,648 |
java
|
Java
|
kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/test/java/org/kie/workbench/common/stunner/core/client/session/command/impl/AbstractExportSessionCommandTest.java
|
tkobayas/kie-wb-common
|
2c69347f0f634268fb7cca77ccf9e1311f1486e9
|
[
"Apache-2.0"
] | 34 |
2017-05-21T11:28:40.000Z
|
2021-07-03T13:15:03.000Z
|
kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/test/java/org/kie/workbench/common/stunner/core/client/session/command/impl/AbstractExportSessionCommandTest.java
|
tkobayas/kie-wb-common
|
2c69347f0f634268fb7cca77ccf9e1311f1486e9
|
[
"Apache-2.0"
] | 2,576 |
2017-03-14T00:57:07.000Z
|
2022-03-29T07:52:38.000Z
|
kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/test/java/org/kie/workbench/common/stunner/core/client/session/command/impl/AbstractExportSessionCommandTest.java
|
tkobayas/kie-wb-common
|
2c69347f0f634268fb7cca77ccf9e1311f1486e9
|
[
"Apache-2.0"
] | 158 |
2017-03-15T08:55:40.000Z
|
2021-11-19T14:07:17.000Z
| 33.948718 | 97 | 0.760196 | 3,474 |
/*
* Copyright 2018 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.session.command.impl;
import org.junit.Before;
import org.junit.Test;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.util.CanvasFileExport;
import org.kie.workbench.common.stunner.core.client.session.command.AbstractClientSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.ClientSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.impl.EditorSession;
import org.kie.workbench.common.stunner.core.client.session.impl.ViewerSession;
import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.kie.workbench.common.stunner.core.diagram.Metadata;
import org.mockito.Mock;
import org.uberfire.backend.vfs.Path;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public abstract class AbstractExportSessionCommandTest {
protected static final String FILE_NAME = "file-name1";
@Mock
protected CanvasFileExport canvasFileExport;
@Mock
protected ViewerSession session;
@Mock
protected AbstractCanvasHandler canvasHandler;
@Mock
protected Diagram diagram;
@Mock
protected Metadata metadata;
@Mock
protected Path path;
@Mock
protected ClientSessionCommand.Callback callback;
@Before
public void setup() {
when(session.getCanvasHandler()).thenReturn(canvasHandler);
when(canvasHandler.getDiagram()).thenReturn(diagram);
when(diagram.getMetadata()).thenReturn(metadata);
when(metadata.getPath()).thenReturn(path);
when(path.getFileName()).thenReturn(FILE_NAME);
}
protected abstract AbstractClientSessionCommand getCommand();
@Test
public void testAcceptsSession() {
assertTrue(getCommand().accepts(mock(EditorSession.class)));
assertTrue(getCommand().accepts(mock(ViewerSession.class)));
}
}
|
3e08374347426364454a5ca4ee3fc08cca38c39c
| 5,790 |
java
|
Java
|
src/main/java/chylex/hee/entity/mob/EntityMobEnderGuardian.java
|
chylex/Hardcore-Ender-Expansion
|
d962137c81eb5d48c05c6083e7700f2156d5b05d
|
[
"FSFAP"
] | 35 |
2015-01-12T07:11:01.000Z
|
2022-03-25T23:29:35.000Z
|
src/main/java/chylex/hee/entity/mob/EntityMobEnderGuardian.java
|
chylex/Hardcore-Ender-Expansion
|
d962137c81eb5d48c05c6083e7700f2156d5b05d
|
[
"FSFAP"
] | 132 |
2015-01-08T01:30:04.000Z
|
2022-01-16T02:19:01.000Z
|
src/main/java/chylex/hee/entity/mob/EntityMobEnderGuardian.java
|
chylex/Hardcore-Ender-Expansion
|
d962137c81eb5d48c05c6083e7700f2156d5b05d
|
[
"FSFAP"
] | 37 |
2015-01-07T19:46:52.000Z
|
2021-10-31T14:50:22.000Z
| 34.879518 | 178 | 0.753713 | 3,475 |
package chylex.hee.entity.mob;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import chylex.hee.entity.GlobalMobData.IIgnoreEnderGoo;
import chylex.hee.entity.fx.FXType;
import chylex.hee.init.ItemList;
import chylex.hee.mechanics.misc.Baconizer;
import chylex.hee.packets.PacketPipeline;
import chylex.hee.packets.client.C21EffectEntity;
import chylex.hee.proxy.ModCommonProxy;
import chylex.hee.system.abstractions.entity.EntityAttributes;
import chylex.hee.system.abstractions.entity.EntityAttributes.Operation;
import chylex.hee.system.util.MathUtil;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class EntityMobEnderGuardian extends EntityMob implements IIgnoreEnderGoo{
private static final AttributeModifier dashModifier = EntityAttributes.createModifier("Guardian Dash", Operation.ADD_MULTIPLIED, 1.2D);
private byte attackTimer, dashCooldown;
public EntityMobEnderGuardian(World world){
super(world);
setSize(1.5F, 3.2F);
}
@Override
protected Entity findPlayerToAttack(){
EntityPlayer player = worldObj.getClosestVulnerablePlayerToEntity(this, 3D);
return player != null && canEntityBeSeen(player) ? player : null;
}
@Override
protected void applyEntityAttributes(){
super.applyEntityAttributes();
EntityAttributes.setValue(this, EntityAttributes.movementSpeed, ModCommonProxy.opMobs ? 0.7D : 0.65D);
EntityAttributes.setValue(this, EntityAttributes.maxHealth, ModCommonProxy.opMobs ? 100D : 80D);
EntityAttributes.setValue(this, EntityAttributes.attackDamage, ModCommonProxy.opMobs ? 25D : 17D);
}
@Override
public void onLivingUpdate(){
super.onLivingUpdate();
if (attackTimer > 0)--attackTimer;
if (!worldObj.isRemote && !isDead){
if (dashCooldown > 0){
if (--dashCooldown == 70)EntityAttributes.removeModifier(this, EntityAttributes.movementSpeed, dashModifier);
else if (dashCooldown > 1 && dashCooldown < 70 && ((ModCommonProxy.opMobs && rand.nextInt(3) == 0) || rand.nextInt(5) == 0))--dashCooldown;
}
else if (dashCooldown == 0 && entityToAttack != null && MathUtil.distance(posX-entityToAttack.posX, posZ-entityToAttack.posZ) < 4D && Math.abs(posY-entityToAttack.posY) <= 3){
dashCooldown = 80;
EntityAttributes.applyModifier(this, EntityAttributes.movementSpeed, dashModifier);
PacketPipeline.sendToAllAround(this, 64D, new C21EffectEntity(FXType.Entity.ENDER_GUARDIAN_DASH, this));
}
}
}
@Override
public float getAIMoveSpeed(){
return (float)EntityAttributes.getValue(this, EntityAttributes.movementSpeed)*0.3F;
}
@Override
public boolean attackEntityAsMob(Entity entity){
attackTimer = 8;
worldObj.setEntityState(this, (byte)4);
float damage = (float)this.getEntityAttribute(SharedMonsterAttributes.attackDamage).getAttributeValue(); // TODO
if (entity.attackEntityFrom(DamageSource.causeMobDamage(this), damage)){
entity.addVelocity(-MathHelper.sin(MathUtil.toRad(rotationYaw))*1.7D, 0.2D, MathHelper.cos(MathUtil.toRad(rotationYaw))*1.7D);
motionX *= 0.8D;
motionZ *= 0.8D;
if (dashCooldown > 70){
motionX *= 0.5D;
motionZ *= 0.5D;
dashCooldown = 71;
}
EnchantmentHelper.func_151385_b(this, entity);
return true;
}
else return false;
}
@Override
@SideOnly(Side.CLIENT)
public void handleHealthUpdate(byte eventId){
if (eventId == 4)attackTimer = 8;
else super.handleHealthUpdate(eventId);
}
@Override
public boolean attackEntityFrom(DamageSource source, float amount){
if (source == DamageSource.fallingBlock || source == DamageSource.anvil)amount *= 0.8F;
else if (source.isProjectile())amount *= 0.5F;
else if (source.isFireDamage() || source == DamageSource.drown)amount *= 0.2F;
else if (source == DamageSource.cactus)amount = 0F;
if (amount >= 0.1F && super.attackEntityFrom(source, amount)){
// TODO CausatumUtils.increase(source, CausatumMeters.END_MOB_DAMAGE, amount*0.5F);
return true;
}
else return false;
}
@Override
protected void dropFewItems(boolean recentlyHit, int looting){
int amount = rand.nextInt(2+looting)-rand.nextInt(2);
for(int a = 0; a < amount; a++)dropItem(Items.ender_pearl, 1);
amount = 1+rand.nextInt(3+(looting>>1));
for(int a = 0; a < amount; a++)dropItem(Item.getItemFromBlock(Blocks.obsidian), 1);
if (recentlyHit){
amount = rand.nextInt(4-rand.nextInt(3)+(looting>>1));
for(int a = 0; a < amount; a++)dropItem(ItemList.obsidian_fragment, 1);
}
}
@Override
public void addVelocity(double xVelocity, double yVelocity, double zVelocity){
double mp = rand.nextInt(5) == 0 ? 0D : 0.3D+rand.nextDouble()*0.2D;
super.addVelocity(xVelocity*mp, yVelocity*mp, zVelocity*mp);
}
@SideOnly(Side.CLIENT)
public int getAttackTimerClient(){
return attackTimer;
}
@Override
protected String getLivingSound(){
return Baconizer.soundNormal(super.getLivingSound());
}
@Override
protected String getHurtSound(){
return Baconizer.soundNormal(super.getHurtSound());
}
@Override
protected String getDeathSound(){
return Baconizer.soundDeath(super.getDeathSound());
}
@Override
public String getCommandSenderName(){
return hasCustomNameTag() ? getCustomNameTag() : StatCollector.translateToLocal(Baconizer.mobName("entity.enderGuardian.name"));
}
}
|
3e0837ded020398695da4e925802d4222e9b1c54
| 206 |
java
|
Java
|
src/main/java/com/rkjha/msscbrewery/web/service/CustomerService.java
|
opencodes/mssc-brewery
|
86219c1447f7125dd1aebc9758fc3af71ba95cf5
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/rkjha/msscbrewery/web/service/CustomerService.java
|
opencodes/mssc-brewery
|
86219c1447f7125dd1aebc9758fc3af71ba95cf5
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/rkjha/msscbrewery/web/service/CustomerService.java
|
opencodes/mssc-brewery
|
86219c1447f7125dd1aebc9758fc3af71ba95cf5
|
[
"Apache-2.0"
] | null | null | null | 20.6 | 49 | 0.805825 | 3,476 |
package com.rkjha.msscbrewery.web.service;
import com.rkjha.msscbrewery.web.dto.CustomerDto;
import java.util.UUID;
public interface CustomerService {
CustomerDto getCustomerById(UUID customerId);
}
|
3e08385493431e7fcd09a12129b578e4c5bb73f9
| 1,885 |
java
|
Java
|
polkaj-json-types/src/main/java/io/emeraldpay/polkaj/json/jackson/StorageChangeSetDeserializer.java
|
gianinbasler/polkaj
|
5b2a9d50d234928cee198d914cde7969fc5a939d
|
[
"Apache-2.0"
] | 53 |
2020-05-10T06:53:34.000Z
|
2022-03-21T01:07:10.000Z
|
polkaj-json-types/src/main/java/io/emeraldpay/polkaj/json/jackson/StorageChangeSetDeserializer.java
|
gianinbasler/polkaj
|
5b2a9d50d234928cee198d914cde7969fc5a939d
|
[
"Apache-2.0"
] | 79 |
2020-05-09T01:03:29.000Z
|
2022-02-24T13:33:50.000Z
|
polkaj-json-types/src/main/java/io/emeraldpay/polkaj/json/jackson/StorageChangeSetDeserializer.java
|
gianinbasler/polkaj
|
5b2a9d50d234928cee198d914cde7969fc5a939d
|
[
"Apache-2.0"
] | 38 |
2020-05-12T19:55:26.000Z
|
2022-03-06T10:06:57.000Z
| 44.880952 | 151 | 0.717772 | 3,477 |
package io.emeraldpay.polkaj.json.jackson;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import io.emeraldpay.polkaj.json.StorageChangeSetJson;
import io.emeraldpay.polkaj.types.ByteData;
import java.io.IOException;
public class StorageChangeSetDeserializer {
static class KeyValueOptionDeserializer extends StdDeserializer<StorageChangeSetJson.KeyValueOption> {
protected KeyValueOptionDeserializer() {
super(StorageChangeSetJson.KeyValueOption.class);
}
@Override
public StorageChangeSetJson.KeyValueOption deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
if (p.currentToken() != JsonToken.START_ARRAY) {
throw new InvalidFormatException(p, "Not an array", null, StorageChangeSetJson.KeyValueOption.class);
}
p.nextToken();
if (p.currentToken() != JsonToken.VALUE_STRING) {
throw new InvalidFormatException(p, "Not a string item for key", null, StorageChangeSetJson.KeyValueOption.class);
}
StorageChangeSetJson.KeyValueOption result = new StorageChangeSetJson.KeyValueOption();
result.setKey(p.readValueAs(ByteData.class));
p.nextToken();
if (p.currentToken() != JsonToken.VALUE_STRING) {
throw new InvalidFormatException(p, "Not a string item for data", null, StorageChangeSetJson.KeyValueOption.class);
}
result.setData(p.readValueAs(ByteData.class));
return result;
}
}
}
|
3e0838a3936b88cd7366e082a9b1b33ea1009a02
| 598 |
java
|
Java
|
springbase-util/src/test/java/wang/conge/springbase/util/test/bean/Other.java
|
haoran10/springbase
|
374430c4bc60949bdac31b1595308d8c38eba976
|
[
"Apache-2.0"
] | 1 |
2017-03-28T03:37:02.000Z
|
2017-03-28T03:37:02.000Z
|
springbase-util/src/test/java/wang/conge/springbase/util/test/bean/Other.java
|
haoran10/springbase
|
374430c4bc60949bdac31b1595308d8c38eba976
|
[
"Apache-2.0"
] | null | null | null |
springbase-util/src/test/java/wang/conge/springbase/util/test/bean/Other.java
|
haoran10/springbase
|
374430c4bc60949bdac31b1595308d8c38eba976
|
[
"Apache-2.0"
] | null | null | null | 16.611111 | 61 | 0.680602 | 3,478 |
package wang.conge.springbase.util.test.bean;
public class Other {
private String username;
private String password;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Other: " + username + ", " + password + ", " + age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
3e08399617234f0be1998e8c5b31b7647fa2d76c
| 3,088 |
java
|
Java
|
ent/java/src/main/java/com/antgroup/antchain/openapi/ent/models/QueryTppAllinfoResponse.java
|
alipay/antchain-openapi-prod-sdk
|
f78549e5135d91756093bd88d191ca260b28e083
|
[
"MIT"
] | 6 |
2020-06-28T06:40:50.000Z
|
2022-02-25T11:02:18.000Z
|
ent/java/src/main/java/com/antgroup/antchain/openapi/ent/models/QueryTppAllinfoResponse.java
|
alipay/antchain-openapi-prod-sdk
|
f78549e5135d91756093bd88d191ca260b28e083
|
[
"MIT"
] | null | null | null |
ent/java/src/main/java/com/antgroup/antchain/openapi/ent/models/QueryTppAllinfoResponse.java
|
alipay/antchain-openapi-prod-sdk
|
f78549e5135d91756093bd88d191ca260b28e083
|
[
"MIT"
] | 6 |
2020-06-30T09:29:03.000Z
|
2022-01-07T10:42:22.000Z
| 28.330275 | 102 | 0.70272 | 3,479 |
// This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.ent.models;
import com.aliyun.tea.*;
public class QueryTppAllinfoResponse extends TeaModel {
// 请求唯一ID,用于链路跟踪和问题排查
@NameInMap("req_msg_id")
public String reqMsgId;
// 结果码,一般OK表示调用成功
@NameInMap("result_code")
public String resultCode;
// 异常信息的文本描述
@NameInMap("result_msg")
public String resultMsg;
// 累计全部参与收益
@NameInMap("accumulative_revenue")
public Revenue accumulativeRevenue;
// 累计参与用书
@NameInMap("accumulative_users")
public Long accumulativeUsers;
// 用户资产详情列表
@NameInMap("asset_detail_list")
public java.util.List<AssetDetail> assetDetailList;
// 用户当前累计收益
@NameInMap("current_accumulative_revenue")
public Revenue currentAccumulativeRevenue;
// 当前用户收益
@NameInMap("current_revenue")
public Revenue currentRevenue;
public static QueryTppAllinfoResponse build(java.util.Map<String, ?> map) throws Exception {
QueryTppAllinfoResponse self = new QueryTppAllinfoResponse();
return TeaModel.build(map, self);
}
public QueryTppAllinfoResponse setReqMsgId(String reqMsgId) {
this.reqMsgId = reqMsgId;
return this;
}
public String getReqMsgId() {
return this.reqMsgId;
}
public QueryTppAllinfoResponse setResultCode(String resultCode) {
this.resultCode = resultCode;
return this;
}
public String getResultCode() {
return this.resultCode;
}
public QueryTppAllinfoResponse setResultMsg(String resultMsg) {
this.resultMsg = resultMsg;
return this;
}
public String getResultMsg() {
return this.resultMsg;
}
public QueryTppAllinfoResponse setAccumulativeRevenue(Revenue accumulativeRevenue) {
this.accumulativeRevenue = accumulativeRevenue;
return this;
}
public Revenue getAccumulativeRevenue() {
return this.accumulativeRevenue;
}
public QueryTppAllinfoResponse setAccumulativeUsers(Long accumulativeUsers) {
this.accumulativeUsers = accumulativeUsers;
return this;
}
public Long getAccumulativeUsers() {
return this.accumulativeUsers;
}
public QueryTppAllinfoResponse setAssetDetailList(java.util.List<AssetDetail> assetDetailList) {
this.assetDetailList = assetDetailList;
return this;
}
public java.util.List<AssetDetail> getAssetDetailList() {
return this.assetDetailList;
}
public QueryTppAllinfoResponse setCurrentAccumulativeRevenue(Revenue currentAccumulativeRevenue) {
this.currentAccumulativeRevenue = currentAccumulativeRevenue;
return this;
}
public Revenue getCurrentAccumulativeRevenue() {
return this.currentAccumulativeRevenue;
}
public QueryTppAllinfoResponse setCurrentRevenue(Revenue currentRevenue) {
this.currentRevenue = currentRevenue;
return this;
}
public Revenue getCurrentRevenue() {
return this.currentRevenue;
}
}
|
3e083a0f1e95a1d87fc7af3a0045b2948b773091
| 8,960 |
java
|
Java
|
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/apollographql/apollo/internal/cache/normalized/NoOpApolloStore.java
|
Andreas237/AndroidPolicyAutomation
|
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
|
[
"MIT"
] | 3 |
2019-05-01T09:22:08.000Z
|
2019-07-06T22:21:59.000Z
|
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/apollographql/apollo/internal/cache/normalized/NoOpApolloStore.java
|
Andreas237/AndroidPolicyAutomation
|
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
|
[
"MIT"
] | null | null | null |
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/apollographql/apollo/internal/cache/normalized/NoOpApolloStore.java
|
Andreas237/AndroidPolicyAutomation
|
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
|
[
"MIT"
] | 1 |
2020-11-26T12:22:02.000Z
|
2020-11-26T12:22:02.000Z
| 38.956522 | 161 | 0.692634 | 3,480 |
// 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.apollographql.apollo.internal.cache.normalized;
import com.apollographql.apollo.api.*;
import com.apollographql.apollo.cache.CacheHeaders;
import com.apollographql.apollo.cache.normalized.*;
import java.util.*;
// Referenced classes of package com.apollographql.apollo.internal.cache.normalized:
// ReadableStore, WriteableStore, ResponseNormalizer, Transaction
public final class NoOpApolloStore
implements ApolloStore, ReadableStore, WriteableStore
{
public NoOpApolloStore()
{
// 0 0:aload_0
// 1 1:invokespecial #14 <Method void Object()>
// 2 4:return
}
public CacheKeyResolver cacheKeyResolver()
{
return null;
// 0 0:aconst_null
// 1 1:areturn
}
public ResponseNormalizer cacheResponseNormalizer()
{
return ResponseNormalizer.NO_OP_NORMALIZER;
// 0 0:getstatic #25 <Field ResponseNormalizer ResponseNormalizer.NO_OP_NORMALIZER>
// 1 3:areturn
}
public ApolloStoreOperation clearAll()
{
return ApolloStoreOperation.emptyOperation(((Object) (Boolean.FALSE)));
// 0 0:getstatic #36 <Field Boolean Boolean.FALSE>
// 1 3:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 6:areturn
}
public Set merge(Record record, CacheHeaders cacheheaders)
{
return Collections.emptySet();
// 0 0:invokestatic #52 <Method Set Collections.emptySet()>
// 1 3:areturn
}
public Set merge(Collection collection, CacheHeaders cacheheaders)
{
return Collections.emptySet();
// 0 0:invokestatic #52 <Method Set Collections.emptySet()>
// 1 3:areturn
}
public ResponseNormalizer networkResponseNormalizer()
{
return ResponseNormalizer.NO_OP_NORMALIZER;
// 0 0:getstatic #25 <Field ResponseNormalizer ResponseNormalizer.NO_OP_NORMALIZER>
// 1 3:areturn
}
public NormalizedCache normalizedCache()
{
return null;
// 0 0:aconst_null
// 1 1:areturn
}
public void publish(Set set)
{
// 0 0:return
}
public ApolloStoreOperation read(Operation operation)
{
return ApolloStoreOperation.emptyOperation(((Object) (null)));
// 0 0:aconst_null
// 1 1:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 4:areturn
}
public ApolloStoreOperation read(Operation operation, ResponseFieldMapper responsefieldmapper, ResponseNormalizer responsenormalizer, CacheHeaders cacheheaders)
{
return ApolloStoreOperation.emptyOperation(((Object) (Response.builder(operation).build())));
// 0 0:aload_1
// 1 1:invokestatic #73 <Method com.apollographql.apollo.api.Response$Builder Response.builder(Operation)>
// 2 4:invokevirtual #79 <Method Response com.apollographql.apollo.api.Response$Builder.build()>
// 3 7:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 4 10:areturn
}
public ApolloStoreOperation read(ResponseFieldMapper responsefieldmapper, CacheKey cachekey, com.apollographql.apollo.api.Operation.Variables variables)
{
return ApolloStoreOperation.emptyOperation(((Object) (null)));
// 0 0:aconst_null
// 1 1:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 4:areturn
}
public Record read(String s, CacheHeaders cacheheaders)
{
return null;
// 0 0:aconst_null
// 1 1:areturn
}
public Collection read(Collection collection, CacheHeaders cacheheaders)
{
return ((Collection) (Collections.emptySet()));
// 0 0:invokestatic #52 <Method Set Collections.emptySet()>
// 1 3:areturn
}
public Object readTransaction(Transaction transaction)
{
return transaction.execute(((Object) (this)));
// 0 0:aload_1
// 1 1:aload_0
// 2 2:invokeinterface #94 <Method Object Transaction.execute(Object)>
// 3 7:areturn
}
public ApolloStoreOperation remove(CacheKey cachekey)
{
return ApolloStoreOperation.emptyOperation(((Object) (Boolean.FALSE)));
// 0 0:getstatic #36 <Field Boolean Boolean.FALSE>
// 1 3:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 6:areturn
}
public ApolloStoreOperation remove(List list)
{
return ApolloStoreOperation.emptyOperation(((Object) (Integer.valueOf(0))));
// 0 0:iconst_0
// 1 1:invokestatic #105 <Method Integer Integer.valueOf(int)>
// 2 4:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 3 7:areturn
}
public ApolloStoreOperation rollbackOptimisticUpdates(UUID uuid)
{
return ApolloStoreOperation.emptyOperation(((Object) (Collections.emptySet())));
// 0 0:invokestatic #52 <Method Set Collections.emptySet()>
// 1 3:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 6:areturn
}
public ApolloStoreOperation rollbackOptimisticUpdatesAndPublish(UUID uuid)
{
return ApolloStoreOperation.emptyOperation(((Object) (Boolean.FALSE)));
// 0 0:getstatic #36 <Field Boolean Boolean.FALSE>
// 1 3:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 6:areturn
}
public void subscribe(com.apollographql.apollo.cache.normalized.ApolloStore.RecordChangeSubscriber recordchangesubscriber)
{
// 0 0:return
}
public void unsubscribe(com.apollographql.apollo.cache.normalized.ApolloStore.RecordChangeSubscriber recordchangesubscriber)
{
// 0 0:return
}
public ApolloStoreOperation write(GraphqlFragment graphqlfragment, CacheKey cachekey, com.apollographql.apollo.api.Operation.Variables variables)
{
return ApolloStoreOperation.emptyOperation(((Object) (Collections.emptySet())));
// 0 0:invokestatic #52 <Method Set Collections.emptySet()>
// 1 3:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 6:areturn
}
public ApolloStoreOperation write(Operation operation, com.apollographql.apollo.api.Operation.Data data)
{
return ApolloStoreOperation.emptyOperation(((Object) (Collections.emptySet())));
// 0 0:invokestatic #52 <Method Set Collections.emptySet()>
// 1 3:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 6:areturn
}
public ApolloStoreOperation writeAndPublish(GraphqlFragment graphqlfragment, CacheKey cachekey, com.apollographql.apollo.api.Operation.Variables variables)
{
return ApolloStoreOperation.emptyOperation(((Object) (Boolean.FALSE)));
// 0 0:getstatic #36 <Field Boolean Boolean.FALSE>
// 1 3:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 6:areturn
}
public ApolloStoreOperation writeAndPublish(Operation operation, com.apollographql.apollo.api.Operation.Data data)
{
return ApolloStoreOperation.emptyOperation(((Object) (Boolean.FALSE)));
// 0 0:getstatic #36 <Field Boolean Boolean.FALSE>
// 1 3:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 6:areturn
}
public ApolloStoreOperation writeOptimisticUpdates(Operation operation, com.apollographql.apollo.api.Operation.Data data, UUID uuid)
{
return ApolloStoreOperation.emptyOperation(((Object) (Collections.emptySet())));
// 0 0:invokestatic #52 <Method Set Collections.emptySet()>
// 1 3:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 6:areturn
}
public ApolloStoreOperation writeOptimisticUpdatesAndPublish(Operation operation, com.apollographql.apollo.api.Operation.Data data, UUID uuid)
{
return ApolloStoreOperation.emptyOperation(((Object) (Boolean.FALSE)));
// 0 0:getstatic #36 <Field Boolean Boolean.FALSE>
// 1 3:invokestatic #42 <Method ApolloStoreOperation ApolloStoreOperation.emptyOperation(Object)>
// 2 6:areturn
}
public Object writeTransaction(Transaction transaction)
{
return transaction.execute(((Object) (this)));
// 0 0:aload_1
// 1 1:aload_0
// 2 2:invokeinterface #94 <Method Object Transaction.execute(Object)>
// 3 7:areturn
}
}
|
3e083a71236db0596721a506d89759127cb07129
| 1,107 |
java
|
Java
|
src/org/mindinformatics/gwt/domeo/model/MAnnotationCitationReference.java
|
rkboyce/DomeoClient
|
f247733cc9a67c34d0d983defcec74124c3b0dc5
|
[
"Apache-2.0"
] | null | null | null |
src/org/mindinformatics/gwt/domeo/model/MAnnotationCitationReference.java
|
rkboyce/DomeoClient
|
f247733cc9a67c34d0d983defcec74124c3b0dc5
|
[
"Apache-2.0"
] | 19 |
2015-03-10T15:36:41.000Z
|
2016-01-14T17:46:27.000Z
|
src/org/mindinformatics/gwt/domeo/model/MAnnotationCitationReference.java
|
rkboyce/DomeoClient
|
f247733cc9a67c34d0d983defcec74124c3b0dc5
|
[
"Apache-2.0"
] | null | null | null | 27.875 | 72 | 0.799103 | 3,481 |
package org.mindinformatics.gwt.domeo.model;
import java.util.ArrayList;
import java.util.List;
import org.mindinformatics.gwt.domeo.model.selectors.MSelector;
/**
* @author Paolo Ciccarese <[email protected]>
*/
@SuppressWarnings("serial")
public class MAnnotationCitationReference extends MAnnotationReference {
private Integer referenceIndex;
private List<MSelector> citationSelectors = new ArrayList<MSelector>();
private MSelector referenceSelector;
public Integer getReferenceIndex() {
return referenceIndex;
}
public void setReferenceIndex(Integer referenceIndex) {
this.referenceIndex = referenceIndex;
}
public List<MSelector> getCitationSelectors() {
return citationSelectors;
}
public void addCitation(MSelector selector) {
citationSelectors.add(selector);
}
public void setCitationSelectors(List<MSelector> citationSelectors) {
this.citationSelectors = citationSelectors;
}
public MSelector getReferenceSelector() {
return referenceSelector;
}
public void setReferenceSelector(MSelector referenceSelector) {
this.referenceSelector = referenceSelector;
}
}
|
3e083adf2e8c5d2a2c617c41720599ecf1dd49d4
| 1,589 |
java
|
Java
|
src/test/java/com/rabbit/validationsamples/integrations/reservations/ReservationServiceReturnIntegrationTest.java
|
bygui86/spring-validation
|
91165ad3b6b88e899028b9db7d7ecf71258f83bf
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/rabbit/validationsamples/integrations/reservations/ReservationServiceReturnIntegrationTest.java
|
bygui86/spring-validation
|
91165ad3b6b88e899028b9db7d7ecf71258f83bf
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/rabbit/validationsamples/integrations/reservations/ReservationServiceReturnIntegrationTest.java
|
bygui86/spring-validation
|
91165ad3b6b88e899028b9db7d7ecf71258f83bf
|
[
"Apache-2.0"
] | 1 |
2022-02-08T01:26:27.000Z
|
2022-02-08T01:26:27.000Z
| 25.629032 | 71 | 0.826935 | 3,482 |
package com.rabbit.validationsamples.integrations.reservations;
import com.rabbit.validationsamples.configs.TestingConfig;
import com.rabbit.validationsamples.services.ReservationService;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import javax.validation.ConstraintViolationException;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {TestingConfig.class}
)
public class ReservationServiceReturnIntegrationTest {
@Resource(name = "reservationService")
ReservationService reservationService;
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void validateReturn_singleParams_ok() {
reservationService.getAllPersons_ok();
}
@Test
public void validateReturn_singleParams_error() {
exception.expect(ConstraintViolationException.class);
reservationService.getAllPersons_error();
}
@Test
public void validateReturn_crossParams_ok() {
reservationService.getReservationById_ok("001");
}
@Test
public void validateReturn_crossParams_nullError() {
exception.expect(ConstraintViolationException.class);
reservationService.getReservationById_error_null("001");
}
@Test
public void validateReturn_crossParams_wrongError() {
exception.expect(ConstraintViolationException.class);
reservationService.getReservationById_error_wrong("001");
}
}
|
3e083b0c24b29d809ea94daa26aa99ed04f8524e
| 7,305 |
java
|
Java
|
java-client/src/main/java/co/elastic/clients/elasticsearch/watcher/WatcherStatsResponse.java
|
ksurendra/elasticsearch-java
|
33cdf3a9916af93004aa25e8c6f7e2ab13db8ad9
|
[
"Apache-2.0"
] | null | null | null |
java-client/src/main/java/co/elastic/clients/elasticsearch/watcher/WatcherStatsResponse.java
|
ksurendra/elasticsearch-java
|
33cdf3a9916af93004aa25e8c6f7e2ab13db8ad9
|
[
"Apache-2.0"
] | null | null | null |
java-client/src/main/java/co/elastic/clients/elasticsearch/watcher/WatcherStatsResponse.java
|
ksurendra/elasticsearch-java
|
33cdf3a9916af93004aa25e8c6f7e2ab13db8ad9
|
[
"Apache-2.0"
] | null | null | null | 29.103586 | 115 | 0.695962 | 3,483 |
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//----------------------------------------------------
// THIS CODE IS GENERATED. MANUAL EDITS WILL BE LOST.
//----------------------------------------------------
package co.elastic.clients.elasticsearch.watcher;
import co.elastic.clients.elasticsearch._types.NodeStatistics;
import co.elastic.clients.elasticsearch.watcher.stats.WatcherNodeStats;
import co.elastic.clients.json.JsonpDeserializable;
import co.elastic.clients.json.JsonpDeserializer;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.JsonpSerializable;
import co.elastic.clients.json.ObjectBuilderDeserializer;
import co.elastic.clients.json.ObjectDeserializer;
import co.elastic.clients.util.ApiTypeHelper;
import co.elastic.clients.util.ObjectBuilder;
import co.elastic.clients.util.WithJsonObjectBuilderBase;
import jakarta.json.stream.JsonGenerator;
import java.lang.Boolean;
import java.lang.String;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import javax.annotation.Nullable;
// typedef: watcher.stats.Response
/**
*
* @see <a href="../doc-files/api-spec.html#watcher.stats.Response">API
* specification</a>
*/
@JsonpDeserializable
public class WatcherStatsResponse implements JsonpSerializable {
private final NodeStatistics nodeStats;
private final String clusterName;
private final boolean manuallyStopped;
private final List<WatcherNodeStats> stats;
// ---------------------------------------------------------------------------------------------
private WatcherStatsResponse(Builder builder) {
this.nodeStats = ApiTypeHelper.requireNonNull(builder.nodeStats, this, "nodeStats");
this.clusterName = ApiTypeHelper.requireNonNull(builder.clusterName, this, "clusterName");
this.manuallyStopped = ApiTypeHelper.requireNonNull(builder.manuallyStopped, this, "manuallyStopped");
this.stats = ApiTypeHelper.unmodifiableRequired(builder.stats, this, "stats");
}
public static WatcherStatsResponse of(Function<Builder, ObjectBuilder<WatcherStatsResponse>> fn) {
return fn.apply(new Builder()).build();
}
/**
* Required - API name: {@code _nodes}
*/
public final NodeStatistics nodeStats() {
return this.nodeStats;
}
/**
* Required - API name: {@code cluster_name}
*/
public final String clusterName() {
return this.clusterName;
}
/**
* Required - API name: {@code manually_stopped}
*/
public final boolean manuallyStopped() {
return this.manuallyStopped;
}
/**
* Required - API name: {@code stats}
*/
public final List<WatcherNodeStats> stats() {
return this.stats;
}
/**
* Serialize this object to JSON.
*/
public void serialize(JsonGenerator generator, JsonpMapper mapper) {
generator.writeStartObject();
serializeInternal(generator, mapper);
generator.writeEnd();
}
protected void serializeInternal(JsonGenerator generator, JsonpMapper mapper) {
generator.writeKey("_nodes");
this.nodeStats.serialize(generator, mapper);
generator.writeKey("cluster_name");
generator.write(this.clusterName);
generator.writeKey("manually_stopped");
generator.write(this.manuallyStopped);
if (ApiTypeHelper.isDefined(this.stats)) {
generator.writeKey("stats");
generator.writeStartArray();
for (WatcherNodeStats item0 : this.stats) {
item0.serialize(generator, mapper);
}
generator.writeEnd();
}
}
// ---------------------------------------------------------------------------------------------
/**
* Builder for {@link WatcherStatsResponse}.
*/
public static class Builder extends WithJsonObjectBuilderBase<Builder>
implements
ObjectBuilder<WatcherStatsResponse> {
private NodeStatistics nodeStats;
private String clusterName;
private Boolean manuallyStopped;
private List<WatcherNodeStats> stats;
/**
* Required - API name: {@code _nodes}
*/
public final Builder nodeStats(NodeStatistics value) {
this.nodeStats = value;
return this;
}
/**
* Required - API name: {@code _nodes}
*/
public final Builder nodeStats(Function<NodeStatistics.Builder, ObjectBuilder<NodeStatistics>> fn) {
return this.nodeStats(fn.apply(new NodeStatistics.Builder()).build());
}
/**
* Required - API name: {@code cluster_name}
*/
public final Builder clusterName(String value) {
this.clusterName = value;
return this;
}
/**
* Required - API name: {@code manually_stopped}
*/
public final Builder manuallyStopped(boolean value) {
this.manuallyStopped = value;
return this;
}
/**
* Required - API name: {@code stats}
* <p>
* Adds all elements of <code>list</code> to <code>stats</code>.
*/
public final Builder stats(List<WatcherNodeStats> list) {
this.stats = _listAddAll(this.stats, list);
return this;
}
/**
* Required - API name: {@code stats}
* <p>
* Adds one or more values to <code>stats</code>.
*/
public final Builder stats(WatcherNodeStats value, WatcherNodeStats... values) {
this.stats = _listAdd(this.stats, value, values);
return this;
}
/**
* Required - API name: {@code stats}
* <p>
* Adds a value to <code>stats</code> using a builder lambda.
*/
public final Builder stats(Function<WatcherNodeStats.Builder, ObjectBuilder<WatcherNodeStats>> fn) {
return stats(fn.apply(new WatcherNodeStats.Builder()).build());
}
@Override
protected Builder self() {
return this;
}
/**
* Builds a {@link WatcherStatsResponse}.
*
* @throws NullPointerException
* if some of the required fields are null.
*/
public WatcherStatsResponse build() {
_checkSingleUse();
return new WatcherStatsResponse(this);
}
}
// ---------------------------------------------------------------------------------------------
/**
* Json deserializer for {@link WatcherStatsResponse}
*/
public static final JsonpDeserializer<WatcherStatsResponse> _DESERIALIZER = ObjectBuilderDeserializer
.lazy(Builder::new, WatcherStatsResponse::setupWatcherStatsResponseDeserializer);
protected static void setupWatcherStatsResponseDeserializer(ObjectDeserializer<WatcherStatsResponse.Builder> op) {
op.add(Builder::nodeStats, NodeStatistics._DESERIALIZER, "_nodes");
op.add(Builder::clusterName, JsonpDeserializer.stringDeserializer(), "cluster_name");
op.add(Builder::manuallyStopped, JsonpDeserializer.booleanDeserializer(), "manually_stopped");
op.add(Builder::stats, JsonpDeserializer.arrayDeserializer(WatcherNodeStats._DESERIALIZER), "stats");
}
}
|
3e083b117bc1e4c2aab329025df819f91516ec95
| 7,510 |
java
|
Java
|
src/main/java/org/osgl/mvc/result/Gone.java
|
osglworks/java-mvc
|
c661c96ba187986cc5dcd0a9482bb542dc4d7994
|
[
"Apache-2.0"
] | 4 |
2017-04-11T02:42:50.000Z
|
2018-12-21T10:03:36.000Z
|
src/main/java/org/osgl/mvc/result/Gone.java
|
osglworks/java-mvc
|
c661c96ba187986cc5dcd0a9482bb542dc4d7994
|
[
"Apache-2.0"
] | 41 |
2017-03-16T20:03:37.000Z
|
2021-03-20T21:43:00.000Z
|
src/main/java/org/osgl/mvc/result/Gone.java
|
greenlaw110/java-mvc
|
c661c96ba187986cc5dcd0a9482bb542dc4d7994
|
[
"Apache-2.0"
] | 3 |
2017-01-13T06:39:21.000Z
|
2018-12-21T10:03:39.000Z
| 32.37069 | 97 | 0.632889 | 3,484 |
package org.osgl.mvc.result;
/*-
* #%L
* OSGL MVC
* %%
* Copyright (C) 2014 - 2017 OSGL (Open Source General Library)
* %%
* 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.
* #L%
*/
import static org.osgl.http.H.Status.GONE;
/**
* Indicates that the resource requested is no longer available and will not be available again.
* This should be used when a resource has been intentionally removed and the resource should be
* purged. Upon receiving a 410 status code, the client should not request the resource in the
* future. Clients such as search engines should remove the resource from their indices. Most use
* cases do not require clients and search engines to purge the resource, and a "404 Not Found"
* may be used instead.
*/
public class Gone extends ErrorResult {
private static final Gone _INSTANCE = new Gone() {
@Override
public String getMessage() {
return payload().message;
}
@Override
public Integer errorCode() {
return payload().errorCode;
}
@Override
public long timestamp() {
return payload().timestamp;
}
};
public Gone() {
super(GONE);
}
public Gone(String message, Object... args) {
super(GONE, message, args);
}
public Gone(Throwable cause, String message, Object... args) {
super(GONE, cause, message, args);
}
public Gone(Throwable cause) {
super(GONE, cause);
}
public Gone(int errorCode) {
super(GONE, errorCode);
}
public Gone(int errorCode, String message, Object... args) {
super(GONE, errorCode, message, args);
}
public Gone(int errorCode, Throwable cause, String message, Object... args) {
super(GONE, errorCode, cause, message, args);
}
public Gone(int errorCode, Throwable cause) {
super(GONE, errorCode, cause);
}
/**
* Returns a static Gone instance and set the {@link #payload} thread local
* with default message.
*
* When calling the instance on {@link #getMessage()} method, it will return whatever
* stored in the {@link #payload} thread local
*
* @return a static Gone instance as described above
*/
public static Gone get() {
if (_localizedErrorMsg()) {
return of(defaultMessage(GONE));
} else {
touchPayload();
return _INSTANCE;
}
}
/**
* Returns a static Gone instance and set the {@link #payload} thread local
* with message specified.
*
* When calling the instance on {@link #getMessage()} method, it will return whatever
* stored in the {@link #payload} thread local
*
* @param message the message
* @param args the message arguments
* @return a static Gone instance as described above
*/
public static Gone of(String message, Object... args) {
touchPayload().message(message, args);
return _INSTANCE;
}
/**
* Returns a static Gone instance and set the {@link #payload} thread local
* with cause specified.
*
* When calling the instance on {@link #getMessage()} method, it will return whatever
* stored in the {@link #payload} thread local
*
* @param cause the cause
* @return a static Gone instance as described above
*/
public static Gone of(Throwable cause) {
if (_localizedErrorMsg()) {
return of(cause, defaultMessage(GONE));
} else {
touchPayload().cause(cause);
return _INSTANCE;
}
}
/**
* Returns a static Gone instance and set the {@link #payload} thread local
* with cause and message specified.
*
* When calling the instance on {@link #getMessage()} method, it will return whatever
* stored in the {@link #payload} thread local
*
* @param cause the cause
* @param message the message
* @param args the message arguments
* @return a static Gone instance as described above
*/
public static Gone of(Throwable cause, String message, Object... args) {
touchPayload().message(message, args).cause(cause);
return _INSTANCE;
}
/**
* Returns a static Gone instance and set the {@link #payload} thread local
* with error code and default message.
*
* When calling the instance on {@link #getMessage()} method, it will return whatever
* stored in the {@link #payload} thread local
*
* @param errorCode the app defined error code
* @return a static Gone instance as described above
*/
public static Gone of(int errorCode) {
if (_localizedErrorMsg()) {
return of(errorCode, defaultMessage(GONE));
} else {
touchPayload().errorCode(errorCode);
return _INSTANCE;
}
}
/**
* Returns a static Gone instance and set the {@link #payload} thread local
* with error code and message specified.
*
* When calling the instance on {@link #getMessage()} method, it will return whatever
* stored in the {@link #payload} thread local
*
* @param errorCode the app defined error code
* @param message the message
* @param args the message arguments
* @return a static Gone instance as described above
*/
public static Gone of(int errorCode, String message, Object... args) {
touchPayload().errorCode(errorCode).message(message, args);
return _INSTANCE;
}
/**
* Returns a static Gone instance and set the {@link #payload} thread local
* with error code and cause specified
*
* When calling the instance on {@link #getMessage()} method, it will return whatever
* stored in the {@link #payload} thread local
*
* @param cause the cause
* @param errorCode the app defined error code
* @return a static Gone instance as described above
*/
public static Gone of(int errorCode, Throwable cause) {
if (_localizedErrorMsg()) {
return of(errorCode, cause, defaultMessage(GONE));
} else {
touchPayload().errorCode(errorCode).cause(cause);
return _INSTANCE;
}
}
/**
* Returns a static Gone instance and set the {@link #payload} thread local
* with error code, cause and message specified.
*
* When calling the instance on {@link #getMessage()} method, it will return whatever
* stored in the {@link #payload} thread local
*
* @param cause the cause
* @param errorCode the app defined error code
* @param message the message
* @param args the message arguments
* @return a static Gone instance as described above
*/
public static Gone of(int errorCode, Throwable cause, String message, Object... args) {
touchPayload().errorCode(errorCode).message(message, args).cause(cause);
return _INSTANCE;
}
}
|
3e083d0b0709f78e407907c11f3324760175bdcc
| 1,112 |
java
|
Java
|
com.vxml.browser/src/main/java/com/vxml/tag/ScriptTag.java
|
catchme1412/vxml-player
|
5f8cce20b7ad7404f926b4e86dc6f4bbf6c1a36a
|
[
"Apache-2.0"
] | 1 |
2018-05-06T19:14:10.000Z
|
2018-05-06T19:14:10.000Z
|
com.vxml.browser/src/main/java/com/vxml/tag/ScriptTag.java
|
catchme1412/vxml-player
|
5f8cce20b7ad7404f926b4e86dc6f4bbf6c1a36a
|
[
"Apache-2.0"
] | null | null | null |
com.vxml.browser/src/main/java/com/vxml/tag/ScriptTag.java
|
catchme1412/vxml-player
|
5f8cce20b7ad7404f926b4e86dc6f4bbf6c1a36a
|
[
"Apache-2.0"
] | null | null | null | 23.659574 | 79 | 0.59982 | 3,485 |
package com.vxml.tag;
import java.io.InputStream;
import java.net.URI;
import org.w3c.dom.Node;
import com.vxml.core.browser.VxmlBrowser;
import com.vxml.core.browser.VxmlExecutionContext;
import com.vxml.store.DocumentStore;
public class ScriptTag extends AbstractTag {
public ScriptTag(Node node) {
super(node);
}
@Override
public void startTag() {
VxmlExecutionContext.setTtsAllowed(false);
}
@Override
public void execute() {
String src = getAttribute("src");
if (src != null) {
URI uri = VxmlBrowser.getContext().getFullUri(src);
InputStream script;
try {
script = new DocumentStore().getInputStream(uri);
VxmlBrowser.getContext().executeScript(script);
} catch (Exception e) {
e.printStackTrace();
}
} else {
VxmlBrowser.getContext().executeScript(getNode().getTextContent());
}
}
@Override
public void endTag() {
VxmlExecutionContext.setTtsAllowed(true);
}
}
|
3e083d944667d8bcc224cef0aa3ca7558b14063c
| 4,586 |
java
|
Java
|
QCloudCosXmlSample/app/src/main/java/com/tencent/qcloud/cosxml/sample/ObjectSample/PutObjectSample.java
|
dktlu/QCloudCosXmlSample
|
518aa363eb412522ecf62566a912a223675deabe
|
[
"MIT"
] | 1 |
2019-12-11T08:36:58.000Z
|
2019-12-11T08:36:58.000Z
|
QCloudCosXmlSample/app/src/main/java/com/tencent/qcloud/cosxml/sample/ObjectSample/PutObjectSample.java
|
dktlu/QCloudCosXmlSample
|
518aa363eb412522ecf62566a912a223675deabe
|
[
"MIT"
] | null | null | null |
QCloudCosXmlSample/app/src/main/java/com/tencent/qcloud/cosxml/sample/ObjectSample/PutObjectSample.java
|
dktlu/QCloudCosXmlSample
|
518aa363eb412522ecf62566a912a223675deabe
|
[
"MIT"
] | null | null | null | 38.864407 | 147 | 0.647187 | 3,486 |
package com.tencent.qcloud.cosxml.sample.ObjectSample;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.model.object.PutObjectRequest;
import com.tencent.cos.xml.model.object.PutObjectResult;
import com.tencent.qcloud.cosxml.sample.ResultActivity;
import com.tencent.qcloud.cosxml.sample.ResultHelper;
import com.tencent.qcloud.cosxml.sample.common.QServiceCfg;
/**
* Created by bradyxiao on 2017/6/1.
* author bradyxiao
* <p>
* Put Object 接口请求可以将本地的文件(Object)上传至指定 Bucket 中。该操作需要请求者对 Bucket 有 WRITE 权限。
*/
public class PutObjectSample {
PutObjectRequest putObjectRequest;
QServiceCfg qServiceCfg;
public PutObjectSample(QServiceCfg qServiceCfg) {
this.qServiceCfg = qServiceCfg;
}
public ResultHelper start() {
ResultHelper resultHelper = new ResultHelper();
String bucket = qServiceCfg.getBucketForObjectAPITest();
String cosPath = qServiceCfg.getUploadCosPath();
String srcPath = qServiceCfg.getUploadFileUrl();
putObjectRequest = new PutObjectRequest(bucket,cosPath,
srcPath);
putObjectRequest.setProgressListener(new CosXmlProgressListener() {
@Override
public void onProgress(long progress, long max) {
float result = (float) (progress * 100.0 / max);
Log.w("XIAO", "progress =" + (long) result + "%");
}
});
putObjectRequest.setSign(600, null, null);
try {
final PutObjectResult putObjectResult =
qServiceCfg.cosXmlService.putObject(putObjectRequest);
Log.w("XIAO","success");
resultHelper.cosXmlResult = putObjectResult;
return resultHelper;
} catch (CosXmlClientException e) {
Log.w("XIAO","QCloudException =" + e.getMessage());
resultHelper.qCloudException = e;
return resultHelper;
} catch (CosXmlServiceException e) {
Log.w("XIAO","QCloudServiceException =" + e.toString());
resultHelper.qCloudServiceException = e;
return resultHelper;
}
}
/**
* 采用异步回调操作
*/
public void startAsync(final Activity activity) {
String bucket = qServiceCfg.getBucketForObjectAPITest();
String cosPath = qServiceCfg.getUploadCosPath();
String srcPath = qServiceCfg.getUploadFileUrl();
putObjectRequest = new PutObjectRequest(bucket,cosPath,
srcPath);
putObjectRequest.setProgressListener(new CosXmlProgressListener() {
@Override
public void onProgress(long progress, long max) {
float result = (float) (progress * 100.0 / max);
Log.w("XIAO", "progress =" + (long) result + "%");
}
});
putObjectRequest.setSign(600, null, null);
qServiceCfg.cosXmlService.putObjectAsync(putObjectRequest, new CosXmlResultListener() {
@Override
public void onSuccess(CosXmlRequest cosXmlRequest, CosXmlResult cosXmlResult) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(cosXmlResult.printResult());
Log.w("XIAO", "success = " + stringBuilder.toString());
show(activity, stringBuilder.toString());
}
@Override
public void onFail(CosXmlRequest cosXmlRequest, CosXmlClientException qcloudException, CosXmlServiceException qcloudServiceException) {
StringBuilder stringBuilder = new StringBuilder();
if(qcloudException != null){
stringBuilder.append(qcloudException.getMessage());
}else {
stringBuilder.append(qcloudServiceException.toString());
}
Log.w("XIAO", "failed = " + stringBuilder.toString());
show(activity, stringBuilder.toString());
}
});
}
private void show(Activity activity, String message) {
Intent intent = new Intent(activity, ResultActivity.class);
intent.putExtra("RESULT", message);
activity.startActivity(intent);
}
}
|
3e083dacbb8330199ec746fc7c1e8f66dc343e24
| 980 |
java
|
Java
|
src/main/java/aimproject/aim/model/Member.java
|
kiziri/Comprehensive_Project
|
034c529ba5c17c1e52cd36790c529382247d0032
|
[
"MIT"
] | null | null | null |
src/main/java/aimproject/aim/model/Member.java
|
kiziri/Comprehensive_Project
|
034c529ba5c17c1e52cd36790c529382247d0032
|
[
"MIT"
] | null | null | null |
src/main/java/aimproject/aim/model/Member.java
|
kiziri/Comprehensive_Project
|
034c529ba5c17c1e52cd36790c529382247d0032
|
[
"MIT"
] | null | null | null | 20.416667 | 64 | 0.658163 | 3,487 |
package aimproject.aim.model;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Getter @Setter
public class Member {
@Id
@Column(name = "member_id") // 회원 로그인 아이디
private String memberId; // 테이블 기본키
@Column(name = "member_pw")
private String memberPw;
@Column(name = "member_name")
private String name;
@Column(name = "member_nickname")
private String nickname;
@Column(name = "member_telnumber")
private String telNumber;
@Column(name = "member_address")
private String address;
@OneToMany(mappedBy = "member")
private List<AnalysisHistory> histories = new ArrayList<>();
@OneToMany(mappedBy = "member")
private List<Image> images = new ArrayList<>();
// 비즈니스 로직 //
/**
* 비밀번호 일치 확인인
*/
public boolean matchPassword(String memberPw) {
return this.memberPw.equals(memberPw);
}
}
|
3e083ded13f67ce371b0e17376325f6636fa28fd
| 398 |
java
|
Java
|
webapp/noteapp/src/main/java/com/csye6225/noteapp/model/UploadFileResponse.java
|
AkashBalani/AWS_CICD_Serverless
|
7eceed136a636d92bcef1be0be7244813df62806
|
[
"Apache-2.0"
] | null | null | null |
webapp/noteapp/src/main/java/com/csye6225/noteapp/model/UploadFileResponse.java
|
AkashBalani/AWS_CICD_Serverless
|
7eceed136a636d92bcef1be0be7244813df62806
|
[
"Apache-2.0"
] | null | null | null |
webapp/noteapp/src/main/java/com/csye6225/noteapp/model/UploadFileResponse.java
|
AkashBalani/AWS_CICD_Serverless
|
7eceed136a636d92bcef1be0be7244813df62806
|
[
"Apache-2.0"
] | 2 |
2020-02-24T05:49:36.000Z
|
2020-04-02T20:07:14.000Z
| 14.214286 | 51 | 0.670854 | 3,488 |
package com.csye6225.noteapp.model;
public class UploadFileResponse {
private String id;
private String url;
public UploadFileResponse(String id, String url) {
this.id = id;
this.url = url;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
3e083e0adc7ae01e58077e30c535d696599cb645
| 808 |
java
|
Java
|
main/src/main/java/io/github/nhwalker/jsonup/elements/JsonParser.java
|
nhwalker/json-up
|
d7de47857b3df52ad0bcdf05e9d9fda5e963cc69
|
[
"MIT"
] | null | null | null |
main/src/main/java/io/github/nhwalker/jsonup/elements/JsonParser.java
|
nhwalker/json-up
|
d7de47857b3df52ad0bcdf05e9d9fda5e963cc69
|
[
"MIT"
] | null | null | null |
main/src/main/java/io/github/nhwalker/jsonup/elements/JsonParser.java
|
nhwalker/json-up
|
d7de47857b3df52ad0bcdf05e9d9fda5e963cc69
|
[
"MIT"
] | null | null | null | 35.130435 | 114 | 0.813119 | 3,489 |
package io.github.nhwalker.jsonup.elements;
import java.io.IOException;
import io.github.nhwalker.jsonup.exceptions.JsonParseException;
public abstract class JsonParser<T extends JsonElement> {
public static JsonElement read(PeekingReader reader) throws IOException, JsonParseException {
return JsonParserContext.DEFAULT.elementParser().parse(JsonParserContext.DEFAULT, reader);
}
public static JsonElement read(JsonParserContext context, PeekingReader reader)
throws IOException, JsonParseException {
return context.elementParser().parse(context, reader);
}
public abstract boolean isNext(JsonParserContext context, PeekingReader reader) throws IOException;
public abstract T parse(JsonParserContext context, PeekingReader reader) throws IOException, JsonParseException;
}
|
3e083e1ffb243da92eacfbc1a479d7cd90773461
| 4,161 |
java
|
Java
|
apfloat-samples/src/main/java/org/apfloat/samples/PiParallelAWT.java
|
mtommila/apfloat
|
f157007e0b474297466b976eccc205926dd85c8f
|
[
"MIT"
] | 39 |
2017-04-27T19:40:46.000Z
|
2022-03-30T00:08:18.000Z
|
apfloat-samples/src/main/java/org/apfloat/samples/PiParallelAWT.java
|
mtommila/apfloat
|
f157007e0b474297466b976eccc205926dd85c8f
|
[
"MIT"
] | 18 |
2017-04-21T14:37:10.000Z
|
2021-06-14T16:54:39.000Z
|
apfloat-samples/src/main/java/org/apfloat/samples/PiParallelAWT.java
|
mtommila/apfloat
|
f157007e0b474297466b976eccc205926dd85c8f
|
[
"MIT"
] | 8 |
2017-05-12T02:52:48.000Z
|
2019-12-19T15:27:40.000Z
| 34.106557 | 124 | 0.65417 | 3,490 |
/*
* MIT License
*
* Copyright (c) 2002-2021 Mikko Tommila
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.apfloat.samples;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.Label;
import java.awt.TextField;
import org.apfloat.Apfloat;
import org.apfloat.ApfloatContext;
import org.apfloat.ApfloatRuntimeException;
/**
* Graphical AWT elements for calculating pi using multiple threads in parallel.
*
* @version 1.9.0
* @author Mikko Tommila
*/
public class PiParallelAWT
extends PiAWT
{
/**
* Construct a panel with graphical elements.
*
* @param statusIndicator Handler for showing error messages in the application.
*/
public PiParallelAWT(StatusIndicator statusIndicator)
{
super(statusIndicator);
}
@Override
protected void initThreads(Container container, GridBagConstraints constraints)
{
this.threadsLabel = new Label("Threads:");
container.add(this.threadsLabel, constraints);
this.threadsField = new TextField(ApfloatContext.getContext().getProperty(ApfloatContext.NUMBER_OF_PROCESSORS), 5);
constraints.gridwidth = GridBagConstraints.REMAINDER;
container.add(this.threadsField, constraints);
}
@Override
protected boolean isInputValid()
{
if (!super.isInputValid())
{
return false;
}
else
{
String threadsString = this.threadsField.getText();
try
{
int threads = Integer.parseInt(threadsString);
if (threads <= 0)
{
throw new NumberFormatException();
}
showStatus(null);
return true;
}
catch (NumberFormatException nfe)
{
showStatus("Invalid number of threads: " + threadsString);
this.threadsField.requestFocus();
return false;
}
}
}
@Override
protected Operation<Apfloat> getOperation(long precision, int radix)
throws ApfloatRuntimeException
{
ApfloatContext ctx = ApfloatContext.getContext();
int numberOfProcessors = Integer.parseInt(this.threadsField.getText());
ctx.setNumberOfProcessors(numberOfProcessors);
ctx.setExecutorService(ApfloatContext.getDefaultExecutorService());
Operation<Apfloat> operation = super.getOperation(precision, radix);
if (operation instanceof Pi.ChudnovskyPiCalculator)
{
operation = new PiParallel.ParallelChudnovskyPiCalculator(precision, radix);
}
else if (operation instanceof Pi.RamanujanPiCalculator)
{
operation = new PiParallel.ParallelRamanujanPiCalculator(precision, radix);
}
return operation;
}
private static final long serialVersionUID = 1L;
private Label threadsLabel;
private TextField threadsField;
}
|
3e083f08db591ed9747b61fd6814d93740ac67b0
| 1,617 |
java
|
Java
|
src/main/java/com/bremp/autobuyer/logic/old/BuyerSnapshot.java
|
bremp/autobuyer
|
d7794e2ec0429c2d0ee77479a35ef702a436a01d
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/bremp/autobuyer/logic/old/BuyerSnapshot.java
|
bremp/autobuyer
|
d7794e2ec0429c2d0ee77479a35ef702a436a01d
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/bremp/autobuyer/logic/old/BuyerSnapshot.java
|
bremp/autobuyer
|
d7794e2ec0429c2d0ee77479a35ef702a436a01d
|
[
"Apache-2.0"
] | null | null | null | 26.508197 | 116 | 0.74026 | 3,491 |
package com.bremp.autobuyer.logic.old;
public class BuyerSnapshot {
private final String itemId;
private final int currentPrice;
private final int numberInStock;
private final int boughtSoFar;
private final BuyerState state;
public BuyerSnapshot(String itemId, int currentPrice, int numberInStock, int boughtSoFar,
BuyerState state) {
this.itemId = itemId;
this.currentPrice = currentPrice;
this.numberInStock = numberInStock;
this.boughtSoFar = boughtSoFar;
this.state = state;
}
public String getItemId() {
return itemId;
}
public int getCurrentPrice() {
return currentPrice;
}
public int getNumberInStock() {
return numberInStock;
}
public int getBoughtSoFar() {
return boughtSoFar;
}
public BuyerState getState() {
return state;
}
public static BuyerSnapshot joining(String itemId) {
return new BuyerSnapshot(itemId, 0, 0, 0, BuyerState.JOINING);
}
public BuyerSnapshot monitoring(int currentPrice, int numberInStock) {
return new BuyerSnapshot(itemId, currentPrice, numberInStock, boughtSoFar, BuyerState.MONITORING);
}
public BuyerSnapshot bought(int numberBought) {
return new BuyerSnapshot(itemId, currentPrice, numberInStock - numberBought, boughtSoFar + numberBought, state);
}
public BuyerSnapshot closed() {
return new BuyerSnapshot(itemId, currentPrice, numberInStock, boughtSoFar, BuyerState.CLOSED);
}
public BuyerSnapshot buying(int currentPrice, int numberInStock) {
return new BuyerSnapshot(itemId, currentPrice, numberInStock, boughtSoFar, BuyerState.BUYING);
}
}
|
3e083f4e20f2646e9ec1a3dbe994d3c903baa283
| 3,543 |
java
|
Java
|
workbenchfx-demo/src/main/java/com/dlsc/workbenchfx/modules/gantt/GanttView.java
|
fossabot/WorkbenchFX
|
44d5ab5d6ffcf4756ffd59e6a5efefe18d355391
|
[
"Apache-2.0"
] | 248 |
2019-07-24T10:02:09.000Z
|
2022-03-12T11:10:08.000Z
|
workbenchfx-demo/src/main/java/com/dlsc/workbenchfx/modules/gantt/GanttView.java
|
fossabot/WorkbenchFX
|
44d5ab5d6ffcf4756ffd59e6a5efefe18d355391
|
[
"Apache-2.0"
] | 517 |
2019-07-29T18:54:12.000Z
|
2022-01-06T13:58:13.000Z
|
workbenchfx-demo/src/main/java/com/dlsc/workbenchfx/modules/gantt/GanttView.java
|
fossabot/WorkbenchFX
|
44d5ab5d6ffcf4756ffd59e6a5efefe18d355391
|
[
"Apache-2.0"
] | 49 |
2019-08-05T00:24:23.000Z
|
2022-03-21T17:22:03.000Z
| 33.424528 | 77 | 0.717471 | 3,492 |
/*
* Copyright (C) 2017 Dirk Lemmermann Software & Consulting (dlsc.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.dlsc.workbenchfx.modules.gantt;
import com.flexganttfx.model.Layer;
import com.flexganttfx.model.Row;
import com.flexganttfx.model.activity.MutableActivityBase;
import com.flexganttfx.model.layout.GanttLayout;
import com.flexganttfx.view.GanttChart;
import com.flexganttfx.view.graphics.GraphicsBase;
import com.flexganttfx.view.graphics.renderer.ActivityBarRenderer;
import com.flexganttfx.view.timeline.Timeline;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import javafx.scene.layout.StackPane;
public class GanttView extends StackPane {
/*
* Plain data object storing dummy flight information.
*/
class FlightData {
String flightNo;
Instant departureTime = Instant.now();
Instant arrivalTime = Instant.now().plus(Duration.ofHours(6));
public FlightData(String flightNo, int day) {
this.flightNo = flightNo;
departureTime = departureTime.plus(Duration.ofDays(day));
arrivalTime = arrivalTime.plus(Duration.ofDays(day));
}
}
/*
* The activity representing the flight. This object will be rendered as a
* bar in the graphics view of the Gantt chart. The flight is mutable, so
* the user will be able to interact with it.
*/
class Flight extends MutableActivityBase<FlightData> {
public Flight(FlightData data) {
setUserObject(data);
setName(data.flightNo);
setStartTime(data.departureTime);
setEndTime(data.arrivalTime);
}
}
/*
* Each row represents an aircraft in this example. The activities shown on
* the row are of type Flight.
*/
class Aircraft extends Row<Aircraft, Aircraft, Flight> {
public Aircraft(String name) {
super(name);
}
}
public GanttView() {
// Create the Gantt chart
GanttChart<Aircraft> gantt = new GanttChart<Aircraft>(new Aircraft(
"ROOT"));
Layer layer = new Layer("Flights");
gantt.getLayers().add(layer);
Aircraft b747 = new Aircraft("B747");
b747.addActivity(layer, new Flight(new FlightData("flight1", 1)));
b747.addActivity(layer, new Flight(new FlightData("flight2", 2)));
b747.addActivity(layer, new Flight(new FlightData("flight3", 3)));
Aircraft a380 = new Aircraft("A380");
a380.addActivity(layer, new Flight(new FlightData("flight1", 1)));
a380.addActivity(layer, new Flight(new FlightData("flight2", 2)));
a380.addActivity(layer, new Flight(new FlightData("flight3", 3)));
gantt.getRoot().getChildren().setAll(b747, a380);
Timeline timeline = gantt.getTimeline();
timeline.showTemporalUnit(ChronoUnit.HOURS, 10);
GraphicsBase<Aircraft> graphics = gantt.getGraphics();
graphics.setActivityRenderer(Flight.class, GanttLayout.class,
new ActivityBarRenderer<>(graphics, "Flight Renderer"));
graphics.showEarliestActivities();
getChildren().addAll(gantt);
}
}
|
3e08414d104f67de7b6f50caeafe43ddbc793fd4
| 850 |
java
|
Java
|
src/main/java/com/ruoyi/project/content/TemplateTypeEnum.java
|
GuXW/LeBang
|
9115d345831b22e30ac7893bf6c9be6682454da0
|
[
"MIT"
] | null | null | null |
src/main/java/com/ruoyi/project/content/TemplateTypeEnum.java
|
GuXW/LeBang
|
9115d345831b22e30ac7893bf6c9be6682454da0
|
[
"MIT"
] | 2 |
2021-04-22T16:58:56.000Z
|
2021-09-20T20:53:15.000Z
|
src/main/java/com/ruoyi/project/content/TemplateTypeEnum.java
|
GuXW/LeBang
|
9115d345831b22e30ac7893bf6c9be6682454da0
|
[
"MIT"
] | null | null | null | 19.318182 | 62 | 0.556471 | 3,493 |
package com.ruoyi.project.content;
public enum TemplateTypeEnum {
msg_1(1,"消息模板1");
private Integer value;
private String text;
TemplateTypeEnum(Integer value, String text) {
this.value = value;
this.text = text;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public static TemplateTypeEnum findByValue(Integer value){
if (null==value){
return null;
}
for (TemplateTypeEnum e : TemplateTypeEnum.values()){
if (value.intValue()==e.getValue().intValue()){
return e;
}
}
return null;
}
}
|
3e0842b5f66fe9f1fa395095b47f75c12eda9b60
| 860 |
java
|
Java
|
platform-hr/src/main/java/org/hzero/plugin/platform/hr/domain/repository/HrSyncRepository.java
|
mm20140616/hzero-plugin-parent
|
960b308e03396934bf48fbc178ba31ef1718a2e9
|
[
"Apache-2.0"
] | null | null | null |
platform-hr/src/main/java/org/hzero/plugin/platform/hr/domain/repository/HrSyncRepository.java
|
mm20140616/hzero-plugin-parent
|
960b308e03396934bf48fbc178ba31ef1718a2e9
|
[
"Apache-2.0"
] | null | null | null |
platform-hr/src/main/java/org/hzero/plugin/platform/hr/domain/repository/HrSyncRepository.java
|
mm20140616/hzero-plugin-parent
|
960b308e03396934bf48fbc178ba31ef1718a2e9
|
[
"Apache-2.0"
] | 12 |
2020-09-23T07:54:24.000Z
|
2021-11-23T13:53:41.000Z
| 24.138889 | 125 | 0.685846 | 3,494 |
package org.hzero.plugin.platform.hr.domain.repository;
import org.hzero.mybatis.base.BaseRepository;
import org.hzero.plugin.platform.hr.domain.entity.HrSync;
import io.choerodon.core.domain.Page;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
/**
* hr基础数据同步外部系统资源库
*
* @author [email protected] 2019-10-14 21:20:14
*/
public interface HrSyncRepository extends BaseRepository<HrSync> {
/**
* 分页查询列表
* @param pageRequest 分页属性
* @param tenantId 租户ID
* @param authType 编码
* @param syncTypeCode 名称
* @param enabledFlag 启用
* @return 查询结果
*/
Page<HrSync> listHrSync(PageRequest pageRequest, Long tenantId,String syncTypeCode,String authType, Integer enabledFlag);
/**
* 查询详情
*
* @param syncId 主键
* @return 查询结果
*/
HrSync getHrSyncById(Long syncId);
}
|
3e0842e7deee06a6bd385f8b9d1f75f08450156f
| 294 |
java
|
Java
|
name.martingeisse.osm/src/main/java/name/martingeisse/osm/data/OsmRelationMember.java
|
MartinGeisse/public
|
57b905485322222447187ae78a5a56bf3ce67900
|
[
"MIT"
] | 1 |
2015-06-16T13:18:45.000Z
|
2015-06-16T13:18:45.000Z
|
name.martingeisse.osm/src/main/java/name/martingeisse/osm/data/OsmRelationMember.java
|
MartinGeisse/public
|
57b905485322222447187ae78a5a56bf3ce67900
|
[
"MIT"
] | 3 |
2022-03-08T21:11:04.000Z
|
2022-03-08T21:11:15.000Z
|
name.martingeisse.osm/src/main/java/name/martingeisse/osm/data/OsmRelationMember.java
|
MartinGeisse/public
|
57b905485322222447187ae78a5a56bf3ce67900
|
[
"MIT"
] | null | null | null | 19.6 | 67 | 0.714286 | 3,495 |
/**
* Copyright (c) 2013 Martin Geisse
*
* This file is distributed under the terms of the MIT license.
*/
package name.martingeisse.osm.data;
/**
* This interface is implemented by all objects that can be members
* of an {@link OsmRelation}.
*/
public interface OsmRelationMember {
}
|
3e084300de0eec5f86d896fcbeb193cb3483ad7a
| 7,744 |
java
|
Java
|
malcompiler-lib/src/main/java/org/mal_lang/compiler/lib/securicad/DefenseGenerator.java
|
mal-lang/malcompiler
|
8ac7f6a823dac2fadf0bfb0aa310efef14193028
|
[
"Apache-2.0"
] | 6 |
2019-11-22T17:18:15.000Z
|
2022-01-31T13:25:30.000Z
|
malcompiler-lib/src/main/java/org/mal_lang/compiler/lib/securicad/DefenseGenerator.java
|
mal-lang/malcompiler
|
8ac7f6a823dac2fadf0bfb0aa310efef14193028
|
[
"Apache-2.0"
] | 22 |
2019-09-13T07:03:03.000Z
|
2021-04-29T12:24:43.000Z
|
malcompiler-lib/src/main/java/org/mal_lang/compiler/lib/securicad/DefenseGenerator.java
|
mal-lang/malcompiler
|
8ac7f6a823dac2fadf0bfb0aa310efef14193028
|
[
"Apache-2.0"
] | 11 |
2019-10-04T07:19:07.000Z
|
2021-06-04T02:21:37.000Z
| 41.859459 | 100 | 0.715263 | 3,496 |
/*
* Copyright 2019 Foreseeti AB
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mal_lang.compiler.lib.securicad;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import javax.lang.model.element.Modifier;
import org.mal_lang.compiler.lib.JavaGenerator;
import org.mal_lang.compiler.lib.Lang.Asset;
import org.mal_lang.compiler.lib.Lang.AttackStep;
import org.mal_lang.compiler.lib.Lang.AttackStepType;
import org.mal_lang.compiler.lib.Lang.StepExpr;
import org.mal_lang.compiler.lib.Lang.TTCFunc;
import org.mal_lang.compiler.lib.MalLogger;
public class DefenseGenerator extends JavaGenerator {
private final ExpressionGenerator exprGen;
protected DefenseGenerator(MalLogger LOGGER, String pkg) {
super(LOGGER, pkg);
this.exprGen = new ExpressionGenerator(LOGGER, pkg);
}
private static String getDescription(AttackStep attackStep) {
String userInfo = attackStep.getMeta().get("user");
if (userInfo != null) {
return userInfo;
}
if (!attackStep.hasParent()) {
return null;
}
return getDescription(
attackStep.getAsset().getSuperAsset().getAttackStep(attackStep.getName()));
}
protected void generate(TypeSpec.Builder parentBuilder, Asset asset, AttackStep attackStep) {
ClassName type = ClassName.get(this.pkg, asset.getName(), ucFirst(attackStep.getName()));
TypeSpec.Builder builder = TypeSpec.classBuilder(type);
ClassName typeName = ClassName.get("com.foreseeti.corelib.FAnnotations", "TypeName");
ClassName typeDescription =
ClassName.get("com.foreseeti.corelib.FAnnotations", "TypeDescription");
AnnotationSpec.Builder asBuilder = AnnotationSpec.builder(typeName);
asBuilder.addMember("name", "$S", ucFirst(attackStep.getName()));
builder.addAnnotation(asBuilder.build());
var description = getDescription(attackStep);
asBuilder = AnnotationSpec.builder(typeDescription);
asBuilder.addMember(
"text", "$S", description == null ? ucFirst(attackStep.getName()) : description);
builder.addAnnotation(asBuilder.build());
Generator.createMetaInfoAnnotations(builder, Generator.getMetaInfoMap(attackStep));
builder.addModifiers(Modifier.PUBLIC);
if (attackStep.hasParent()) {
AttackStep parent = attackStep.getAsset().getSuperAsset().getAttackStep(attackStep.getName());
Asset parentAsset = parent.getAsset();
type = ClassName.get(pkg, parentAsset.getName(), ucFirst(parent.getName()));
builder.superclass(type);
} else {
builder.superclass(ClassName.get(this.pkg, asset.getName(), "LocalDefense"));
}
// default constructor
MethodSpec.Builder constructor = MethodSpec.constructorBuilder();
constructor.addModifiers(Modifier.PUBLIC);
constructor.addParameter(boolean.class, "enabled");
constructor.addStatement("super(enabled)");
ClassName disable =
ClassName.get(this.pkg, asset.getName(), ucFirst(attackStep.getName()), "Disable");
constructor.addStatement("this.disable = new $T()", disable);
if (attackStep.hasTTC()) {
ClassName fmath = ClassName.get("com.foreseeti.corelib.math", "FMath");
// Analyzer guarantees this is a ttcfunc
TTCFunc func = (TTCFunc) attackStep.getTTC();
constructor.addStatement(
"setEvidenceDistribution($T.getBernoulliDist($L))", fmath, func.dist.getMean());
}
builder.addMethod(constructor.build());
// copy constructor
constructor = MethodSpec.constructorBuilder();
constructor.addModifiers(Modifier.PUBLIC);
constructor.addParameter(type, "other");
constructor.addStatement("super(other)");
constructor.addStatement("this.disable = new $T()", disable);
if (attackStep.hasTTC()) {
ClassName fmath = ClassName.get("com.foreseeti.corelib.math", "FMath");
// Analyzer guarantees this is a ttcfunc
TTCFunc func = (TTCFunc) attackStep.getTTC();
constructor.addStatement(
"setEvidenceDistribution($T.getBernoulliDist($L))", fmath, func.dist.getMean());
}
builder.addMethod(constructor.build());
if (attackStep.isConditionalDefense()) {
createIsEnabled(builder, attackStep);
}
createDisable(builder, asset, attackStep);
parentBuilder.addType(builder.build());
}
private void createIsEnabled(TypeSpec.Builder parentBuilder, AttackStep attackStep) {
// Overriding the isEnabled method, defense will be enabled if all requirements exist
MethodSpec.Builder method = MethodSpec.methodBuilder("isEnabled");
method.addAnnotation(Override.class);
method.addModifiers(Modifier.PUBLIC);
method.returns(boolean.class);
ClassName concreteSample = ClassName.get("com.foreseeti.simulator", "ConcreteSample");
method.addParameter(concreteSample, "sample");
if (attackStep.getType() == AttackStepType.EXIST) {
for (StepExpr expr : attackStep.getRequires()) {
AutoFlow af = new AutoFlow();
AutoFlow end = exprGen.generateExpr(af, expr, attackStep.getAsset());
end.addStatement("return false");
af.build(method);
}
method.addStatement("return true");
} else {
method.addStatement("int count = $L", attackStep.getRequires().size());
for (StepExpr expr : attackStep.getRequires()) {
AutoFlow af = new AutoFlow();
AutoFlow end = exprGen.generateExpr(af, expr, attackStep.getAsset());
end.addStatement("count--");
if (end.isLoop()) {
end.addStatement("break");
}
af.build(method);
}
method.addStatement("return count == 0");
}
parentBuilder.addMethod(method.build());
}
private void createDisable(TypeSpec.Builder parentBuilder, Asset asset, AttackStep attackStep) {
ClassName disable =
ClassName.get(this.pkg, asset.getName(), ucFirst(attackStep.getName()), "Disable");
TypeSpec.Builder builder = TypeSpec.classBuilder(disable);
builder.addModifiers(Modifier.PUBLIC);
if (attackStep.hasParent()) {
AttackStep parent = attackStep.getAsset().getSuperAsset().getAttackStep(attackStep.getName());
Asset parentAsset = parent.getAsset();
ClassName type =
ClassName.get(pkg, parentAsset.getName(), ucFirst(parent.getName()), "Disable");
builder.superclass(type);
} else {
ClassName localAttackStepMin = ClassName.get(this.pkg, asset.getName(), "LocalAttackStepMin");
builder.superclass(localAttackStepMin);
}
// getInfluencingDefense
ClassName defense = ClassName.get("com.foreseeti.simulator", "Defense");
ClassName parent = ClassName.get(this.pkg, asset.getName(), ucFirst(attackStep.getName()));
MethodSpec.Builder method = MethodSpec.methodBuilder("getInfluencingDefense");
method.addAnnotation(Override.class);
method.addModifiers(Modifier.PUBLIC);
method.returns(defense);
method.addStatement("return $T.this", parent);
builder.addMethod(method.build());
AttackStepGenerator.createSteps(builder, exprGen, attackStep);
AttackStepGenerator.createGetTags(builder, attackStep);
parentBuilder.addType(builder.build());
}
}
|
3e08430f6e94804a2579976b9ea6e46d227d95e5
| 999 |
java
|
Java
|
osgp/shared/osgp-dto/src/main/java/org/opensmartgridplatform/dto/valueobjects/orm/RtuDeviceDto.java
|
ahiguerat/open-smart-grid-platform
|
10e70f5752d9ec674b6ab26dd45b15a42c572f5e
|
[
"Apache-2.0"
] | null | null | null |
osgp/shared/osgp-dto/src/main/java/org/opensmartgridplatform/dto/valueobjects/orm/RtuDeviceDto.java
|
ahiguerat/open-smart-grid-platform
|
10e70f5752d9ec674b6ab26dd45b15a42c572f5e
|
[
"Apache-2.0"
] | null | null | null |
osgp/shared/osgp-dto/src/main/java/org/opensmartgridplatform/dto/valueobjects/orm/RtuDeviceDto.java
|
ahiguerat/open-smart-grid-platform
|
10e70f5752d9ec674b6ab26dd45b15a42c572f5e
|
[
"Apache-2.0"
] | null | null | null | 19.98 | 80 | 0.761762 | 3,497 |
package org.opensmartgridplatform.dto.valueobjects.orm;
import java.io.Serializable;
import java.util.List;
public class RtuDeviceDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2196653168046111111L;
private String deviceIdentification;
private List<PositionDto> positions;
private String ip;
public RtuDeviceDto() {}
public RtuDeviceDto(String deviceIdentification, List<PositionDto> positions) {
this.positions = positions;
this.deviceIdentification = deviceIdentification;
}
public String getDeviceIdentification() {
return deviceIdentification;
}
public void setDeviceIdentification(String deviceIdentification) {
this.deviceIdentification = deviceIdentification;
}
public List<PositionDto> getPositions() {
return positions;
}
public void setPositions(List<PositionDto> positions) {
this.positions = positions;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
|
3e084447bed850664d728d2db620ce23b45f20f4
| 1,495 |
java
|
Java
|
src/org/neu/alg/hw/hw5/Hop.java
|
lanshunfang/alg-hw
|
5e2b16cc5aa7598aad6648c22da57c20d8a9b532
|
[
"MIT"
] | 1 |
2020-01-29T18:35:49.000Z
|
2020-01-29T18:35:49.000Z
|
src/org/neu/alg/hw/hw5/Hop.java
|
lanshunfang/alg-hw
|
5e2b16cc5aa7598aad6648c22da57c20d8a9b532
|
[
"MIT"
] | 21 |
2020-01-15T21:17:06.000Z
|
2020-04-01T18:58:15.000Z
|
src/org/neu/alg/hw/hw5/Hop.java
|
lanshunfang/alg-hw
|
5e2b16cc5aa7598aad6648c22da57c20d8a9b532
|
[
"MIT"
] | null | null | null | 23.359375 | 97 | 0.632107 | 3,498 |
package org.neu.alg.hw.hw5;
import org.neu.alg.hw.*;
/**
* File Name: Hop.java
* Hop concrete class
*
*
* To Compile: IntUtil.java RandomInt.java Hop.java HopBase.java
*
* @author Jagadeesh Vasudevamurthy
* @year 2019
*/
class Hop extends HopBase{
//You cannot have any functions or data here
Hop() {
//NOTHING CAN BE CHANGED HERE
testBed();
}
@Override
int hopSmart(int [] s, int x) {
//NOTHING CAN BE CHANGED HERE
return alg(s,x) ;
}
/*
* WRITE CODE IN alg
* YOU CANNOT USE ANY static variable in this function
* YOU can use many local variables inside the function
* Cannot use any loop statements like: for, while, do, while, go to
* Can use if
* ONLY AFTER THE execution of this routine array s MUST have the same contents as you got it.
* YOU cannot call any subroutine inside this function except alg itself
*
*/
private int alg(int [] s, int x) {
//WRITE CODE
//If your code is more than 10 lines, you don't understand the problem
final int currentValue = s[x];
if (s[x] == x) {
return 0;
} else {
s[x] = s[currentValue];
}
final int sum = 1 + alg(s, s[x]);
s[x] = currentValue;
return sum;
}
public static void main(String[] args) {
//NOTHING CAN BE CHANGED HERE
System.out.println("Hop problem STARTS");
Hop m = new Hop() ;
System.out.println("All Hop tests passed. You are great");
System.out.println("Hop problem ENDS");
}
}
|
3e0844689441579d78919d7c57350647435b1147
| 494 |
java
|
Java
|
domain/src/main/java/com/qtimes/domain/bean/ResultException.java
|
houwenbiao/BaseProject
|
ab3d7d8142d2bcf33d573226b01e1424c5cdef55
|
[
"Apache-2.0"
] | null | null | null |
domain/src/main/java/com/qtimes/domain/bean/ResultException.java
|
houwenbiao/BaseProject
|
ab3d7d8142d2bcf33d573226b01e1424c5cdef55
|
[
"Apache-2.0"
] | null | null | null |
domain/src/main/java/com/qtimes/domain/bean/ResultException.java
|
houwenbiao/BaseProject
|
ab3d7d8142d2bcf33d573226b01e1424c5cdef55
|
[
"Apache-2.0"
] | null | null | null | 16.466667 | 55 | 0.582996 | 3,499 |
package com.qtimes.domain.bean;
/**
* Created by hong on 16-12-21.
*/
public class ResultException extends RuntimeException {
private int errCode = 0;
private String msg;
public ResultException(int code, String msg) {
super(msg);
this.msg = msg;
errCode = code;
}
public int getErrCode() {
return errCode;
}
public String getMsg() {
return msg;
}
public void setMsg(String mMsg) {
msg = mMsg;
}
}
|
3e084468ab227a501f1466574dc2629ac74553e9
| 227 |
java
|
Java
|
fonte/ComparisonOperator.java
|
northy/lazylang
|
86f06be1adca4458c7ff6168ea2a613361ab5e46
|
[
"MIT"
] | null | null | null |
fonte/ComparisonOperator.java
|
northy/lazylang
|
86f06be1adca4458c7ff6168ea2a613361ab5e46
|
[
"MIT"
] | null | null | null |
fonte/ComparisonOperator.java
|
northy/lazylang
|
86f06be1adca4458c7ff6168ea2a613361ab5e46
|
[
"MIT"
] | null | null | null | 18.230769 | 49 | 0.654008 | 3,500 |
//Alexsandro Thomas <[email protected]>
package fonte;
public enum ComparisonOperator {
EQ, //EQUALS
GT, //GREATER THAN
LT, //LESSER THAN
GE, //GREATER OR EQUAL
LE, //LESSER OR EQUAL
NE; //NOT EQUAL
}
|
3e0844998229ccd542572171f98ad2011b03191a
| 3,710 |
java
|
Java
|
src/main/java/org/osc/sdk/manager/api/ManagerSecurityGroupInterfaceApi.java
|
opensecuritycontroller/security-mgr-api
|
9eff91d76ba541ce890e5beb90ea239af965bd82
|
[
"Apache-2.0"
] | 7 |
2017-06-28T16:22:46.000Z
|
2022-02-26T03:27:49.000Z
|
src/main/java/org/osc/sdk/manager/api/ManagerSecurityGroupInterfaceApi.java
|
opensecuritycontroller/security-mgr-api
|
9eff91d76ba541ce890e5beb90ea239af965bd82
|
[
"Apache-2.0"
] | 3 |
2017-07-07T15:41:38.000Z
|
2017-10-10T00:35:39.000Z
|
src/main/java/org/osc/sdk/manager/api/ManagerSecurityGroupInterfaceApi.java
|
opensecuritycontroller/security-mgr-api
|
9eff91d76ba541ce890e5beb90ea239af965bd82
|
[
"Apache-2.0"
] | 11 |
2017-06-29T10:37:15.000Z
|
2020-06-02T14:51:56.000Z
| 40.769231 | 124 | 0.715094 | 3,501 |
/*******************************************************************************
* Copyright (c) Intel Corporation
* Copyright (c) 2017
*
* 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.osc.sdk.manager.api;
import java.util.List;
import org.osc.sdk.manager.Constants;
import org.osc.sdk.manager.element.ManagerSecurityGroupInterfaceElement;
import org.osc.sdk.manager.element.SecurityGroupInterfaceElement;
import org.osgi.annotation.versioning.ConsumerType;
/**
* This interface documents the operations used by OSC to manage security group interfaces.
* <p>
* This API is required only by security managers configured to sync policy mappings,
* see {@link Constants#SYNC_POLICY_MAPPING}.
*/
@ConsumerType
public interface ManagerSecurityGroupInterfaceApi extends AutoCloseable {
/**
* Creates a security group interface within context of the current virtual system
*
* @param sgiElement the information needed to create a security group interface
* @return the identifier of the security group interface defined by the security manager
*
* @throws Exception upon failure
*/
String createSecurityGroupInterface(SecurityGroupInterfaceElement sgiElement) throws Exception;
/**
* Updates a security group interface within context of the current virtual system
*
* @param sgiElement the information needed to update a security group interface
*
* @throws Exception upon failure
*/
void updateSecurityGroupInterface(SecurityGroupInterfaceElement sgiElement) throws Exception;
/**
* Deletes a security group interface within context of the current virtual system.
*
* @param mgrSecurityGroupInterfaceId the identifier of the manager security group interface to be deleted
* @throws Exception upon failure
*/
void deleteSecurityGroupInterface(String mgrSecurityGroupInterfaceId) throws Exception;
/**
* Retrieves the security group interface by its identifier within the context of the current virtual system.
*
* @param mgrSecurityGroupInterfaceId the identifier of the manager security group interface
* @return the security group interface, null if not found
* @throws Exception upon failure
*/
ManagerSecurityGroupInterfaceElement getSecurityGroupInterfaceById(String mgrSecurityGroupInterfaceId) throws Exception;
/**
* Retrieves the security group interface by its name within the context of the current virtual system.
*
* @param name the name of the security group interface
* @return the security group interface, null if not found
* @throws Exception upon failure
*/
String findSecurityGroupInterfaceByName(String name) throws Exception;
/**
* Gets all the security group interfaces within the context of the current virtual system.
*
* @return the collection of security group interfaces.
* @throws Exception upon failure
*/
List<? extends ManagerSecurityGroupInterfaceElement> listSecurityGroupInterfaces() throws Exception;
@Override
void close();
}
|
3e08449d0955478c26787158ee9a096aebe4485f
| 800 |
java
|
Java
|
src/gradingTools/comp533s20/assignment2/A2ConfigurationProvided.java
|
pdewan/Comp533LocalChecks
|
46ccdf3a26a115b1f41a9ce40a0692f649afd54e
|
[
"MIT"
] | null | null | null |
src/gradingTools/comp533s20/assignment2/A2ConfigurationProvided.java
|
pdewan/Comp533LocalChecks
|
46ccdf3a26a115b1f41a9ce40a0692f649afd54e
|
[
"MIT"
] | null | null | null |
src/gradingTools/comp533s20/assignment2/A2ConfigurationProvided.java
|
pdewan/Comp533LocalChecks
|
46ccdf3a26a115b1f41a9ce40a0692f649afd54e
|
[
"MIT"
] | null | null | null | 34.782609 | 80 | 0.83125 | 3,502 |
package gradingTools.comp533s20.assignment2;
import gradingTools.comp533s19.assignment0.testcases.ConfigurationProvided;
import gradingTools.comp533s21.assignment1.interfaces.A1MapReduceConfiguration;
import gradingTools.comp533s21.assignment1.interfaces.MapReduceConfiguration;
import gradingTools.shared.testcases.utils.AbstractConfigurationProvided;
import util.annotations.MaxValue;
@MaxValue(10)
public class A2ConfigurationProvided extends AbstractConfigurationProvided{
public Class referenceClass() {
return A2ReferenceConfigurationClass.class;
}
@Override
public Class referenceInterface() {
return MapReduceConfiguration.class;
}
public MapReduceConfiguration getTestConfiguration() {
return (MapReduceConfiguration) super.getTestConfiguration() ;
}
}
|
3e08451e3b8d6f87b2b3df484b10d7ab0e6468d5
| 6,667 |
java
|
Java
|
plugins/org.jkiss.dbeaver.ext.db2/src/org/jkiss/dbeaver/ext/db2/model/security/DB2Grantee.java
|
Cynyard999/dbeaver
|
29b44b16cfb5291c96fdec1a1a50e6b76e1c1d68
|
[
"Apache-2.0"
] | 22,779 |
2017-12-23T15:47:03.000Z
|
2022-03-31T15:48:15.000Z
|
plugins/org.jkiss.dbeaver.ext.db2/src/org/jkiss/dbeaver/ext/db2/model/security/DB2Grantee.java
|
Cynyard999/dbeaver
|
29b44b16cfb5291c96fdec1a1a50e6b76e1c1d68
|
[
"Apache-2.0"
] | 10,922 |
2017-12-23T12:01:39.000Z
|
2022-03-31T23:52:18.000Z
|
plugins/org.jkiss.dbeaver.ext.db2/src/org/jkiss/dbeaver/ext/db2/model/security/DB2Grantee.java
|
Cynyard999/dbeaver
|
29b44b16cfb5291c96fdec1a1a50e6b76e1c1d68
|
[
"Apache-2.0"
] | 2,552 |
2017-12-26T21:31:27.000Z
|
2022-03-31T09:05:03.000Z
| 31.338028 | 125 | 0.696479 | 3,503 |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2013-2015 Denis Forveille ([email protected])
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ext.db2.model.security;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.db2.model.DB2DataSource;
import org.jkiss.dbeaver.ext.db2.model.DB2GlobalObject;
import org.jkiss.dbeaver.model.DBPRefreshableObject;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.meta.Association;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* DB2 Super class for Users, Groups and Roles (=Grantees)
*
* @author Denis Forveille
*/
public abstract class DB2Grantee extends DB2GlobalObject implements DBPRefreshableObject {
private final DB2GranteeAuthCache authCache = new DB2GranteeAuthCache();
private final DB2GranteeRoleCache roleCache = new DB2GranteeRoleCache();
private final DB2GranteeDatabaseAuthCache databaseAuthCache = new DB2GranteeDatabaseAuthCache();
private Map<Class<?>, Collection<? extends DB2AuthBase>> cachePerObject;
private String name;
// -----------------------
// Constructors
// -----------------------
public DB2Grantee(DBRProgressMonitor monitor, DB2DataSource dataSource, ResultSet resultSet, String keyColName)
{
super(dataSource, true);
this.name = JDBCUtils.safeGetStringTrimmed(resultSet, keyColName);
cachePerObject = new HashMap<>(12);
}
// -----------------
// Business Contract
// -----------------
public abstract DB2AuthIDType getType();
@Override
public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException
{
authCache.clearCache();
roleCache.clearCache();
databaseAuthCache.clearCache();
cachePerObject.clear();
return this;
}
// -----------------
// Associations
// -----------------
@Association
public Collection<DB2AuthColumn> getColumnsAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthColumn.class);
}
@Association
public Collection<DB2DatabaseAuth> getDatabaseAuths(DBRProgressMonitor monitor) throws DBException
{
return databaseAuthCache.getAllObjects(monitor, this);
}
@Association
public Collection<DB2AuthUDF> getFunctionsAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthUDF.class);
}
@Association
public Collection<DB2AuthIndex> getIndexesAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthIndex.class);
}
@Association
public Collection<DB2AuthModule> getModulesAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthModule.class);
}
@Association
public Collection<DB2AuthPackage> getPackagesAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthPackage.class);
}
@Association
public Collection<DB2AuthProcedure> getProceduresAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthProcedure.class);
}
@Association
public Collection<DB2RoleAuth> getRoles(DBRProgressMonitor monitor) throws DBException
{
return roleCache.getAllObjects(monitor, this);
}
@Association
public Collection<DB2AuthSchema> getSchemasAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthSchema.class);
}
@Association
public Collection<DB2AuthSequence> getSequencesAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthSequence.class);
}
@Association
public Collection<DB2AuthTable> getTablesAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthTable.class);
}
@Association
public Collection<DB2AuthTablespace> getTablespacesAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthTablespace.class);
}
@Association
public Collection<DB2AuthVariable> getVariablesAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthVariable.class);
}
@Association
public Collection<DB2AuthView> getViewsAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthView.class);
}
@Association
public Collection<DB2AuthMaterializedQueryTable> getMQTAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthMaterializedQueryTable.class);
}
@Association
public Collection<DB2AuthXMLSchema> getXMLSchemasAuths(DBRProgressMonitor monitor) throws DBException
{
return getAuths(monitor, DB2AuthXMLSchema.class);
}
// -----------------
// Helper
// -----------------
// Filter
@SuppressWarnings("unchecked")
private <T extends DB2AuthBase> Collection<T> getAuths(DBRProgressMonitor monitor, Class<T> authClass) throws DBException
{
Collection<T> listAuths = (Collection<T>) cachePerObject.get(authClass.getClass());
if (listAuths == null) {
listAuths = new ArrayList<>();
for (DB2AuthBase db2Auth : authCache.getAllObjects(monitor, this)) {
if (authClass.isInstance(db2Auth)) {
listAuths.add((T) db2Auth);
}
}
}
return listAuths;
}
// -----------------
// Properties
// -----------------
@NotNull
@Override
@Property(viewable = true, order = 1)
public String getName()
{
return name;
}
}
|
3e084537a996ec1ae6b4c43ea7feb3677ec87e05
| 2,513 |
java
|
Java
|
PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.core/src/com/microsoft/azure/toolkit/eclipse/common/component/AzureComboBoxViewer.java
|
G-arj/azure-tools-for-java
|
4780137b1b07c59cb16475c9f5698fe9d3acf19b
|
[
"MIT"
] | 131 |
2016-03-24T05:34:57.000Z
|
2019-04-23T14:41:48.000Z
|
PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.core/src/com/microsoft/azure/toolkit/eclipse/common/component/AzureComboBoxViewer.java
|
G-arj/azure-tools-for-java
|
4780137b1b07c59cb16475c9f5698fe9d3acf19b
|
[
"MIT"
] | 2,277 |
2016-03-23T06:19:19.000Z
|
2019-05-06T11:35:49.000Z
|
PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.core/src/com/microsoft/azure/toolkit/eclipse/common/component/AzureComboBoxViewer.java
|
G-arj/azure-tools-for-java
|
4780137b1b07c59cb16475c9f5698fe9d3acf19b
|
[
"MIT"
] | 98 |
2016-03-25T03:23:42.000Z
|
2019-04-09T17:42:50.000Z
| 25.383838 | 95 | 0.627139 | 3,504 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.azure.toolkit.eclipse.common.component;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class AzureComboBoxViewer<T> extends ComboViewer {
public AzureComboBoxViewer(AzureComboBox<T> parent) {
super(parent);
}
public List<T> getItems() {
final List<T> result = new ArrayList<>();
final Object input = super.getInput();
if (input instanceof Collection) {
//noinspection unchecked
result.addAll((Collection<T>) input);
}
return result;
}
@Override
public void setSelection(ISelection selection) {
super.setSelection(selection);
}
public void setItems(List<? extends T> items) {
if (this.getControl().isDisposed()) {
return;
}
super.setInput(items);
}
public void removeAllItems() {
if (this.getControl().isDisposed()) {
return;
}
super.setInput(Collections.emptyList());
}
public int getItemCount() {
return super.listGetItemCount();
}
public int getSelectedIndex() {
return super.listGetSelectionIndices()[0];
}
public void setSelectedIndex(int i) {
super.listSetSelection(new int[]{i});
}
public Object getSelectedItem() {
return this.getStructuredSelection().getFirstElement();
}
public void setSelectedItem(Object value) {
if (Objects.nonNull(value)) {
this.setSelection(new StructuredSelection(value));
} else {
this.setSelection(StructuredSelection.EMPTY);
}
}
public void setEditable(boolean b) {
if (this.getControl().isDisposed()) {
return;
}
super.getControl().setEnabled(b);
}
public void setEnabled(boolean b) {
if (this.getControl().isDisposed()) {
return;
}
super.getControl().setEnabled(b);
}
public boolean isEnabled() {
return super.getControl().getEnabled();
}
public void repaint() {
this.getControl().redraw();
}
}
|
3e0845d08a8f65ef1d5661980f2722547c713f0f
| 445 |
java
|
Java
|
src/main/java/org/rublin/service/EventService.java
|
rublin/SmartSpace
|
196fce7f3e013cda03f03dcce6f5dcc31ca1c6ab
|
[
"MIT"
] | 2 |
2016-11-03T11:22:47.000Z
|
2017-12-21T16:07:28.000Z
|
src/main/java/org/rublin/service/EventService.java
|
rublin/SmartSpace
|
196fce7f3e013cda03f03dcce6f5dcc31ca1c6ab
|
[
"MIT"
] | 1 |
2019-06-16T08:38:18.000Z
|
2019-06-16T08:38:18.000Z
|
src/main/java/org/rublin/service/EventService.java
|
rublin/SmartSpace
|
196fce7f3e013cda03f03dcce6f5dcc31ca1c6ab
|
[
"MIT"
] | null | null | null | 20.227273 | 65 | 0.737079 | 3,505 |
package org.rublin.service;
import org.rublin.model.Trigger;
import org.rublin.model.event.Event;
import java.time.LocalDateTime;
import java.util.List;
public interface EventService {
void save(Event event);
List<Event> get(Trigger trigger);
List<Event> get(Trigger trigger, int numberLatestEvents);
List<Event> getAll();
List<Event> getBetween(LocalDateTime from, LocalDateTime to);
List<Event> getAlarmed();
}
|
3e084690b049d0501b92b49600e8da2f3597239b
| 26,045 |
java
|
Java
|
src/main/java/net/ymate/platform/mock/web/MockHttpServletRequest.java
|
suninformation/ymate-platform-webmock
|
33292fa4730edb89e2940516da424ee59c613986
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/net/ymate/platform/mock/web/MockHttpServletRequest.java
|
suninformation/ymate-platform-webmock
|
33292fa4730edb89e2940516da424ee59c613986
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/net/ymate/platform/mock/web/MockHttpServletRequest.java
|
suninformation/ymate-platform-webmock
|
33292fa4730edb89e2940516da424ee59c613986
|
[
"Apache-2.0"
] | null | null | null | 28.938889 | 157 | 0.633711 | 3,506 |
package net.ymate.platform.mock.web;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class MockHttpServletRequest implements HttpServletRequest {
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static final String CONTENT_TYPE_HEADER = "Content-Type";
private static final String HOST_HEADER = "Host";
private static final String CHARSET_PREFIX = "charset=";
private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
private static final ServletInputStream EMPTY_SERVLET_INPUT_STREAM = new DelegatingServletInputStream(IOUtils.toInputStream("", StandardCharsets.UTF_8));
private static final BufferedReader EMPTY_BUFFERED_READER = new BufferedReader(new StringReader(""));
private static final String[] DATE_FORMATS = new String[]{
"EEE, dd MMM yyyy HH:mm:ss zzz",
"EEE, dd-MMM-yy HH:mm:ss zzz",
"EEE MMM dd HH:mm:ss yyyy"
};
public static final String DEFAULT_PROTOCOL = "HTTP/1.1";
public static final String DEFAULT_SCHEME = HTTP;
public static final String DEFAULT_SERVER_ADDR = "127.0.0.1";
public static final String DEFAULT_SERVER_NAME = "localhost";
public static final int DEFAULT_SERVER_PORT = 80;
public static final String DEFAULT_REMOTE_ADDR = "127.0.0.1";
public static final String DEFAULT_REMOTE_HOST = "localhost";
private final ServletContext servletContext;
private boolean active = true;
private final Map<String, Object> attributes = new LinkedHashMap<>();
private String characterEncoding;
private byte[] content;
private String contentType;
private final Map<String, String[]> parameters = new LinkedHashMap<>();
private String protocol = DEFAULT_PROTOCOL;
private String scheme = DEFAULT_SCHEME;
private String serverName = DEFAULT_SERVER_NAME;
private int serverPort = DEFAULT_SERVER_PORT;
private String remoteAddr = DEFAULT_REMOTE_ADDR;
private String remoteHost = DEFAULT_REMOTE_HOST;
private final List<Locale> locales = new LinkedList<>();
private boolean secure = false;
private int remotePort = DEFAULT_SERVER_PORT;
private String localName = DEFAULT_SERVER_NAME;
private String localAddr = DEFAULT_SERVER_ADDR;
private int localPort = DEFAULT_SERVER_PORT;
private boolean asyncStarted = false;
private boolean asyncSupported = false;
private MockAsyncContext asyncContext;
private DispatcherType dispatcherType = DispatcherType.REQUEST;
private String authType;
private Cookie[] cookies;
private final Map<String, HeaderValueHolder> headers = new LinkedHashMap<>();
private String method;
private String pathInfo;
private String contextPath = "";
private String queryString;
private String remoteUser;
private final Set<String> userRoles = new HashSet<>();
private Principal userPrincipal;
private String requestedSessionId;
private String requestURI;
private String servletPath = "";
private HttpSession session;
private boolean requestedSessionIdValid = true;
private boolean requestedSessionIdFromCookie = true;
private boolean requestedSessionIdFromURL = false;
private final Map<String, Part> parts = new LinkedHashMap<>();
public MockHttpServletRequest() {
this(null, "", "");
}
public MockHttpServletRequest(String method, String requestURI) {
this(null, method, requestURI);
}
public MockHttpServletRequest(ServletContext servletContext) {
this(servletContext, "", "");
}
public MockHttpServletRequest(ServletContext servletContext, String method, String requestURI) {
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
this.method = method;
this.requestURI = requestURI;
this.locales.add(Locale.ENGLISH);
}
@Override
public ServletContext getServletContext() {
return this.servletContext;
}
public boolean isActive() {
return this.active;
}
public void close() {
this.active = false;
}
public void invalidate() {
close();
clearAttributes();
}
protected void checkActive() throws IllegalStateException {
if (!this.active) {
throw new IllegalStateException("Request is not active anymore");
}
}
@Override
public Object getAttribute(String name) {
checkActive();
return this.attributes.get(name);
}
@Override
public Enumeration<String> getAttributeNames() {
checkActive();
return Collections.enumeration(new LinkedHashSet<>(this.attributes.keySet()));
}
@Override
public String getCharacterEncoding() {
return this.characterEncoding;
}
@Override
public void setCharacterEncoding(String characterEncoding) {
this.characterEncoding = characterEncoding;
updateContentTypeHeader();
}
private void updateContentTypeHeader() {
if (StringUtils.isNotBlank(this.contentType)) {
StringBuilder sb = new StringBuilder(this.contentType);
if (!this.contentType.toLowerCase().contains(CHARSET_PREFIX) &&
StringUtils.isNotBlank(this.characterEncoding)) {
sb.append(";").append(CHARSET_PREFIX).append(this.characterEncoding);
}
doAddHeaderValue(CONTENT_TYPE_HEADER, sb.toString(), true);
}
}
public void setContent(byte[] content) {
this.content = content;
}
@Override
public int getContentLength() {
return (this.content != null ? this.content.length : -1);
}
public long getContentLengthLong() {
return getContentLength();
}
public void setContentType(String contentType) {
this.contentType = contentType;
if (contentType != null) {
int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX);
if (charsetIndex != -1) {
this.characterEncoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length());
}
updateContentTypeHeader();
}
}
@Override
public String getContentType() {
return this.contentType;
}
@Override
public ServletInputStream getInputStream() {
if (this.content != null) {
return new DelegatingServletInputStream(new ByteArrayInputStream(this.content));
}
return EMPTY_SERVLET_INPUT_STREAM;
}
public void setParameter(String name, String value) {
setParameter(name, new String[]{value});
}
public void setParameter(String name, String... values) {
Assert.assertNotNull("Parameter name must not be null", name);
this.parameters.put(name, values);
}
public void setParameters(Map<String, ?> params) {
Assert.assertNotNull("Parameter map must not be null", params);
for (String key : params.keySet()) {
Object value = params.get(key);
if (value instanceof String) {
setParameter(key, (String) value);
} else if (value instanceof String[]) {
setParameter(key, (String[]) value);
} else {
throw new IllegalArgumentException("Parameter map value must be single value " + " or array of type [" + String.class.getName() + "]");
}
}
}
public void addParameter(String name, String value) {
addParameter(name, new String[]{value});
}
public void addParameter(String name, String... values) {
Assert.assertNotNull("Parameter name must not be null", name);
String[] oldArr = this.parameters.get(name);
if (oldArr != null) {
String[] newArr = new String[oldArr.length + values.length];
System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
System.arraycopy(values, 0, newArr, oldArr.length, values.length);
this.parameters.put(name, newArr);
} else {
this.parameters.put(name, values);
}
}
public void addParameters(Map<String, ?> params) {
Assert.assertNotNull("Parameter map must not be null", params);
for (String key : params.keySet()) {
Object value = params.get(key);
if (value instanceof String) {
addParameter(key, (String) value);
} else if (value instanceof String[]) {
addParameter(key, (String[]) value);
} else {
throw new IllegalArgumentException("Parameter map value must be single value " + " or array of type [" + String.class.getName() + "]");
}
}
}
public void removeParameter(String name) {
Assert.assertNotNull("Parameter name must not be null", name);
this.parameters.remove(name);
}
public void removeAllParameters() {
this.parameters.clear();
}
@Override
public String getParameter(String name) {
String[] arr = (name != null ? this.parameters.get(name) : null);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
@Override
public Enumeration<String> getParameterNames() {
return Collections.enumeration(this.parameters.keySet());
}
@Override
public String[] getParameterValues(String name) {
return (name != null ? this.parameters.get(name) : null);
}
@Override
public Map<String, String[]> getParameterMap() {
return Collections.unmodifiableMap(this.parameters);
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
@Override
public String getProtocol() {
return this.protocol;
}
public void setScheme(String scheme) {
this.scheme = scheme;
}
@Override
public String getScheme() {
return this.scheme;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
@Override
public String getServerName() {
String rawHostHeader = getHeader(HOST_HEADER);
String host = rawHostHeader;
if (host != null) {
host = host.trim();
if (host.startsWith("[")) {
int indexOfClosingBracket = host.indexOf(']');
Assert.assertTrue("Invalid Host header: " + rawHostHeader, indexOfClosingBracket > -1);
host = host.substring(0, indexOfClosingBracket + 1);
} else if (host.contains(":")) {
host = host.substring(0, host.indexOf(':'));
}
return host;
}
return this.serverName;
}
public void setServerPort(int serverPort) {
this.serverPort = serverPort;
}
@Override
public int getServerPort() {
String rawHostHeader = getHeader(HOST_HEADER);
String host = rawHostHeader;
if (host != null) {
host = host.trim();
int idx;
if (host.startsWith("[")) {
int indexOfClosingBracket = host.indexOf(']');
Assert.assertTrue("Invalid Host header: " + rawHostHeader, indexOfClosingBracket > -1);
idx = host.indexOf(':', indexOfClosingBracket);
} else {
idx = host.indexOf(':');
}
if (idx != -1) {
return Integer.parseInt(host.substring(idx + 1));
}
}
return this.serverPort;
}
@Override
public BufferedReader getReader() throws UnsupportedEncodingException {
if (this.content != null) {
InputStream sourceStream = new ByteArrayInputStream(this.content);
Reader sourceReader = (this.characterEncoding != null) ?
new InputStreamReader(sourceStream, this.characterEncoding) :
new InputStreamReader(sourceStream);
return new BufferedReader(sourceReader);
} else {
return EMPTY_BUFFERED_READER;
}
}
public void setRemoteAddr(String remoteAddr) {
this.remoteAddr = remoteAddr;
}
@Override
public String getRemoteAddr() {
return this.remoteAddr;
}
public void setRemoteHost(String remoteHost) {
this.remoteHost = remoteHost;
}
@Override
public String getRemoteHost() {
return this.remoteHost;
}
@Override
public void setAttribute(String name, Object value) {
checkActive();
Assert.assertNotNull("Attribute name must not be null", name);
if (value != null) {
this.attributes.put(name, value);
} else {
this.attributes.remove(name);
}
}
@Override
public void removeAttribute(String name) {
checkActive();
Assert.assertNotNull("Attribute name must not be null", name);
this.attributes.remove(name);
}
public void clearAttributes() {
this.attributes.clear();
}
public void addPreferredLocale(Locale locale) {
Assert.assertNotNull("Locale must not be null", locale);
this.locales.add(0, locale);
}
public void setPreferredLocales(List<Locale> locales) {
Assert.assertTrue("Locale list must not be empty", locales.isEmpty());
this.locales.clear();
this.locales.addAll(locales);
}
@Override
public Locale getLocale() {
return this.locales.get(0);
}
@Override
public Enumeration<Locale> getLocales() {
return Collections.enumeration(this.locales);
}
public void setSecure(boolean secure) {
this.secure = secure;
}
@Override
public boolean isSecure() {
return (this.secure || HTTPS.equalsIgnoreCase(this.scheme));
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
return new MockRequestDispatcher(path);
}
@Override
@Deprecated
public String getRealPath(String path) {
return this.servletContext.getRealPath(path);
}
public void setRemotePort(int remotePort) {
this.remotePort = remotePort;
}
@Override
public int getRemotePort() {
return this.remotePort;
}
public void setLocalName(String localName) {
this.localName = localName;
}
@Override
public String getLocalName() {
return this.localName;
}
public void setLocalAddr(String localAddr) {
this.localAddr = localAddr;
}
@Override
public String getLocalAddr() {
return this.localAddr;
}
public void setLocalPort(int localPort) {
this.localPort = localPort;
}
@Override
public int getLocalPort() {
return this.localPort;
}
@Override
public AsyncContext startAsync() {
return startAsync(this, null);
}
@Override
public AsyncContext startAsync(ServletRequest request, ServletResponse response) {
if (!this.asyncSupported) {
throw new IllegalStateException("Async not supported");
}
this.asyncStarted = true;
this.asyncContext = new MockAsyncContext(request, response);
return this.asyncContext;
}
public void setAsyncStarted(boolean asyncStarted) {
this.asyncStarted = asyncStarted;
}
@Override
public boolean isAsyncStarted() {
return this.asyncStarted;
}
public void setAsyncSupported(boolean asyncSupported) {
this.asyncSupported = asyncSupported;
}
@Override
public boolean isAsyncSupported() {
return this.asyncSupported;
}
public void setAsyncContext(MockAsyncContext asyncContext) {
this.asyncContext = asyncContext;
}
@Override
public AsyncContext getAsyncContext() {
return this.asyncContext;
}
public void setDispatcherType(DispatcherType dispatcherType) {
this.dispatcherType = dispatcherType;
}
@Override
public DispatcherType getDispatcherType() {
return this.dispatcherType;
}
public void setAuthType(String authType) {
this.authType = authType;
}
@Override
public String getAuthType() {
return this.authType;
}
public void setCookies(Cookie... cookies) {
this.cookies = cookies;
}
@Override
public Cookie[] getCookies() {
return this.cookies;
}
public void addHeader(String name, Object value) {
if (CONTENT_TYPE_HEADER.equalsIgnoreCase(name) && !this.headers.containsKey(CONTENT_TYPE_HEADER)) {
setContentType(value.toString());
} else {
doAddHeaderValue(name, value, false);
}
}
private void doAddHeaderValue(String name, Object value, boolean replace) {
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
Assert.assertNotNull("Header value must not be null", value);
if (header == null || replace) {
header = new HeaderValueHolder();
this.headers.put(name, header);
}
if (value instanceof Collection) {
header.addValues((Collection<?>) value);
} else if (value.getClass().isArray()) {
header.addValueArray(value);
} else {
header.addValue(value);
}
}
public void removeHeader(String name) {
Assert.assertNotNull("Header name must not be null", name);
this.headers.remove(name);
}
@Override
public long getDateHeader(String name) {
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
Object value = (header != null ? header.getValue() : null);
if (value instanceof Date) {
return ((Date) value).getTime();
} else if (value instanceof Number) {
return ((Number) value).longValue();
} else if (value instanceof String) {
return parseDateHeader(name, (String) value);
} else if (value != null) {
throw new IllegalArgumentException("Value for header '" + name + "' is not a Date, Number, or String: " + value);
} else {
return -1L;
}
}
private long parseDateHeader(String name, String value) {
for (String dateFormat : DATE_FORMATS) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
simpleDateFormat.setTimeZone(GMT);
try {
return simpleDateFormat.parse(value).getTime();
} catch (ParseException ex) {
// ignore
}
}
throw new IllegalArgumentException("Cannot parse date value '" + value + "' for '" + name + "' header");
}
@Override
public String getHeader(String name) {
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
return (header != null ? header.getStringValue() : null);
}
@Override
public Enumeration<String> getHeaders(String name) {
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
return Collections.enumeration(header != null ? header.getStringValues() : new LinkedList<String>());
}
@Override
public Enumeration<String> getHeaderNames() {
return Collections.enumeration(this.headers.keySet());
}
@Override
public int getIntHeader(String name) {
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
Object value = (header != null ? header.getValue() : null);
if (value instanceof Number) {
return ((Number) value).intValue();
} else if (value instanceof String) {
return Integer.parseInt((String) value);
} else if (value != null) {
throw new NumberFormatException("Value for header '" + name + "' is not a Number: " + value);
} else {
return -1;
}
}
public void setMethod(String method) {
this.method = method;
}
@Override
public String getMethod() {
return this.method;
}
public void setPathInfo(String pathInfo) {
this.pathInfo = pathInfo;
}
@Override
public String getPathInfo() {
return this.pathInfo;
}
@Override
public String getPathTranslated() {
return (this.pathInfo != null ? getRealPath(this.pathInfo) : null);
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
@Override
public String getContextPath() {
return this.contextPath;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
@Override
public String getQueryString() {
return this.queryString;
}
public void setRemoteUser(String remoteUser) {
this.remoteUser = remoteUser;
}
@Override
public String getRemoteUser() {
return this.remoteUser;
}
public void addUserRole(String role) {
this.userRoles.add(role);
}
@Override
public boolean isUserInRole(String role) {
return (this.userRoles.contains(role) || (this.servletContext instanceof MockServletContext &&
((MockServletContext) this.servletContext).getDeclaredRoles().contains(role)));
}
public void setUserPrincipal(Principal userPrincipal) {
this.userPrincipal = userPrincipal;
}
@Override
public Principal getUserPrincipal() {
return this.userPrincipal;
}
public void setRequestedSessionId(String requestedSessionId) {
this.requestedSessionId = requestedSessionId;
}
@Override
public String getRequestedSessionId() {
return this.requestedSessionId;
}
public void setRequestURI(String requestURI) {
this.requestURI = requestURI;
}
@Override
public String getRequestURI() {
return this.requestURI;
}
@Override
public StringBuffer getRequestURL() {
String scheme = getScheme();
String server = getServerName();
int port = getServerPort();
String uri = getRequestURI();
StringBuffer url = new StringBuffer(scheme).append("://").append(server);
if (port > 0 && ((HTTP.equalsIgnoreCase(scheme) && port != 80) ||
(HTTPS.equalsIgnoreCase(scheme) && port != 443))) {
url.append(':').append(port);
}
if (StringUtils.isNotBlank(uri)) {
url.append(uri);
}
return url;
}
public void setServletPath(String servletPath) {
this.servletPath = servletPath;
}
@Override
public String getServletPath() {
return this.servletPath;
}
public void setSession(HttpSession session) {
this.session = session;
if (session instanceof MockHttpSession) {
MockHttpSession mockSession = ((MockHttpSession) session);
mockSession.access();
}
}
@Override
public HttpSession getSession(boolean create) {
checkActive();
if (this.session instanceof MockHttpSession && ((MockHttpSession) this.session).isInvalid()) {
this.session = null;
}
if (this.session == null && create) {
this.session = new MockHttpSession(this.servletContext);
}
return this.session;
}
@Override
public HttpSession getSession() {
return getSession(true);
}
public String changeSessionId() {
Assert.assertNotNull("The request does not have a session", this.session);
if (this.session instanceof MockHttpSession) {
return ((MockHttpSession) this.session).changeSessionId();
}
return this.session.getId();
}
public void setRequestedSessionIdValid(boolean requestedSessionIdValid) {
this.requestedSessionIdValid = requestedSessionIdValid;
}
@Override
public boolean isRequestedSessionIdValid() {
return this.requestedSessionIdValid;
}
public void setRequestedSessionIdFromCookie(boolean requestedSessionIdFromCookie) {
this.requestedSessionIdFromCookie = requestedSessionIdFromCookie;
}
@Override
public boolean isRequestedSessionIdFromCookie() {
return this.requestedSessionIdFromCookie;
}
public void setRequestedSessionIdFromURL(boolean requestedSessionIdFromURL) {
this.requestedSessionIdFromURL = requestedSessionIdFromURL;
}
@Override
public boolean isRequestedSessionIdFromURL() {
return this.requestedSessionIdFromURL;
}
@Override
@Deprecated
public boolean isRequestedSessionIdFromUrl() {
return isRequestedSessionIdFromURL();
}
@Override
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
throw new UnsupportedOperationException();
}
@Override
public void login(String username, String password) throws ServletException {
throw new UnsupportedOperationException();
}
@Override
public void logout() throws ServletException {
this.userPrincipal = null;
this.remoteUser = null;
this.authType = null;
}
public void addPart(Part part) {
parts.put(part.getName(), part);
}
@Override
public Part getPart(String name) throws IOException, ServletException {
return this.parts.get(name);
}
@Override
public Collection<Part> getParts() throws IOException, ServletException {
return parts.values();
}
}
|
3e0847910815e5b62d179d3ce2b5812bc28b225d
| 6,487 |
java
|
Java
|
netreflected/src/net461/system.web_version_4.0.0.0_culture_neutral_publickeytoken_b03f5f7f11d50a3a/system/web/ui/IDataSourceViewSchemaAccessorImplementation.java
|
mariomastrodicasa/JCOReflector
|
a88b6de9d3cc607fd375ab61df8c61f44de88c93
|
[
"MIT"
] | 35 |
2020-08-30T03:19:42.000Z
|
2022-03-12T09:22:23.000Z
|
netreflected/src/net461/system.web_version_4.0.0.0_culture_neutral_publickeytoken_b03f5f7f11d50a3a/system/web/ui/IDataSourceViewSchemaAccessorImplementation.java
|
mariomastrodicasa/JCOReflector
|
a88b6de9d3cc607fd375ab61df8c61f44de88c93
|
[
"MIT"
] | 50 |
2020-06-22T17:03:18.000Z
|
2022-03-30T21:19:05.000Z
|
netreflected/src/net461/system.web_version_4.0.0.0_culture_neutral_publickeytoken_b03f5f7f11d50a3a/system/web/ui/IDataSourceViewSchemaAccessorImplementation.java
|
mariomastrodicasa/JCOReflector
|
a88b6de9d3cc607fd375ab61df8c61f44de88c93
|
[
"MIT"
] | 12 |
2020-08-30T03:19:45.000Z
|
2022-03-05T02:22:37.000Z
| 38.844311 | 211 | 0.665793 | 3,507 |
/*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.web.ui;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
/**
* The base .NET class managing System.Web.UI.IDataSourceViewSchemaAccessor, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Web.UI.IDataSourceViewSchemaAccessor" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Web.UI.IDataSourceViewSchemaAccessor</a>
*/
public class IDataSourceViewSchemaAccessorImplementation extends NetObject implements IDataSourceViewSchemaAccessor {
/**
* Fully assembly qualified name: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
*/
public static final String assemblyFullName = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
/**
* Assembly name: System.Web
*/
public static final String assemblyShortName = "System.Web";
/**
* Qualified class name: System.Web.UI.IDataSourceViewSchemaAccessor
*/
public static final String className = "System.Web.UI.IDataSourceViewSchemaAccessor";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
/**
* Internal constructor. Use with caution
*/
public IDataSourceViewSchemaAccessorImplementation(java.lang.Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link IDataSourceViewSchemaAccessor}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link IDataSourceViewSchemaAccessor} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static IDataSourceViewSchemaAccessor ToIDataSourceViewSchemaAccessor(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new IDataSourceViewSchemaAccessorImplementation(from.getJCOInstance());
}
// Methods section
// Properties section
public NetObject getDataSourceViewSchema() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("DataSourceViewSchema");
return new NetObject(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setDataSourceViewSchema(NetObject DataSourceViewSchema) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("DataSourceViewSchema", DataSourceViewSchema == null ? null : DataSourceViewSchema.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
}
|
3e08496f2319c116d07229eed6b3a183ca25ce52
| 147 |
java
|
Java
|
src/main/java/com/roamsys/swagger/SwaggerAPIModel.java
|
jorada/swaggerapi
|
49d8318234946108128dac38c753702d4c4b5ef8
|
[
"MIT"
] | 11 |
2015-04-05T16:05:18.000Z
|
2020-10-22T15:55:20.000Z
|
src/main/java/com/roamsys/swagger/SwaggerAPIModel.java
|
jorada/swaggerapi
|
49d8318234946108128dac38c753702d4c4b5ef8
|
[
"MIT"
] | null | null | null |
src/main/java/com/roamsys/swagger/SwaggerAPIModel.java
|
jorada/swaggerapi
|
49d8318234946108128dac38c753702d4c4b5ef8
|
[
"MIT"
] | 9 |
2015-02-19T12:53:27.000Z
|
2017-08-16T09:59:57.000Z
| 13.363636 | 44 | 0.693878 | 3,508 |
package com.roamsys.swagger;
/**
* A marker interface for swagger API models
*
* @author johanna
*/
public interface SwaggerAPIModel {
}
|
3e084bb136e44cdb137a354953e1b42e885b4dbb
| 1,910 |
java
|
Java
|
agent/src/test/java/com/github/kornilova_l/flamegraph/javaagent/generate/test_classes/UseProxyExpected.java
|
brtubb-patagonia/FlameViewer
|
e4ead70bcf92caa5514d86c9a87c41ea3dc67b6c
|
[
"MIT"
] | null | null | null |
agent/src/test/java/com/github/kornilova_l/flamegraph/javaagent/generate/test_classes/UseProxyExpected.java
|
brtubb-patagonia/FlameViewer
|
e4ead70bcf92caa5514d86c9a87c41ea3dc67b6c
|
[
"MIT"
] | null | null | null |
agent/src/test/java/com/github/kornilova_l/flamegraph/javaagent/generate/test_classes/UseProxyExpected.java
|
brtubb-patagonia/FlameViewer
|
e4ead70bcf92caa5514d86c9a87c41ea3dc67b6c
|
[
"MIT"
] | 1 |
2020-05-09T10:52:33.000Z
|
2020-05-09T10:52:33.000Z
| 38.979592 | 105 | 0.485864 | 3,509 |
package com.github.kornilova_l.flamegraph.javaagent.generate.test_classes;
import com.github.kornilova_l.flamegraph.proxy.Proxy;
import com.github.kornilova_l.flamegraph.proxy.StartData;
/**
* Created by Liudmila Kornilova
* on 11.08.17.
*/
public class UseProxyExpected {
public static void main(String[] args) {
StartData startData = new StartData(System.currentTimeMillis(), null);
try {
System.out.println("Hello, world!");
startData.setDuration(System.currentTimeMillis());
if (startData.getDuration() > 1) {
Proxy.addToQueue(null,
startData.getStartTime(),
startData.getDuration(),
startData.getParameters(),
Thread.currentThread(),
"com/github/kornilova_l/flamegraph/javaagent/generate/test_classes/UseProxy",
"main",
"([Ljava/lang/String;)V",
true,
"");
}
} catch (Throwable throwable) {
if (!startData.isThrownByMethod()) {
startData.setDuration(System.currentTimeMillis());
if (startData.getDuration() > 1) {
Proxy.addToQueue(throwable,
true,
startData.getStartTime(),
startData.getDuration(),
startData.getParameters(),
Thread.currentThread(),
"com/github/kornilova_l/flamegraph/javaagent/generate/test_classes/UseProxy",
"main",
"([Ljava/lang/String;)V",
true,
"");
}
}
throw throwable;
}
}
}
|
3e084c0471f84c541a12369c957d22217fd905f5
| 217 |
java
|
Java
|
src/main/java/com/totvs/api/repositories/TelefoneRepository.java
|
duartedanilo/avaliacao-tecnica-totvs
|
51f13e5d8da253c3acbb0451d504cb37f5080888
|
[
"MIT"
] | null | null | null |
src/main/java/com/totvs/api/repositories/TelefoneRepository.java
|
duartedanilo/avaliacao-tecnica-totvs
|
51f13e5d8da253c3acbb0451d504cb37f5080888
|
[
"MIT"
] | null | null | null |
src/main/java/com/totvs/api/repositories/TelefoneRepository.java
|
duartedanilo/avaliacao-tecnica-totvs
|
51f13e5d8da253c3acbb0451d504cb37f5080888
|
[
"MIT"
] | null | null | null | 27.125 | 77 | 0.829493 | 3,510 |
package com.totvs.api.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.totvs.api.models.Telefone;
public interface TelefoneRepository extends JpaRepository<Telefone, Long> { }
|
3e084d0f9f9f56d687f42eb7e3f782f93730ed78
| 1,752 |
java
|
Java
|
src/main/java/com/tencentcloudapi/iai/v20180301/models/Mouth.java
|
feixueck/tencentcloud-sdk-java
|
ebdfb9cf12ce7630f53b387e2ac8d17471c6c7d0
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/tencentcloudapi/iai/v20180301/models/Mouth.java
|
feixueck/tencentcloud-sdk-java
|
ebdfb9cf12ce7630f53b387e2ac8d17471c6c7d0
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/tencentcloudapi/iai/v20180301/models/Mouth.java
|
feixueck/tencentcloud-sdk-java
|
ebdfb9cf12ce7630f53b387e2ac8d17471c6c7d0
|
[
"Apache-2.0"
] | null | null | null | 28.258065 | 83 | 0.698059 | 3,511 |
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.iai.v20180301.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class Mouth extends AbstractModel{
/**
* 是否张嘴信息。
AttributeItem对应的Type为 —— 0:不张嘴,1:张嘴。
*/
@SerializedName("MouthOpen")
@Expose
private AttributeItem MouthOpen;
/**
* Get 是否张嘴信息。
AttributeItem对应的Type为 —— 0:不张嘴,1:张嘴。
* @return MouthOpen 是否张嘴信息。
AttributeItem对应的Type为 —— 0:不张嘴,1:张嘴。
*/
public AttributeItem getMouthOpen() {
return this.MouthOpen;
}
/**
* Set 是否张嘴信息。
AttributeItem对应的Type为 —— 0:不张嘴,1:张嘴。
* @param MouthOpen 是否张嘴信息。
AttributeItem对应的Type为 —— 0:不张嘴,1:张嘴。
*/
public void setMouthOpen(AttributeItem MouthOpen) {
this.MouthOpen = MouthOpen;
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamObj(map, prefix + "MouthOpen.", this.MouthOpen);
}
}
|
3e084d130c7bc4c4e74b8e41765515af8805bbf2
| 2,819 |
java
|
Java
|
src/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/util/PageRange.java
|
EuKaique/Projeto-Diagnostico-Medico
|
cf7cc535ff31992b7568dba777c8faafafa6920c
|
[
"MIT"
] | null | null | null |
src/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/util/PageRange.java
|
EuKaique/Projeto-Diagnostico-Medico
|
cf7cc535ff31992b7568dba777c8faafafa6920c
|
[
"MIT"
] | null | null | null |
src/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/util/PageRange.java
|
EuKaique/Projeto-Diagnostico-Medico
|
cf7cc535ff31992b7568dba777c8faafafa6920c
|
[
"MIT"
] | null | null | null | 23.204918 | 92 | 0.675026 | 3,512 |
/*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2019 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.engine.util;
import java.util.ArrayList;
import java.util.List;
/**
* @author Teodor Danciu ([email protected])
*/
public class PageRange
{
private Integer startPageIndex;
private Integer endPageIndex;
/**
*
*/
public PageRange(Integer startPageIndex, Integer endPageIndex)
{
this.startPageIndex = startPageIndex;
this.endPageIndex = endPageIndex;
}
/**
*
*/
public Integer getStartPageIndex()
{
return startPageIndex;
}
/**
*
*/
public Integer getEndPageIndex()
{
return endPageIndex;
}
/**
*
*/
public static PageRange[] parse(String strRanges)
{
List<PageRange> ranges = null;
if (strRanges != null && strRanges.trim().length() > 0)
{
ranges = new ArrayList<PageRange>();
String[] rangeTokens = strRanges.split(",");
for (String rangeToken : rangeTokens)
{
PageRange pageRange = null;
int hyphenPos = rangeToken.indexOf("-");
if (hyphenPos > 0 && hyphenPos < rangeToken.length() - 1)
{
pageRange =
new PageRange(
Integer.valueOf(rangeToken.substring(0, hyphenPos).trim()),
Integer.valueOf(rangeToken.substring(hyphenPos + 1).trim())
);
}
else
{
int pageIndex = Integer.valueOf(rangeToken.trim());
pageRange = new PageRange(pageIndex, pageIndex);
}
ranges.add(pageRange);
}
}
return ranges == null ? null : (PageRange[]) ranges.toArray(new PageRange[ranges.size()]);
}
/**
*
*/
public static boolean isPageInRanges(int pageIndex, PageRange[] ranges)
{
boolean isInRanges = false;
if (ranges != null)
{
for (PageRange range : ranges)
{
if (range.startPageIndex <= pageIndex && pageIndex <= range.endPageIndex)
{
isInRanges = true;
break;
}
}
}
return isInRanges;
}
}
|
3e084d34faba92253d6ac5e6055515e568988ac2
| 4,026 |
java
|
Java
|
src/main/java/seedu/multitasky/logic/commands/DeleteByFindCommand.java
|
ChuaPingChan/MultiTasky
|
05c123cfc93c176e56fc34472558f67c4a00326f
|
[
"MIT"
] | 1 |
2019-04-02T17:21:54.000Z
|
2019-04-02T17:21:54.000Z
|
src/main/java/seedu/multitasky/logic/commands/DeleteByFindCommand.java
|
ChuaPingChan/MultiTasky
|
05c123cfc93c176e56fc34472558f67c4a00326f
|
[
"MIT"
] | null | null | null |
src/main/java/seedu/multitasky/logic/commands/DeleteByFindCommand.java
|
ChuaPingChan/MultiTasky
|
05c123cfc93c176e56fc34472558f67c4a00326f
|
[
"MIT"
] | null | null | null | 45.235955 | 113 | 0.618231 | 3,513 |
package seedu.multitasky.logic.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import seedu.multitasky.logic.commands.exceptions.CommandException;
import seedu.multitasky.logic.parser.CliSyntax;
import seedu.multitasky.model.Model;
import seedu.multitasky.model.entry.Entry;
import seedu.multitasky.model.entry.ReadOnlyEntry;
import seedu.multitasky.model.entry.exceptions.DuplicateEntryException;
import seedu.multitasky.model.entry.exceptions.EntryNotFoundException;
import seedu.multitasky.model.entry.exceptions.EntryOverdueException;
import seedu.multitasky.model.entry.exceptions.OverlappingAndOverdueEventException;
import seedu.multitasky.model.entry.exceptions.OverlappingEventException;
// @@author A0140633R
/**
* Finds entries from given keywords and deletes entry if it is the only one found.
*/
public class DeleteByFindCommand extends DeleteCommand {
public static final String MESSAGE_NO_ENTRIES = "No entries found! Please try again with different keywords";
public static final String MESSAGE_MULTIPLE_ENTRIES = "More than one entry found! \n"
+ "Use " + COMMAND_WORD + " ["
+ String.join(" | ",
CliSyntax.PREFIX_EVENT.toString(),
CliSyntax.PREFIX_DEADLINE.toString(),
CliSyntax.PREFIX_FLOATINGTASK.toString())
+ "]"
+ " INDEX to specify which entry to delete.";
private Set<String> keywords;
public DeleteByFindCommand(Set<String> keywords) {
this.keywords = keywords;
}
@Override
public CommandResult execute() throws CommandException, DuplicateEntryException {
List<ReadOnlyEntry> allList = getListAfterSearch();
if (allList.size() == 1) { // proceed to delete
entryToDelete = allList.get(0);
try {
model.changeEntryState(entryToDelete, Entry.State.DELETED);
} catch (EntryNotFoundException | OverlappingEventException
| EntryOverdueException | OverlappingAndOverdueEventException e) {
throw new AssertionError("These errors should not be occuring in delete.");
}
revertListView();
return new CommandResult(String.format(MESSAGE_SUCCESS, entryToDelete));
} else {
// save search parameters
history.setPrevSearch(keywords, null, null, Entry.State.ACTIVE, Model.STRICT_SEARCHES);
if (allList.size() >= 2) { // multiple entries found
throw new CommandException(MESSAGE_MULTIPLE_ENTRIES);
} else {
assert (allList.size() == 0); // no entries found
throw new CommandException(MESSAGE_NO_ENTRIES);
}
}
}
/**
* reverts inner lists in model to how they were before by using command history
*/
private void revertListView() {
model.updateAllFilteredLists(history.getPrevKeywords(), history.getPrevStartDate(),
history.getPrevEndDate(), history.getPrevState(),
history.getPrevSearches());
}
/**
* updates inner lists with new keyword terms and returns a collated list with all found entries.
*/
private List<ReadOnlyEntry> getListAfterSearch() {
model.updateAllFilteredLists(keywords, null, null, Entry.State.ACTIVE, Model.STRICT_SEARCHES);
List<ReadOnlyEntry> allList = new ArrayList<>();
allList.addAll(model.getFilteredDeadlineList());
allList.addAll(model.getFilteredEventList());
allList.addAll(model.getFilteredFloatingTaskList());
return allList;
}
}
|
3e084d6375ffa22567f33fcdea7231c5a8bf30b3
| 3,699 |
java
|
Java
|
komet/application/src/test/java/sh/komet/fx/stage/TestMenu.java
|
TheAdityaKedia/ISAAC
|
7a63d7a38dc16c747c3b414ebd221a9f26479b75
|
[
"Apache-2.0"
] | 1 |
2020-06-21T02:45:14.000Z
|
2020-06-21T02:45:14.000Z
|
komet/application/src/test/java/sh/komet/fx/stage/TestMenu.java
|
TheAdityaKedia/ISAAC
|
7a63d7a38dc16c747c3b414ebd221a9f26479b75
|
[
"Apache-2.0"
] | 2 |
2020-05-17T22:35:48.000Z
|
2022-01-21T23:43:11.000Z
|
komet/application/src/test/java/sh/komet/fx/stage/TestMenu.java
|
mindcomputing/knowledge-core
|
5e00971b773a70d90eab597681300d5555125558
|
[
"Apache-2.0"
] | null | null | null | 33.026786 | 113 | 0.731008 | 3,514 |
/*
* Copyright 2018 ISAAC's KOMET Collaborators.
*
* 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 sh.komet.fx.stage;
import de.codecentric.centerdevice.MenuToolkit;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
* @author kec
*/
public class TestMenu extends Application {
static final String appName = "Standard";
static final String mainWindowTitle = "Main";
static final String childWindowTitle = "Child";
static long counter = 1;
@Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane();
Button button = new Button();
button.setText("Create new Stage");
button.setOnAction(action -> createNewStage());
root.getChildren().add(button);
primaryStage.setScene(new Scene(root, 300, 200));
primaryStage.requestFocus();
primaryStage.setTitle(mainWindowTitle);
primaryStage.show();
MenuToolkit tk = MenuToolkit.toolkit();
MenuBar bar = new MenuBar();
// Application Menu
// TBD: services menu
Menu appMenu = new Menu(appName); // Name for appMenu can't be set at
// Runtime
MenuItem aboutItem = tk.createAboutMenuItem(appName);
MenuItem prefsItem = new MenuItem("Preferences...");
appMenu.getItems().addAll(aboutItem, new SeparatorMenuItem(), prefsItem, new SeparatorMenuItem(),
tk.createHideMenuItem(appName), tk.createHideOthersMenuItem(), tk.createUnhideAllMenuItem(),
new SeparatorMenuItem(), tk.createQuitMenuItem(appName));
// File Menu (items TBD)
Menu fileMenu = new Menu("File");
MenuItem newItem = new MenuItem("New...");
fileMenu.getItems().addAll(newItem, new SeparatorMenuItem(), tk.createCloseWindowMenuItem(),
new SeparatorMenuItem(), new MenuItem("TBD"));
// Edit (items TBD)
Menu editMenu = new Menu("Edit");
editMenu.getItems().addAll(new MenuItem("TBD"));
// Format (items TBD)
Menu formatMenu = new Menu("Format");
formatMenu.getItems().addAll(new MenuItem("TBD"));
// View Menu (items TBD)
Menu viewMenu = new Menu("View");
viewMenu.getItems().addAll(new MenuItem("TBD"));
// Window Menu
// TBD standard window menu items
Menu windowMenu = new Menu("Window");
windowMenu.getItems().addAll(tk.createMinimizeMenuItem(), tk.createZoomMenuItem(), tk.createCycleWindowsItem(),
new SeparatorMenuItem(), tk.createBringAllToFrontItem());
// Help Menu (items TBD)
Menu helpMenu = new Menu("Help");
helpMenu.getItems().addAll(new MenuItem("TBD"));
bar.getMenus().addAll(appMenu, fileMenu, editMenu, formatMenu, viewMenu, windowMenu, helpMenu);
tk.autoAddWindowMenuItems(windowMenu);
tk.setGlobalMenuBar(bar);
}
private void createNewStage() {
Stage stage = new Stage();
stage.setScene(new Scene(new StackPane()));
stage.setTitle(childWindowTitle + " " + (counter++));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
3e084d95c6b4049709c649b5d9c7d066cb19dffd
| 3,063 |
java
|
Java
|
build/generated-src/antlr/main/cymbol/CymbolCFGLexer.java
|
courses-at-nju-by-hfwei/compilers-antlr
|
22f14d442da731d7015284ef43eafa5120e88f40
|
[
"MIT"
] | 7 |
2021-11-14T05:43:19.000Z
|
2021-12-16T03:24:37.000Z
|
build/generated-src/antlr/main/cymbol/CymbolCFGLexer.java
|
courses-at-nju-by-hfwei/compilers-antlr
|
22f14d442da731d7015284ef43eafa5120e88f40
|
[
"MIT"
] | null | null | null |
build/generated-src/antlr/main/cymbol/CymbolCFGLexer.java
|
courses-at-nju-by-hfwei/compilers-antlr
|
22f14d442da731d7015284ef43eafa5120e88f40
|
[
"MIT"
] | 2 |
2021-12-02T12:20:00.000Z
|
2021-12-16T10:36:39.000Z
| 26.634783 | 97 | 0.708129 | 3,515 |
// Generated from cymbol/CymbolCFG.g4 by ANTLR 4.9.2
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.misc.*;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class CymbolCFGLexer extends Lexer {
static { RuntimeMetaData.checkVersion("4.9.2", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
T__0=1;
public static String[] channelNames = {
"DEFAULT_TOKEN_CHANNEL", "HIDDEN"
};
public static String[] modeNames = {
"DEFAULT_MODE"
};
private static String[] makeRuleNames() {
return new String[] {
"T__0"
};
}
public static final String[] ruleNames = makeRuleNames();
private static String[] makeLiteralNames() {
return new String[] {
null, "' '"
};
}
private static final String[] _LITERAL_NAMES = makeLiteralNames();
private static String[] makeSymbolicNames() {
return new String[] {
};
}
private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames();
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
public CymbolCFGLexer(CharStream input) {
super(input);
_interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
@Override
public String getGrammarFileName() { return "CymbolCFG.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public String[] getChannelNames() { return channelNames; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
public ATN getATN() { return _ATN; }
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\3\7\b\1\4\2\t\2\3"+
"\2\3\2\2\2\3\3\3\3\2\2\2\6\2\3\3\2\2\2\3\5\3\2\2\2\5\6\7\"\2\2\6\4\3\2"+
"\2\2\3\2\2";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}
|
3e084dd67b25e22414f9bd0e9615f6f1515420f2
| 118 |
java
|
Java
|
src/main/java/refactor/factoryPattern/Product.java
|
xiapeng612430/demos
|
cd988452cd6e0281b322fc4186fde5f49883773d
|
[
"MIT"
] | 1 |
2020-06-03T13:50:59.000Z
|
2020-06-03T13:50:59.000Z
|
src/main/java/refactor/factoryPattern/Product.java
|
xiapeng612430/demos
|
cd988452cd6e0281b322fc4186fde5f49883773d
|
[
"MIT"
] | 4 |
2021-03-22T23:54:17.000Z
|
2022-02-01T00:59:20.000Z
|
src/main/java/refactor/factoryPattern/Product.java
|
xiapeng612430/demos
|
cd988452cd6e0281b322fc4186fde5f49883773d
|
[
"MIT"
] | null | null | null | 11.8 | 32 | 0.686441 | 3,516 |
package refactor.factoryPattern;
/**
* Created by xianpeng.xia
* on 2019-04-21 21:36
*/
public class Product {
}
|
3e084e7801d5947c23395e7351996e66b0d90afd
| 2,569 |
java
|
Java
|
src/main/java/com/sid/leetcode/problem/puzzle/NQueens.java
|
rencht/LeetCode
|
b791c39858784273a9f66a0b0326f8e721ba4c1d
|
[
"MIT"
] | null | null | null |
src/main/java/com/sid/leetcode/problem/puzzle/NQueens.java
|
rencht/LeetCode
|
b791c39858784273a9f66a0b0326f8e721ba4c1d
|
[
"MIT"
] | null | null | null |
src/main/java/com/sid/leetcode/problem/puzzle/NQueens.java
|
rencht/LeetCode
|
b791c39858784273a9f66a0b0326f8e721ba4c1d
|
[
"MIT"
] | null | null | null | 25.949495 | 121 | 0.514986 | 3,517 |
package com.sid.leetcode.problem.puzzle;
import java.util.ArrayList;
import java.util.List;
/**
* 51. N-Queens.
*
* <blockquote>
* The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens atack each other.
* <p><img src="https://assets.leetcode.com/uploads/2018/10/12/8-queens.png"/>
* <p>Given an integer n, return all distinct solutions to the n-queens puzzle.
* <p>Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a
* queen and an empty space respectively.
*
*
* <p>
* <b>Example:</b>
* <blockquote>
* <b>Input:</b> 4
* <p><b>Output:</b>
* <p>[
* <pre>[ ".Q..",
* <p> "...Q",
* <p> "Q...",
* <p> "..Q."],
* <p>[ "..Q.",
* <p> "Q...",
* <p> "...Q",
* <p> ".Q.."]
* </pre>
* <p>]
* </blockquote>
* </blockquote>
*
* @author Sid.Chen
* @version 1.0, 2019-07-22
*
*/
public class NQueens {
// DFS
public List<List<String>> solveNQueens(int n) {
final List<List<String>> result = new ArrayList<List<String>>();
final List<String> board = new ArrayList<String>();
for (int i = 0; i < n; i++) {
board.add("");
}
this.dfs(result, board, 0);
return result;
}
private void dfs(final List<List<String>> result, final List<String> board, final int i) {
for (final String row : this.validPos(board, i)) {
board.remove(i);
board.add(i, row);
if (i == board.size() - 1) {
result.add(new ArrayList<String>(board));
continue;
}
this.dfs(result, board, i + 1);
}
}
private List<String> validPos(final List<String> board, final int i) {
final boolean[] flags = new boolean[board.size()];
for (int j = 0; j < i; j++) {
final int k = board.get(j).indexOf("Q");
flags[k] = true;
final int l = k + j - i;
if (l >= 0) flags[l] = true;
final int r = k + i - j;
if (r < board.size()) flags[r] = true;
}
final List<String> result = new ArrayList<String>();
for (int j = 0; j < flags.length; j++) {
if (!flags[j]) result.add(this.row(j, board.size()));
}
return result;
}
private String row(final int i, final int n) {
final char[] chs = new char[n];
for (int j = 0; j < n; j++) {
chs[j] = i == j ? 'Q' : '.';
}
return String.valueOf(chs);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.